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> {
50 /** comparator that sorts Sones by their nice name. */
51 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
54 public int compare(Sone leftSone, Sone rightSone) {
55 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
59 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
65 * Comparator that sorts Sones by last activity (least recent active first).
67 public static final Comparator<Sone> LAST_ACTIVITY_COMPARATOR = new Comparator<Sone>() {
70 public int compare(Sone firstSone, Sone secondSone) {
71 return (int) Math.min(Integer.MAX_VALUE, Math.max(Integer.MIN_VALUE, secondSone.getTime() - firstSone.getTime()));
75 /** Comparator that sorts Sones by numbers of posts (descending). */
76 public static final Comparator<Sone> POST_COUNT_COMPARATOR = new Comparator<Sone>() {
82 public int compare(Sone leftSone, Sone rightSone) {
83 return (leftSone.getPosts().size() != rightSone.getPosts().size()) ? (rightSone.getPosts().size() - leftSone.getPosts().size()) : (rightSone.getReplies().size() - leftSone.getReplies().size());
87 /** Comparator that sorts Sones by number of images (descending). */
88 public static final Comparator<Sone> IMAGE_COUNT_COMPARATOR = new Comparator<Sone>() {
94 public int compare(Sone leftSone, Sone rightSone) {
95 return rightSone.getAllImages().size() - leftSone.getAllImages().size();
99 /** Filter to remove Sones that have not been downloaded. */
100 public static final Filter<Sone> EMPTY_SONE_FILTER = new Filter<Sone>() {
103 public boolean filterObject(Sone sone) {
104 return sone.getTime() != 0;
108 /** Filter that matches all {@link Core#isLocalSone(Sone) local Sones}. */
109 public static final Filter<Sone> LOCAL_SONE_FILTER = new Filter<Sone>() {
112 public boolean filterObject(Sone sone) {
113 return sone.getIdentity() instanceof OwnIdentity;
118 /** Filter that matches Sones that have at least one album. */
119 public static final Filter<Sone> HAS_ALBUM_FILTER = new Filter<Sone>() {
122 public boolean filterObject(Sone sone) {
123 return !sone.getAlbums().isEmpty();
128 private static final Logger logger = Logging.getLogger(Sone.class);
130 /** The ID of this Sone. */
131 private final String id;
133 /** The identity of this Sone. */
134 private Identity identity;
136 /** The URI under which the Sone is stored in Freenet. */
137 private volatile FreenetURI requestUri;
139 /** The URI used to insert a new version of this Sone. */
140 /* This will be null for remote Sones! */
141 private volatile FreenetURI insertUri;
143 /** The latest edition of the Sone. */
144 private volatile long latestEdition;
146 /** The time of the last inserted update. */
147 private volatile long time;
149 /** The profile of this Sone. */
150 private volatile Profile profile = new Profile();
152 /** The client used by the Sone. */
153 private volatile Client client;
155 /** All friend Sones. */
156 private final Set<String> friendSones = Collections.synchronizedSet(new HashSet<String>());
159 private final Set<Post> posts = Collections.synchronizedSet(new HashSet<Post>());
162 private final Set<PostReply> replies = Collections.synchronizedSet(new HashSet<PostReply>());
164 /** The IDs of all liked posts. */
165 private final Set<String> likedPostIds = Collections.synchronizedSet(new HashSet<String>());
167 /** The IDs of all liked replies. */
168 private final Set<String> likedReplyIds = Collections.synchronizedSet(new HashSet<String>());
170 /** The albums of this Sone. */
171 private final List<Album> albums = Collections.synchronizedList(new ArrayList<Album>());
173 /** Sone-specific options. */
174 private final Options options = new Options();
176 /** The avatar of this Sone. */
177 private volatile String avatar;
180 * Creates a new Sone.
185 public Sone(String id) {
194 * Returns the identity of this Sone.
196 * @return The identity of this Sone
198 public String getId() {
203 * Returns the identity of this Sone.
205 * @return The identity of this Sone
207 public Identity getIdentity() {
212 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
213 * identity has to match this Sone’s {@link #getId()}.
216 * The identity of this Sone
217 * @return This Sone (for method chaining)
218 * @throws IllegalArgumentException
219 * if the ID of the identity does not match this Sone’s ID
221 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
222 if (!identity.getId().equals(id)) {
223 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
225 this.identity = identity;
230 * Returns the name of this Sone.
232 * @return The name of this Sone
234 public String getName() {
235 return (identity != null) ? identity.getNickname() : null;
239 * Returns the request URI of this Sone.
241 * @return The request URI of this Sone
243 public FreenetURI getRequestUri() {
244 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
248 * Sets the request URI of this Sone.
251 * The request URI of this Sone
252 * @return This Sone (for method chaining)
254 public Sone setRequestUri(FreenetURI requestUri) {
255 if (this.requestUri == null) {
256 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
259 if (!this.requestUri.equalsKeypair(requestUri)) {
260 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
267 * Returns the insert URI of this Sone.
269 * @return The insert URI of this Sone
271 public FreenetURI getInsertUri() {
272 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
276 * Sets the insert URI of this Sone.
279 * The insert URI of this Sone
280 * @return This Sone (for method chaining)
282 public Sone setInsertUri(FreenetURI insertUri) {
283 if (this.insertUri == null) {
284 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
287 if (!this.insertUri.equalsKeypair(insertUri)) {
288 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
295 * Returns the latest edition of this Sone.
297 * @return The latest edition of this Sone
299 public long getLatestEdition() {
300 return latestEdition;
304 * Sets the latest edition of this Sone. If the given latest edition is not
305 * greater than the current latest edition, the latest edition of this Sone
308 * @param latestEdition
309 * The latest edition of this Sone
311 public void setLatestEdition(long latestEdition) {
312 if (!(latestEdition > this.latestEdition)) {
313 logger.log(Level.FINE, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
316 this.latestEdition = latestEdition;
320 * Return the time of the last inserted update of this Sone.
322 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
324 public long getTime() {
329 * Sets the time of the last inserted update of this Sone.
332 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
333 * @return This Sone (for method chaining)
335 public Sone setTime(long time) {
341 * Returns a copy of the profile. If you want to update values in the
342 * profile of this Sone, update the values in the returned {@link Profile}
343 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
345 * @return A copy of the profile
347 public synchronized Profile getProfile() {
348 return new Profile(profile);
352 * Sets the profile of this Sone. A copy of the given profile is stored so
353 * that subsequent modifications of the given profile are not reflected in
359 public synchronized void setProfile(Profile profile) {
360 this.profile = new Profile(profile);
364 * Returns the client used by this Sone.
366 * @return The client used by this Sone, or {@code null}
368 public Client getClient() {
373 * Sets the client used by this Sone.
376 * The client used by this Sone, or {@code null}
377 * @return This Sone (for method chaining)
379 public Sone setClient(Client client) {
380 this.client = client;
385 * Returns all friend Sones of this Sone.
387 * @return The friend Sones of this Sone
389 public List<String> getFriends() {
390 List<String> friends = new ArrayList<String>(friendSones);
395 * Returns whether this Sone has the given Sone as a friend Sone.
397 * @param friendSoneId
398 * The ID of the Sone to check for
399 * @return {@code true} if this Sone has the given Sone as a friend,
400 * {@code false} otherwise
402 public boolean hasFriend(String friendSoneId) {
403 return friendSones.contains(friendSoneId);
407 * Adds the given Sone as a friend Sone.
410 * The friend Sone to add
411 * @return This Sone (for method chaining)
413 public Sone addFriend(String friendSone) {
414 if (!friendSone.equals(id)) {
415 friendSones.add(friendSone);
421 * Removes the given Sone as a friend Sone.
423 * @param friendSoneId
424 * The ID of the friend Sone to remove
425 * @return This Sone (for method chaining)
427 public Sone removeFriend(String friendSoneId) {
428 friendSones.remove(friendSoneId);
433 * Returns the list of posts of this Sone, sorted by time, newest first.
435 * @return All posts of this Sone
437 public List<Post> getPosts() {
438 List<Post> sortedPosts;
439 synchronized (this) {
440 sortedPosts = new ArrayList<Post>(posts);
442 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
447 * Sets all posts of this Sone at once.
450 * The new (and only) posts of this Sone
451 * @return This Sone (for method chaining)
453 public synchronized Sone setPosts(Collection<Post> posts) {
454 synchronized (this) {
456 this.posts.addAll(posts);
462 * Adds the given post to this Sone. The post will not be added if its
463 * {@link Post#getSone() Sone} is not this Sone.
468 public synchronized void addPost(Post post) {
469 if (post.getSone().equals(this) && posts.add(post)) {
470 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
475 * Removes the given post from this Sone.
480 public synchronized void removePost(Post post) {
481 if (post.getSone().equals(this)) {
487 * Returns all replies this Sone made.
489 * @return All replies this Sone made
491 public synchronized Set<PostReply> getReplies() {
492 return Collections.unmodifiableSet(replies);
496 * Sets all replies of this Sone at once.
499 * The new (and only) replies of this Sone
500 * @return This Sone (for method chaining)
502 public synchronized Sone setReplies(Collection<PostReply> replies) {
503 this.replies.clear();
504 this.replies.addAll(replies);
509 * Adds a reply to this Sone. If the given reply was not made by this Sone,
510 * nothing is added to this Sone.
515 public synchronized void addReply(PostReply reply) {
516 if (reply.getSone().equals(this)) {
522 * Removes a reply from this Sone.
525 * The reply to remove
527 public synchronized void removeReply(PostReply reply) {
528 if (reply.getSone().equals(this)) {
529 replies.remove(reply);
534 * Returns the IDs of all liked posts.
536 * @return All liked posts’ IDs
538 public Set<String> getLikedPostIds() {
539 return Collections.unmodifiableSet(likedPostIds);
543 * Sets the IDs of all liked posts.
545 * @param likedPostIds
546 * All liked posts’ IDs
547 * @return This Sone (for method chaining)
549 public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
550 this.likedPostIds.clear();
551 this.likedPostIds.addAll(likedPostIds);
556 * Checks whether the given post ID is liked by this Sone.
560 * @return {@code true} if this Sone likes the given post, {@code false}
563 public boolean isLikedPostId(String postId) {
564 return likedPostIds.contains(postId);
568 * Adds the given post ID to the list of posts this Sone likes.
572 * @return This Sone (for method chaining)
574 public synchronized Sone addLikedPostId(String postId) {
575 likedPostIds.add(postId);
580 * Removes the given post ID from the list of posts this Sone likes.
584 * @return This Sone (for method chaining)
586 public synchronized Sone removeLikedPostId(String postId) {
587 likedPostIds.remove(postId);
592 * Returns the IDs of all liked replies.
594 * @return All liked replies’ IDs
596 public Set<String> getLikedReplyIds() {
597 return Collections.unmodifiableSet(likedReplyIds);
601 * Sets the IDs of all liked replies.
603 * @param likedReplyIds
604 * All liked replies’ IDs
605 * @return This Sone (for method chaining)
607 public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
608 this.likedReplyIds.clear();
609 this.likedReplyIds.addAll(likedReplyIds);
614 * Checks whether the given reply ID is liked by this Sone.
617 * The ID of the reply
618 * @return {@code true} if this Sone likes the given reply, {@code false}
621 public boolean isLikedReplyId(String replyId) {
622 return likedReplyIds.contains(replyId);
626 * Adds the given reply ID to the list of replies this Sone likes.
629 * The ID of the reply
630 * @return This Sone (for method chaining)
632 public synchronized Sone addLikedReplyId(String replyId) {
633 likedReplyIds.add(replyId);
638 * Removes the given post ID from the list of replies this Sone likes.
641 * The ID of the reply
642 * @return This Sone (for method chaining)
644 public synchronized Sone removeLikedReplyId(String replyId) {
645 likedReplyIds.remove(replyId);
650 * Returns the albums of this Sone.
652 * @return The albums of this Sone
654 public List<Album> getAlbums() {
655 return Collections.unmodifiableList(albums);
659 * Returns a flattened list of all albums of this Sone. The resulting list
660 * contains parent albums before child albums so that the resulting list can
661 * be parsed in a single pass.
663 * @return The flattened albums
665 public List<Album> getAllAlbums() {
666 List<Album> flatAlbums = new ArrayList<Album>();
667 flatAlbums.addAll(albums);
668 int lastAlbumIndex = 0;
669 while (lastAlbumIndex < flatAlbums.size()) {
670 int previousAlbumCount = flatAlbums.size();
671 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
672 flatAlbums.addAll(album.getAlbums());
674 lastAlbumIndex = previousAlbumCount;
680 * Returns all images of a Sone. Images of a album are inserted into this
681 * list before images of all child albums.
683 * @return The list of all images
685 public List<Image> getAllImages() {
686 List<Image> allImages = new ArrayList<Image>();
687 for (Album album : getAllAlbums()) {
688 allImages.addAll(album.getImages());
694 * Adds an album to this Sone.
699 public synchronized void addAlbum(Album album) {
700 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
705 * Sets the albums of this Sone.
708 * The albums of this Sone
710 public synchronized void setAlbums(Collection<? extends Album> albums) {
711 Validation.begin().isNotNull("Albums", albums).check();
713 for (Album album : albums) {
719 * Removes an album from this Sone.
722 * The album to remove
724 public synchronized void removeAlbum(Album album) {
725 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
726 albums.remove(album);
730 * Moves the given album up in this album’s albums. If the album is already
731 * the first album, nothing happens.
734 * The album to move up
735 * @return The album that the given album swapped the place with, or
736 * <code>null</code> if the album did not change its place
738 public Album moveAlbumUp(Album album) {
739 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
740 int oldIndex = albums.indexOf(album);
744 albums.remove(oldIndex);
745 albums.add(oldIndex - 1, album);
746 return albums.get(oldIndex);
750 * Moves the given album down in this album’s albums. If the album is
751 * already the last album, nothing happens.
754 * The album to move down
755 * @return The album that the given album swapped the place with, or
756 * <code>null</code> if the album did not change its place
758 public Album moveAlbumDown(Album album) {
759 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
760 int oldIndex = albums.indexOf(album);
761 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
764 albums.remove(oldIndex);
765 albums.add(oldIndex + 1, album);
766 return albums.get(oldIndex);
770 * Returns the ID of the currently selected avatar image.
772 * @return The ID of the currently selected avatar image, or {@code null} if
773 * no avatar is selected.
775 public String getAvatar() {
780 * Sets the avatar image.
783 * The new avatar image, or {@code null} to not select an avatar
787 public Sone setAvatar(Image avatar) {
788 if (avatar == null) {
792 Validation.begin().isEqual("Image Owner", avatar.getSone(), this).check();
793 this.avatar = avatar.getId();
798 * Returns Sone-specific options.
800 * @return The options of this Sone
802 public Options getOptions() {
807 // FINGERPRINTABLE METHODS
814 public synchronized String getFingerprint() {
815 StringBuilder fingerprint = new StringBuilder();
816 fingerprint.append(profile.getFingerprint());
818 fingerprint.append("Posts(");
819 for (Post post : getPosts()) {
820 fingerprint.append("Post(").append(post.getId()).append(')');
822 fingerprint.append(")");
824 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
825 Collections.sort(replies, Reply.TIME_COMPARATOR);
826 fingerprint.append("Replies(");
827 for (PostReply reply : replies) {
828 fingerprint.append("Reply(").append(reply.getId()).append(')');
830 fingerprint.append(')');
832 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
833 Collections.sort(likedPostIds);
834 fingerprint.append("LikedPosts(");
835 for (String likedPostId : likedPostIds) {
836 fingerprint.append("Post(").append(likedPostId).append(')');
838 fingerprint.append(')');
840 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
841 Collections.sort(likedReplyIds);
842 fingerprint.append("LikedReplies(");
843 for (String likedReplyId : likedReplyIds) {
844 fingerprint.append("Reply(").append(likedReplyId).append(')');
846 fingerprint.append(')');
848 fingerprint.append("Albums(");
849 for (Album album : albums) {
850 fingerprint.append(album.getFingerprint());
852 fingerprint.append(')');
854 fingerprint.append("Avatar(").append(avatar).append(')');
856 return fingerprint.toString();
860 // INTERFACE Comparable<Sone>
867 public int compareTo(Sone sone) {
868 return NICE_NAME_COMPARATOR.compare(this, sone);
879 public int hashCode() {
880 return id.hashCode();
887 public boolean equals(Object object) {
888 if (!(object instanceof Sone)) {
891 return ((Sone) object).id.equals(id);
898 public String toString() {
899 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";