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;
119 private static final Logger logger = Logging.getLogger(Sone.class);
121 /** The ID of this Sone. */
122 private final String id;
124 /** The identity of this Sone. */
125 private Identity identity;
127 /** The URI under which the Sone is stored in Freenet. */
128 private volatile FreenetURI requestUri;
130 /** The URI used to insert a new version of this Sone. */
131 /* This will be null for remote Sones! */
132 private volatile FreenetURI insertUri;
134 /** The latest edition of the Sone. */
135 private volatile long latestEdition;
137 /** The time of the last inserted update. */
138 private volatile long time;
140 /** The profile of this Sone. */
141 private volatile Profile profile = new Profile();
143 /** The client used by the Sone. */
144 private volatile Client client;
146 /** All friend Sones. */
147 private final Set<String> friendSones = Collections.synchronizedSet(new HashSet<String>());
150 private final Set<Post> posts = Collections.synchronizedSet(new HashSet<Post>());
153 private final Set<PostReply> replies = Collections.synchronizedSet(new HashSet<PostReply>());
155 /** The IDs of all liked posts. */
156 private final Set<String> likedPostIds = Collections.synchronizedSet(new HashSet<String>());
158 /** The IDs of all liked replies. */
159 private final Set<String> likedReplyIds = Collections.synchronizedSet(new HashSet<String>());
161 /** The albums of this Sone. */
162 private final List<Album> albums = Collections.synchronizedList(new ArrayList<Album>());
164 /** Sone-specific options. */
165 private final Options options = new Options();
168 * Creates a new Sone.
173 public Sone(String id) {
182 * Returns the identity of this Sone.
184 * @return The identity of this Sone
186 public String getId() {
191 * Returns the identity of this Sone.
193 * @return The identity of this Sone
195 public Identity getIdentity() {
200 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
201 * identity has to match this Sone’s {@link #getId()}.
204 * The identity of this Sone
205 * @return This Sone (for method chaining)
206 * @throws IllegalArgumentException
207 * if the ID of the identity does not match this Sone’s ID
209 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
210 if (!identity.getId().equals(id)) {
211 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
213 this.identity = identity;
218 * Returns the name of this Sone.
220 * @return The name of this Sone
222 public String getName() {
223 return (identity != null) ? identity.getNickname() : null;
227 * Returns the request URI of this Sone.
229 * @return The request URI of this Sone
231 public FreenetURI getRequestUri() {
232 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
236 * Sets the request URI of this Sone.
239 * The request URI of this Sone
240 * @return This Sone (for method chaining)
242 public Sone setRequestUri(FreenetURI requestUri) {
243 if (this.requestUri == null) {
244 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
247 if (!this.requestUri.equalsKeypair(requestUri)) {
248 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
255 * Returns the insert URI of this Sone.
257 * @return The insert URI of this Sone
259 public FreenetURI getInsertUri() {
260 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
264 * Sets the insert URI of this Sone.
267 * The insert URI of this Sone
268 * @return This Sone (for method chaining)
270 public Sone setInsertUri(FreenetURI insertUri) {
271 if (this.insertUri == null) {
272 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
275 if (!this.insertUri.equalsKeypair(insertUri)) {
276 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
283 * Returns the latest edition of this Sone.
285 * @return The latest edition of this Sone
287 public long getLatestEdition() {
288 return latestEdition;
292 * Sets the latest edition of this Sone. If the given latest edition is not
293 * greater than the current latest edition, the latest edition of this Sone
296 * @param latestEdition
297 * The latest edition of this Sone
299 public void setLatestEdition(long latestEdition) {
300 if (!(latestEdition > this.latestEdition)) {
301 logger.log(Level.FINE, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
304 this.latestEdition = latestEdition;
308 * Return the time of the last inserted update of this Sone.
310 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
312 public long getTime() {
317 * Sets the time of the last inserted update of this Sone.
320 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
321 * @return This Sone (for method chaining)
323 public Sone setTime(long time) {
329 * Returns a copy of the profile. If you want to update values in the
330 * profile of this Sone, update the values in the returned {@link Profile}
331 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
333 * @return A copy of the profile
335 public synchronized Profile getProfile() {
336 return new Profile(profile);
340 * Sets the profile of this Sone. A copy of the given profile is stored so
341 * that subsequent modifications of the given profile are not reflected in
347 public synchronized void setProfile(Profile profile) {
348 this.profile = new Profile(profile);
352 * Returns the client used by this Sone.
354 * @return The client used by this Sone, or {@code null}
356 public Client getClient() {
361 * Sets the client used by this Sone.
364 * The client used by this Sone, or {@code null}
365 * @return This Sone (for method chaining)
367 public Sone setClient(Client client) {
368 this.client = client;
373 * Returns all friend Sones of this Sone.
375 * @return The friend Sones of this Sone
377 public List<String> getFriends() {
378 List<String> friends = new ArrayList<String>(friendSones);
383 * Returns whether this Sone has the given Sone as a friend Sone.
385 * @param friendSoneId
386 * The ID of the Sone to check for
387 * @return {@code true} if this Sone has the given Sone as a friend,
388 * {@code false} otherwise
390 public boolean hasFriend(String friendSoneId) {
391 return friendSones.contains(friendSoneId);
395 * Adds the given Sone as a friend Sone.
398 * The friend Sone to add
399 * @return This Sone (for method chaining)
401 public Sone addFriend(String friendSone) {
402 if (!friendSone.equals(id)) {
403 friendSones.add(friendSone);
409 * Removes the given Sone as a friend Sone.
411 * @param friendSoneId
412 * The ID of the friend Sone to remove
413 * @return This Sone (for method chaining)
415 public Sone removeFriend(String friendSoneId) {
416 friendSones.remove(friendSoneId);
421 * Returns the list of posts of this Sone, sorted by time, newest first.
423 * @return All posts of this Sone
425 public List<Post> getPosts() {
426 List<Post> sortedPosts;
427 synchronized (this) {
428 sortedPosts = new ArrayList<Post>(posts);
430 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
435 * Sets all posts of this Sone at once.
438 * The new (and only) posts of this Sone
439 * @return This Sone (for method chaining)
441 public synchronized Sone setPosts(Collection<Post> posts) {
442 synchronized (this) {
444 this.posts.addAll(posts);
450 * Adds the given post to this Sone. The post will not be added if its
451 * {@link Post#getSone() Sone} is not this Sone.
456 public synchronized void addPost(Post post) {
457 if (post.getSone().equals(this) && posts.add(post)) {
458 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
463 * Removes the given post from this Sone.
468 public synchronized void removePost(Post post) {
469 if (post.getSone().equals(this)) {
475 * Returns all replies this Sone made.
477 * @return All replies this Sone made
479 public synchronized Set<PostReply> getReplies() {
480 return Collections.unmodifiableSet(replies);
484 * Sets all replies of this Sone at once.
487 * The new (and only) replies of this Sone
488 * @return This Sone (for method chaining)
490 public synchronized Sone setReplies(Collection<PostReply> replies) {
491 this.replies.clear();
492 this.replies.addAll(replies);
497 * Adds a reply to this Sone. If the given reply was not made by this Sone,
498 * nothing is added to this Sone.
503 public synchronized void addReply(PostReply reply) {
504 if (reply.getSone().equals(this)) {
510 * Removes a reply from this Sone.
513 * The reply to remove
515 public synchronized void removeReply(PostReply reply) {
516 if (reply.getSone().equals(this)) {
517 replies.remove(reply);
522 * Returns the IDs of all liked posts.
524 * @return All liked posts’ IDs
526 public Set<String> getLikedPostIds() {
527 return Collections.unmodifiableSet(likedPostIds);
531 * Sets the IDs of all liked posts.
533 * @param likedPostIds
534 * All liked posts’ IDs
535 * @return This Sone (for method chaining)
537 public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
538 this.likedPostIds.clear();
539 this.likedPostIds.addAll(likedPostIds);
544 * Checks whether the given post ID is liked by this Sone.
548 * @return {@code true} if this Sone likes the given post, {@code false}
551 public boolean isLikedPostId(String postId) {
552 return likedPostIds.contains(postId);
556 * Adds the given post ID to the list of posts this Sone likes.
560 * @return This Sone (for method chaining)
562 public synchronized Sone addLikedPostId(String postId) {
563 likedPostIds.add(postId);
568 * Removes the given post ID from the list of posts this Sone likes.
572 * @return This Sone (for method chaining)
574 public synchronized Sone removeLikedPostId(String postId) {
575 likedPostIds.remove(postId);
580 * Returns the IDs of all liked replies.
582 * @return All liked replies’ IDs
584 public Set<String> getLikedReplyIds() {
585 return Collections.unmodifiableSet(likedReplyIds);
589 * Sets the IDs of all liked replies.
591 * @param likedReplyIds
592 * All liked replies’ IDs
593 * @return This Sone (for method chaining)
595 public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
596 this.likedReplyIds.clear();
597 this.likedReplyIds.addAll(likedReplyIds);
602 * Checks whether the given reply ID is liked by this Sone.
605 * The ID of the reply
606 * @return {@code true} if this Sone likes the given reply, {@code false}
609 public boolean isLikedReplyId(String replyId) {
610 return likedReplyIds.contains(replyId);
614 * Adds the given reply ID to the list of replies this Sone likes.
617 * The ID of the reply
618 * @return This Sone (for method chaining)
620 public synchronized Sone addLikedReplyId(String replyId) {
621 likedReplyIds.add(replyId);
626 * Removes the given post ID from the list of replies this Sone likes.
629 * The ID of the reply
630 * @return This Sone (for method chaining)
632 public synchronized Sone removeLikedReplyId(String replyId) {
633 likedReplyIds.remove(replyId);
638 * Returns the albums of this Sone.
640 * @return The albums of this Sone
642 public List<Album> getAlbums() {
643 return Collections.unmodifiableList(albums);
647 * Returns a flattened list of all albums of this Sone. The resulting list
648 * contains parent albums before child albums so that the resulting list can
649 * be parsed in a single pass.
651 * @return The flattened albums
653 public List<Album> getAllAlbums() {
654 List<Album> flatAlbums = new ArrayList<Album>();
655 flatAlbums.addAll(albums);
656 int lastAlbumIndex = 0;
657 while (lastAlbumIndex < flatAlbums.size()) {
658 int previousAlbumCount = flatAlbums.size();
659 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
660 flatAlbums.addAll(album.getAlbums());
662 lastAlbumIndex = previousAlbumCount;
668 * Returns all images of a Sone. Images of a album are inserted into this
669 * list before images of all child albums.
671 * @return The list of all images
673 public List<Image> getAllImages() {
674 List<Image> allImages = new ArrayList<Image>();
675 for (Album album : getAllAlbums()) {
676 allImages.addAll(album.getImages());
682 * Adds an album to this Sone.
687 public synchronized void addAlbum(Album album) {
688 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
693 * Sets the albums of this Sone.
696 * The albums of this Sone
698 public synchronized void setAlbums(Collection<? extends Album> albums) {
699 Validation.begin().isNotNull("Albums", albums).check();
701 for (Album album : albums) {
707 * Removes an album from this Sone.
710 * The album to remove
712 public synchronized void removeAlbum(Album album) {
713 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
714 albums.remove(album);
718 * Moves the given album up in this album’s albums. If the album is already
719 * the first album, nothing happens.
722 * The album to move up
723 * @return The album that the given album swapped the place with, or
724 * <code>null</code> if the album did not change its place
726 public Album moveAlbumUp(Album album) {
727 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
728 int oldIndex = albums.indexOf(album);
732 albums.remove(oldIndex);
733 albums.add(oldIndex - 1, album);
734 return albums.get(oldIndex);
738 * Moves the given album down in this album’s albums. If the album is
739 * already the last album, nothing happens.
742 * The album to move down
743 * @return The album that the given album swapped the place with, or
744 * <code>null</code> if the album did not change its place
746 public Album moveAlbumDown(Album album) {
747 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
748 int oldIndex = albums.indexOf(album);
749 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
752 albums.remove(oldIndex);
753 albums.add(oldIndex + 1, album);
754 return albums.get(oldIndex);
758 * Returns Sone-specific options.
760 * @return The options of this Sone
762 public Options getOptions() {
767 // FINGERPRINTABLE METHODS
774 public synchronized String getFingerprint() {
775 StringBuilder fingerprint = new StringBuilder();
776 fingerprint.append(profile.getFingerprint());
778 fingerprint.append("Posts(");
779 for (Post post : getPosts()) {
780 fingerprint.append("Post(").append(post.getId()).append(')');
782 fingerprint.append(")");
784 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
785 Collections.sort(replies, Reply.TIME_COMPARATOR);
786 fingerprint.append("Replies(");
787 for (PostReply reply : replies) {
788 fingerprint.append("Reply(").append(reply.getId()).append(')');
790 fingerprint.append(')');
792 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
793 Collections.sort(likedPostIds);
794 fingerprint.append("LikedPosts(");
795 for (String likedPostId : likedPostIds) {
796 fingerprint.append("Post(").append(likedPostId).append(')');
798 fingerprint.append(')');
800 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
801 Collections.sort(likedReplyIds);
802 fingerprint.append("LikedReplies(");
803 for (String likedReplyId : likedReplyIds) {
804 fingerprint.append("Reply(").append(likedReplyId).append(')');
806 fingerprint.append(')');
808 fingerprint.append("Albums(");
809 for (Album album : albums) {
810 fingerprint.append(album.getFingerprint());
812 fingerprint.append(')');
814 return fingerprint.toString();
818 // INTERFACE Comparable<Sone>
825 public int compareTo(Sone sone) {
826 return NICE_NAME_COMPARATOR.compare(this, sone);
837 public int hashCode() {
838 return id.hashCode();
845 public boolean equals(Object object) {
846 if (!(object instanceof Sone)) {
849 return ((Sone) object).id.equals(id);
856 public String toString() {
857 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";