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.collect.FluentIterable;
42 import com.google.common.hash.Hasher;
43 import com.google.common.hash.Hashing;
45 import freenet.keys.FreenetURI;
48 * A Sone defines everything about a user: her profile, her status updates, her
49 * replies, her likes and dislikes, etc.
51 * Operations that modify the Sone need to synchronize on the Sone in question.
53 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55 public class Sone implements Fingerprintable, Comparable<Sone> {
58 * Enumeration for the possible states of a {@link Sone}.
60 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62 public enum SoneStatus {
64 /** The Sone is unknown, i.e. not yet downloaded. */
67 /** The Sone is idle, i.e. not being downloaded or inserted. */
70 /** The Sone is currently being inserted. */
73 /** The Sone is currently being downloaded. */
78 * The possible values for the “show custom avatars” option.
80 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82 public static enum ShowCustomAvatars {
84 /** Never show custom avatars. */
87 /** Only show custom avatars of followed Sones. */
90 /** Only show custom avatars of Sones you manually trust. */
93 /** Only show custom avatars of automatically trusted Sones. */
96 /** Always show custom avatars. */
101 /** comparator that sorts Sones by their nice name. */
102 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
105 public int compare(Sone leftSone, Sone rightSone) {
106 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
110 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
116 * Comparator that sorts Sones by last activity (least recent active first).
118 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
121 public int compare(Sone firstSone, Sone secondSone) {
122 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
126 /** Comparator that sorts Sones by numbers of posts (descending). */
127 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
133 public int compare(Sone leftSone, Sone rightSone) {
134 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
138 /** Comparator that sorts Sones by number of images (descending). */
139 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
145 public int compare(Sone leftSone, Sone rightSone) {
146 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
150 /** Filter to remove Sones that have not been downloaded. */
151 public static final Predicate<Sone> EMPTY_SONE_FILTER = new Predicate<Sone>() {
154 public boolean apply(Sone sone) {
155 return sone.getTime() != 0;
159 /** Filter that matches all {@link Sone#isLocal() local Sones}. */
160 public static final Predicate<Sone> LOCAL_SONE_FILTER = new Predicate<Sone>() {
163 public boolean apply(Sone sone) {
164 return sone.getIdentity() instanceof OwnIdentity;
169 /** Filter that matches Sones that have at least one album. */
170 public static final Predicate<Sone> HAS_ALBUM_FILTER = new Predicate<Sone>() {
173 public boolean apply(Sone sone) {
174 return !sone.getAlbums().isEmpty();
179 private static final Logger logger = Logging.getLogger(Sone.class);
181 /** The ID of this Sone. */
182 private final String id;
184 /** Whether the Sone is local. */
185 private final boolean local;
187 /** The identity of this Sone. */
188 private Identity identity;
190 /** The URI under which the Sone is stored in Freenet. */
191 private volatile FreenetURI requestUri;
193 /** The URI used to insert a new version of this Sone. */
194 /* This will be null for remote Sones! */
195 private volatile FreenetURI insertUri;
197 /** The latest edition of the Sone. */
198 private volatile long latestEdition;
200 /** The time of the last inserted update. */
201 private volatile long time;
203 /** The status of this Sone. */
204 private volatile SoneStatus status = SoneStatus.unknown;
206 /** The profile of this Sone. */
207 private volatile Profile profile = new Profile(this);
209 /** The client used by the Sone. */
210 private volatile Client client;
212 /** Whether this Sone is known. */
213 private volatile boolean known;
215 /** All friend Sones. */
216 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
219 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
222 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
224 /** The IDs of all liked posts. */
225 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
227 /** The IDs of all liked replies. */
228 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
230 /** The albums of this Sone. */
231 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
233 /** Sone-specific options. */
234 private Options options = new Options();
237 * Creates a new Sone.
242 * {@code true} if the Sone is a local Sone, {@code false}
245 public Sone(String id, boolean local) {
255 * Returns the identity of this Sone.
257 * @return The identity of this Sone
259 public String getId() {
264 * Returns the identity of this Sone.
266 * @return The identity of this Sone
268 public Identity getIdentity() {
273 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
274 * identity has to match this Sone’s {@link #getId()}.
277 * The identity of this Sone
278 * @return This Sone (for method chaining)
279 * @throws IllegalArgumentException
280 * if the ID of the identity does not match this Sone’s ID
282 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
283 if (!identity.getId().equals(id)) {
284 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
286 this.identity = identity;
291 * Returns the name of this Sone.
293 * @return The name of this Sone
295 public String getName() {
296 return (identity != null) ? identity.getNickname() : null;
300 * Returns whether this Sone is a local Sone.
302 * @return {@code true} if this Sone is a local Sone, {@code false}
305 public boolean isLocal() {
310 * Returns the request URI of this Sone.
312 * @return The request URI of this Sone
314 public FreenetURI getRequestUri() {
315 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
319 * Sets the request URI of this Sone.
322 * The request URI of this Sone
323 * @return This Sone (for method chaining)
325 public Sone setRequestUri(FreenetURI requestUri) {
326 if (this.requestUri == null) {
327 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
330 if (!this.requestUri.equalsKeypair(requestUri)) {
331 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
338 * Returns the insert URI of this Sone.
340 * @return The insert URI of this Sone
342 public FreenetURI getInsertUri() {
343 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
347 * Sets the insert URI of this Sone.
350 * The insert URI of this Sone
351 * @return This Sone (for method chaining)
353 public Sone setInsertUri(FreenetURI insertUri) {
354 if (this.insertUri == null) {
355 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
358 if (!this.insertUri.equalsKeypair(insertUri)) {
359 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
366 * Returns the latest edition of this Sone.
368 * @return The latest edition of this Sone
370 public long getLatestEdition() {
371 return latestEdition;
375 * Sets the latest edition of this Sone. If the given latest edition is not
376 * greater than the current latest edition, the latest edition of this Sone
379 * @param latestEdition
380 * The latest edition of this Sone
382 public void setLatestEdition(long latestEdition) {
383 if (!(latestEdition > this.latestEdition)) {
384 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
387 this.latestEdition = latestEdition;
391 * Return the time of the last inserted update of this Sone.
393 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
395 public long getTime() {
400 * Sets the time of the last inserted update of this Sone.
403 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
404 * @return This Sone (for method chaining)
406 public Sone setTime(long time) {
412 * Returns the status of this Sone.
414 * @return The status of this Sone
416 public SoneStatus getStatus() {
421 * Sets the new status of this Sone.
424 * The new status of this Sone
426 * @throws IllegalArgumentException
427 * if {@code status} is {@code null}
429 public Sone setStatus(SoneStatus status) {
430 this.status = checkNotNull(status, "status must not be null");
435 * Returns a copy of the profile. If you want to update values in the
436 * profile of this Sone, update the values in the returned {@link Profile}
437 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
439 * @return A copy of the profile
441 public Profile getProfile() {
442 return new Profile(profile);
446 * Sets the profile of this Sone. A copy of the given profile is stored so
447 * that subsequent modifications of the given profile are not reflected in
453 public void setProfile(Profile profile) {
454 this.profile = new Profile(profile);
458 * Returns the client used by this Sone.
460 * @return The client used by this Sone, or {@code null}
462 public Client getClient() {
467 * Sets the client used by this Sone.
470 * The client used by this Sone, or {@code null}
471 * @return This Sone (for method chaining)
473 public Sone setClient(Client client) {
474 this.client = client;
479 * Returns whether this Sone is known.
481 * @return {@code true} if this Sone is known, {@code false} otherwise
483 public boolean isKnown() {
488 * Sets whether this Sone is known.
491 * {@code true} if this Sone is known, {@code false} otherwise
494 public Sone setKnown(boolean known) {
500 * Returns all friend Sones of this Sone.
502 * @return The friend Sones of this Sone
504 public List<String> getFriends() {
505 List<String> friends = new ArrayList<String>(friendSones);
510 * Returns whether this Sone has the given Sone as a friend Sone.
512 * @param friendSoneId
513 * The ID of the Sone to check for
514 * @return {@code true} if this Sone has the given Sone as a friend,
515 * {@code false} otherwise
517 public boolean hasFriend(String friendSoneId) {
518 return friendSones.contains(friendSoneId);
522 * Adds the given Sone as a friend Sone.
525 * The friend Sone to add
526 * @return This Sone (for method chaining)
528 public Sone addFriend(String friendSone) {
529 if (!friendSone.equals(id)) {
530 friendSones.add(friendSone);
536 * Removes the given Sone as a friend Sone.
538 * @param friendSoneId
539 * The ID of the friend Sone to remove
540 * @return This Sone (for method chaining)
542 public Sone removeFriend(String friendSoneId) {
543 friendSones.remove(friendSoneId);
548 * Returns the list of posts of this Sone, sorted by time, newest first.
550 * @return All posts of this Sone
552 public List<Post> getPosts() {
553 List<Post> sortedPosts;
554 synchronized (this) {
555 sortedPosts = new ArrayList<Post>(posts);
557 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
562 * Sets all posts of this Sone at once.
565 * The new (and only) posts of this Sone
566 * @return This Sone (for method chaining)
568 public Sone setPosts(Collection<Post> posts) {
569 synchronized (this) {
571 this.posts.addAll(posts);
577 * Adds the given post to this Sone. The post will not be added if its
578 * {@link Post#getSone() Sone} is not this Sone.
583 public void addPost(Post post) {
584 if (post.getSone().equals(this) && posts.add(post)) {
585 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
590 * Removes the given post from this Sone.
595 public void removePost(Post post) {
596 if (post.getSone().equals(this)) {
602 * Returns all replies this Sone made.
604 * @return All replies this Sone made
606 public Set<PostReply> getReplies() {
607 return Collections.unmodifiableSet(replies);
611 * Sets all replies of this Sone at once.
614 * The new (and only) replies of this Sone
615 * @return This Sone (for method chaining)
617 public Sone setReplies(Collection<PostReply> replies) {
618 this.replies.clear();
619 this.replies.addAll(replies);
624 * Adds a reply to this Sone. If the given reply was not made by this Sone,
625 * nothing is added to this Sone.
630 public void addReply(PostReply reply) {
631 if (reply.getSone().equals(this)) {
637 * Removes a reply from this Sone.
640 * The reply to remove
642 public void removeReply(PostReply reply) {
643 if (reply.getSone().equals(this)) {
644 replies.remove(reply);
649 * Returns the IDs of all liked posts.
651 * @return All liked posts’ IDs
653 public Set<String> getLikedPostIds() {
654 return Collections.unmodifiableSet(likedPostIds);
658 * Sets the IDs of all liked posts.
660 * @param likedPostIds
661 * All liked posts’ IDs
662 * @return This Sone (for method chaining)
664 public Sone setLikePostIds(Set<String> likedPostIds) {
665 this.likedPostIds.clear();
666 this.likedPostIds.addAll(likedPostIds);
671 * Checks whether the given post ID is liked by this Sone.
675 * @return {@code true} if this Sone likes the given post, {@code false}
678 public boolean isLikedPostId(String postId) {
679 return likedPostIds.contains(postId);
683 * Adds the given post ID to the list of posts this Sone likes.
687 * @return This Sone (for method chaining)
689 public Sone addLikedPostId(String postId) {
690 likedPostIds.add(postId);
695 * Removes the given post ID from the list of posts this Sone likes.
699 * @return This Sone (for method chaining)
701 public Sone removeLikedPostId(String postId) {
702 likedPostIds.remove(postId);
707 * Returns the IDs of all liked replies.
709 * @return All liked replies’ IDs
711 public Set<String> getLikedReplyIds() {
712 return Collections.unmodifiableSet(likedReplyIds);
716 * Sets the IDs of all liked replies.
718 * @param likedReplyIds
719 * All liked replies’ IDs
720 * @return This Sone (for method chaining)
722 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
723 this.likedReplyIds.clear();
724 this.likedReplyIds.addAll(likedReplyIds);
729 * Checks whether the given reply ID is liked by this Sone.
732 * The ID of the reply
733 * @return {@code true} if this Sone likes the given reply, {@code false}
736 public boolean isLikedReplyId(String replyId) {
737 return likedReplyIds.contains(replyId);
741 * Adds the given reply ID to the list of replies this Sone likes.
744 * The ID of the reply
745 * @return This Sone (for method chaining)
747 public Sone addLikedReplyId(String replyId) {
748 likedReplyIds.add(replyId);
753 * Removes the given post ID from the list of replies this Sone likes.
756 * The ID of the reply
757 * @return This Sone (for method chaining)
759 public Sone removeLikedReplyId(String replyId) {
760 likedReplyIds.remove(replyId);
765 * Returns the albums of this Sone.
767 * @return The albums of this Sone
769 public List<Album> getAlbums() {
770 return Collections.unmodifiableList(albums);
774 * Returns all images of a Sone. Images of a album are inserted into this
775 * list before images of all child albums.
777 * @return The list of all images
779 public List<Image> getAllImages() {
780 List<Image> allImages = new ArrayList<Image>();
781 for (Album album : FluentIterable.from(getAlbums()).transformAndConcat(Album.FLATTENER).toList()) {
782 allImages.addAll(album.getImages());
788 * Adds an album to this Sone.
793 public void addAlbum(Album album) {
794 checkNotNull(album, "album must not be null");
795 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
796 if (!albums.contains(album)) {
802 * Sets the albums of this Sone.
805 * The albums of this Sone
807 public void setAlbums(Collection<? extends Album> albums) {
808 checkNotNull(albums, "albums must not be null");
810 for (Album album : albums) {
816 * Removes an album from this Sone.
819 * The album to remove
821 public void removeAlbum(Album album) {
822 checkNotNull(album, "album must not be null");
823 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
824 albums.remove(album);
828 * Moves the given album up in this album’s albums. If the album is already
829 * the first album, nothing happens.
832 * The album to move up
833 * @return The album that the given album swapped the place with, or
834 * <code>null</code> if the album did not change its place
836 public Album moveAlbumUp(Album album) {
837 checkNotNull(album, "album must not be null");
838 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
839 checkArgument(album.getParent() == null, "album must not have a parent");
840 int oldIndex = albums.indexOf(album);
844 albums.remove(oldIndex);
845 albums.add(oldIndex - 1, album);
846 return albums.get(oldIndex);
850 * Moves the given album down in this album’s albums. If the album is
851 * already the last album, nothing happens.
854 * The album to move down
855 * @return The album that the given album swapped the place with, or
856 * <code>null</code> if the album did not change its place
858 public Album moveAlbumDown(Album album) {
859 checkNotNull(album, "album must not be null");
860 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
861 checkArgument(album.getParent() == null, "album must not have a parent");
862 int oldIndex = albums.indexOf(album);
863 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
866 albums.remove(oldIndex);
867 albums.add(oldIndex + 1, album);
868 return albums.get(oldIndex);
872 * Returns Sone-specific options.
874 * @return The options of this Sone
876 public Options getOptions() {
881 * Sets the options of this Sone.
884 * The options of this Sone
886 /* TODO - remove this method again, maybe add an option provider */
887 public void setOptions(Options options) {
888 this.options = options;
892 // FINGERPRINTABLE METHODS
899 public synchronized String getFingerprint() {
900 Hasher hash = Hashing.sha256().newHasher();
901 hash.putString(profile.getFingerprint());
903 hash.putString("Posts(");
904 for (Post post : getPosts()) {
905 hash.putString("Post(").putString(post.getId()).putString(")");
909 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
910 Collections.sort(replies, Reply.TIME_COMPARATOR);
911 hash.putString("Replies(");
912 for (PostReply reply : replies) {
913 hash.putString("Reply(").putString(reply.getId()).putString(")");
917 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
918 Collections.sort(likedPostIds);
919 hash.putString("LikedPosts(");
920 for (String likedPostId : likedPostIds) {
921 hash.putString("Post(").putString(likedPostId).putString(")");
925 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
926 Collections.sort(likedReplyIds);
927 hash.putString("LikedReplies(");
928 for (String likedReplyId : likedReplyIds) {
929 hash.putString("Reply(").putString(likedReplyId).putString(")");
933 hash.putString("Albums(");
934 for (Album album : albums) {
935 hash.putString(album.getFingerprint());
939 return hash.hash().toString();
943 // INTERFACE Comparable<Sone>
950 public int compareTo(Sone sone) {
951 return NICE_NAME_COMPARATOR.compare(this, sone);
962 public int hashCode() {
963 return id.hashCode();
970 public boolean equals(Object object) {
971 if (!(object instanceof Sone)) {
974 return ((Sone) object).id.equals(id);
981 public String toString() {
982 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";