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.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.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 /** All friend Sones. */
204 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
207 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
210 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
212 /** The IDs of all liked posts. */
213 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
215 /** The IDs of all liked replies. */
216 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
218 /** The albums of this Sone. */
219 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
221 /** Sone-specific options. */
222 private final Options options = new Options();
225 * Creates a new Sone.
230 public Sone(String id) {
239 * Returns the identity of this Sone.
241 * @return The identity of this Sone
243 public String getId() {
248 * Returns the identity of this Sone.
250 * @return The identity of this Sone
252 public Identity getIdentity() {
257 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
258 * identity has to match this Sone’s {@link #getId()}.
261 * The identity of this Sone
262 * @return This Sone (for method chaining)
263 * @throws IllegalArgumentException
264 * if the ID of the identity does not match this Sone’s ID
266 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
267 if (!identity.getId().equals(id)) {
268 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
270 this.identity = identity;
275 * Returns the name of this Sone.
277 * @return The name of this Sone
279 public String getName() {
280 return (identity != null) ? identity.getNickname() : null;
284 * Returns the request URI of this Sone.
286 * @return The request URI of this Sone
288 public FreenetURI getRequestUri() {
289 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
293 * Sets the request URI of this Sone.
296 * The request URI of this Sone
297 * @return This Sone (for method chaining)
299 public Sone setRequestUri(FreenetURI requestUri) {
300 if (this.requestUri == null) {
301 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
304 if (!this.requestUri.equalsKeypair(requestUri)) {
305 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
312 * Returns the insert URI of this Sone.
314 * @return The insert URI of this Sone
316 public FreenetURI getInsertUri() {
317 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
321 * Sets the insert URI of this Sone.
324 * The insert URI of this Sone
325 * @return This Sone (for method chaining)
327 public Sone setInsertUri(FreenetURI insertUri) {
328 if (this.insertUri == null) {
329 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
332 if (!this.insertUri.equalsKeypair(insertUri)) {
333 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
340 * Returns the latest edition of this Sone.
342 * @return The latest edition of this Sone
344 public long getLatestEdition() {
345 return latestEdition;
349 * Sets the latest edition of this Sone. If the given latest edition is not
350 * greater than the current latest edition, the latest edition of this Sone
353 * @param latestEdition
354 * The latest edition of this Sone
356 public void setLatestEdition(long latestEdition) {
357 if (!(latestEdition > this.latestEdition)) {
358 logger.log(Level.FINE, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
361 this.latestEdition = latestEdition;
365 * Return the time of the last inserted update of this Sone.
367 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
369 public long getTime() {
374 * Sets the time of the last inserted update of this Sone.
377 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
378 * @return This Sone (for method chaining)
380 public Sone setTime(long time) {
386 * Returns the status of this Sone.
388 * @return The status of this Sone
390 public SoneStatus getStatus() {
395 * Sets the new status of this Sone.
398 * The new status of this Sone
400 * @throws IllegalArgumentException
401 * if {@code status} is {@code null}
403 public Sone setStatus(SoneStatus status) {
404 Validation.begin().isNotNull("Sone Status", status).check();
405 this.status = status;
410 * Returns a copy of the profile. If you want to update values in the
411 * profile of this Sone, update the values in the returned {@link Profile}
412 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
414 * @return A copy of the profile
416 public Profile getProfile() {
417 return new Profile(profile);
421 * Sets the profile of this Sone. A copy of the given profile is stored so
422 * that subsequent modifications of the given profile are not reflected in
428 public void setProfile(Profile profile) {
429 this.profile = new Profile(profile);
433 * Returns the client used by this Sone.
435 * @return The client used by this Sone, or {@code null}
437 public Client getClient() {
442 * Sets the client used by this Sone.
445 * The client used by this Sone, or {@code null}
446 * @return This Sone (for method chaining)
448 public Sone setClient(Client client) {
449 this.client = client;
454 * Returns all friend Sones of this Sone.
456 * @return The friend Sones of this Sone
458 public List<String> getFriends() {
459 List<String> friends = new ArrayList<String>(friendSones);
464 * Returns whether this Sone has the given Sone as a friend Sone.
466 * @param friendSoneId
467 * The ID of the Sone to check for
468 * @return {@code true} if this Sone has the given Sone as a friend,
469 * {@code false} otherwise
471 public boolean hasFriend(String friendSoneId) {
472 return friendSones.contains(friendSoneId);
476 * Adds the given Sone as a friend Sone.
479 * The friend Sone to add
480 * @return This Sone (for method chaining)
482 public Sone addFriend(String friendSone) {
483 if (!friendSone.equals(id)) {
484 friendSones.add(friendSone);
490 * Removes the given Sone as a friend Sone.
492 * @param friendSoneId
493 * The ID of the friend Sone to remove
494 * @return This Sone (for method chaining)
496 public Sone removeFriend(String friendSoneId) {
497 friendSones.remove(friendSoneId);
502 * Returns the list of posts of this Sone, sorted by time, newest first.
504 * @return All posts of this Sone
506 public List<Post> getPosts() {
507 List<Post> sortedPosts;
508 synchronized (this) {
509 sortedPosts = new ArrayList<Post>(posts);
511 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
516 * Sets all posts of this Sone at once.
519 * The new (and only) posts of this Sone
520 * @return This Sone (for method chaining)
522 public Sone setPosts(Collection<Post> posts) {
523 synchronized (this) {
525 this.posts.addAll(posts);
531 * Adds the given post to this Sone. The post will not be added if its
532 * {@link Post#getSone() Sone} is not this Sone.
537 public void addPost(Post post) {
538 if (post.getSone().equals(this) && posts.add(post)) {
539 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
544 * Removes the given post from this Sone.
549 public void removePost(Post post) {
550 if (post.getSone().equals(this)) {
556 * Returns all replies this Sone made.
558 * @return All replies this Sone made
560 public Set<PostReply> getReplies() {
561 return Collections.unmodifiableSet(replies);
565 * Sets all replies of this Sone at once.
568 * The new (and only) replies of this Sone
569 * @return This Sone (for method chaining)
571 public Sone setReplies(Collection<PostReply> replies) {
572 this.replies.clear();
573 this.replies.addAll(replies);
578 * Adds a reply to this Sone. If the given reply was not made by this Sone,
579 * nothing is added to this Sone.
584 public void addReply(PostReply reply) {
585 if (reply.getSone().equals(this)) {
591 * Removes a reply from this Sone.
594 * The reply to remove
596 public void removeReply(PostReply reply) {
597 if (reply.getSone().equals(this)) {
598 replies.remove(reply);
603 * Returns the IDs of all liked posts.
605 * @return All liked posts’ IDs
607 public Set<String> getLikedPostIds() {
608 return Collections.unmodifiableSet(likedPostIds);
612 * Sets the IDs of all liked posts.
614 * @param likedPostIds
615 * All liked posts’ IDs
616 * @return This Sone (for method chaining)
618 public Sone setLikePostIds(Set<String> likedPostIds) {
619 this.likedPostIds.clear();
620 this.likedPostIds.addAll(likedPostIds);
625 * Checks whether the given post ID is liked by this Sone.
629 * @return {@code true} if this Sone likes the given post, {@code false}
632 public boolean isLikedPostId(String postId) {
633 return likedPostIds.contains(postId);
637 * Adds the given post ID to the list of posts this Sone likes.
641 * @return This Sone (for method chaining)
643 public Sone addLikedPostId(String postId) {
644 likedPostIds.add(postId);
649 * Removes the given post ID from the list of posts this Sone likes.
653 * @return This Sone (for method chaining)
655 public Sone removeLikedPostId(String postId) {
656 likedPostIds.remove(postId);
661 * Returns the IDs of all liked replies.
663 * @return All liked replies’ IDs
665 public Set<String> getLikedReplyIds() {
666 return Collections.unmodifiableSet(likedReplyIds);
670 * Sets the IDs of all liked replies.
672 * @param likedReplyIds
673 * All liked replies’ IDs
674 * @return This Sone (for method chaining)
676 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
677 this.likedReplyIds.clear();
678 this.likedReplyIds.addAll(likedReplyIds);
683 * Checks whether the given reply ID is liked by this Sone.
686 * The ID of the reply
687 * @return {@code true} if this Sone likes the given reply, {@code false}
690 public boolean isLikedReplyId(String replyId) {
691 return likedReplyIds.contains(replyId);
695 * Adds the given reply ID to the list of replies this Sone likes.
698 * The ID of the reply
699 * @return This Sone (for method chaining)
701 public Sone addLikedReplyId(String replyId) {
702 likedReplyIds.add(replyId);
707 * Removes the given post ID from the list of replies this Sone likes.
710 * The ID of the reply
711 * @return This Sone (for method chaining)
713 public Sone removeLikedReplyId(String replyId) {
714 likedReplyIds.remove(replyId);
719 * Returns the albums of this Sone.
721 * @return The albums of this Sone
723 public List<Album> getAlbums() {
724 return Collections.unmodifiableList(albums);
728 * Returns a flattened list of all albums of this Sone. The resulting list
729 * contains parent albums before child albums so that the resulting list can
730 * be parsed in a single pass.
732 * @return The flattened albums
734 public List<Album> getAllAlbums() {
735 List<Album> flatAlbums = new ArrayList<Album>();
736 flatAlbums.addAll(albums);
737 int lastAlbumIndex = 0;
738 while (lastAlbumIndex < flatAlbums.size()) {
739 int previousAlbumCount = flatAlbums.size();
740 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
741 flatAlbums.addAll(album.getAlbums());
743 lastAlbumIndex = previousAlbumCount;
749 * Returns all images of a Sone. Images of a album are inserted into this
750 * list before images of all child albums.
752 * @return The list of all images
754 public List<Image> getAllImages() {
755 List<Image> allImages = new ArrayList<Image>();
756 for (Album album : getAllAlbums()) {
757 allImages.addAll(album.getImages());
763 * Adds an album to this Sone.
768 public void addAlbum(Album album) {
769 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
774 * Sets the albums of this Sone.
777 * The albums of this Sone
779 public void setAlbums(Collection<? extends Album> albums) {
780 Validation.begin().isNotNull("Albums", albums).check();
782 for (Album album : albums) {
788 * Removes an album from this Sone.
791 * The album to remove
793 public void removeAlbum(Album album) {
794 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
795 albums.remove(album);
799 * Moves the given album up in this album’s albums. If the album is already
800 * the first album, nothing happens.
803 * The album to move up
804 * @return The album that the given album swapped the place with, or
805 * <code>null</code> if the album did not change its place
807 public Album moveAlbumUp(Album album) {
808 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
809 int oldIndex = albums.indexOf(album);
813 albums.remove(oldIndex);
814 albums.add(oldIndex - 1, album);
815 return albums.get(oldIndex);
819 * Moves the given album down in this album’s albums. If the album is
820 * already the last album, nothing happens.
823 * The album to move down
824 * @return The album that the given album swapped the place with, or
825 * <code>null</code> if the album did not change its place
827 public Album moveAlbumDown(Album album) {
828 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
829 int oldIndex = albums.indexOf(album);
830 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
833 albums.remove(oldIndex);
834 albums.add(oldIndex + 1, album);
835 return albums.get(oldIndex);
839 * Returns Sone-specific options.
841 * @return The options of this Sone
843 public Options getOptions() {
848 // FINGERPRINTABLE METHODS
855 public synchronized String getFingerprint() {
856 StringBuilder fingerprint = new StringBuilder();
857 fingerprint.append(profile.getFingerprint());
859 fingerprint.append("Posts(");
860 for (Post post : getPosts()) {
861 fingerprint.append("Post(").append(post.getId()).append(')');
863 fingerprint.append(")");
865 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
866 Collections.sort(replies, Reply.TIME_COMPARATOR);
867 fingerprint.append("Replies(");
868 for (PostReply reply : replies) {
869 fingerprint.append("Reply(").append(reply.getId()).append(')');
871 fingerprint.append(')');
873 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
874 Collections.sort(likedPostIds);
875 fingerprint.append("LikedPosts(");
876 for (String likedPostId : likedPostIds) {
877 fingerprint.append("Post(").append(likedPostId).append(')');
879 fingerprint.append(')');
881 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
882 Collections.sort(likedReplyIds);
883 fingerprint.append("LikedReplies(");
884 for (String likedReplyId : likedReplyIds) {
885 fingerprint.append("Reply(").append(likedReplyId).append(')');
887 fingerprint.append(')');
889 fingerprint.append("Albums(");
890 for (Album album : albums) {
891 fingerprint.append(album.getFingerprint());
893 fingerprint.append(')');
895 return fingerprint.toString();
899 // INTERFACE Comparable<Sone>
906 public int compareTo(Sone sone) {
907 return NICE_NAME_COMPARATOR.compare(this, sone);
918 public int hashCode() {
919 return id.hashCode();
926 public boolean equals(Object object) {
927 if (!(object instanceof Sone)) {
930 return ((Sone) object).id.equals(id);
937 public String toString() {
938 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";