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 /** Whether the Sone is local. */
179 private final boolean local;
181 /** The identity of this Sone. */
182 private Identity identity;
184 /** The URI under which the Sone is stored in Freenet. */
185 private volatile FreenetURI requestUri;
187 /** The URI used to insert a new version of this Sone. */
188 /* This will be null for remote Sones! */
189 private volatile FreenetURI insertUri;
191 /** The latest edition of the Sone. */
192 private volatile long latestEdition;
194 /** The time of the last inserted update. */
195 private volatile long time;
197 /** The status of this Sone. */
198 private volatile SoneStatus status = SoneStatus.unknown;
200 /** The profile of this Sone. */
201 private volatile Profile profile = new Profile(this);
203 /** The client used by the Sone. */
204 private volatile Client client;
206 /** Whether this Sone is known. */
207 private volatile boolean known;
209 /** All friend Sones. */
210 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
213 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
216 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
218 /** The IDs of all liked posts. */
219 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
221 /** The IDs of all liked replies. */
222 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
224 /** The albums of this Sone. */
225 private final List<Album> albums = new CopyOnWriteArrayList<Album>();
227 /** Sone-specific options. */
228 private final Options options = new Options();
231 * Creates a new Sone.
236 * {@code true} if the Sone is a local Sone, {@code false}
239 public Sone(String id, boolean local) {
249 * Returns the identity of this Sone.
251 * @return The identity of this Sone
253 public String getId() {
258 * Returns the identity of this Sone.
260 * @return The identity of this Sone
262 public Identity getIdentity() {
267 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
268 * identity has to match this Sone’s {@link #getId()}.
271 * The identity of this Sone
272 * @return This Sone (for method chaining)
273 * @throws IllegalArgumentException
274 * if the ID of the identity does not match this Sone’s ID
276 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
277 if (!identity.getId().equals(id)) {
278 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
280 this.identity = identity;
285 * Returns the name of this Sone.
287 * @return The name of this Sone
289 public String getName() {
290 return (identity != null) ? identity.getNickname() : null;
294 * Returns whether this Sone is a local Sone.
296 * @return {@code true} if this Sone is a local Sone, {@code false}
299 public boolean isLocal() {
304 * Returns the request URI of this Sone.
306 * @return The request URI of this Sone
308 public FreenetURI getRequestUri() {
309 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
313 * Sets the request URI of this Sone.
316 * The request URI of this Sone
317 * @return This Sone (for method chaining)
319 public Sone setRequestUri(FreenetURI requestUri) {
320 if (this.requestUri == null) {
321 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
324 if (!this.requestUri.equalsKeypair(requestUri)) {
325 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
332 * Returns the insert URI of this Sone.
334 * @return The insert URI of this Sone
336 public FreenetURI getInsertUri() {
337 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
341 * Sets the insert URI of this Sone.
344 * The insert URI of this Sone
345 * @return This Sone (for method chaining)
347 public Sone setInsertUri(FreenetURI insertUri) {
348 if (this.insertUri == null) {
349 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
352 if (!this.insertUri.equalsKeypair(insertUri)) {
353 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
360 * Returns the latest edition of this Sone.
362 * @return The latest edition of this Sone
364 public long getLatestEdition() {
365 return latestEdition;
369 * Sets the latest edition of this Sone. If the given latest edition is not
370 * greater than the current latest edition, the latest edition of this Sone
373 * @param latestEdition
374 * The latest edition of this Sone
376 public void setLatestEdition(long latestEdition) {
377 if (!(latestEdition > this.latestEdition)) {
378 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
381 this.latestEdition = latestEdition;
385 * Return the time of the last inserted update of this Sone.
387 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
389 public long getTime() {
394 * Sets the time of the last inserted update of this Sone.
397 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
398 * @return This Sone (for method chaining)
400 public Sone setTime(long time) {
406 * Returns the status of this Sone.
408 * @return The status of this Sone
410 public SoneStatus getStatus() {
415 * Sets the new status of this Sone.
418 * The new status of this Sone
420 * @throws IllegalArgumentException
421 * if {@code status} is {@code null}
423 public Sone setStatus(SoneStatus status) {
424 Validation.begin().isNotNull("Sone Status", status).check();
425 this.status = status;
430 * Returns a copy of the profile. If you want to update values in the
431 * profile of this Sone, update the values in the returned {@link Profile}
432 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
434 * @return A copy of the profile
436 public Profile getProfile() {
437 return new Profile(profile);
441 * Sets the profile of this Sone. A copy of the given profile is stored so
442 * that subsequent modifications of the given profile are not reflected in
448 public void setProfile(Profile profile) {
449 this.profile = new Profile(profile);
453 * Returns the client used by this Sone.
455 * @return The client used by this Sone, or {@code null}
457 public Client getClient() {
462 * Sets the client used by this Sone.
465 * The client used by this Sone, or {@code null}
466 * @return This Sone (for method chaining)
468 public Sone setClient(Client client) {
469 this.client = client;
474 * Returns whether this Sone is known.
476 * @return {@code true} if this Sone is known, {@code false} otherwise
478 public boolean isKnown() {
483 * Sets whether this Sone is known.
486 * {@code true} if this Sone is known, {@code false} otherwise
489 public Sone setKnown(boolean known) {
495 * Returns all friend Sones of this Sone.
497 * @return The friend Sones of this Sone
499 public List<String> getFriends() {
500 List<String> friends = new ArrayList<String>(friendSones);
505 * Returns whether this Sone has the given Sone as a friend Sone.
507 * @param friendSoneId
508 * The ID of the Sone to check for
509 * @return {@code true} if this Sone has the given Sone as a friend,
510 * {@code false} otherwise
512 public boolean hasFriend(String friendSoneId) {
513 return friendSones.contains(friendSoneId);
517 * Adds the given Sone as a friend Sone.
520 * The friend Sone to add
521 * @return This Sone (for method chaining)
523 public Sone addFriend(String friendSone) {
524 if (!friendSone.equals(id)) {
525 friendSones.add(friendSone);
531 * Removes the given Sone as a friend Sone.
533 * @param friendSoneId
534 * The ID of the friend Sone to remove
535 * @return This Sone (for method chaining)
537 public Sone removeFriend(String friendSoneId) {
538 friendSones.remove(friendSoneId);
543 * Returns the list of posts of this Sone, sorted by time, newest first.
545 * @return All posts of this Sone
547 public List<Post> getPosts() {
548 List<Post> sortedPosts;
549 synchronized (this) {
550 sortedPosts = new ArrayList<Post>(posts);
552 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
557 * Sets all posts of this Sone at once.
560 * The new (and only) posts of this Sone
561 * @return This Sone (for method chaining)
563 public Sone setPosts(Collection<Post> posts) {
564 synchronized (this) {
566 this.posts.addAll(posts);
572 * Adds the given post to this Sone. The post will not be added if its
573 * {@link Post#getSone() Sone} is not this Sone.
578 public void addPost(Post post) {
579 if (post.getSone().equals(this) && posts.add(post)) {
580 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
585 * Removes the given post from this Sone.
590 public void removePost(Post post) {
591 if (post.getSone().equals(this)) {
597 * Returns all replies this Sone made.
599 * @return All replies this Sone made
601 public Set<PostReply> getReplies() {
602 return Collections.unmodifiableSet(replies);
606 * Sets all replies of this Sone at once.
609 * The new (and only) replies of this Sone
610 * @return This Sone (for method chaining)
612 public Sone setReplies(Collection<PostReply> replies) {
613 this.replies.clear();
614 this.replies.addAll(replies);
619 * Adds a reply to this Sone. If the given reply was not made by this Sone,
620 * nothing is added to this Sone.
625 public void addReply(PostReply reply) {
626 if (reply.getSone().equals(this)) {
632 * Removes a reply from this Sone.
635 * The reply to remove
637 public void removeReply(PostReply reply) {
638 if (reply.getSone().equals(this)) {
639 replies.remove(reply);
644 * Returns the IDs of all liked posts.
646 * @return All liked posts’ IDs
648 public Set<String> getLikedPostIds() {
649 return Collections.unmodifiableSet(likedPostIds);
653 * Sets the IDs of all liked posts.
655 * @param likedPostIds
656 * All liked posts’ IDs
657 * @return This Sone (for method chaining)
659 public Sone setLikePostIds(Set<String> likedPostIds) {
660 this.likedPostIds.clear();
661 this.likedPostIds.addAll(likedPostIds);
666 * Checks whether the given post ID is liked by this Sone.
670 * @return {@code true} if this Sone likes the given post, {@code false}
673 public boolean isLikedPostId(String postId) {
674 return likedPostIds.contains(postId);
678 * Adds the given post ID to the list of posts this Sone likes.
682 * @return This Sone (for method chaining)
684 public Sone addLikedPostId(String postId) {
685 likedPostIds.add(postId);
690 * Removes the given post ID from the list of posts this Sone likes.
694 * @return This Sone (for method chaining)
696 public Sone removeLikedPostId(String postId) {
697 likedPostIds.remove(postId);
702 * Returns the IDs of all liked replies.
704 * @return All liked replies’ IDs
706 public Set<String> getLikedReplyIds() {
707 return Collections.unmodifiableSet(likedReplyIds);
711 * Sets the IDs of all liked replies.
713 * @param likedReplyIds
714 * All liked replies’ IDs
715 * @return This Sone (for method chaining)
717 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
718 this.likedReplyIds.clear();
719 this.likedReplyIds.addAll(likedReplyIds);
724 * Checks whether the given reply ID is liked by this Sone.
727 * The ID of the reply
728 * @return {@code true} if this Sone likes the given reply, {@code false}
731 public boolean isLikedReplyId(String replyId) {
732 return likedReplyIds.contains(replyId);
736 * Adds the given reply ID to the list of replies this Sone likes.
739 * The ID of the reply
740 * @return This Sone (for method chaining)
742 public Sone addLikedReplyId(String replyId) {
743 likedReplyIds.add(replyId);
748 * Removes the given post ID from the list of replies this Sone likes.
751 * The ID of the reply
752 * @return This Sone (for method chaining)
754 public Sone removeLikedReplyId(String replyId) {
755 likedReplyIds.remove(replyId);
760 * Returns the albums of this Sone.
762 * @return The albums of this Sone
764 public List<Album> getAlbums() {
765 return Collections.unmodifiableList(albums);
769 * Returns a flattened list of all albums of this Sone. The resulting list
770 * contains parent albums before child albums so that the resulting list can
771 * be parsed in a single pass.
773 * @return The flattened albums
775 public List<Album> getAllAlbums() {
776 List<Album> flatAlbums = new ArrayList<Album>();
777 flatAlbums.addAll(albums);
778 int lastAlbumIndex = 0;
779 while (lastAlbumIndex < flatAlbums.size()) {
780 int previousAlbumCount = flatAlbums.size();
781 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
782 flatAlbums.addAll(album.getAlbums());
784 lastAlbumIndex = previousAlbumCount;
790 * Returns all images of a Sone. Images of a album are inserted into this
791 * list before images of all child albums.
793 * @return The list of all images
795 public List<Image> getAllImages() {
796 List<Image> allImages = new ArrayList<Image>();
797 for (Album album : getAllAlbums()) {
798 allImages.addAll(album.getImages());
804 * Adds an album to this Sone.
809 public void addAlbum(Album album) {
810 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
811 if (!albums.contains(album)) {
817 * Sets the albums of this Sone.
820 * The albums of this Sone
822 public void setAlbums(Collection<? extends Album> albums) {
823 Validation.begin().isNotNull("Albums", albums).check();
825 for (Album album : albums) {
831 * Removes an album from this Sone.
834 * The album to remove
836 public void removeAlbum(Album album) {
837 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
838 albums.remove(album);
842 * Moves the given album up in this album’s albums. If the album is already
843 * the first album, nothing happens.
846 * The album to move up
847 * @return The album that the given album swapped the place with, or
848 * <code>null</code> if the album did not change its place
850 public Album moveAlbumUp(Album album) {
851 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
852 int oldIndex = albums.indexOf(album);
856 albums.remove(oldIndex);
857 albums.add(oldIndex - 1, album);
858 return albums.get(oldIndex);
862 * Moves the given album down in this album’s albums. If the album is
863 * already the last album, nothing happens.
866 * The album to move down
867 * @return The album that the given album swapped the place with, or
868 * <code>null</code> if the album did not change its place
870 public Album moveAlbumDown(Album album) {
871 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
872 int oldIndex = albums.indexOf(album);
873 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
876 albums.remove(oldIndex);
877 albums.add(oldIndex + 1, album);
878 return albums.get(oldIndex);
882 * Returns Sone-specific options.
884 * @return The options of this Sone
886 public Options getOptions() {
891 // FINGERPRINTABLE METHODS
898 public synchronized String getFingerprint() {
899 StringBuilder fingerprint = new StringBuilder();
900 fingerprint.append(profile.getFingerprint());
902 fingerprint.append("Posts(");
903 for (Post post : getPosts()) {
904 fingerprint.append("Post(").append(post.getId()).append(')');
906 fingerprint.append(")");
908 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
909 Collections.sort(replies, Reply.TIME_COMPARATOR);
910 fingerprint.append("Replies(");
911 for (PostReply reply : replies) {
912 fingerprint.append("Reply(").append(reply.getId()).append(')');
914 fingerprint.append(')');
916 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
917 Collections.sort(likedPostIds);
918 fingerprint.append("LikedPosts(");
919 for (String likedPostId : likedPostIds) {
920 fingerprint.append("Post(").append(likedPostId).append(')');
922 fingerprint.append(')');
924 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
925 Collections.sort(likedReplyIds);
926 fingerprint.append("LikedReplies(");
927 for (String likedReplyId : likedReplyIds) {
928 fingerprint.append("Reply(").append(likedReplyId).append(')');
930 fingerprint.append(')');
932 fingerprint.append("Albums(");
933 for (Album album : albums) {
934 fingerprint.append(album.getFingerprint());
936 fingerprint.append(')');
938 return fingerprint.toString();
942 // INTERFACE Comparable<Sone>
949 public int compareTo(Sone sone) {
950 return NICE_NAME_COMPARATOR.compare(this, sone);
961 public int hashCode() {
962 return id.hashCode();
969 public boolean equals(Object object) {
970 if (!(object instanceof Sone)) {
973 return ((Sone) object).id.equals(id);
980 public String toString() {
981 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";