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#isLocalSone(Sone) 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 /** The identity of this Sone. */
179 private Identity identity;
181 /** The URI under which the Sone is stored in Freenet. */
182 private volatile FreenetURI requestUri;
184 /** The URI used to insert a new version of this Sone. */
185 /* This will be null for remote Sones! */
186 private volatile FreenetURI insertUri;
188 /** The latest edition of the Sone. */
189 private volatile long latestEdition;
191 /** The time of the last inserted update. */
192 private volatile long time;
194 /** The status of this Sone. */
195 private volatile SoneStatus status = SoneStatus.unknown;
197 /** The profile of this Sone. */
198 private volatile Profile profile = new Profile(this);
200 /** The client used by the Sone. */
201 private volatile Client client;
203 /** Whether this Sone is known. */
204 private volatile boolean known;
206 /** All friend Sones. */
207 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
210 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
213 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
215 /** The IDs of all liked posts. */
216 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
218 /** The IDs of all liked replies. */
219 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
221 /** The albums of this Sone. */
222 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
224 /** Sone-specific options. */
225 private final Options options = new Options();
228 * Creates a new Sone.
233 public Sone(String id) {
242 * Returns the identity of this Sone.
244 * @return The identity of this Sone
246 public String getId() {
251 * Returns the identity of this Sone.
253 * @return The identity of this Sone
255 public Identity getIdentity() {
260 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
261 * identity has to match this Sone’s {@link #getId()}.
264 * The identity of this Sone
265 * @return This Sone (for method chaining)
266 * @throws IllegalArgumentException
267 * if the ID of the identity does not match this Sone’s ID
269 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
270 if (!identity.getId().equals(id)) {
271 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
273 this.identity = identity;
278 * Returns the name of this Sone.
280 * @return The name of this Sone
282 public String getName() {
283 return (identity != null) ? identity.getNickname() : null;
287 * Returns the request URI of this Sone.
289 * @return The request URI of this Sone
291 public FreenetURI getRequestUri() {
292 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
296 * Sets the request URI of this Sone.
299 * The request URI of this Sone
300 * @return This Sone (for method chaining)
302 public Sone setRequestUri(FreenetURI requestUri) {
303 if (this.requestUri == null) {
304 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
307 if (!this.requestUri.equalsKeypair(requestUri)) {
308 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
315 * Returns the insert URI of this Sone.
317 * @return The insert URI of this Sone
319 public FreenetURI getInsertUri() {
320 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
324 * Sets the insert URI of this Sone.
327 * The insert URI of this Sone
328 * @return This Sone (for method chaining)
330 public Sone setInsertUri(FreenetURI insertUri) {
331 if (this.insertUri == null) {
332 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
335 if (!this.insertUri.equalsKeypair(insertUri)) {
336 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
343 * Returns the latest edition of this Sone.
345 * @return The latest edition of this Sone
347 public long getLatestEdition() {
348 return latestEdition;
352 * Sets the latest edition of this Sone. If the given latest edition is not
353 * greater than the current latest edition, the latest edition of this Sone
356 * @param latestEdition
357 * The latest edition of this Sone
359 public void setLatestEdition(long latestEdition) {
360 if (!(latestEdition > this.latestEdition)) {
361 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
364 this.latestEdition = latestEdition;
368 * Return the time of the last inserted update of this Sone.
370 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
372 public long getTime() {
377 * Sets the time of the last inserted update of this Sone.
380 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
381 * @return This Sone (for method chaining)
383 public Sone setTime(long time) {
389 * Returns the status of this Sone.
391 * @return The status of this Sone
393 public SoneStatus getStatus() {
398 * Sets the new status of this Sone.
401 * The new status of this Sone
403 * @throws IllegalArgumentException
404 * if {@code status} is {@code null}
406 public Sone setStatus(SoneStatus status) {
407 Validation.begin().isNotNull("Sone Status", status).check();
408 this.status = status;
413 * Returns a copy of the profile. If you want to update values in the
414 * profile of this Sone, update the values in the returned {@link Profile}
415 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
417 * @return A copy of the profile
419 public Profile getProfile() {
420 return new Profile(profile);
424 * Sets the profile of this Sone. A copy of the given profile is stored so
425 * that subsequent modifications of the given profile are not reflected in
431 public void setProfile(Profile profile) {
432 this.profile = new Profile(profile);
436 * Returns the client used by this Sone.
438 * @return The client used by this Sone, or {@code null}
440 public Client getClient() {
445 * Sets the client used by this Sone.
448 * The client used by this Sone, or {@code null}
449 * @return This Sone (for method chaining)
451 public Sone setClient(Client client) {
452 this.client = client;
457 * Returns whether this Sone is known.
459 * @return {@code true} if this Sone is known, {@code false} otherwise
461 public boolean isKnown() {
466 * Sets whether this Sone is known.
469 * {@code true} if this Sone is known, {@code false} otherwise
472 public Sone setKnown(boolean known) {
478 * Returns all friend Sones of this Sone.
480 * @return The friend Sones of this Sone
482 public List<String> getFriends() {
483 List<String> friends = new ArrayList<String>(friendSones);
488 * Returns whether this Sone has the given Sone as a friend Sone.
490 * @param friendSoneId
491 * The ID of the Sone to check for
492 * @return {@code true} if this Sone has the given Sone as a friend,
493 * {@code false} otherwise
495 public boolean hasFriend(String friendSoneId) {
496 return friendSones.contains(friendSoneId);
500 * Adds the given Sone as a friend Sone.
503 * The friend Sone to add
504 * @return This Sone (for method chaining)
506 public Sone addFriend(String friendSone) {
507 if (!friendSone.equals(id)) {
508 friendSones.add(friendSone);
514 * Removes the given Sone as a friend Sone.
516 * @param friendSoneId
517 * The ID of the friend Sone to remove
518 * @return This Sone (for method chaining)
520 public Sone removeFriend(String friendSoneId) {
521 friendSones.remove(friendSoneId);
526 * Returns the list of posts of this Sone, sorted by time, newest first.
528 * @return All posts of this Sone
530 public List<Post> getPosts() {
531 List<Post> sortedPosts;
532 synchronized (this) {
533 sortedPosts = new ArrayList<Post>(posts);
535 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
540 * Sets all posts of this Sone at once.
543 * The new (and only) posts of this Sone
544 * @return This Sone (for method chaining)
546 public Sone setPosts(Collection<Post> posts) {
547 synchronized (this) {
549 this.posts.addAll(posts);
555 * Adds the given post to this Sone. The post will not be added if its
556 * {@link Post#getSone() Sone} is not this Sone.
561 public void addPost(Post post) {
562 if (post.getSone().equals(this) && posts.add(post)) {
563 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
568 * Removes the given post from this Sone.
573 public void removePost(Post post) {
574 if (post.getSone().equals(this)) {
580 * Returns all replies this Sone made.
582 * @return All replies this Sone made
584 public Set<PostReply> getReplies() {
585 return Collections.unmodifiableSet(replies);
589 * Sets all replies of this Sone at once.
592 * The new (and only) replies of this Sone
593 * @return This Sone (for method chaining)
595 public Sone setReplies(Collection<PostReply> replies) {
596 this.replies.clear();
597 this.replies.addAll(replies);
602 * Adds a reply to this Sone. If the given reply was not made by this Sone,
603 * nothing is added to this Sone.
608 public void addReply(PostReply reply) {
609 if (reply.getSone().equals(this)) {
615 * Removes a reply from this Sone.
618 * The reply to remove
620 public void removeReply(PostReply reply) {
621 if (reply.getSone().equals(this)) {
622 replies.remove(reply);
627 * Returns the IDs of all liked posts.
629 * @return All liked posts’ IDs
631 public Set<String> getLikedPostIds() {
632 return Collections.unmodifiableSet(likedPostIds);
636 * Sets the IDs of all liked posts.
638 * @param likedPostIds
639 * All liked posts’ IDs
640 * @return This Sone (for method chaining)
642 public Sone setLikePostIds(Set<String> likedPostIds) {
643 this.likedPostIds.clear();
644 this.likedPostIds.addAll(likedPostIds);
649 * Checks whether the given post ID is liked by this Sone.
653 * @return {@code true} if this Sone likes the given post, {@code false}
656 public boolean isLikedPostId(String postId) {
657 return likedPostIds.contains(postId);
661 * Adds the given post ID to the list of posts this Sone likes.
665 * @return This Sone (for method chaining)
667 public Sone addLikedPostId(String postId) {
668 likedPostIds.add(postId);
673 * Removes the given post ID from the list of posts this Sone likes.
677 * @return This Sone (for method chaining)
679 public Sone removeLikedPostId(String postId) {
680 likedPostIds.remove(postId);
685 * Returns the IDs of all liked replies.
687 * @return All liked replies’ IDs
689 public Set<String> getLikedReplyIds() {
690 return Collections.unmodifiableSet(likedReplyIds);
694 * Sets the IDs of all liked replies.
696 * @param likedReplyIds
697 * All liked replies’ IDs
698 * @return This Sone (for method chaining)
700 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
701 this.likedReplyIds.clear();
702 this.likedReplyIds.addAll(likedReplyIds);
707 * Checks whether the given reply ID is liked by this Sone.
710 * The ID of the reply
711 * @return {@code true} if this Sone likes the given reply, {@code false}
714 public boolean isLikedReplyId(String replyId) {
715 return likedReplyIds.contains(replyId);
719 * Adds the given reply ID to the list of replies this Sone likes.
722 * The ID of the reply
723 * @return This Sone (for method chaining)
725 public Sone addLikedReplyId(String replyId) {
726 likedReplyIds.add(replyId);
731 * Removes the given post ID from the list of replies this Sone likes.
734 * The ID of the reply
735 * @return This Sone (for method chaining)
737 public Sone removeLikedReplyId(String replyId) {
738 likedReplyIds.remove(replyId);
743 * Returns the albums of this Sone.
745 * @return The albums of this Sone
747 public List<Album> getAlbums() {
748 return Collections.unmodifiableList(albums);
752 * Returns a flattened list of all albums of this Sone. The resulting list
753 * contains parent albums before child albums so that the resulting list can
754 * be parsed in a single pass.
756 * @return The flattened albums
758 public List<Album> getAllAlbums() {
759 List<Album> flatAlbums = new ArrayList<Album>();
760 flatAlbums.addAll(albums);
761 int lastAlbumIndex = 0;
762 while (lastAlbumIndex < flatAlbums.size()) {
763 int previousAlbumCount = flatAlbums.size();
764 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
765 flatAlbums.addAll(album.getAlbums());
767 lastAlbumIndex = previousAlbumCount;
773 * Returns all images of a Sone. Images of a album are inserted into this
774 * list before images of all child albums.
776 * @return The list of all images
778 public List<Image> getAllImages() {
779 List<Image> allImages = new ArrayList<Image>();
780 for (Album album : getAllAlbums()) {
781 allImages.addAll(album.getImages());
787 * Adds an album to this Sone.
792 public void addAlbum(Album album) {
793 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
794 if (!albums.contains(album)) {
800 * Sets the albums of this Sone.
803 * The albums of this Sone
805 public void setAlbums(Collection<? extends Album> albums) {
806 Validation.begin().isNotNull("Albums", albums).check();
808 for (Album album : albums) {
814 * Removes an album from this Sone.
817 * The album to remove
819 public void removeAlbum(Album album) {
820 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
821 albums.remove(album);
825 * Moves the given album up in this album’s albums. If the album is already
826 * the first album, nothing happens.
829 * The album to move up
830 * @return The album that the given album swapped the place with, or
831 * <code>null</code> if the album did not change its place
833 public Album moveAlbumUp(Album album) {
834 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
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
846 * already 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 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
855 int oldIndex = albums.indexOf(album);
856 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
859 albums.remove(oldIndex);
860 albums.add(oldIndex + 1, album);
861 return albums.get(oldIndex);
865 * Returns Sone-specific options.
867 * @return The options of this Sone
869 public Options getOptions() {
874 // FINGERPRINTABLE METHODS
881 public synchronized String getFingerprint() {
882 StringBuilder fingerprint = new StringBuilder();
883 fingerprint.append(profile.getFingerprint());
885 fingerprint.append("Posts(");
886 for (Post post : getPosts()) {
887 fingerprint.append("Post(").append(post.getId()).append(')');
889 fingerprint.append(")");
891 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
892 Collections.sort(replies, Reply.TIME_COMPARATOR);
893 fingerprint.append("Replies(");
894 for (PostReply reply : replies) {
895 fingerprint.append("Reply(").append(reply.getId()).append(')');
897 fingerprint.append(')');
899 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
900 Collections.sort(likedPostIds);
901 fingerprint.append("LikedPosts(");
902 for (String likedPostId : likedPostIds) {
903 fingerprint.append("Post(").append(likedPostId).append(')');
905 fingerprint.append(')');
907 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
908 Collections.sort(likedReplyIds);
909 fingerprint.append("LikedReplies(");
910 for (String likedReplyId : likedReplyIds) {
911 fingerprint.append("Reply(").append(likedReplyId).append(')');
913 fingerprint.append(')');
915 fingerprint.append("Albums(");
916 for (Album album : albums) {
917 fingerprint.append(album.getFingerprint());
919 fingerprint.append(')');
921 return fingerprint.toString();
925 // INTERFACE Comparable<Sone>
932 public int compareTo(Sone sone) {
933 return NICE_NAME_COMPARATOR.compare(this, sone);
944 public int hashCode() {
945 return id.hashCode();
952 public boolean equals(Object object) {
953 if (!(object instanceof Sone)) {
956 return ((Sone) object).id.equals(id);
963 public String toString() {
964 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";