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();
177 * Creates a new Sone.
182 public Sone(String id) {
191 * Returns the identity of this Sone.
193 * @return The identity of this Sone
195 public String getId() {
200 * Returns the identity of this Sone.
202 * @return The identity of this Sone
204 public Identity getIdentity() {
209 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
210 * identity has to match this Sone’s {@link #getId()}.
213 * The identity of this Sone
214 * @return This Sone (for method chaining)
215 * @throws IllegalArgumentException
216 * if the ID of the identity does not match this Sone’s ID
218 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
219 if (!identity.getId().equals(id)) {
220 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
222 this.identity = identity;
227 * Returns the name of this Sone.
229 * @return The name of this Sone
231 public String getName() {
232 return (identity != null) ? identity.getNickname() : null;
236 * Returns the request URI of this Sone.
238 * @return The request URI of this Sone
240 public FreenetURI getRequestUri() {
241 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
245 * Sets the request URI of this Sone.
248 * The request URI of this Sone
249 * @return This Sone (for method chaining)
251 public Sone setRequestUri(FreenetURI requestUri) {
252 if (this.requestUri == null) {
253 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
256 if (!this.requestUri.equalsKeypair(requestUri)) {
257 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
264 * Returns the insert URI of this Sone.
266 * @return The insert URI of this Sone
268 public FreenetURI getInsertUri() {
269 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
273 * Sets the insert URI of this Sone.
276 * The insert URI of this Sone
277 * @return This Sone (for method chaining)
279 public Sone setInsertUri(FreenetURI insertUri) {
280 if (this.insertUri == null) {
281 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
284 if (!this.insertUri.equalsKeypair(insertUri)) {
285 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
292 * Returns the latest edition of this Sone.
294 * @return The latest edition of this Sone
296 public long getLatestEdition() {
297 return latestEdition;
301 * Sets the latest edition of this Sone. If the given latest edition is not
302 * greater than the current latest edition, the latest edition of this Sone
305 * @param latestEdition
306 * The latest edition of this Sone
308 public void setLatestEdition(long latestEdition) {
309 if (!(latestEdition > this.latestEdition)) {
310 logger.log(Level.FINE, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
313 this.latestEdition = latestEdition;
317 * Return the time of the last inserted update of this Sone.
319 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
321 public long getTime() {
326 * Sets the time of the last inserted update of this Sone.
329 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
330 * @return This Sone (for method chaining)
332 public Sone setTime(long time) {
338 * Returns a copy of the profile. If you want to update values in the
339 * profile of this Sone, update the values in the returned {@link Profile}
340 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
342 * @return A copy of the profile
344 public synchronized Profile getProfile() {
345 return new Profile(profile);
349 * Sets the profile of this Sone. A copy of the given profile is stored so
350 * that subsequent modifications of the given profile are not reflected in
356 public synchronized void setProfile(Profile profile) {
357 this.profile = new Profile(profile);
361 * Returns the client used by this Sone.
363 * @return The client used by this Sone, or {@code null}
365 public Client getClient() {
370 * Sets the client used by this Sone.
373 * The client used by this Sone, or {@code null}
374 * @return This Sone (for method chaining)
376 public Sone setClient(Client client) {
377 this.client = client;
382 * Returns all friend Sones of this Sone.
384 * @return The friend Sones of this Sone
386 public List<String> getFriends() {
387 List<String> friends = new ArrayList<String>(friendSones);
392 * Returns whether this Sone has the given Sone as a friend Sone.
394 * @param friendSoneId
395 * The ID of the Sone to check for
396 * @return {@code true} if this Sone has the given Sone as a friend,
397 * {@code false} otherwise
399 public boolean hasFriend(String friendSoneId) {
400 return friendSones.contains(friendSoneId);
404 * Adds the given Sone as a friend Sone.
407 * The friend Sone to add
408 * @return This Sone (for method chaining)
410 public Sone addFriend(String friendSone) {
411 if (!friendSone.equals(id)) {
412 friendSones.add(friendSone);
418 * Removes the given Sone as a friend Sone.
420 * @param friendSoneId
421 * The ID of the friend Sone to remove
422 * @return This Sone (for method chaining)
424 public Sone removeFriend(String friendSoneId) {
425 friendSones.remove(friendSoneId);
430 * Returns the list of posts of this Sone, sorted by time, newest first.
432 * @return All posts of this Sone
434 public List<Post> getPosts() {
435 List<Post> sortedPosts;
436 synchronized (this) {
437 sortedPosts = new ArrayList<Post>(posts);
439 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
444 * Sets all posts of this Sone at once.
447 * The new (and only) posts of this Sone
448 * @return This Sone (for method chaining)
450 public synchronized Sone setPosts(Collection<Post> posts) {
451 synchronized (this) {
453 this.posts.addAll(posts);
459 * Adds the given post to this Sone. The post will not be added if its
460 * {@link Post#getSone() Sone} is not this Sone.
465 public synchronized void addPost(Post post) {
466 if (post.getSone().equals(this) && posts.add(post)) {
467 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
472 * Removes the given post from this Sone.
477 public synchronized void removePost(Post post) {
478 if (post.getSone().equals(this)) {
484 * Returns all replies this Sone made.
486 * @return All replies this Sone made
488 public synchronized Set<PostReply> getReplies() {
489 return Collections.unmodifiableSet(replies);
493 * Sets all replies of this Sone at once.
496 * The new (and only) replies of this Sone
497 * @return This Sone (for method chaining)
499 public synchronized Sone setReplies(Collection<PostReply> replies) {
500 this.replies.clear();
501 this.replies.addAll(replies);
506 * Adds a reply to this Sone. If the given reply was not made by this Sone,
507 * nothing is added to this Sone.
512 public synchronized void addReply(PostReply reply) {
513 if (reply.getSone().equals(this)) {
519 * Removes a reply from this Sone.
522 * The reply to remove
524 public synchronized void removeReply(PostReply reply) {
525 if (reply.getSone().equals(this)) {
526 replies.remove(reply);
531 * Returns the IDs of all liked posts.
533 * @return All liked posts’ IDs
535 public Set<String> getLikedPostIds() {
536 return Collections.unmodifiableSet(likedPostIds);
540 * Sets the IDs of all liked posts.
542 * @param likedPostIds
543 * All liked posts’ IDs
544 * @return This Sone (for method chaining)
546 public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
547 this.likedPostIds.clear();
548 this.likedPostIds.addAll(likedPostIds);
553 * Checks whether the given post ID is liked by this Sone.
557 * @return {@code true} if this Sone likes the given post, {@code false}
560 public boolean isLikedPostId(String postId) {
561 return likedPostIds.contains(postId);
565 * Adds the given post ID to the list of posts this Sone likes.
569 * @return This Sone (for method chaining)
571 public synchronized Sone addLikedPostId(String postId) {
572 likedPostIds.add(postId);
577 * Removes the given post ID from the list of posts this Sone likes.
581 * @return This Sone (for method chaining)
583 public synchronized Sone removeLikedPostId(String postId) {
584 likedPostIds.remove(postId);
589 * Returns the IDs of all liked replies.
591 * @return All liked replies’ IDs
593 public Set<String> getLikedReplyIds() {
594 return Collections.unmodifiableSet(likedReplyIds);
598 * Sets the IDs of all liked replies.
600 * @param likedReplyIds
601 * All liked replies’ IDs
602 * @return This Sone (for method chaining)
604 public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
605 this.likedReplyIds.clear();
606 this.likedReplyIds.addAll(likedReplyIds);
611 * Checks whether the given reply ID is liked by this Sone.
614 * The ID of the reply
615 * @return {@code true} if this Sone likes the given reply, {@code false}
618 public boolean isLikedReplyId(String replyId) {
619 return likedReplyIds.contains(replyId);
623 * Adds the given reply ID to the list of replies this Sone likes.
626 * The ID of the reply
627 * @return This Sone (for method chaining)
629 public synchronized Sone addLikedReplyId(String replyId) {
630 likedReplyIds.add(replyId);
635 * Removes the given post ID from the list of replies this Sone likes.
638 * The ID of the reply
639 * @return This Sone (for method chaining)
641 public synchronized Sone removeLikedReplyId(String replyId) {
642 likedReplyIds.remove(replyId);
647 * Returns the albums of this Sone.
649 * @return The albums of this Sone
651 public List<Album> getAlbums() {
652 return Collections.unmodifiableList(albums);
656 * Returns a flattened list of all albums of this Sone. The resulting list
657 * contains parent albums before child albums so that the resulting list can
658 * be parsed in a single pass.
660 * @return The flattened albums
662 public List<Album> getAllAlbums() {
663 List<Album> flatAlbums = new ArrayList<Album>();
664 flatAlbums.addAll(albums);
665 int lastAlbumIndex = 0;
666 while (lastAlbumIndex < flatAlbums.size()) {
667 int previousAlbumCount = flatAlbums.size();
668 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
669 flatAlbums.addAll(album.getAlbums());
671 lastAlbumIndex = previousAlbumCount;
677 * Returns all images of a Sone. Images of a album are inserted into this
678 * list before images of all child albums.
680 * @return The list of all images
682 public List<Image> getAllImages() {
683 List<Image> allImages = new ArrayList<Image>();
684 for (Album album : getAllAlbums()) {
685 allImages.addAll(album.getImages());
691 * Adds an album to this Sone.
696 public synchronized void addAlbum(Album album) {
697 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
702 * Sets the albums of this Sone.
705 * The albums of this Sone
707 public synchronized void setAlbums(Collection<? extends Album> albums) {
708 Validation.begin().isNotNull("Albums", albums).check();
710 for (Album album : albums) {
716 * Removes an album from this Sone.
719 * The album to remove
721 public synchronized void removeAlbum(Album album) {
722 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
723 albums.remove(album);
727 * Moves the given album up in this album’s albums. If the album is already
728 * the first album, nothing happens.
731 * The album to move up
732 * @return The album that the given album swapped the place with, or
733 * <code>null</code> if the album did not change its place
735 public Album moveAlbumUp(Album album) {
736 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
737 int oldIndex = albums.indexOf(album);
741 albums.remove(oldIndex);
742 albums.add(oldIndex - 1, album);
743 return albums.get(oldIndex);
747 * Moves the given album down in this album’s albums. If the album is
748 * already the last album, nothing happens.
751 * The album to move down
752 * @return The album that the given album swapped the place with, or
753 * <code>null</code> if the album did not change its place
755 public Album moveAlbumDown(Album album) {
756 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
757 int oldIndex = albums.indexOf(album);
758 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
761 albums.remove(oldIndex);
762 albums.add(oldIndex + 1, album);
763 return albums.get(oldIndex);
767 * Returns Sone-specific options.
769 * @return The options of this Sone
771 public Options getOptions() {
776 // FINGERPRINTABLE METHODS
783 public synchronized String getFingerprint() {
784 StringBuilder fingerprint = new StringBuilder();
785 fingerprint.append(profile.getFingerprint());
787 fingerprint.append("Posts(");
788 for (Post post : getPosts()) {
789 fingerprint.append("Post(").append(post.getId()).append(')');
791 fingerprint.append(")");
793 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
794 Collections.sort(replies, Reply.TIME_COMPARATOR);
795 fingerprint.append("Replies(");
796 for (PostReply reply : replies) {
797 fingerprint.append("Reply(").append(reply.getId()).append(')');
799 fingerprint.append(')');
801 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
802 Collections.sort(likedPostIds);
803 fingerprint.append("LikedPosts(");
804 for (String likedPostId : likedPostIds) {
805 fingerprint.append("Post(").append(likedPostId).append(')');
807 fingerprint.append(')');
809 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
810 Collections.sort(likedReplyIds);
811 fingerprint.append("LikedReplies(");
812 for (String likedReplyId : likedReplyIds) {
813 fingerprint.append("Reply(").append(likedReplyId).append(')');
815 fingerprint.append(')');
817 fingerprint.append("Albums(");
818 for (Album album : albums) {
819 fingerprint.append(album.getFingerprint());
821 fingerprint.append(')');
823 return fingerprint.toString();
827 // INTERFACE Comparable<Sone>
834 public int compareTo(Sone sone) {
835 return NICE_NAME_COMPARATOR.compare(this, sone);
846 public int hashCode() {
847 return id.hashCode();
854 public boolean equals(Object object) {
855 if (!(object instanceof Sone)) {
858 return ((Sone) object).id.equals(id);
865 public String toString() {
866 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";