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 * Sets all friends of this Sone at once.
386 * The new (and only) friends of this Sone
387 * @return This Sone (for method chaining)
389 public Sone setFriends(Collection<String> friends) {
391 friendSones.addAll(friends);
396 * Returns whether this Sone has the given Sone as a friend Sone.
398 * @param friendSoneId
399 * The ID of the Sone to check for
400 * @return {@code true} if this Sone has the given Sone as a friend,
401 * {@code false} otherwise
403 public boolean hasFriend(String friendSoneId) {
404 return friendSones.contains(friendSoneId);
408 * Adds the given Sone as a friend Sone.
411 * The friend Sone to add
412 * @return This Sone (for method chaining)
414 public Sone addFriend(String friendSone) {
415 if (!friendSone.equals(id)) {
416 friendSones.add(friendSone);
422 * Removes the given Sone as a friend Sone.
424 * @param friendSoneId
425 * The ID of the friend Sone to remove
426 * @return This Sone (for method chaining)
428 public Sone removeFriend(String friendSoneId) {
429 friendSones.remove(friendSoneId);
434 * Returns the list of posts of this Sone, sorted by time, newest first.
436 * @return All posts of this Sone
438 public List<Post> getPosts() {
439 List<Post> sortedPosts;
440 synchronized (this) {
441 sortedPosts = new ArrayList<Post>(posts);
443 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
448 * Sets all posts of this Sone at once.
451 * The new (and only) posts of this Sone
452 * @return This Sone (for method chaining)
454 public synchronized Sone setPosts(Collection<Post> posts) {
455 synchronized (this) {
457 this.posts.addAll(posts);
463 * Adds the given post to this Sone. The post will not be added if its
464 * {@link Post#getSone() Sone} is not this Sone.
469 public synchronized void addPost(Post post) {
470 if (post.getSone().equals(this) && posts.add(post)) {
471 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
476 * Removes the given post from this Sone.
481 public synchronized void removePost(Post post) {
482 if (post.getSone().equals(this)) {
488 * Returns all replies this Sone made.
490 * @return All replies this Sone made
492 public synchronized Set<PostReply> getReplies() {
493 return Collections.unmodifiableSet(replies);
497 * Sets all replies of this Sone at once.
500 * The new (and only) replies of this Sone
501 * @return This Sone (for method chaining)
503 public synchronized Sone setReplies(Collection<PostReply> replies) {
504 this.replies.clear();
505 this.replies.addAll(replies);
510 * Adds a reply to this Sone. If the given reply was not made by this Sone,
511 * nothing is added to this Sone.
516 public synchronized void addReply(PostReply reply) {
517 if (reply.getSone().equals(this)) {
523 * Removes a reply from this Sone.
526 * The reply to remove
528 public synchronized void removeReply(PostReply reply) {
529 if (reply.getSone().equals(this)) {
530 replies.remove(reply);
535 * Returns the IDs of all liked posts.
537 * @return All liked posts’ IDs
539 public Set<String> getLikedPostIds() {
540 return Collections.unmodifiableSet(likedPostIds);
544 * Sets the IDs of all liked posts.
546 * @param likedPostIds
547 * All liked posts’ IDs
548 * @return This Sone (for method chaining)
550 public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
551 this.likedPostIds.clear();
552 this.likedPostIds.addAll(likedPostIds);
557 * Checks whether the given post ID is liked by this Sone.
561 * @return {@code true} if this Sone likes the given post, {@code false}
564 public boolean isLikedPostId(String postId) {
565 return likedPostIds.contains(postId);
569 * Adds the given post ID to the list of posts this Sone likes.
573 * @return This Sone (for method chaining)
575 public synchronized Sone addLikedPostId(String postId) {
576 likedPostIds.add(postId);
581 * Removes the given post ID from the list of posts this Sone likes.
585 * @return This Sone (for method chaining)
587 public synchronized Sone removeLikedPostId(String postId) {
588 likedPostIds.remove(postId);
593 * Returns the IDs of all liked replies.
595 * @return All liked replies’ IDs
597 public Set<String> getLikedReplyIds() {
598 return Collections.unmodifiableSet(likedReplyIds);
602 * Sets the IDs of all liked replies.
604 * @param likedReplyIds
605 * All liked replies’ IDs
606 * @return This Sone (for method chaining)
608 public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
609 this.likedReplyIds.clear();
610 this.likedReplyIds.addAll(likedReplyIds);
615 * Checks whether the given reply ID is liked by this Sone.
618 * The ID of the reply
619 * @return {@code true} if this Sone likes the given reply, {@code false}
622 public boolean isLikedReplyId(String replyId) {
623 return likedReplyIds.contains(replyId);
627 * Adds the given reply ID to the list of replies this Sone likes.
630 * The ID of the reply
631 * @return This Sone (for method chaining)
633 public synchronized Sone addLikedReplyId(String replyId) {
634 likedReplyIds.add(replyId);
639 * Removes the given post ID from the list of replies this Sone likes.
642 * The ID of the reply
643 * @return This Sone (for method chaining)
645 public synchronized Sone removeLikedReplyId(String replyId) {
646 likedReplyIds.remove(replyId);
651 * Returns the albums of this Sone.
653 * @return The albums of this Sone
655 public List<Album> getAlbums() {
656 return Collections.unmodifiableList(albums);
660 * Returns a flattened list of all albums of this Sone. The resulting list
661 * contains parent albums before child albums so that the resulting list can
662 * be parsed in a single pass.
664 * @return The flattened albums
666 public List<Album> getAllAlbums() {
667 List<Album> flatAlbums = new ArrayList<Album>();
668 flatAlbums.addAll(albums);
669 int lastAlbumIndex = 0;
670 while (lastAlbumIndex < flatAlbums.size()) {
671 int previousAlbumCount = flatAlbums.size();
672 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
673 flatAlbums.addAll(album.getAlbums());
675 lastAlbumIndex = previousAlbumCount;
681 * Returns all images of a Sone. Images of a album are inserted into this
682 * list before images of all child albums.
684 * @return The list of all images
686 public List<Image> getAllImages() {
687 List<Image> allImages = new ArrayList<Image>();
688 for (Album album : getAllAlbums()) {
689 allImages.addAll(album.getImages());
695 * Adds an album to this Sone.
700 public synchronized void addAlbum(Album album) {
701 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
706 * Sets the albums of this Sone.
709 * The albums of this Sone
711 public synchronized void setAlbums(Collection<? extends Album> albums) {
712 Validation.begin().isNotNull("Albums", albums).check();
714 for (Album album : albums) {
720 * Removes an album from this Sone.
723 * The album to remove
725 public synchronized void removeAlbum(Album album) {
726 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
727 albums.remove(album);
731 * Moves the given album up in this album’s albums. If the album is already
732 * the first album, nothing happens.
735 * The album to move up
736 * @return The album that the given album swapped the place with, or
737 * <code>null</code> if the album did not change its place
739 public Album moveAlbumUp(Album album) {
740 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
741 int oldIndex = albums.indexOf(album);
745 albums.remove(oldIndex);
746 albums.add(oldIndex - 1, album);
747 return albums.get(oldIndex);
751 * Moves the given album down in this album’s albums. If the album is
752 * already the last album, nothing happens.
755 * The album to move down
756 * @return The album that the given album swapped the place with, or
757 * <code>null</code> if the album did not change its place
759 public Album moveAlbumDown(Album album) {
760 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).isNull("Album Parent", album.getParent()).check();
761 int oldIndex = albums.indexOf(album);
762 if ((oldIndex < 0) || (oldIndex >= (albums.size() - 1))) {
765 albums.remove(oldIndex);
766 albums.add(oldIndex + 1, album);
767 return albums.get(oldIndex);
771 * Returns Sone-specific options.
773 * @return The options of this Sone
775 public Options getOptions() {
780 // FINGERPRINTABLE METHODS
787 public synchronized String getFingerprint() {
788 StringBuilder fingerprint = new StringBuilder();
789 fingerprint.append(profile.getFingerprint());
791 fingerprint.append("Posts(");
792 for (Post post : getPosts()) {
793 fingerprint.append("Post(").append(post.getId()).append(')');
795 fingerprint.append(")");
797 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
798 Collections.sort(replies, Reply.TIME_COMPARATOR);
799 fingerprint.append("Replies(");
800 for (PostReply reply : replies) {
801 fingerprint.append("Reply(").append(reply.getId()).append(')');
803 fingerprint.append(')');
805 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
806 Collections.sort(likedPostIds);
807 fingerprint.append("LikedPosts(");
808 for (String likedPostId : likedPostIds) {
809 fingerprint.append("Post(").append(likedPostId).append(')');
811 fingerprint.append(')');
813 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
814 Collections.sort(likedReplyIds);
815 fingerprint.append("LikedReplies(");
816 for (String likedReplyId : likedReplyIds) {
817 fingerprint.append("Reply(").append(likedReplyId).append(')');
819 fingerprint.append(')');
821 fingerprint.append("Albums(");
822 for (Album album : albums) {
823 fingerprint.append(album.getFingerprint());
825 fingerprint.append(')');
827 return fingerprint.toString();
831 // INTERFACE Comparable<Sone>
838 public int compareTo(Sone sone) {
839 return NICE_NAME_COMPARATOR.compare(this, sone);
850 public int hashCode() {
851 return id.hashCode();
858 public boolean equals(Object object) {
859 if (!(object instanceof Sone)) {
862 return ((Sone) object).id.equals(id);
869 public String toString() {
870 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";