2 * Sone - Sone.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.data;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.List;
29 import java.util.concurrent.CopyOnWriteArrayList;
30 import java.util.concurrent.CopyOnWriteArraySet;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options;
35 import net.pterodactylus.sone.freenet.wot.Identity;
36 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
37 import net.pterodactylus.sone.template.SoneAccessor;
38 import net.pterodactylus.util.logging.Logging;
40 import com.google.common.base.Predicate;
41 import com.google.common.hash.Hasher;
42 import com.google.common.hash.Hashing;
44 import freenet.keys.FreenetURI;
47 * A Sone defines everything about a user: her profile, her status updates, her
48 * replies, her likes and dislikes, etc.
50 * Operations that modify the Sone need to synchronize on the Sone in question.
52 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54 public class Sone implements Fingerprintable, Comparable<Sone> {
57 * Enumeration for the possible states of a {@link Sone}.
59 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61 public enum SoneStatus {
63 /** The Sone is unknown, i.e. not yet downloaded. */
66 /** The Sone is idle, i.e. not being downloaded or inserted. */
69 /** The Sone is currently being inserted. */
72 /** The Sone is currently being downloaded. */
77 * The possible values for the “show custom avatars” option.
79 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
81 public static enum ShowCustomAvatars {
83 /** Never show custom avatars. */
86 /** Only show custom avatars of followed Sones. */
89 /** Only show custom avatars of Sones you manually trust. */
92 /** Only show custom avatars of automatically trusted Sones. */
95 /** Always show custom avatars. */
100 /** comparator that sorts Sones by their nice name. */
101 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
104 public int compare(Sone leftSone, Sone rightSone) {
105 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
109 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
115 * Comparator that sorts Sones by last activity (least recent active first).
117 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
120 public int compare(Sone firstSone, Sone secondSone) {
121 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
125 /** Comparator that sorts Sones by numbers of posts (descending). */
126 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
132 public int compare(Sone leftSone, Sone rightSone) {
133 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
137 /** Comparator that sorts Sones by number of images (descending). */
138 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
144 public int compare(Sone leftSone, Sone rightSone) {
145 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
149 /** Filter to remove Sones that have not been downloaded. */
150 public static final Predicate<Sone> EMPTY_SONE_FILTER = new Predicate<Sone>() {
153 public boolean apply(Sone sone) {
154 return sone.getTime() != 0;
158 /** Filter that matches all {@link Sone#isLocal() local Sones}. */
159 public static final Predicate<Sone> LOCAL_SONE_FILTER = new Predicate<Sone>() {
162 public boolean apply(Sone sone) {
163 return sone.getIdentity() instanceof OwnIdentity;
168 /** Filter that matches Sones that have at least one album. */
169 public static final Predicate<Sone> HAS_ALBUM_FILTER = new Predicate<Sone>() {
172 public boolean apply(Sone sone) {
173 return !sone.getAlbums().isEmpty();
178 private static final Logger logger = Logging.getLogger(Sone.class);
180 /** The ID of this Sone. */
181 private final String id;
183 /** Whether the Sone is local. */
184 private final boolean local;
186 /** The identity of this Sone. */
187 private Identity identity;
189 /** The URI under which the Sone is stored in Freenet. */
190 private volatile FreenetURI requestUri;
192 /** The URI used to insert a new version of this Sone. */
193 /* This will be null for remote Sones! */
194 private volatile FreenetURI insertUri;
196 /** The latest edition of the Sone. */
197 private volatile long latestEdition;
199 /** The time of the last inserted update. */
200 private volatile long time;
202 /** The status of this Sone. */
203 private volatile SoneStatus status = SoneStatus.unknown;
205 /** The profile of this Sone. */
206 private volatile Profile profile = new Profile(this);
208 /** The client used by the Sone. */
209 private volatile Client client;
211 /** Whether this Sone is known. */
212 private volatile boolean known;
214 /** All friend Sones. */
215 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
218 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
221 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
223 /** The IDs of all liked posts. */
224 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
226 /** The IDs of all liked replies. */
227 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
229 /** The albums of this Sone. */
230 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
232 /** Sone-specific options. */
233 private Options options = new Options();
236 * Creates a new Sone.
241 * {@code true} if the Sone is a local Sone, {@code false}
244 public Sone(String id, boolean local) {
254 * Returns the identity of this Sone.
256 * @return The identity of this Sone
258 public String getId() {
263 * Returns the identity of this Sone.
265 * @return The identity of this Sone
267 public Identity getIdentity() {
272 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
273 * identity has to match this Sone’s {@link #getId()}.
276 * The identity of this Sone
277 * @return This Sone (for method chaining)
278 * @throws IllegalArgumentException
279 * if the ID of the identity does not match this Sone’s ID
281 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
282 if (!identity.getId().equals(id)) {
283 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
285 this.identity = identity;
290 * Returns the name of this Sone.
292 * @return The name of this Sone
294 public String getName() {
295 return (identity != null) ? identity.getNickname() : null;
299 * Returns whether this Sone is a local Sone.
301 * @return {@code true} if this Sone is a local Sone, {@code false}
304 public boolean isLocal() {
309 * Returns the request URI of this Sone.
311 * @return The request URI of this Sone
313 public FreenetURI getRequestUri() {
314 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
318 * Sets the request URI of this Sone.
321 * The request URI of this Sone
322 * @return This Sone (for method chaining)
324 public Sone setRequestUri(FreenetURI requestUri) {
325 if (this.requestUri == null) {
326 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
329 if (!this.requestUri.equalsKeypair(requestUri)) {
330 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
337 * Returns the insert URI of this Sone.
339 * @return The insert URI of this Sone
341 public FreenetURI getInsertUri() {
342 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
346 * Sets the insert URI of this Sone.
349 * The insert URI of this Sone
350 * @return This Sone (for method chaining)
352 public Sone setInsertUri(FreenetURI insertUri) {
353 if (this.insertUri == null) {
354 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
357 if (!this.insertUri.equalsKeypair(insertUri)) {
358 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
365 * Returns the latest edition of this Sone.
367 * @return The latest edition of this Sone
369 public long getLatestEdition() {
370 return latestEdition;
374 * Sets the latest edition of this Sone. If the given latest edition is not
375 * greater than the current latest edition, the latest edition of this Sone
378 * @param latestEdition
379 * The latest edition of this Sone
381 public void setLatestEdition(long latestEdition) {
382 if (!(latestEdition > this.latestEdition)) {
383 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
386 this.latestEdition = latestEdition;
390 * Return the time of the last inserted update of this Sone.
392 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
394 public long getTime() {
399 * Sets the time of the last inserted update of this Sone.
402 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
403 * @return This Sone (for method chaining)
405 public Sone setTime(long time) {
411 * Returns the status of this Sone.
413 * @return The status of this Sone
415 public SoneStatus getStatus() {
420 * Sets the new status of this Sone.
423 * The new status of this Sone
425 * @throws IllegalArgumentException
426 * if {@code status} is {@code null}
428 public Sone setStatus(SoneStatus status) {
429 this.status = checkNotNull(status, "status must not be null");
434 * Returns a copy of the profile. If you want to update values in the
435 * profile of this Sone, update the values in the returned {@link Profile}
436 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
438 * @return A copy of the profile
440 public Profile getProfile() {
441 return new Profile(profile);
445 * Sets the profile of this Sone. A copy of the given profile is stored so
446 * that subsequent modifications of the given profile are not reflected in
452 public void setProfile(Profile profile) {
453 this.profile = new Profile(profile);
457 * Returns the client used by this Sone.
459 * @return The client used by this Sone, or {@code null}
461 public Client getClient() {
466 * Sets the client used by this Sone.
469 * The client used by this Sone, or {@code null}
470 * @return This Sone (for method chaining)
472 public Sone setClient(Client client) {
473 this.client = client;
478 * Returns whether this Sone is known.
480 * @return {@code true} if this Sone is known, {@code false} otherwise
482 public boolean isKnown() {
487 * Sets whether this Sone is known.
490 * {@code true} if this Sone is known, {@code false} otherwise
493 public Sone setKnown(boolean known) {
499 * Returns all friend Sones of this Sone.
501 * @return The friend Sones of this Sone
503 public List<String> getFriends() {
504 List<String> friends = new ArrayList<String>(friendSones);
509 * Returns whether this Sone has the given Sone as a friend Sone.
511 * @param friendSoneId
512 * The ID of the Sone to check for
513 * @return {@code true} if this Sone has the given Sone as a friend,
514 * {@code false} otherwise
516 public boolean hasFriend(String friendSoneId) {
517 return friendSones.contains(friendSoneId);
521 * Adds the given Sone as a friend Sone.
524 * The friend Sone to add
525 * @return This Sone (for method chaining)
527 public Sone addFriend(String friendSone) {
528 if (!friendSone.equals(id)) {
529 friendSones.add(friendSone);
535 * Removes the given Sone as a friend Sone.
537 * @param friendSoneId
538 * The ID of the friend Sone to remove
539 * @return This Sone (for method chaining)
541 public Sone removeFriend(String friendSoneId) {
542 friendSones.remove(friendSoneId);
547 * Returns the list of posts of this Sone, sorted by time, newest first.
549 * @return All posts of this Sone
551 public List<Post> getPosts() {
552 List<Post> sortedPosts;
553 synchronized (this) {
554 sortedPosts = new ArrayList<Post>(posts);
556 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
561 * Sets all posts of this Sone at once.
564 * The new (and only) posts of this Sone
565 * @return This Sone (for method chaining)
567 public Sone setPosts(Collection<Post> posts) {
568 synchronized (this) {
570 this.posts.addAll(posts);
576 * Adds the given post to this Sone. The post will not be added if its
577 * {@link Post#getSone() Sone} is not this Sone.
582 public void addPost(Post post) {
583 if (post.getSone().equals(this) && posts.add(post)) {
584 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
589 * Removes the given post from this Sone.
594 public void removePost(Post post) {
595 if (post.getSone().equals(this)) {
601 * Returns all replies this Sone made.
603 * @return All replies this Sone made
605 public Set<PostReply> getReplies() {
606 return Collections.unmodifiableSet(replies);
610 * Sets all replies of this Sone at once.
613 * The new (and only) replies of this Sone
614 * @return This Sone (for method chaining)
616 public Sone setReplies(Collection<PostReply> replies) {
617 this.replies.clear();
618 this.replies.addAll(replies);
623 * Adds a reply to this Sone. If the given reply was not made by this Sone,
624 * nothing is added to this Sone.
629 public void addReply(PostReply reply) {
630 if (reply.getSone().equals(this)) {
636 * Removes a reply from this Sone.
639 * The reply to remove
641 public void removeReply(PostReply reply) {
642 if (reply.getSone().equals(this)) {
643 replies.remove(reply);
648 * Returns the IDs of all liked posts.
650 * @return All liked posts’ IDs
652 public Set<String> getLikedPostIds() {
653 return Collections.unmodifiableSet(likedPostIds);
657 * Sets the IDs of all liked posts.
659 * @param likedPostIds
660 * All liked posts’ IDs
661 * @return This Sone (for method chaining)
663 public Sone setLikePostIds(Set<String> likedPostIds) {
664 this.likedPostIds.clear();
665 this.likedPostIds.addAll(likedPostIds);
670 * Checks whether the given post ID is liked by this Sone.
674 * @return {@code true} if this Sone likes the given post, {@code false}
677 public boolean isLikedPostId(String postId) {
678 return likedPostIds.contains(postId);
682 * Adds the given post ID to the list of posts this Sone likes.
686 * @return This Sone (for method chaining)
688 public Sone addLikedPostId(String postId) {
689 likedPostIds.add(postId);
694 * Removes the given post ID from the list of posts this Sone likes.
698 * @return This Sone (for method chaining)
700 public Sone removeLikedPostId(String postId) {
701 likedPostIds.remove(postId);
706 * Returns the IDs of all liked replies.
708 * @return All liked replies’ IDs
710 public Set<String> getLikedReplyIds() {
711 return Collections.unmodifiableSet(likedReplyIds);
715 * Sets the IDs of all liked replies.
717 * @param likedReplyIds
718 * All liked replies’ IDs
719 * @return This Sone (for method chaining)
721 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
722 this.likedReplyIds.clear();
723 this.likedReplyIds.addAll(likedReplyIds);
728 * Checks whether the given reply ID is liked by this Sone.
731 * The ID of the reply
732 * @return {@code true} if this Sone likes the given reply, {@code false}
735 public boolean isLikedReplyId(String replyId) {
736 return likedReplyIds.contains(replyId);
740 * Adds the given reply ID to the list of replies this Sone likes.
743 * The ID of the reply
744 * @return This Sone (for method chaining)
746 public Sone addLikedReplyId(String replyId) {
747 likedReplyIds.add(replyId);
752 * Removes the given post ID from the list of replies this Sone likes.
755 * The ID of the reply
756 * @return This Sone (for method chaining)
758 public Sone removeLikedReplyId(String replyId) {
759 likedReplyIds.remove(replyId);
764 * Returns the albums of this Sone.
766 * @return The albums of this Sone
768 public List<Album> getAlbums() {
769 return Collections.unmodifiableList(albums);
773 * Returns a flattened list of all albums of this Sone. The resulting list
774 * contains parent albums before child albums so that the resulting list can
775 * be parsed in a single pass.
777 * @return The flattened albums
779 public List<Album> getAllAlbums() {
780 List<Album> flatAlbums = new ArrayList<Album>();
781 flatAlbums.addAll(albums);
782 int lastAlbumIndex = 0;
783 while (lastAlbumIndex < flatAlbums.size()) {
784 int previousAlbumCount = flatAlbums.size();
785 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
786 flatAlbums.addAll(album.getAlbums());
788 lastAlbumIndex = previousAlbumCount;
794 * Returns all images of a Sone. Images of a album are inserted into this
795 * list before images of all child albums.
797 * @return The list of all images
799 public List<Image> getAllImages() {
800 List<Image> allImages = new ArrayList<Image>();
801 for (Album album : getAllAlbums()) {
802 allImages.addAll(album.getImages());
808 * Adds an album to this Sone.
813 public void addAlbum(Album album) {
814 checkNotNull(album, "album must not be null");
815 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
816 if (!albums.contains(album)) {
822 * Sets the albums of this Sone.
825 * The albums of this Sone
827 public void setAlbums(Collection<? extends Album> albums) {
828 checkNotNull(albums, "albums must not be null");
830 for (Album album : albums) {
836 * Removes an album from this Sone.
839 * The album to remove
841 public void removeAlbum(Album album) {
842 checkNotNull(album, "album must not be null");
843 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
844 albums.remove(album);
848 * Moves the given album up in this album’s albums. If the album is already
849 * the first album, nothing happens.
852 * The album to move up
853 * @return The album that the given album swapped the place with, or
854 * <code>null</code> if the album did not change its place
856 public Album moveAlbumUp(Album album) {
857 checkNotNull(album, "album must not be null");
858 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
859 checkArgument(album.getParent() == null, "album must not have a parent");
860 int oldIndex = albums.indexOf(album);
864 albums.remove(oldIndex);
865 albums.add(oldIndex - 1, album);
866 return albums.get(oldIndex);
870 * Moves the given album down in this album’s albums. If the album is
871 * already the last album, nothing happens.
874 * The album to move down
875 * @return The album that the given album swapped the place with, or
876 * <code>null</code> if the album did not change its place
878 public Album moveAlbumDown(Album album) {
879 checkNotNull(album, "album must not be null");
880 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
881 checkArgument(album.getParent() == null, "album must not have a parent");
882 int oldIndex = albums.indexOf(album);
883 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
886 albums.remove(oldIndex);
887 albums.add(oldIndex + 1, album);
888 return albums.get(oldIndex);
892 * Returns Sone-specific options.
894 * @return The options of this Sone
896 public Options getOptions() {
901 * Sets the options of this Sone.
904 * The options of this Sone
906 /* TODO - remove this method again, maybe add an option provider */
907 public void setOptions(Options options) {
908 this.options = options;
912 // FINGERPRINTABLE METHODS
919 public synchronized String getFingerprint() {
920 Hasher hash = Hashing.sha256().newHasher();
921 hash.putString(profile.getFingerprint());
923 hash.putString("Posts(");
924 for (Post post : getPosts()) {
925 hash.putString("Post(").putString(post.getId()).putString(")");
929 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
930 Collections.sort(replies, Reply.TIME_COMPARATOR);
931 hash.putString("Replies(");
932 for (PostReply reply : replies) {
933 hash.putString("Reply(").putString(reply.getId()).putString(")");
937 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
938 Collections.sort(likedPostIds);
939 hash.putString("LikedPosts(");
940 for (String likedPostId : likedPostIds) {
941 hash.putString("Post(").putString(likedPostId).putString(")");
945 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
946 Collections.sort(likedReplyIds);
947 hash.putString("LikedReplies(");
948 for (String likedReplyId : likedReplyIds) {
949 hash.putString("Reply(").putString(likedReplyId).putString(")");
953 hash.putString("Albums(");
954 for (Album album : albums) {
955 hash.putString(album.getFingerprint());
959 return hash.hash().toString();
963 // INTERFACE Comparable<Sone>
970 public int compareTo(Sone sone) {
971 return NICE_NAME_COMPARATOR.compare(this, sone);
982 public int hashCode() {
983 return id.hashCode();
990 public boolean equals(Object object) {
991 if (!(object instanceof Sone)) {
994 return ((Sone) object).id.equals(id);
1001 public String toString() {
1002 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";