2 * Sone - Sone.java - Copyright © 2010–2012 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 java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.List;
26 import java.util.concurrent.CopyOnWriteArrayList;
27 import java.util.concurrent.CopyOnWriteArraySet;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.core.Core;
32 import net.pterodactylus.sone.core.Options;
33 import net.pterodactylus.sone.freenet.wot.Identity;
34 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
35 import net.pterodactylus.sone.template.SoneAccessor;
36 import net.pterodactylus.util.collection.filter.Filter;
37 import net.pterodactylus.util.logging.Logging;
38 import net.pterodactylus.util.validation.Validation;
39 import freenet.keys.FreenetURI;
42 * A Sone defines everything about a user: her profile, her status updates, her
43 * replies, her likes and dislikes, etc.
45 * Operations that modify the Sone need to synchronize on the Sone in question.
47 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49 public class Sone implements Fingerprintable, Comparable<Sone> {
52 * Enumeration for the possible states of a {@link Sone}.
54 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56 public enum SoneStatus {
58 /** The Sone is unknown, i.e. not yet downloaded. */
61 /** The Sone is idle, i.e. not being downloaded or inserted. */
64 /** The Sone is currently being inserted. */
67 /** The Sone is currently being downloaded. */
72 * The possible values for the “show custom avatars” option.
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public static enum ShowCustomAvatars {
78 /** Never show custom avatars. */
81 /** Only show custom avatars of followed Sones. */
84 /** Only show custom avatars of Sones you manually trust. */
87 /** Only show custom avatars of automatically trusted Sones. */
90 /** Always show custom avatars. */
95 /** comparator that sorts Sones by their nice name. */
96 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
99 public int compare(Sone leftSone, Sone rightSone) {
100 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
104 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
110 * Comparator that sorts Sones by last activity (least recent active first).
112 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
115 public int compare(Sone firstSone, Sone secondSone) {
116 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
120 /** Comparator that sorts Sones by numbers of posts (descending). */
121 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
127 public int compare(Sone leftSone, Sone rightSone) {
128 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
132 /** Comparator that sorts Sones by number of images (descending). */
133 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
139 public int compare(Sone leftSone, Sone rightSone) {
140 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
144 /** Filter to remove Sones that have not been downloaded. */
145 public static final Filter<Sone> EMPTY_SONE_FILTER = new Filter<Sone>() {
148 public boolean filterObject(Sone sone) {
149 return sone.getTime() != 0;
153 /** Filter that matches all {@link Core#getLocalSones() local Sones}. */
154 public static final Filter<Sone> LOCAL_SONE_FILTER = new Filter<Sone>() {
157 public boolean filterObject(Sone sone) {
158 return sone.getIdentity() instanceof OwnIdentity;
163 /** Filter that matches Sones that have at least one album. */
164 public static final Filter<Sone> HAS_ALBUM_FILTER = new Filter<Sone>() {
167 public boolean filterObject(Sone sone) {
168 return !sone.getAlbums().isEmpty();
173 private static final Logger logger = Logging.getLogger(Sone.class);
175 /** The ID of this Sone. */
176 private final String id;
178 /** Whether this is a local Sone. */
179 private final boolean local;
181 /** The identity of this Sone. */
182 private Identity identity;
184 /** The URI under which the Sone is stored in Freenet. */
185 private volatile FreenetURI requestUri;
187 /** The URI used to insert a new version of this Sone. */
188 /* This will be null for remote Sones! */
189 private volatile FreenetURI insertUri;
191 /** The latest edition of the Sone. */
192 private volatile long latestEdition;
194 /** The time of the last inserted update. */
195 private volatile long time;
197 /** The status of this Sone. */
198 private volatile SoneStatus status = SoneStatus.unknown;
200 /** The profile of this Sone. */
201 private volatile Profile profile = new Profile(this);
203 /** The client used by the Sone. */
204 private volatile Client client;
206 /** Whether this Sone is known. */
207 private volatile boolean known;
209 /** All friend Sones. */
210 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
213 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
216 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
218 /** The IDs of all liked posts. */
219 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
221 /** The IDs of all liked replies. */
222 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
224 /** The albums of this Sone. */
225 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
227 /** Sone-specific options. */
228 private final Options options = new Options();
231 * Creates a new Sone.
236 * {@code true} if this Sone is local, {@code false} otherwise
238 public Sone(String id, boolean local) {
248 * Returns the identity of this Sone.
250 * @return The identity of this Sone
252 public String getId() {
257 * Returns the identity of this Sone.
259 * @return The identity of this Sone
261 public Identity getIdentity() {
266 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
267 * identity has to match this Sone’s {@link #getId()}.
270 * The identity of this Sone
271 * @return This Sone (for method chaining)
272 * @throws IllegalArgumentException
273 * if the ID of the identity does not match this Sone’s ID
275 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
276 if (!identity.getId().equals(id)) {
277 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
279 this.identity = identity;
284 * Returns whether this Sone is local.
286 * @return {@code true} if this Sone is local, {@code false} otherwise
288 public boolean isLocal() {
293 * Returns the name of this Sone.
295 * @return The name of this Sone
297 public String getName() {
298 return (identity != null) ? identity.getNickname() : null;
302 * Returns the request URI of this Sone.
304 * @return The request URI of this Sone
306 public FreenetURI getRequestUri() {
307 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
311 * Sets the request URI of this Sone.
314 * The request URI of this Sone
315 * @return This Sone (for method chaining)
317 public Sone setRequestUri(FreenetURI requestUri) {
318 if (this.requestUri == null) {
319 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
322 if (!this.requestUri.equalsKeypair(requestUri)) {
323 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
330 * Returns the insert URI of this Sone.
332 * @return The insert URI of this Sone
334 public FreenetURI getInsertUri() {
335 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
339 * Sets the insert URI of this Sone.
342 * The insert URI of this Sone
343 * @return This Sone (for method chaining)
345 public Sone setInsertUri(FreenetURI insertUri) {
346 if (this.insertUri == null) {
347 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
350 if (!this.insertUri.equalsKeypair(insertUri)) {
351 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
358 * Returns the latest edition of this Sone.
360 * @return The latest edition of this Sone
362 public long getLatestEdition() {
363 return latestEdition;
367 * Sets the latest edition of this Sone. If the given latest edition is not
368 * greater than the current latest edition, the latest edition of this Sone
371 * @param latestEdition
372 * The latest edition of this Sone
374 public void setLatestEdition(long latestEdition) {
375 if (!(latestEdition > this.latestEdition)) {
376 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
379 this.latestEdition = latestEdition;
383 * Return the time of the last inserted update of this Sone.
385 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
387 public long getTime() {
392 * Sets the time of the last inserted update of this Sone.
395 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
396 * @return This Sone (for method chaining)
398 public Sone setTime(long time) {
404 * Returns the status of this Sone.
406 * @return The status of this Sone
408 public SoneStatus getStatus() {
413 * Sets the new status of this Sone.
416 * The new status of this Sone
418 * @throws IllegalArgumentException
419 * if {@code status} is {@code null}
421 public Sone setStatus(SoneStatus status) {
422 Validation.begin().isNotNull("Sone Status", status).check();
423 this.status = status;
428 * Returns a copy of the profile. If you want to update values in the
429 * profile of this Sone, update the values in the returned {@link Profile}
430 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
432 * @return A copy of the profile
434 public Profile getProfile() {
435 return new Profile(profile);
439 * Sets the profile of this Sone. A copy of the given profile is stored so
440 * that subsequent modifications of the given profile are not reflected in
446 public void setProfile(Profile profile) {
447 this.profile = new Profile(profile);
451 * Returns the client used by this Sone.
453 * @return The client used by this Sone, or {@code null}
455 public Client getClient() {
460 * Sets the client used by this Sone.
463 * The client used by this Sone, or {@code null}
464 * @return This Sone (for method chaining)
466 public Sone setClient(Client client) {
467 this.client = client;
472 * Returns whether this Sone is known.
474 * @return {@code true} if this Sone is known, {@code false} otherwise
476 public boolean isKnown() {
481 * Sets whether this Sone is known.
484 * {@code true} if this Sone is known, {@code false} otherwise
487 public Sone setKnown(boolean known) {
493 * Returns all friend Sones of this Sone.
495 * @return The friend Sones of this Sone
497 public List<String> getFriends() {
498 List<String> friends = new ArrayList<String>(friendSones);
503 * Returns whether this Sone has the given Sone as a friend Sone.
505 * @param friendSoneId
506 * The ID of the Sone to check for
507 * @return {@code true} if this Sone has the given Sone as a friend,
508 * {@code false} otherwise
510 public boolean hasFriend(String friendSoneId) {
511 return friendSones.contains(friendSoneId);
515 * Adds the given Sone as a friend Sone.
518 * The friend Sone to add
519 * @return This Sone (for method chaining)
521 public Sone addFriend(String friendSone) {
522 if (!friendSone.equals(id)) {
523 friendSones.add(friendSone);
529 * Removes the given Sone as a friend Sone.
531 * @param friendSoneId
532 * The ID of the friend Sone to remove
533 * @return This Sone (for method chaining)
535 public Sone removeFriend(String friendSoneId) {
536 friendSones.remove(friendSoneId);
541 * Returns the list of posts of this Sone, sorted by time, newest first.
543 * @return All posts of this Sone
545 public List<Post> getPosts() {
546 List<Post> sortedPosts;
547 synchronized (this) {
548 sortedPosts = new ArrayList<Post>(posts);
550 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
555 * Sets all posts of this Sone at once.
558 * The new (and only) posts of this Sone
559 * @return This Sone (for method chaining)
561 public Sone setPosts(Collection<Post> posts) {
562 synchronized (this) {
564 this.posts.addAll(posts);
570 * Adds the given post to this Sone. The post will not be added if its
571 * {@link Post#getSone() Sone} is not this Sone.
576 public void addPost(Post post) {
577 if (post.getSone().equals(this) && posts.add(post)) {
578 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
583 * Removes the given post from this Sone.
588 public void removePost(Post post) {
589 if (post.getSone().equals(this)) {
595 * Returns all replies this Sone made.
597 * @return All replies this Sone made
599 public Set<PostReply> getReplies() {
600 return Collections.unmodifiableSet(replies);
604 * Sets all replies of this Sone at once.
607 * The new (and only) replies of this Sone
608 * @return This Sone (for method chaining)
610 public Sone setReplies(Collection<PostReply> replies) {
611 this.replies.clear();
612 this.replies.addAll(replies);
617 * Adds a reply to this Sone. If the given reply was not made by this Sone,
618 * nothing is added to this Sone.
623 public void addReply(PostReply reply) {
624 if (reply.getSone().equals(this)) {
630 * Removes a reply from this Sone.
633 * The reply to remove
635 public void removeReply(PostReply reply) {
636 if (reply.getSone().equals(this)) {
637 replies.remove(reply);
642 * Returns the IDs of all liked posts.
644 * @return All liked posts’ IDs
646 public Set<String> getLikedPostIds() {
647 return Collections.unmodifiableSet(likedPostIds);
651 * Sets the IDs of all liked posts.
653 * @param likedPostIds
654 * All liked posts’ IDs
655 * @return This Sone (for method chaining)
657 public Sone setLikePostIds(Set<String> likedPostIds) {
658 this.likedPostIds.clear();
659 this.likedPostIds.addAll(likedPostIds);
664 * Checks whether the given post ID is liked by this Sone.
668 * @return {@code true} if this Sone likes the given post, {@code false}
671 public boolean isLikedPostId(String postId) {
672 return likedPostIds.contains(postId);
676 * Adds the given post ID to the list of posts this Sone likes.
680 * @return This Sone (for method chaining)
682 public Sone addLikedPostId(String postId) {
683 likedPostIds.add(postId);
688 * Removes the given post ID from the list of posts this Sone likes.
692 * @return This Sone (for method chaining)
694 public Sone removeLikedPostId(String postId) {
695 likedPostIds.remove(postId);
700 * Returns the IDs of all liked replies.
702 * @return All liked replies’ IDs
704 public Set<String> getLikedReplyIds() {
705 return Collections.unmodifiableSet(likedReplyIds);
709 * Sets the IDs of all liked replies.
711 * @param likedReplyIds
712 * All liked replies’ IDs
713 * @return This Sone (for method chaining)
715 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
716 this.likedReplyIds.clear();
717 this.likedReplyIds.addAll(likedReplyIds);
722 * Checks whether the given reply ID is liked by this Sone.
725 * The ID of the reply
726 * @return {@code true} if this Sone likes the given reply, {@code false}
729 public boolean isLikedReplyId(String replyId) {
730 return likedReplyIds.contains(replyId);
734 * Adds the given reply ID to the list of replies this Sone likes.
737 * The ID of the reply
738 * @return This Sone (for method chaining)
740 public Sone addLikedReplyId(String replyId) {
741 likedReplyIds.add(replyId);
746 * Removes the given post ID from the list of replies this Sone likes.
749 * The ID of the reply
750 * @return This Sone (for method chaining)
752 public Sone removeLikedReplyId(String replyId) {
753 likedReplyIds.remove(replyId);
758 * Returns the albums of this Sone.
760 * @return The albums of this Sone
762 public List<Album> getAlbums() {
763 return Collections.unmodifiableList(albums);
767 * Returns a flattened list of all albums of this Sone. The resulting list
768 * contains parent albums before child albums so that the resulting list can
769 * be parsed in a single pass.
771 * @return The flattened albums
773 public List<Album> getAllAlbums() {
774 List<Album> flatAlbums = new ArrayList<Album>();
775 flatAlbums.addAll(albums);
776 int lastAlbumIndex = 0;
777 while (lastAlbumIndex < flatAlbums.size()) {
778 int previousAlbumCount = flatAlbums.size();
779 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
780 flatAlbums.addAll(album.getAlbums());
782 lastAlbumIndex = previousAlbumCount;
788 * Returns all images of a Sone. Images of a album are inserted into this
789 * list before images of all child albums.
791 * @return The list of all images
793 public List<Image> getAllImages() {
794 List<Image> allImages = new ArrayList<Image>();
795 for (Album album : getAllAlbums()) {
796 allImages.addAll(album.getImages());
802 * Adds an album to this Sone.
807 public void addAlbum(Album album) {
808 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
813 * Sets the albums of this Sone.
816 * The albums of this Sone
818 public void setAlbums(Collection<? extends Album> albums) {
819 Validation.begin().isNotNull("Albums", albums).check();
821 for (Album album : albums) {
827 * Removes an album from this Sone.
830 * The album to remove
832 public void removeAlbum(Album album) {
833 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
834 albums.remove(album);
838 * Moves the given album up in this album’s albums. If the album is already
839 * the first album, nothing happens.
842 * The album to move up
843 * @return The album that the given album swapped the place with, or
844 * <code>null</code> if the album did not change its place
846 public Album moveAlbumUp(Album album) {
847 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
848 int oldIndex = albums.indexOf(album);
852 albums.remove(oldIndex);
853 albums.add(oldIndex - 1, album);
854 return albums.get(oldIndex);
858 * Moves the given album down in this album’s albums. If the album is
859 * already the last album, nothing happens.
862 * The album to move down
863 * @return The album that the given album swapped the place with, or
864 * <code>null</code> if the album did not change its place
866 public Album moveAlbumDown(Album album) {
867 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
868 int oldIndex = albums.indexOf(album);
869 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
872 albums.remove(oldIndex);
873 albums.add(oldIndex + 1, album);
874 return albums.get(oldIndex);
878 * Returns Sone-specific options.
880 * @return The options of this Sone
882 public Options getOptions() {
887 // FINGERPRINTABLE METHODS
894 public synchronized String getFingerprint() {
895 StringBuilder fingerprint = new StringBuilder();
896 fingerprint.append(profile.getFingerprint());
898 fingerprint.append("Posts(");
899 for (Post post : getPosts()) {
900 fingerprint.append("Post(").append(post.getId()).append(')');
902 fingerprint.append(")");
904 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
905 Collections.sort(replies, Reply.TIME_COMPARATOR);
906 fingerprint.append("Replies(");
907 for (PostReply reply : replies) {
908 fingerprint.append("Reply(").append(reply.getId()).append(')');
910 fingerprint.append(')');
912 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
913 Collections.sort(likedPostIds);
914 fingerprint.append("LikedPosts(");
915 for (String likedPostId : likedPostIds) {
916 fingerprint.append("Post(").append(likedPostId).append(')');
918 fingerprint.append(')');
920 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
921 Collections.sort(likedReplyIds);
922 fingerprint.append("LikedReplies(");
923 for (String likedReplyId : likedReplyIds) {
924 fingerprint.append("Reply(").append(likedReplyId).append(')');
926 fingerprint.append(')');
928 fingerprint.append("Albums(");
929 for (Album album : albums) {
930 fingerprint.append(album.getFingerprint());
932 fingerprint.append(')');
934 return fingerprint.toString();
938 // INTERFACE Comparable<Sone>
945 public int compareTo(Sone sone) {
946 return NICE_NAME_COMPARATOR.compare(this, sone);
957 public int hashCode() {
958 return id.hashCode();
965 public boolean equals(Object object) {
966 if (!(object instanceof Sone)) {
969 return ((Sone) object).id.equals(id);
976 public String toString() {
977 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";