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.*;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.List;
28 import java.util.concurrent.CopyOnWriteArrayList;
29 import java.util.concurrent.CopyOnWriteArraySet;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.sone.core.Options;
34 import net.pterodactylus.sone.freenet.wot.Identity;
35 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
36 import net.pterodactylus.sone.template.SoneAccessor;
37 import net.pterodactylus.util.logging.Logging;
39 import freenet.keys.FreenetURI;
41 import com.google.common.base.Predicate;
42 import com.google.common.collect.FluentIterable;
43 import com.google.common.hash.Hasher;
44 import com.google.common.hash.Hashing;
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());
114 /** Comparator that sorts Sones by last activity (least recent active first). */
115 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
118 public int compare(Sone firstSone, Sone secondSone) {
119 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
123 /** Comparator that sorts Sones by numbers of posts (descending). */
124 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
130 public int compare(Sone leftSone, Sone rightSone) {
131 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
135 /** Comparator that sorts Sones by number of images (descending). */
136 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
142 public int compare(Sone leftSone, Sone rightSone) {
143 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
147 /** Filter to remove Sones that have not been downloaded. */
148 public static final Predicate<Sone> EMPTY_SONE_FILTER = new Predicate<Sone>() {
151 public boolean apply(Sone sone) {
152 return sone.getTime() != 0;
156 /** Filter that matches all {@link Sone#isLocal() local Sones}. */
157 public static final Predicate<Sone> LOCAL_SONE_FILTER = new Predicate<Sone>() {
160 public boolean apply(Sone sone) {
161 return sone.getIdentity() instanceof OwnIdentity;
166 /** Filter that matches Sones that have at least one album. */
167 public static final Predicate<Sone> HAS_ALBUM_FILTER = new Predicate<Sone>() {
170 public boolean apply(Sone sone) {
171 return !sone.getAlbums().isEmpty();
176 private static final Logger logger = Logging.getLogger(Sone.class);
178 /** The ID of this Sone. */
179 private final String id;
181 /** Whether the Sone is local. */
182 private final boolean local;
184 /** The identity of this Sone. */
185 private Identity identity;
187 /** The URI under which the Sone is stored in Freenet. */
188 private volatile FreenetURI requestUri;
190 /** The URI used to insert a new version of this Sone. */
191 /* This will be null for remote Sones! */
192 private volatile FreenetURI insertUri;
194 /** The latest edition of the Sone. */
195 private volatile long latestEdition;
197 /** The time of the last inserted update. */
198 private volatile long time;
200 /** The status of this Sone. */
201 private volatile SoneStatus status = SoneStatus.unknown;
203 /** The profile of this Sone. */
204 private volatile Profile profile = new Profile(this);
206 /** The client used by the Sone. */
207 private volatile Client client;
209 /** Whether this Sone is known. */
210 private volatile boolean known;
212 /** All friend Sones. */
213 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
216 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
219 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
221 /** The IDs of all liked posts. */
222 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
224 /** The IDs of all liked replies. */
225 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
227 /** The albums of this Sone. */
228 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
230 /** Sone-specific options. */
231 private Options options = new Options();
234 * Creates a new Sone.
239 * {@code true} if the Sone is a local Sone, {@code false} otherwise
241 public Sone(String id, boolean local) {
251 * Returns the identity of this Sone.
253 * @return The identity of this Sone
255 public String getId() {
260 * Returns the identity of this Sone.
262 * @return The identity of this Sone
264 public Identity getIdentity() {
269 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
270 * identity has to match this Sone’s {@link #getId()}.
273 * The identity of this Sone
274 * @return This Sone (for method chaining)
275 * @throws IllegalArgumentException
276 * if the ID of the identity does not match this Sone’s ID
278 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
279 if (!identity.getId().equals(id)) {
280 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
282 this.identity = identity;
287 * Returns the name of this Sone.
289 * @return The name of this Sone
291 public String getName() {
292 return (identity != null) ? identity.getNickname() : null;
296 * Returns whether this Sone is a local Sone.
298 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
300 public boolean isLocal() {
305 * Returns the request URI of this Sone.
307 * @return The request URI of this Sone
309 public FreenetURI getRequestUri() {
310 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
314 * Sets the request URI of this Sone.
317 * The request URI of this Sone
318 * @return This Sone (for method chaining)
320 public Sone setRequestUri(FreenetURI requestUri) {
321 if (this.requestUri == null) {
322 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
325 if (!this.requestUri.equalsKeypair(requestUri)) {
326 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
333 * Returns the insert URI of this Sone.
335 * @return The insert URI of this Sone
337 public FreenetURI getInsertUri() {
338 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
342 * Sets the insert URI of this Sone.
345 * The insert URI of this Sone
346 * @return This Sone (for method chaining)
348 public Sone setInsertUri(FreenetURI insertUri) {
349 if (this.insertUri == null) {
350 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
353 if (!this.insertUri.equalsKeypair(insertUri)) {
354 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
361 * Returns the latest edition of this Sone.
363 * @return The latest edition of this Sone
365 public long getLatestEdition() {
366 return latestEdition;
370 * Sets the latest edition of this Sone. If the given latest edition is not
371 * greater than the current latest edition, the latest edition of this Sone is
374 * @param latestEdition
375 * The latest edition of this Sone
377 public void setLatestEdition(long latestEdition) {
378 if (!(latestEdition > this.latestEdition)) {
379 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
382 this.latestEdition = latestEdition;
386 * Return the time of the last inserted update of this Sone.
388 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
390 public long getTime() {
395 * Sets the time of the last inserted update of this Sone.
398 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
399 * @return This Sone (for method chaining)
401 public Sone setTime(long time) {
407 * Returns the status of this Sone.
409 * @return The status of this Sone
411 public SoneStatus getStatus() {
416 * Sets the new status of this Sone.
419 * The new status of this Sone
421 * @throws IllegalArgumentException
422 * if {@code status} is {@code null}
424 public Sone setStatus(SoneStatus status) {
425 this.status = checkNotNull(status, "status must not be null");
430 * Returns a copy of the profile. If you want to update values in the profile
431 * of this Sone, update the values in the returned {@link Profile} and use
432 * {@link #setProfile(Profile)} to change the profile in this Sone.
434 * @return A copy of the profile
436 public Profile getProfile() {
437 return new Profile(profile);
441 * Sets the profile of this Sone. A copy of the given profile is stored so that
442 * subsequent modifications of the given profile are not reflected in this
448 public void setProfile(Profile profile) {
449 this.profile = new Profile(profile);
453 * Returns the client used by this Sone.
455 * @return The client used by this Sone, or {@code null}
457 public Client getClient() {
462 * Sets the client used by this Sone.
465 * The client used by this Sone, or {@code null}
466 * @return This Sone (for method chaining)
468 public Sone setClient(Client client) {
469 this.client = client;
474 * Returns whether this Sone is known.
476 * @return {@code true} if this Sone is known, {@code false} otherwise
478 public boolean isKnown() {
483 * Sets whether this Sone is known.
486 * {@code true} if this Sone is known, {@code false} otherwise
489 public Sone setKnown(boolean known) {
495 * Returns all friend Sones of this Sone.
497 * @return The friend Sones of this Sone
499 public List<String> getFriends() {
500 List<String> friends = new ArrayList<String>(friendSones);
505 * Returns whether this Sone has the given Sone as a friend Sone.
507 * @param friendSoneId
508 * The ID of the Sone to check for
509 * @return {@code true} if this Sone has the given Sone as a friend, {@code
512 public boolean hasFriend(String friendSoneId) {
513 return friendSones.contains(friendSoneId);
517 * Adds the given Sone as a friend Sone.
520 * The friend Sone to add
521 * @return This Sone (for method chaining)
523 public Sone addFriend(String friendSone) {
524 if (!friendSone.equals(id)) {
525 friendSones.add(friendSone);
531 * Removes the given Sone as a friend Sone.
533 * @param friendSoneId
534 * The ID of the friend Sone to remove
535 * @return This Sone (for method chaining)
537 public Sone removeFriend(String friendSoneId) {
538 friendSones.remove(friendSoneId);
543 * Returns the list of posts of this Sone, sorted by time, newest first.
545 * @return All posts of this Sone
547 public List<Post> getPosts() {
548 List<Post> sortedPosts;
549 synchronized (this) {
550 sortedPosts = new ArrayList<Post>(posts);
552 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
557 * Sets all posts of this Sone at once.
560 * The new (and only) posts of this Sone
561 * @return This Sone (for method chaining)
563 public Sone setPosts(Collection<Post> posts) {
564 synchronized (this) {
566 this.posts.addAll(posts);
572 * Adds the given post to this Sone. The post will not be added if its {@link
573 * Post#getSone() Sone} is not this Sone.
578 public void addPost(Post post) {
579 if (post.getSone().equals(this) && posts.add(post)) {
580 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
585 * Removes the given post from this Sone.
590 public void removePost(Post post) {
591 if (post.getSone().equals(this)) {
597 * Returns all replies this Sone made.
599 * @return All replies this Sone made
601 public Set<PostReply> getReplies() {
602 return Collections.unmodifiableSet(replies);
606 * Sets all replies of this Sone at once.
609 * The new (and only) replies of this Sone
610 * @return This Sone (for method chaining)
612 public Sone setReplies(Collection<PostReply> replies) {
613 this.replies.clear();
614 this.replies.addAll(replies);
619 * Adds a reply to this Sone. If the given reply was not made by this Sone,
620 * nothing is added to this Sone.
625 public void addReply(PostReply reply) {
626 if (reply.getSone().equals(this)) {
632 * Removes a reply from this Sone.
635 * The reply to remove
637 public void removeReply(PostReply reply) {
638 if (reply.getSone().equals(this)) {
639 replies.remove(reply);
644 * Returns the IDs of all liked posts.
646 * @return All liked posts’ IDs
648 public Set<String> getLikedPostIds() {
649 return Collections.unmodifiableSet(likedPostIds);
653 * Sets the IDs of all liked posts.
655 * @param likedPostIds
656 * All liked posts’ IDs
657 * @return This Sone (for method chaining)
659 public Sone setLikePostIds(Set<String> likedPostIds) {
660 this.likedPostIds.clear();
661 this.likedPostIds.addAll(likedPostIds);
666 * Checks whether the given post ID is liked by this Sone.
670 * @return {@code true} if this Sone likes the given post, {@code false}
673 public boolean isLikedPostId(String postId) {
674 return likedPostIds.contains(postId);
678 * Adds the given post ID to the list of posts this Sone likes.
682 * @return This Sone (for method chaining)
684 public Sone addLikedPostId(String postId) {
685 likedPostIds.add(postId);
690 * Removes the given post ID from the list of posts this Sone likes.
694 * @return This Sone (for method chaining)
696 public Sone removeLikedPostId(String postId) {
697 likedPostIds.remove(postId);
702 * Returns the IDs of all liked replies.
704 * @return All liked replies’ IDs
706 public Set<String> getLikedReplyIds() {
707 return Collections.unmodifiableSet(likedReplyIds);
711 * Sets the IDs of all liked replies.
713 * @param likedReplyIds
714 * All liked replies’ IDs
715 * @return This Sone (for method chaining)
717 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
718 this.likedReplyIds.clear();
719 this.likedReplyIds.addAll(likedReplyIds);
724 * Checks whether the given reply ID is liked by this Sone.
727 * The ID of the reply
728 * @return {@code true} if this Sone likes the given reply, {@code false}
731 public boolean isLikedReplyId(String replyId) {
732 return likedReplyIds.contains(replyId);
736 * Adds the given reply ID to the list of replies this Sone likes.
739 * The ID of the reply
740 * @return This Sone (for method chaining)
742 public Sone addLikedReplyId(String replyId) {
743 likedReplyIds.add(replyId);
748 * Removes the given post ID from the list of replies this Sone likes.
751 * The ID of the reply
752 * @return This Sone (for method chaining)
754 public Sone removeLikedReplyId(String replyId) {
755 likedReplyIds.remove(replyId);
760 * Returns the albums of this Sone.
762 * @return The albums of this Sone
764 public List<Album> getAlbums() {
765 return Collections.unmodifiableList(albums);
769 * Returns all images of a Sone. Images of a album are inserted into this list
770 * before images of all child albums.
772 * @return The list of all images
774 public List<Image> getAllImages() {
775 List<Image> allImages = new ArrayList<Image>();
776 for (Album album : FluentIterable.from(getAlbums()).transformAndConcat(Album.FLATTENER).toList()) {
777 allImages.addAll(album.getImages());
783 * Adds an album to this Sone.
788 public void addAlbum(Album album) {
789 checkNotNull(album, "album must not be null");
790 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
791 if (!albums.contains(album)) {
797 * Sets the albums of this Sone.
800 * The albums of this Sone
802 public void setAlbums(Collection<? extends Album> albums) {
803 checkNotNull(albums, "albums must not be null");
805 for (Album album : albums) {
811 * Removes an album from this Sone.
814 * The album to remove
816 public void removeAlbum(Album album) {
817 checkNotNull(album, "album must not be null");
818 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
819 albums.remove(album);
823 * Moves the given album up in this album’s albums. If the album is already the
824 * first album, nothing happens.
827 * The album to move up
828 * @return The album that the given album swapped the place with, or
829 * <code>null</code> if the album did not change its place
831 public Album moveAlbumUp(Album album) {
832 checkNotNull(album, "album must not be null");
833 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
834 checkArgument(album.getParent() == null, "album must not have a parent");
835 int oldIndex = albums.indexOf(album);
839 albums.remove(oldIndex);
840 albums.add(oldIndex - 1, album);
841 return albums.get(oldIndex);
845 * Moves the given album down in this album’s albums. If the album is already
846 * the last album, nothing happens.
849 * The album to move down
850 * @return The album that the given album swapped the place with, or
851 * <code>null</code> if the album did not change its place
853 public Album moveAlbumDown(Album album) {
854 checkNotNull(album, "album must not be null");
855 checkArgument(album.getSone().equals(this), "album must belong to this Sone");
856 checkArgument(album.getParent() == null, "album must not have a parent");
857 int oldIndex = albums.indexOf(album);
858 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
861 albums.remove(oldIndex);
862 albums.add(oldIndex + 1, album);
863 return albums.get(oldIndex);
867 * Returns Sone-specific options.
869 * @return The options of this Sone
871 public Options getOptions() {
876 * Sets the options of this Sone.
879 * The options of this Sone
881 /* TODO - remove this method again, maybe add an option provider */
882 public void setOptions(Options options) {
883 this.options = options;
887 // FINGERPRINTABLE METHODS
892 public synchronized String getFingerprint() {
893 Hasher hash = Hashing.sha256().newHasher();
894 hash.putString(profile.getFingerprint());
896 hash.putString("Posts(");
897 for (Post post : getPosts()) {
898 hash.putString("Post(").putString(post.getId()).putString(")");
902 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
903 Collections.sort(replies, Reply.TIME_COMPARATOR);
904 hash.putString("Replies(");
905 for (PostReply reply : replies) {
906 hash.putString("Reply(").putString(reply.getId()).putString(")");
910 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
911 Collections.sort(likedPostIds);
912 hash.putString("LikedPosts(");
913 for (String likedPostId : likedPostIds) {
914 hash.putString("Post(").putString(likedPostId).putString(")");
918 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
919 Collections.sort(likedReplyIds);
920 hash.putString("LikedReplies(");
921 for (String likedReplyId : likedReplyIds) {
922 hash.putString("Reply(").putString(likedReplyId).putString(")");
926 hash.putString("Albums(");
927 for (Album album : albums) {
928 hash.putString(album.getFingerprint());
932 return hash.hash().toString();
936 // INTERFACE Comparable<Sone>
941 public int compareTo(Sone sone) {
942 return NICE_NAME_COMPARATOR.compare(this, sone);
951 public int hashCode() {
952 return id.hashCode();
957 public boolean equals(Object object) {
958 if (!(object instanceof Sone)) {
961 return ((Sone) object).id.equals(id);
966 public String toString() {
967 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";