2 * Sone - Sone.java - Copyright © 2010 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.HashSet;
25 import java.util.List;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.core.Core;
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.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 * The possible values for the “show custom avatars” option.
53 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55 public static enum ShowCustomAvatars {
57 /** Never show custom avatars. */
60 /** Only show custom avatars of followed Sones. */
63 /** Only show custom avatars of Sones you manually trust. */
66 /** Only show custom avatars of automatically trusted Sones. */
69 /** Always show custom avatars. */
74 /** comparator that sorts Sones by their nice name. */
75 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
78 public int compare(Sone leftSone, Sone rightSone) {
79 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
83 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
89 * Comparator that sorts Sones by last activity (least recent active first).
91 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
94 public int compare(Sone firstSone, Sone secondSone) {
95 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
99 /** Comparator that sorts Sones by numbers of posts (descending). */
100 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
106 public int compare(Sone leftSone, Sone rightSone) {
107 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
111 /** Comparator that sorts Sones by number of images (descending). */
112 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
118 public int compare(Sone leftSone, Sone rightSone) {
119 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
123 /** Filter to remove Sones that have not been downloaded. */
124 public static final Filter<Sone> EMPTY_SONE_FILTER = new Filter<Sone>() {
127 public boolean filterObject(Sone sone) {
128 return sone.getTime() != 0;
132 /** Filter that matches all {@link Core#isLocalSone(Sone) local Sones}. */
133 public static final Filter<Sone> LOCAL_SONE_FILTER = new Filter<Sone>() {
136 public boolean filterObject(Sone sone) {
137 return sone.getIdentity() instanceof OwnIdentity;
142 /** Filter that matches Sones that have at least one album. */
143 public static final Filter<Sone> HAS_ALBUM_FILTER = new Filter<Sone>() {
146 public boolean filterObject(Sone sone) {
147 return !sone.getAlbums().isEmpty();
152 private static final Logger logger = Logging.getLogger(Sone.class);
154 /** The ID of this Sone. */
155 private final String id;
157 /** The identity of this Sone. */
158 private Identity identity;
160 /** The URI under which the Sone is stored in Freenet. */
161 private volatile FreenetURI requestUri;
163 /** The URI used to insert a new version of this Sone. */
164 /* This will be null for remote Sones! */
165 private volatile FreenetURI insertUri;
167 /** The latest edition of the Sone. */
168 private volatile long latestEdition;
170 /** The time of the last inserted update. */
171 private volatile long time;
173 /** The profile of this Sone. */
174 private volatile Profile profile = new Profile(this);
176 /** The client used by the Sone. */
177 private volatile Client client;
179 /** All friend Sones. */
180 private final Set<String> friendSones = Collections.synchronizedSet(new HashSet<String>());
183 private final Set<Post> posts = Collections.synchronizedSet(new HashSet<Post>());
186 private final Set<PostReply> replies = Collections.synchronizedSet(new HashSet<PostReply>());
188 /** The IDs of all liked posts. */
189 private final Set<String> likedPostIds = Collections.synchronizedSet(new HashSet<String>());
191 /** The IDs of all liked replies. */
192 private final Set<String> likedReplyIds = Collections.synchronizedSet(new HashSet<String>());
194 /** The albums of this Sone. */
195 private final List<Album> albums = Collections.synchronizedList(new ArrayList<Album>());
197 /** Sone-specific options. */
198 private final Options options = new Options();
201 * Creates a new Sone.
206 public Sone(String id) {
215 * Returns the identity of this Sone.
217 * @return The identity of this Sone
219 public String getId() {
224 * Returns the identity of this Sone.
226 * @return The identity of this Sone
228 public Identity getIdentity() {
233 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
234 * identity has to match this Sone’s {@link #getId()}.
237 * The identity of this Sone
238 * @return This Sone (for method chaining)
239 * @throws IllegalArgumentException
240 * if the ID of the identity does not match this Sone’s ID
242 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
243 if (!identity.getId().equals(id)) {
244 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
246 this.identity = identity;
251 * Returns the name of this Sone.
253 * @return The name of this Sone
255 public String getName() {
256 return (identity != null) ? identity.getNickname() : null;
260 * Returns the request URI of this Sone.
262 * @return The request URI of this Sone
264 public FreenetURI getRequestUri() {
265 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
269 * Sets the request URI of this Sone.
272 * The request URI of this Sone
273 * @return This Sone (for method chaining)
275 public Sone setRequestUri(FreenetURI requestUri) {
276 if (this.requestUri == null) {
277 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
280 if (!this.requestUri.equalsKeypair(requestUri)) {
281 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
288 * Returns the insert URI of this Sone.
290 * @return The insert URI of this Sone
292 public FreenetURI getInsertUri() {
293 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
297 * Sets the insert URI of this Sone.
300 * The insert URI of this Sone
301 * @return This Sone (for method chaining)
303 public Sone setInsertUri(FreenetURI insertUri) {
304 if (this.insertUri == null) {
305 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
308 if (!this.insertUri.equalsKeypair(insertUri)) {
309 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
316 * Returns the latest edition of this Sone.
318 * @return The latest edition of this Sone
320 public long getLatestEdition() {
321 return latestEdition;
325 * Sets the latest edition of this Sone. If the given latest edition is not
326 * greater than the current latest edition, the latest edition of this Sone
329 * @param latestEdition
330 * The latest edition of this Sone
332 public void setLatestEdition(long latestEdition) {
333 if (!(latestEdition > this.latestEdition)) {
334 logger.log(Level.FINE, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
337 this.latestEdition = latestEdition;
341 * Return the time of the last inserted update of this Sone.
343 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
345 public long getTime() {
350 * Sets the time of the last inserted update of this Sone.
353 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
354 * @return This Sone (for method chaining)
356 public Sone setTime(long time) {
362 * Returns a copy of the profile. If you want to update values in the
363 * profile of this Sone, update the values in the returned {@link Profile}
364 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
366 * @return A copy of the profile
368 public synchronized Profile getProfile() {
369 return new Profile(profile);
373 * Sets the profile of this Sone. A copy of the given profile is stored so
374 * that subsequent modifications of the given profile are not reflected in
380 public synchronized void setProfile(Profile profile) {
381 this.profile = new Profile(profile);
385 * Returns the client used by this Sone.
387 * @return The client used by this Sone, or {@code null}
389 public Client getClient() {
394 * Sets the client used by this Sone.
397 * The client used by this Sone, or {@code null}
398 * @return This Sone (for method chaining)
400 public Sone setClient(Client client) {
401 this.client = client;
406 * Returns all friend Sones of this Sone.
408 * @return The friend Sones of this Sone
410 public List<String> getFriends() {
411 List<String> friends = new ArrayList<String>(friendSones);
416 * Returns whether this Sone has the given Sone as a friend Sone.
418 * @param friendSoneId
419 * The ID of the Sone to check for
420 * @return {@code true} if this Sone has the given Sone as a friend,
421 * {@code false} otherwise
423 public boolean hasFriend(String friendSoneId) {
424 return friendSones.contains(friendSoneId);
428 * Adds the given Sone as a friend Sone.
431 * The friend Sone to add
432 * @return This Sone (for method chaining)
434 public Sone addFriend(String friendSone) {
435 if (!friendSone.equals(id)) {
436 friendSones.add(friendSone);
442 * Removes the given Sone as a friend Sone.
444 * @param friendSoneId
445 * The ID of the friend Sone to remove
446 * @return This Sone (for method chaining)
448 public Sone removeFriend(String friendSoneId) {
449 friendSones.remove(friendSoneId);
454 * Returns the list of posts of this Sone, sorted by time, newest first.
456 * @return All posts of this Sone
458 public List<Post> getPosts() {
459 List<Post> sortedPosts;
460 synchronized (this) {
461 sortedPosts = new ArrayList<Post>(posts);
463 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
468 * Sets all posts of this Sone at once.
471 * The new (and only) posts of this Sone
472 * @return This Sone (for method chaining)
474 public synchronized Sone setPosts(Collection<Post> posts) {
475 synchronized (this) {
477 this.posts.addAll(posts);
483 * Adds the given post to this Sone. The post will not be added if its
484 * {@link Post#getSone() Sone} is not this Sone.
489 public synchronized void addPost(Post post) {
490 if (post.getSone().equals(this) && posts.add(post)) {
491 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
496 * Removes the given post from this Sone.
501 public synchronized void removePost(Post post) {
502 if (post.getSone().equals(this)) {
508 * Returns all replies this Sone made.
510 * @return All replies this Sone made
512 public synchronized Set<PostReply> getReplies() {
513 return Collections.unmodifiableSet(replies);
517 * Sets all replies of this Sone at once.
520 * The new (and only) replies of this Sone
521 * @return This Sone (for method chaining)
523 public synchronized Sone setReplies(Collection<PostReply> replies) {
524 this.replies.clear();
525 this.replies.addAll(replies);
530 * Adds a reply to this Sone. If the given reply was not made by this Sone,
531 * nothing is added to this Sone.
536 public synchronized void addReply(PostReply reply) {
537 if (reply.getSone().equals(this)) {
543 * Removes a reply from this Sone.
546 * The reply to remove
548 public synchronized void removeReply(PostReply reply) {
549 if (reply.getSone().equals(this)) {
550 replies.remove(reply);
555 * Returns the IDs of all liked posts.
557 * @return All liked posts’ IDs
559 public Set<String> getLikedPostIds() {
560 return Collections.unmodifiableSet(likedPostIds);
564 * Sets the IDs of all liked posts.
566 * @param likedPostIds
567 * All liked posts’ IDs
568 * @return This Sone (for method chaining)
570 public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
571 this.likedPostIds.clear();
572 this.likedPostIds.addAll(likedPostIds);
577 * Checks whether the given post ID is liked by this Sone.
581 * @return {@code true} if this Sone likes the given post, {@code false}
584 public boolean isLikedPostId(String postId) {
585 return likedPostIds.contains(postId);
589 * Adds the given post ID to the list of posts this Sone likes.
593 * @return This Sone (for method chaining)
595 public synchronized Sone addLikedPostId(String postId) {
596 likedPostIds.add(postId);
601 * Removes the given post ID from the list of posts this Sone likes.
605 * @return This Sone (for method chaining)
607 public synchronized Sone removeLikedPostId(String postId) {
608 likedPostIds.remove(postId);
613 * Returns the IDs of all liked replies.
615 * @return All liked replies’ IDs
617 public Set<String> getLikedReplyIds() {
618 return Collections.unmodifiableSet(likedReplyIds);
622 * Sets the IDs of all liked replies.
624 * @param likedReplyIds
625 * All liked replies’ IDs
626 * @return This Sone (for method chaining)
628 public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
629 this.likedReplyIds.clear();
630 this.likedReplyIds.addAll(likedReplyIds);
635 * Checks whether the given reply ID is liked by this Sone.
638 * The ID of the reply
639 * @return {@code true} if this Sone likes the given reply, {@code false}
642 public boolean isLikedReplyId(String replyId) {
643 return likedReplyIds.contains(replyId);
647 * Adds the given reply ID to the list of replies this Sone likes.
650 * The ID of the reply
651 * @return This Sone (for method chaining)
653 public synchronized Sone addLikedReplyId(String replyId) {
654 likedReplyIds.add(replyId);
659 * Removes the given post ID from the list of replies this Sone likes.
662 * The ID of the reply
663 * @return This Sone (for method chaining)
665 public synchronized Sone removeLikedReplyId(String replyId) {
666 likedReplyIds.remove(replyId);
671 * Returns the albums of this Sone.
673 * @return The albums of this Sone
675 public List<Album> getAlbums() {
676 return Collections.unmodifiableList(albums);
680 * Returns a flattened list of all albums of this Sone. The resulting list
681 * contains parent albums before child albums so that the resulting list can
682 * be parsed in a single pass.
684 * @return The flattened albums
686 public List<Album> getAllAlbums() {
687 List<Album> flatAlbums = new ArrayList<Album>();
688 flatAlbums.addAll(albums);
689 int lastAlbumIndex = 0;
690 while (lastAlbumIndex < flatAlbums.size()) {
691 int previousAlbumCount = flatAlbums.size();
692 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
693 flatAlbums.addAll(album.getAlbums());
695 lastAlbumIndex = previousAlbumCount;
701 * Returns all images of a Sone. Images of a album are inserted into this
702 * list before images of all child albums.
704 * @return The list of all images
706 public List<Image> getAllImages() {
707 List<Image> allImages = new ArrayList<Image>();
708 for (Album album : getAllAlbums()) {
709 allImages.addAll(album.getImages());
715 * Adds an album to this Sone.
720 public synchronized void addAlbum(Album album) {
721 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
726 * Sets the albums of this Sone.
729 * The albums of this Sone
731 public synchronized void setAlbums(Collection<? extends Album> albums) {
732 Validation.begin().isNotNull("Albums", albums).check();
734 for (Album album : albums) {
740 * Removes an album from this Sone.
743 * The album to remove
745 public synchronized void removeAlbum(Album album) {
746 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
747 albums.remove(album);
751 * Moves the given album up in this album’s albums. If the album is already
752 * the first album, nothing happens.
755 * The album to move up
756 * @return The album that the given album swapped the place with, or
757 * <code>null</code> if the album did not change its place
759 public Album moveAlbumUp(Album album) {
760 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
761 int oldIndex = albums.indexOf(album);
765 albums.remove(oldIndex);
766 albums.add(oldIndex - 1, album);
767 return albums.get(oldIndex);
771 * Moves the given album down in this album’s albums. If the album is
772 * already the last album, nothing happens.
775 * The album to move down
776 * @return The album that the given album swapped the place with, or
777 * <code>null</code> if the album did not change its place
779 public Album moveAlbumDown(Album album) {
780 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
781 int oldIndex = albums.indexOf(album);
782 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
785 albums.remove(oldIndex);
786 albums.add(oldIndex + 1, album);
787 return albums.get(oldIndex);
791 * Returns Sone-specific options.
793 * @return The options of this Sone
795 public Options getOptions() {
800 // FINGERPRINTABLE METHODS
807 public synchronized String getFingerprint() {
808 StringBuilder fingerprint = new StringBuilder();
809 fingerprint.append(profile.getFingerprint());
811 fingerprint.append("Posts(");
812 for (Post post : getPosts()) {
813 fingerprint.append("Post(").append(post.getId()).append(')');
815 fingerprint.append(")");
817 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
818 Collections.sort(replies, Reply.TIME_COMPARATOR);
819 fingerprint.append("Replies(");
820 for (PostReply reply : replies) {
821 fingerprint.append("Reply(").append(reply.getId()).append(')');
823 fingerprint.append(')');
825 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
826 Collections.sort(likedPostIds);
827 fingerprint.append("LikedPosts(");
828 for (String likedPostId : likedPostIds) {
829 fingerprint.append("Post(").append(likedPostId).append(')');
831 fingerprint.append(')');
833 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
834 Collections.sort(likedReplyIds);
835 fingerprint.append("LikedReplies(");
836 for (String likedReplyId : likedReplyIds) {
837 fingerprint.append("Reply(").append(likedReplyId).append(')');
839 fingerprint.append(')');
841 fingerprint.append("Albums(");
842 for (Album album : albums) {
843 fingerprint.append(album.getFingerprint());
845 fingerprint.append(')');
847 return fingerprint.toString();
851 // INTERFACE Comparable<Sone>
858 public int compareTo(Sone sone) {
859 return NICE_NAME_COMPARATOR.compare(this, sone);
870 public int hashCode() {
871 return id.hashCode();
878 public boolean equals(Object object) {
879 if (!(object instanceof Sone)) {
882 return ((Sone) object).id.equals(id);
889 public String toString() {
890 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";