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.Options;
32 import net.pterodactylus.sone.freenet.wot.Identity;
33 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
34 import net.pterodactylus.sone.template.SoneAccessor;
35 import net.pterodactylus.util.collection.filter.Filter;
36 import net.pterodactylus.util.logging.Logging;
37 import net.pterodactylus.util.validation.Validation;
38 import freenet.keys.FreenetURI;
41 * A Sone defines everything about a user: her profile, her status updates, her
42 * replies, her likes and dislikes, etc.
44 * Operations that modify the Sone need to synchronize on the Sone in question.
46 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48 public class Sone implements Fingerprintable, Comparable<Sone> {
51 * Enumeration for the possible states of a {@link Sone}.
53 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55 public enum SoneStatus {
57 /** The Sone is unknown, i.e. not yet downloaded. */
60 /** The Sone is idle, i.e. not being downloaded or inserted. */
63 /** The Sone is currently being inserted. */
66 /** The Sone is currently being downloaded. */
71 * The possible values for the “show custom avatars” option.
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public static enum ShowCustomAvatars {
77 /** Never show custom avatars. */
80 /** Only show custom avatars of followed Sones. */
83 /** Only show custom avatars of Sones you manually trust. */
86 /** Only show custom avatars of automatically trusted Sones. */
89 /** Always show custom avatars. */
94 /** comparator that sorts Sones by their nice name. */
95 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
98 public int compare(Sone leftSone, Sone rightSone) {
99 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
103 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
109 * Comparator that sorts Sones by last activity (least recent active first).
111 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
114 public int compare(Sone firstSone, Sone secondSone) {
115 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
119 /** Comparator that sorts Sones by numbers of posts (descending). */
120 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
126 public int compare(Sone leftSone, Sone rightSone) {
127 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
131 /** Comparator that sorts Sones by number of images (descending). */
132 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
138 public int compare(Sone leftSone, Sone rightSone) {
139 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
143 /** Filter to remove Sones that have not been downloaded. */
144 public static final Filter<Sone> EMPTY_SONE_FILTER = new Filter<Sone>() {
147 public boolean filterObject(Sone sone) {
148 return sone.getTime() != 0;
152 /** Filter that matches all {@link Sone#isLocal() local Sones}. */
153 public static final Filter<Sone> LOCAL_SONE_FILTER = new Filter<Sone>() {
156 public boolean filterObject(Sone sone) {
157 return sone.getIdentity() instanceof OwnIdentity;
162 /** Filter that matches Sones that have at least one album. */
163 public static final Filter<Sone> HAS_ALBUM_FILTER = new Filter<Sone>() {
166 public boolean filterObject(Sone sone) {
167 return !sone.getAlbums().isEmpty();
172 private static final Logger logger = Logging.getLogger(Sone.class);
174 /** The ID of this Sone. */
175 private final String id;
177 /** Whether the Sone is local. */
178 private final boolean local;
180 /** The identity of this Sone. */
181 private Identity identity;
183 /** The URI under which the Sone is stored in Freenet. */
184 private volatile FreenetURI requestUri;
186 /** The URI used to insert a new version of this Sone. */
187 /* This will be null for remote Sones! */
188 private volatile FreenetURI insertUri;
190 /** The latest edition of the Sone. */
191 private volatile long latestEdition;
193 /** The time of the last inserted update. */
194 private volatile long time;
196 /** The status of this Sone. */
197 private volatile SoneStatus status = SoneStatus.unknown;
199 /** The profile of this Sone. */
200 private volatile Profile profile = new Profile(this);
202 /** The client used by the Sone. */
203 private volatile Client client;
205 /** Whether this Sone is known. */
206 private volatile boolean known;
208 /** All friend Sones. */
209 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
212 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
215 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
217 /** The IDs of all liked posts. */
218 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
220 /** The IDs of all liked replies. */
221 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
223 /** The albums of this Sone. */
224 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
226 /** Sone-specific options. */
227 private final Options options = new Options();
230 * Creates a new Sone.
235 * {@code true} if the Sone is a local Sone, {@code false}
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 the name of this Sone.
286 * @return The name of this Sone
288 public String getName() {
289 return (identity != null) ? identity.getNickname() : null;
293 * Returns whether this Sone is a local Sone.
295 * @return {@code true} if this Sone is a local Sone, {@code false}
298 public boolean isLocal() {
303 * Returns the request URI of this Sone.
305 * @return The request URI of this Sone
307 public FreenetURI getRequestUri() {
308 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
312 * Sets the request URI of this Sone.
315 * The request URI of this Sone
316 * @return This Sone (for method chaining)
318 public Sone setRequestUri(FreenetURI requestUri) {
319 if (this.requestUri == null) {
320 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
323 if (!this.requestUri.equalsKeypair(requestUri)) {
324 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
331 * Returns the insert URI of this Sone.
333 * @return The insert URI of this Sone
335 public FreenetURI getInsertUri() {
336 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
340 * Sets the insert URI of this Sone.
343 * The insert URI of this Sone
344 * @return This Sone (for method chaining)
346 public Sone setInsertUri(FreenetURI insertUri) {
347 if (this.insertUri == null) {
348 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
351 if (!this.insertUri.equalsKeypair(insertUri)) {
352 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
359 * Returns the latest edition of this Sone.
361 * @return The latest edition of this Sone
363 public long getLatestEdition() {
364 return latestEdition;
368 * Sets the latest edition of this Sone. If the given latest edition is not
369 * greater than the current latest edition, the latest edition of this Sone
372 * @param latestEdition
373 * The latest edition of this Sone
375 public void setLatestEdition(long latestEdition) {
376 if (!(latestEdition > this.latestEdition)) {
377 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
380 this.latestEdition = latestEdition;
384 * Return the time of the last inserted update of this Sone.
386 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
388 public long getTime() {
393 * Sets the time of the last inserted update of this Sone.
396 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
397 * @return This Sone (for method chaining)
399 public Sone setTime(long time) {
405 * Returns the status of this Sone.
407 * @return The status of this Sone
409 public SoneStatus getStatus() {
414 * Sets the new status of this Sone.
417 * The new status of this Sone
419 * @throws IllegalArgumentException
420 * if {@code status} is {@code null}
422 public Sone setStatus(SoneStatus status) {
423 Validation.begin().isNotNull("Sone Status", status).check();
424 this.status = status;
429 * Returns a copy of the profile. If you want to update values in the
430 * profile of this Sone, update the values in the returned {@link Profile}
431 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
433 * @return A copy of the profile
435 public Profile getProfile() {
436 return new Profile(profile);
440 * Sets the profile of this Sone. A copy of the given profile is stored so
441 * that subsequent modifications of the given profile are not reflected in
447 public void setProfile(Profile profile) {
448 this.profile = new Profile(profile);
452 * Returns the client used by this Sone.
454 * @return The client used by this Sone, or {@code null}
456 public Client getClient() {
461 * Sets the client used by this Sone.
464 * The client used by this Sone, or {@code null}
465 * @return This Sone (for method chaining)
467 public Sone setClient(Client client) {
468 this.client = client;
473 * Returns whether this Sone is known.
475 * @return {@code true} if this Sone is known, {@code false} otherwise
477 public boolean isKnown() {
482 * Sets whether this Sone is known.
485 * {@code true} if this Sone is known, {@code false} otherwise
488 public Sone setKnown(boolean known) {
494 * Returns all friend Sones of this Sone.
496 * @return The friend Sones of this Sone
498 public List<String> getFriends() {
499 List<String> friends = new ArrayList<String>(friendSones);
504 * Returns whether this Sone has the given Sone as a friend Sone.
506 * @param friendSoneId
507 * The ID of the Sone to check for
508 * @return {@code true} if this Sone has the given Sone as a friend,
509 * {@code false} otherwise
511 public boolean hasFriend(String friendSoneId) {
512 return friendSones.contains(friendSoneId);
516 * Adds the given Sone as a friend Sone.
519 * The friend Sone to add
520 * @return This Sone (for method chaining)
522 public Sone addFriend(String friendSone) {
523 if (!friendSone.equals(id)) {
524 friendSones.add(friendSone);
530 * Removes the given Sone as a friend Sone.
532 * @param friendSoneId
533 * The ID of the friend Sone to remove
534 * @return This Sone (for method chaining)
536 public Sone removeFriend(String friendSoneId) {
537 friendSones.remove(friendSoneId);
542 * Returns the list of posts of this Sone, sorted by time, newest first.
544 * @return All posts of this Sone
546 public List<Post> getPosts() {
547 List<Post> sortedPosts;
548 synchronized (this) {
549 sortedPosts = new ArrayList<Post>(posts);
551 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
556 * Sets all posts of this Sone at once.
559 * The new (and only) posts of this Sone
560 * @return This Sone (for method chaining)
562 public Sone setPosts(Collection<Post> posts) {
563 synchronized (this) {
565 this.posts.addAll(posts);
571 * Adds the given post to this Sone. The post will not be added if its
572 * {@link Post#getSone() Sone} is not this Sone.
577 public void addPost(Post post) {
578 if (post.getSone().equals(this) && posts.add(post)) {
579 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
584 * Removes the given post from this Sone.
589 public void removePost(Post post) {
590 if (post.getSone().equals(this)) {
596 * Returns all replies this Sone made.
598 * @return All replies this Sone made
600 public Set<PostReply> getReplies() {
601 return Collections.unmodifiableSet(replies);
605 * Sets all replies of this Sone at once.
608 * The new (and only) replies of this Sone
609 * @return This Sone (for method chaining)
611 public Sone setReplies(Collection<PostReply> replies) {
612 this.replies.clear();
613 this.replies.addAll(replies);
618 * Adds a reply to this Sone. If the given reply was not made by this Sone,
619 * nothing is added to this Sone.
624 public void addReply(PostReply reply) {
625 if (reply.getSone().equals(this)) {
631 * Removes a reply from this Sone.
634 * The reply to remove
636 public void removeReply(PostReply reply) {
637 if (reply.getSone().equals(this)) {
638 replies.remove(reply);
643 * Returns the IDs of all liked posts.
645 * @return All liked posts’ IDs
647 public Set<String> getLikedPostIds() {
648 return Collections.unmodifiableSet(likedPostIds);
652 * Sets the IDs of all liked posts.
654 * @param likedPostIds
655 * All liked posts’ IDs
656 * @return This Sone (for method chaining)
658 public Sone setLikePostIds(Set<String> likedPostIds) {
659 this.likedPostIds.clear();
660 this.likedPostIds.addAll(likedPostIds);
665 * Checks whether the given post ID is liked by this Sone.
669 * @return {@code true} if this Sone likes the given post, {@code false}
672 public boolean isLikedPostId(String postId) {
673 return likedPostIds.contains(postId);
677 * Adds the given post ID to the list of posts this Sone likes.
681 * @return This Sone (for method chaining)
683 public Sone addLikedPostId(String postId) {
684 likedPostIds.add(postId);
689 * Removes the given post ID from the list of posts this Sone likes.
693 * @return This Sone (for method chaining)
695 public Sone removeLikedPostId(String postId) {
696 likedPostIds.remove(postId);
701 * Returns the IDs of all liked replies.
703 * @return All liked replies’ IDs
705 public Set<String> getLikedReplyIds() {
706 return Collections.unmodifiableSet(likedReplyIds);
710 * Sets the IDs of all liked replies.
712 * @param likedReplyIds
713 * All liked replies’ IDs
714 * @return This Sone (for method chaining)
716 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
717 this.likedReplyIds.clear();
718 this.likedReplyIds.addAll(likedReplyIds);
723 * Checks whether the given reply ID is liked by this Sone.
726 * The ID of the reply
727 * @return {@code true} if this Sone likes the given reply, {@code false}
730 public boolean isLikedReplyId(String replyId) {
731 return likedReplyIds.contains(replyId);
735 * Adds the given reply ID to the list of replies this Sone likes.
738 * The ID of the reply
739 * @return This Sone (for method chaining)
741 public Sone addLikedReplyId(String replyId) {
742 likedReplyIds.add(replyId);
747 * Removes the given post ID from the list of replies this Sone likes.
750 * The ID of the reply
751 * @return This Sone (for method chaining)
753 public Sone removeLikedReplyId(String replyId) {
754 likedReplyIds.remove(replyId);
759 * Returns the albums of this Sone.
761 * @return The albums of this Sone
763 public List<Album> getAlbums() {
764 return Collections.unmodifiableList(albums);
768 * Returns a flattened list of all albums of this Sone. The resulting list
769 * contains parent albums before child albums so that the resulting list can
770 * be parsed in a single pass.
772 * @return The flattened albums
774 public List<Album> getAllAlbums() {
775 List<Album> flatAlbums = new ArrayList<Album>();
776 flatAlbums.addAll(albums);
777 int lastAlbumIndex = 0;
778 while (lastAlbumIndex < flatAlbums.size()) {
779 int previousAlbumCount = flatAlbums.size();
780 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
781 flatAlbums.addAll(album.getAlbums());
783 lastAlbumIndex = previousAlbumCount;
789 * Returns all images of a Sone. Images of a album are inserted into this
790 * list before images of all child albums.
792 * @return The list of all images
794 public List<Image> getAllImages() {
795 List<Image> allImages = new ArrayList<Image>();
796 for (Album album : getAllAlbums()) {
797 allImages.addAll(album.getImages());
803 * Adds an album to this Sone.
808 public void addAlbum(Album album) {
809 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
810 if (!albums.contains(album)) {
816 * Sets the albums of this Sone.
819 * The albums of this Sone
821 public void setAlbums(Collection<? extends Album> albums) {
822 Validation.begin().isNotNull("Albums", albums).check();
824 for (Album album : albums) {
830 * Removes an album from this Sone.
833 * The album to remove
835 public void removeAlbum(Album album) {
836 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
837 albums.remove(album);
841 * Moves the given album up in this album’s albums. If the album is already
842 * the first album, nothing happens.
845 * The album to move up
846 * @return The album that the given album swapped the place with, or
847 * <code>null</code> if the album did not change its place
849 public Album moveAlbumUp(Album album) {
850 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
851 int oldIndex = albums.indexOf(album);
855 albums.remove(oldIndex);
856 albums.add(oldIndex - 1, album);
857 return albums.get(oldIndex);
861 * Moves the given album down in this album’s albums. If the album is
862 * already the last album, nothing happens.
865 * The album to move down
866 * @return The album that the given album swapped the place with, or
867 * <code>null</code> if the album did not change its place
869 public Album moveAlbumDown(Album album) {
870 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
871 int oldIndex = albums.indexOf(album);
872 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
875 albums.remove(oldIndex);
876 albums.add(oldIndex + 1, album);
877 return albums.get(oldIndex);
881 * Returns Sone-specific options.
883 * @return The options of this Sone
885 public Options getOptions() {
890 // FINGERPRINTABLE METHODS
897 public synchronized String getFingerprint() {
898 StringBuilder fingerprint = new StringBuilder();
899 fingerprint.append(profile.getFingerprint());
901 fingerprint.append("Posts(");
902 for (Post post : getPosts()) {
903 fingerprint.append("Post(").append(post.getId()).append(')');
905 fingerprint.append(")");
907 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
908 Collections.sort(replies, Reply.TIME_COMPARATOR);
909 fingerprint.append("Replies(");
910 for (PostReply reply : replies) {
911 fingerprint.append("Reply(").append(reply.getId()).append(')');
913 fingerprint.append(')');
915 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
916 Collections.sort(likedPostIds);
917 fingerprint.append("LikedPosts(");
918 for (String likedPostId : likedPostIds) {
919 fingerprint.append("Post(").append(likedPostId).append(')');
921 fingerprint.append(')');
923 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
924 Collections.sort(likedReplyIds);
925 fingerprint.append("LikedReplies(");
926 for (String likedReplyId : likedReplyIds) {
927 fingerprint.append("Reply(").append(likedReplyId).append(')');
929 fingerprint.append(')');
931 fingerprint.append("Albums(");
932 for (Album album : albums) {
933 fingerprint.append(album.getFingerprint());
935 fingerprint.append(')');
937 return fingerprint.toString();
941 // INTERFACE Comparable<Sone>
948 public int compareTo(Sone sone) {
949 return NICE_NAME_COMPARATOR.compare(this, sone);
960 public int hashCode() {
961 return id.hashCode();
968 public boolean equals(Object object) {
969 if (!(object instanceof Sone)) {
972 return ((Sone) object).id.equals(id);
979 public String toString() {
980 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";