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.checkNotNull;
21 import static com.google.common.collect.FluentIterable.from;
22 import static java.util.Arrays.asList;
23 import static net.pterodactylus.sone.data.Album.FLATTENER;
24 import static net.pterodactylus.sone.data.Album.IMAGES;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.Comparator;
30 import java.util.List;
32 import java.util.concurrent.CopyOnWriteArraySet;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
36 import net.pterodactylus.sone.core.Options;
37 import net.pterodactylus.sone.freenet.wot.Identity;
38 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
39 import net.pterodactylus.sone.template.SoneAccessor;
40 import net.pterodactylus.util.logging.Logging;
42 import freenet.keys.FreenetURI;
44 import com.google.common.base.Predicate;
45 import com.google.common.hash.Hasher;
46 import com.google.common.hash.Hashing;
47 import com.google.common.primitives.Ints;
50 * A Sone defines everything about a user: her profile, her status updates, her
51 * replies, her likes and dislikes, etc.
53 * Operations that modify the Sone need to synchronize on the Sone in question.
55 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57 public class Sone implements Identified, Fingerprintable, Comparable<Sone> {
60 * Enumeration for the possible states of a {@link Sone}.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public enum SoneStatus {
66 /** The Sone is unknown, i.e. not yet downloaded. */
69 /** The Sone is idle, i.e. not being downloaded or inserted. */
72 /** The Sone is currently being inserted. */
75 /** The Sone is currently being downloaded. */
80 * The possible values for the “show custom avatars” option.
82 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
84 public static enum ShowCustomAvatars {
86 /** Never show custom avatars. */
89 /** Only show custom avatars of followed Sones. */
92 /** Only show custom avatars of Sones you manually trust. */
95 /** Only show custom avatars of automatically trusted Sones. */
98 /** Always show custom avatars. */
103 /** comparator that sorts Sones by their nice name. */
104 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
107 public int compare(Sone leftSone, Sone rightSone) {
108 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
112 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
117 /** 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 int rightSoneImageCount = from(asList(rightSone.getRootAlbum())).transformAndConcat(FLATTENER).transformAndConcat(IMAGES).size();
147 int leftSoneImageCount = from(asList(leftSone.getRootAlbum())).transformAndConcat(FLATTENER).transformAndConcat(IMAGES).size();
148 /* sort descending. */
149 return Ints.compare(rightSoneImageCount, leftSoneImageCount);
153 /** Filter to remove Sones that have not been downloaded. */
154 public static final Predicate<Sone> EMPTY_SONE_FILTER = new Predicate<Sone>() {
157 public boolean apply(Sone sone) {
158 return (sone == null) ? false : sone.getTime() != 0;
162 /** Filter that matches all {@link Sone#isLocal() local Sones}. */
163 public static final Predicate<Sone> LOCAL_SONE_FILTER = new Predicate<Sone>() {
166 public boolean apply(Sone sone) {
167 return (sone == null) ? false : sone.getIdentity() instanceof OwnIdentity;
172 /** Filter that matches Sones that have at least one album. */
173 public static final Predicate<Sone> HAS_ALBUM_FILTER = new Predicate<Sone>() {
176 public boolean apply(Sone sone) {
177 return (sone == null) ? false : !sone.getRootAlbum().getAlbums().isEmpty();
182 private static final Logger logger = Logging.getLogger(Sone.class);
184 /** The ID of this Sone. */
185 private final String id;
187 /** Whether the Sone is local. */
188 private final boolean local;
190 /** The identity of this Sone. */
191 private Identity identity;
193 /** The URI under which the Sone is stored in Freenet. */
194 private volatile FreenetURI requestUri;
196 /** The URI used to insert a new version of this Sone. */
197 /* This will be null for remote Sones! */
198 private volatile FreenetURI insertUri;
200 /** The latest edition of the Sone. */
201 private volatile long latestEdition;
203 /** The time of the last inserted update. */
204 private volatile long time;
206 /** The status of this Sone. */
207 private volatile SoneStatus status = SoneStatus.unknown;
209 /** The profile of this Sone. */
210 private volatile Profile profile = new Profile(this);
212 /** The client used by the Sone. */
213 private volatile Client client;
215 /** Whether this Sone is known. */
216 private volatile boolean known;
218 /** All friend Sones. */
219 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
222 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
225 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
227 /** The IDs of all liked posts. */
228 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
230 /** The IDs of all liked replies. */
231 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
233 /** The root album containing all albums. */
234 private final Album rootAlbum = new Album().setSone(this);
236 /** Sone-specific options. */
237 private Options options = new Options();
240 * Creates a new Sone.
245 * {@code true} if the Sone is a local Sone, {@code false} otherwise
247 public Sone(String id, boolean local) {
257 * Returns the identity of this Sone.
259 * @return The identity of this Sone
261 public String getId() {
266 * Returns the identity of this Sone.
268 * @return The identity of this Sone
270 public Identity getIdentity() {
275 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
276 * identity has to match this Sone’s {@link #getId()}.
279 * The identity of this Sone
280 * @return This Sone (for method chaining)
281 * @throws IllegalArgumentException
282 * if the ID of the identity does not match this Sone’s ID
284 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
285 if (!identity.getId().equals(id)) {
286 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
288 this.identity = identity;
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 whether this Sone is a local Sone.
304 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
306 public boolean isLocal() {
311 * Returns the request URI of this Sone.
313 * @return The request URI of this Sone
315 public FreenetURI getRequestUri() {
316 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
320 * Sets the request URI of this Sone.
323 * The request URI of this Sone
324 * @return This Sone (for method chaining)
326 public Sone setRequestUri(FreenetURI requestUri) {
327 if (this.requestUri == null) {
328 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
331 if (!this.requestUri.equalsKeypair(requestUri)) {
332 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
339 * Returns the insert URI of this Sone.
341 * @return The insert URI of this Sone
343 public FreenetURI getInsertUri() {
344 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
348 * Sets the insert URI of this Sone.
351 * The insert URI of this Sone
352 * @return This Sone (for method chaining)
354 public Sone setInsertUri(FreenetURI insertUri) {
355 if (this.insertUri == null) {
356 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
359 if (!this.insertUri.equalsKeypair(insertUri)) {
360 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
367 * Returns the latest edition of this Sone.
369 * @return The latest edition of this Sone
371 public long getLatestEdition() {
372 return latestEdition;
376 * Sets the latest edition of this Sone. If the given latest edition is not
377 * greater than the current latest edition, the latest edition of this Sone is
380 * @param latestEdition
381 * The latest edition of this Sone
383 public void setLatestEdition(long latestEdition) {
384 if (!(latestEdition > this.latestEdition)) {
385 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
388 this.latestEdition = latestEdition;
392 * Return the time of the last inserted update of this Sone.
394 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
396 public long getTime() {
401 * Sets the time of the last inserted update of this Sone.
404 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
405 * @return This Sone (for method chaining)
407 public Sone setTime(long time) {
413 * Returns the status of this Sone.
415 * @return The status of this Sone
417 public SoneStatus getStatus() {
422 * Sets the new status of this Sone.
425 * The new status of this Sone
427 * @throws IllegalArgumentException
428 * if {@code status} is {@code null}
430 public Sone setStatus(SoneStatus status) {
431 this.status = checkNotNull(status, "status must not be null");
436 * Returns a copy of the profile. If you want to update values in the profile
437 * of this Sone, update the values in the returned {@link Profile} and use
438 * {@link #setProfile(Profile)} to change the profile in this Sone.
440 * @return A copy of the profile
442 public Profile getProfile() {
443 return new Profile(profile);
447 * Sets the profile of this Sone. A copy of the given profile is stored so that
448 * subsequent modifications of the given profile are not reflected in this
454 public void setProfile(Profile profile) {
455 this.profile = new Profile(profile);
459 * Returns the client used by this Sone.
461 * @return The client used by this Sone, or {@code null}
463 public Client getClient() {
468 * Sets the client used by this Sone.
471 * The client used by this Sone, or {@code null}
472 * @return This Sone (for method chaining)
474 public Sone setClient(Client client) {
475 this.client = client;
480 * Returns whether this Sone is known.
482 * @return {@code true} if this Sone is known, {@code false} otherwise
484 public boolean isKnown() {
489 * Sets whether this Sone is known.
492 * {@code true} if this Sone is known, {@code false} otherwise
495 public Sone setKnown(boolean known) {
501 * Returns all friend Sones of this Sone.
503 * @return The friend Sones of this Sone
505 public List<String> getFriends() {
506 List<String> friends = new ArrayList<String>(friendSones);
511 * Returns whether this Sone has the given Sone as a friend Sone.
513 * @param friendSoneId
514 * The ID of the Sone to check for
515 * @return {@code true} if this Sone has the given Sone as a friend, {@code
518 public boolean hasFriend(String friendSoneId) {
519 return friendSones.contains(friendSoneId);
523 * Adds the given Sone as a friend Sone.
526 * The friend Sone to add
527 * @return This Sone (for method chaining)
529 public Sone addFriend(String friendSone) {
530 if (!friendSone.equals(id)) {
531 friendSones.add(friendSone);
537 * Removes the given Sone as a friend Sone.
539 * @param friendSoneId
540 * The ID of the friend Sone to remove
541 * @return This Sone (for method chaining)
543 public Sone removeFriend(String friendSoneId) {
544 friendSones.remove(friendSoneId);
549 * Returns the list of posts of this Sone, sorted by time, newest first.
551 * @return All posts of this Sone
553 public List<Post> getPosts() {
554 List<Post> sortedPosts;
555 synchronized (this) {
556 sortedPosts = new ArrayList<Post>(posts);
558 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
563 * Sets all posts of this Sone at once.
566 * The new (and only) posts of this Sone
567 * @return This Sone (for method chaining)
569 public Sone setPosts(Collection<Post> posts) {
570 synchronized (this) {
572 this.posts.addAll(posts);
578 * Adds the given post to this Sone. The post will not be added if its {@link
579 * Post#getSone() Sone} is not this Sone.
584 public void addPost(Post post) {
585 if (post.getSone().equals(this) && posts.add(post)) {
586 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
591 * Removes the given post from this Sone.
596 public void removePost(Post post) {
597 if (post.getSone().equals(this)) {
603 * Returns all replies this Sone made.
605 * @return All replies this Sone made
607 public Set<PostReply> getReplies() {
608 return Collections.unmodifiableSet(replies);
612 * Sets all replies of this Sone at once.
615 * The new (and only) replies of this Sone
616 * @return This Sone (for method chaining)
618 public Sone setReplies(Collection<PostReply> replies) {
619 this.replies.clear();
620 this.replies.addAll(replies);
625 * Adds a reply to this Sone. If the given reply was not made by this Sone,
626 * nothing is added to this Sone.
631 public void addReply(PostReply reply) {
632 if (reply.getSone().equals(this)) {
638 * Removes a reply from this Sone.
641 * The reply to remove
643 public void removeReply(PostReply reply) {
644 if (reply.getSone().equals(this)) {
645 replies.remove(reply);
650 * Returns the IDs of all liked posts.
652 * @return All liked posts’ IDs
654 public Set<String> getLikedPostIds() {
655 return Collections.unmodifiableSet(likedPostIds);
659 * Sets the IDs of all liked posts.
661 * @param likedPostIds
662 * All liked posts’ IDs
663 * @return This Sone (for method chaining)
665 public Sone setLikePostIds(Set<String> likedPostIds) {
666 this.likedPostIds.clear();
667 this.likedPostIds.addAll(likedPostIds);
672 * Checks whether the given post ID is liked by this Sone.
676 * @return {@code true} if this Sone likes the given post, {@code false}
679 public boolean isLikedPostId(String postId) {
680 return likedPostIds.contains(postId);
684 * Adds the given post ID to the list of posts this Sone likes.
688 * @return This Sone (for method chaining)
690 public Sone addLikedPostId(String postId) {
691 likedPostIds.add(postId);
696 * Removes the given post ID from the list of posts this Sone likes.
700 * @return This Sone (for method chaining)
702 public Sone removeLikedPostId(String postId) {
703 likedPostIds.remove(postId);
708 * Returns the IDs of all liked replies.
710 * @return All liked replies’ IDs
712 public Set<String> getLikedReplyIds() {
713 return Collections.unmodifiableSet(likedReplyIds);
717 * Sets the IDs of all liked replies.
719 * @param likedReplyIds
720 * All liked replies’ IDs
721 * @return This Sone (for method chaining)
723 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
724 this.likedReplyIds.clear();
725 this.likedReplyIds.addAll(likedReplyIds);
730 * Checks whether the given reply ID is liked by this Sone.
733 * The ID of the reply
734 * @return {@code true} if this Sone likes the given reply, {@code false}
737 public boolean isLikedReplyId(String replyId) {
738 return likedReplyIds.contains(replyId);
742 * Adds the given reply ID to the list of replies this Sone likes.
745 * The ID of the reply
746 * @return This Sone (for method chaining)
748 public Sone addLikedReplyId(String replyId) {
749 likedReplyIds.add(replyId);
754 * Removes the given post ID from the list of replies this Sone likes.
757 * The ID of the reply
758 * @return This Sone (for method chaining)
760 public Sone removeLikedReplyId(String replyId) {
761 likedReplyIds.remove(replyId);
766 * Returns the root album that contains all visible albums of this Sone.
768 * @return The root album of this Sone
770 public Album getRootAlbum() {
775 * Returns Sone-specific options.
777 * @return The options of this Sone
779 public Options getOptions() {
784 * Sets the options of this Sone.
787 * The options of this Sone
789 /* TODO - remove this method again, maybe add an option provider */
790 public void setOptions(Options options) {
791 this.options = options;
795 // FINGERPRINTABLE METHODS
800 public synchronized String getFingerprint() {
801 Hasher hash = Hashing.sha256().newHasher();
802 hash.putString(profile.getFingerprint());
804 hash.putString("Posts(");
805 for (Post post : getPosts()) {
806 hash.putString("Post(").putString(post.getId()).putString(")");
810 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
811 Collections.sort(replies, Reply.TIME_COMPARATOR);
812 hash.putString("Replies(");
813 for (PostReply reply : replies) {
814 hash.putString("Reply(").putString(reply.getId()).putString(")");
818 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
819 Collections.sort(likedPostIds);
820 hash.putString("LikedPosts(");
821 for (String likedPostId : likedPostIds) {
822 hash.putString("Post(").putString(likedPostId).putString(")");
826 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
827 Collections.sort(likedReplyIds);
828 hash.putString("LikedReplies(");
829 for (String likedReplyId : likedReplyIds) {
830 hash.putString("Reply(").putString(likedReplyId).putString(")");
834 hash.putString("Albums(");
835 for (Album album : rootAlbum.getAlbums()) {
836 if (!Album.NOT_EMPTY.apply(album)) {
839 hash.putString(album.getFingerprint());
843 return hash.hash().toString();
847 // INTERFACE Comparable<Sone>
852 public int compareTo(Sone sone) {
853 return NICE_NAME_COMPARATOR.compare(this, sone);
862 public int hashCode() {
863 return id.hashCode();
868 public boolean equals(Object object) {
869 if (!(object instanceof Sone)) {
872 return ((Sone) object).id.equals(id);
877 public String toString() {
878 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";