2 * FreenetSone - 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.Options;
31 import net.pterodactylus.sone.freenet.wot.Identity;
32 import net.pterodactylus.sone.template.SoneAccessor;
33 import net.pterodactylus.util.filter.Filter;
34 import net.pterodactylus.util.logging.Logging;
35 import net.pterodactylus.util.validation.Validation;
36 import freenet.keys.FreenetURI;
39 * A Sone defines everything about a user: her profile, her status updates, her
40 * replies, her likes and dislikes, etc.
42 * Operations that modify the Sone need to synchronize on the Sone in question.
44 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46 public class Sone implements Fingerprintable, Comparable<Sone> {
48 /** comparator that sorts Sones by their nice name. */
49 public static final Comparator<Sone> NICE_NAME_COMPARATOR = new Comparator<Sone>() {
52 public int compare(Sone leftSone, Sone rightSone) {
53 int diff = SoneAccessor.getNiceName(leftSone).compareToIgnoreCase(SoneAccessor.getNiceName(rightSone));
57 return leftSone.getId().compareToIgnoreCase(rightSone.getId());
62 /** Filter to remove Sones that have not been downloaded. */
63 public static final Filter<Sone> EMPTY_SONE_FILTER = new Filter<Sone>() {
66 public boolean filterObject(Sone sone) {
67 return sone.getTime() != 0;
72 private static final Logger logger = Logging.getLogger(Sone.class);
74 /** The ID of this Sone. */
75 private final String id;
77 /** The identity of this Sone. */
78 private Identity identity;
80 /** The URI under which the Sone is stored in Freenet. */
81 private volatile FreenetURI requestUri;
83 /** The URI used to insert a new version of this Sone. */
84 /* This will be null for remote Sones! */
85 private volatile FreenetURI insertUri;
87 /** The latest edition of the Sone. */
88 private volatile long latestEdition;
90 /** The time of the last inserted update. */
91 private volatile long time;
93 /** The profile of this Sone. */
94 private volatile Profile profile = new Profile();
96 /** The client used by the Sone. */
97 private volatile Client client;
99 /** All friend Sones. */
100 private final Set<String> friendSones = Collections.synchronizedSet(new HashSet<String>());
103 private final Set<Post> posts = Collections.synchronizedSet(new HashSet<Post>());
106 private final Set<Reply> replies = Collections.synchronizedSet(new HashSet<Reply>());
108 /** The IDs of all liked posts. */
109 private final Set<String> likedPostIds = Collections.synchronizedSet(new HashSet<String>());
111 /** The IDs of all liked replies. */
112 private final Set<String> likedReplyIds = Collections.synchronizedSet(new HashSet<String>());
114 /** The albums of this Sone. */
115 private final List<Album> albums = Collections.synchronizedList(new ArrayList<Album>());
117 /** Sone-specific options. */
118 private final Options options = new Options();
121 * Creates a new Sone.
126 public Sone(String id) {
135 * Returns the identity of this Sone.
137 * @return The identity of this Sone
139 public String getId() {
144 * Returns the identity of this Sone.
146 * @return The identity of this Sone
148 public Identity getIdentity() {
153 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
154 * identity has to match this Sone’s {@link #getId()}.
157 * The identity of this Sone
158 * @return This Sone (for method chaining)
159 * @throws IllegalArgumentException
160 * if the ID of the identity does not match this Sone’s ID
162 public Sone setIdentity(Identity identity) throws IllegalArgumentException {
163 if (!identity.getId().equals(id)) {
164 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
166 this.identity = identity;
171 * Returns the name of this Sone.
173 * @return The name of this Sone
175 public String getName() {
176 return (identity != null) ? identity.getNickname() : null;
180 * Returns the request URI of this Sone.
182 * @return The request URI of this Sone
184 public FreenetURI getRequestUri() {
185 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
189 * Sets the request URI of this Sone.
192 * The request URI of this Sone
193 * @return This Sone (for method chaining)
195 public Sone setRequestUri(FreenetURI requestUri) {
196 if (this.requestUri == null) {
197 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
200 if (!this.requestUri.equalsKeypair(requestUri)) {
201 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { requestUri, this.requestUri });
208 * Returns the insert URI of this Sone.
210 * @return The insert URI of this Sone
212 public FreenetURI getInsertUri() {
213 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
217 * Sets the insert URI of this Sone.
220 * The insert URI of this Sone
221 * @return This Sone (for method chaining)
223 public Sone setInsertUri(FreenetURI insertUri) {
224 if (this.insertUri == null) {
225 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
228 if (!this.insertUri.equalsKeypair(insertUri)) {
229 logger.log(Level.WARNING, "Request URI %s tried to overwrite %s!", new Object[] { insertUri, this.insertUri });
236 * Returns the latest edition of this Sone.
238 * @return The latest edition of this Sone
240 public long getLatestEdition() {
241 return latestEdition;
245 * Sets the latest edition of this Sone. If the given latest edition is not
246 * greater than the current latest edition, the latest edition of this Sone
249 * @param latestEdition
250 * The latest edition of this Sone
252 public void setLatestEdition(long latestEdition) {
253 if (!(latestEdition > this.latestEdition)) {
254 logger.log(Level.FINE, "New latest edition %d is not greater than current latest edition %d!", new Object[] { latestEdition, this.latestEdition });
257 this.latestEdition = latestEdition;
261 * Return the time of the last inserted update of this Sone.
263 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
265 public long getTime() {
270 * Sets the time of the last inserted update of this Sone.
273 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
274 * @return This Sone (for method chaining)
276 public Sone setTime(long time) {
282 * Returns a copy of the profile. If you want to update values in the
283 * profile of this Sone, update the values in the returned {@link Profile}
284 * and use {@link #setProfile(Profile)} to change the profile in this Sone.
286 * @return A copy of the profile
288 public synchronized Profile getProfile() {
289 return new Profile(profile);
293 * Sets the profile of this Sone. A copy of the given profile is stored so
294 * that subsequent modifications of the given profile are not reflected in
300 public synchronized void setProfile(Profile profile) {
301 this.profile = new Profile(profile);
305 * Returns the client used by this Sone.
307 * @return The client used by this Sone, or {@code null}
309 public Client getClient() {
314 * Sets the client used by this Sone.
317 * The client used by this Sone, or {@code null}
318 * @return This Sone (for method chaining)
320 public Sone setClient(Client client) {
321 this.client = client;
326 * Returns all friend Sones of this Sone.
328 * @return The friend Sones of this Sone
330 public List<String> getFriends() {
331 List<String> friends = new ArrayList<String>(friendSones);
336 * Sets all friends of this Sone at once.
339 * The new (and only) friends of this Sone
340 * @return This Sone (for method chaining)
342 public Sone setFriends(Collection<String> friends) {
344 friendSones.addAll(friends);
349 * Returns whether this Sone has the given Sone as a friend Sone.
351 * @param friendSoneId
352 * The ID of the Sone to check for
353 * @return {@code true} if this Sone has the given Sone as a friend,
354 * {@code false} otherwise
356 public boolean hasFriend(String friendSoneId) {
357 return friendSones.contains(friendSoneId);
361 * Adds the given Sone as a friend Sone.
364 * The friend Sone to add
365 * @return This Sone (for method chaining)
367 public Sone addFriend(String friendSone) {
368 if (!friendSone.equals(id)) {
369 friendSones.add(friendSone);
375 * Removes the given Sone as a friend Sone.
377 * @param friendSoneId
378 * The ID of the friend Sone to remove
379 * @return This Sone (for method chaining)
381 public Sone removeFriend(String friendSoneId) {
382 friendSones.remove(friendSoneId);
387 * Returns the list of posts of this Sone, sorted by time, newest first.
389 * @return All posts of this Sone
391 public List<Post> getPosts() {
392 List<Post> sortedPosts;
393 synchronized (this) {
394 sortedPosts = new ArrayList<Post>(posts);
396 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
401 * Sets all posts of this Sone at once.
404 * The new (and only) posts of this Sone
405 * @return This Sone (for method chaining)
407 public synchronized Sone setPosts(Collection<Post> posts) {
408 synchronized (this) {
410 this.posts.addAll(posts);
416 * Adds the given post to this Sone. The post will not be added if its
417 * {@link Post#getSone() Sone} is not this Sone.
422 public synchronized void addPost(Post post) {
423 if (post.getSone().equals(this) && posts.add(post)) {
424 logger.log(Level.FINEST, "Adding %s to “%s”.", new Object[] { post, getName() });
429 * Removes the given post from this Sone.
434 public synchronized void removePost(Post post) {
435 if (post.getSone().equals(this)) {
441 * Returns all replies this Sone made.
443 * @return All replies this Sone made
445 public synchronized Set<Reply> getReplies() {
446 return Collections.unmodifiableSet(replies);
450 * Sets all replies of this Sone at once.
453 * The new (and only) replies of this Sone
454 * @return This Sone (for method chaining)
456 public synchronized Sone setReplies(Collection<Reply> replies) {
457 this.replies.clear();
458 this.replies.addAll(replies);
463 * Adds a reply to this Sone. If the given reply was not made by this Sone,
464 * nothing is added to this Sone.
469 public synchronized void addReply(Reply reply) {
470 if (reply.getSone().equals(this)) {
476 * Removes a reply from this Sone.
479 * The reply to remove
481 public synchronized void removeReply(Reply reply) {
482 if (reply.getSone().equals(this)) {
483 replies.remove(reply);
488 * Returns the IDs of all liked posts.
490 * @return All liked posts’ IDs
492 public Set<String> getLikedPostIds() {
493 return Collections.unmodifiableSet(likedPostIds);
497 * Sets the IDs of all liked posts.
499 * @param likedPostIds
500 * All liked posts’ IDs
501 * @return This Sone (for method chaining)
503 public synchronized Sone setLikePostIds(Set<String> likedPostIds) {
504 this.likedPostIds.clear();
505 this.likedPostIds.addAll(likedPostIds);
510 * Checks whether the given post ID is liked by this Sone.
514 * @return {@code true} if this Sone likes the given post, {@code false}
517 public boolean isLikedPostId(String postId) {
518 return likedPostIds.contains(postId);
522 * Adds the given post ID to the list of posts this Sone likes.
526 * @return This Sone (for method chaining)
528 public synchronized Sone addLikedPostId(String postId) {
529 likedPostIds.add(postId);
534 * Removes the given post ID from the list of posts this Sone likes.
538 * @return This Sone (for method chaining)
540 public synchronized Sone removeLikedPostId(String postId) {
541 likedPostIds.remove(postId);
546 * Returns the IDs of all liked replies.
548 * @return All liked replies’ IDs
550 public Set<String> getLikedReplyIds() {
551 return Collections.unmodifiableSet(likedReplyIds);
555 * Sets the IDs of all liked replies.
557 * @param likedReplyIds
558 * All liked replies’ IDs
559 * @return This Sone (for method chaining)
561 public synchronized Sone setLikeReplyIds(Set<String> likedReplyIds) {
562 this.likedReplyIds.clear();
563 this.likedReplyIds.addAll(likedReplyIds);
568 * Checks whether the given reply ID is liked by this Sone.
571 * The ID of the reply
572 * @return {@code true} if this Sone likes the given reply, {@code false}
575 public boolean isLikedReplyId(String replyId) {
576 return likedReplyIds.contains(replyId);
580 * Adds the given reply ID to the list of replies this Sone likes.
583 * The ID of the reply
584 * @return This Sone (for method chaining)
586 public synchronized Sone addLikedReplyId(String replyId) {
587 likedReplyIds.add(replyId);
592 * Removes the given post ID from the list of replies this Sone likes.
595 * The ID of the reply
596 * @return This Sone (for method chaining)
598 public synchronized Sone removeLikedReplyId(String replyId) {
599 likedReplyIds.remove(replyId);
604 * Returns the albums of this Sone.
606 * @return The albums of this Sone
608 public List<Album> getAlbums() {
609 return Collections.unmodifiableList(albums);
613 * Adds an album to this Sone.
618 public synchronized void addAlbum(Album album) {
619 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
624 * Sets the albums of this Sone.
627 * The albums of this Sone
629 public synchronized void setAlbums(Collection<? extends Album> albums) {
630 Validation.begin().isNotNull("Albums", albums).check();
632 for (Album album : albums) {
638 * Removes an album from this Sone.
641 * The album to remove
643 public synchronized void removeAlbum(Album album) {
644 Validation.begin().isNotNull("Album", album).check().isEqual("Album Owner", album.getSone(), this).check();
645 albums.remove(album);
649 * Returns Sone-specific options.
651 * @return The options of this Sone
653 public Options getOptions() {
658 // FINGERPRINTABLE METHODS
665 public synchronized String getFingerprint() {
666 StringBuilder fingerprint = new StringBuilder();
667 fingerprint.append(profile.getFingerprint());
669 fingerprint.append("Posts(");
670 for (Post post : getPosts()) {
671 fingerprint.append("Post(").append(post.getId()).append(')');
673 fingerprint.append(")");
675 List<Reply> replies = new ArrayList<Reply>(getReplies());
676 Collections.sort(replies, Reply.TIME_COMPARATOR);
677 fingerprint.append("Replies(");
678 for (Reply reply : replies) {
679 fingerprint.append("Reply(").append(reply.getId()).append(')');
681 fingerprint.append(')');
683 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
684 Collections.sort(likedPostIds);
685 fingerprint.append("LikedPosts(");
686 for (String likedPostId : likedPostIds) {
687 fingerprint.append("Post(").append(likedPostId).append(')');
689 fingerprint.append(')');
691 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
692 Collections.sort(likedReplyIds);
693 fingerprint.append("LikedReplies(");
694 for (String likedReplyId : likedReplyIds) {
695 fingerprint.append("Reply(").append(likedReplyId).append(')');
697 fingerprint.append(')');
699 fingerprint.append("Albums(");
700 for (Album album : albums) {
701 fingerprint.append(album.getFingerprint());
703 fingerprint.append(')');
705 return fingerprint.toString();
713 * Flattens the given top-level albums so that the resulting list contains
714 * parent albums before child albums and the resulting list can be parsed in
718 * The albums to flatten
719 * @return The flattened albums
721 public static List<Album> flattenAlbums(Collection<? extends Album> albums) {
722 List<Album> flatAlbums = new ArrayList<Album>();
723 flatAlbums.addAll(albums);
724 int lastAlbumIndex = 0;
725 while (lastAlbumIndex < flatAlbums.size()) {
726 int previousAlbumCount = flatAlbums.size();
727 for (Album album : new ArrayList<Album>(flatAlbums.subList(lastAlbumIndex, flatAlbums.size()))) {
728 flatAlbums.addAll(album.getAlbums());
730 lastAlbumIndex = previousAlbumCount;
736 // INTERFACE Comparable<Sone>
743 public int compareTo(Sone sone) {
744 return NICE_NAME_COMPARATOR.compare(this, sone);
755 public int hashCode() {
756 return id.hashCode();
763 public boolean equals(Object object) {
764 if (!(object instanceof Sone)) {
767 return ((Sone) object).id.equals(id);
774 public String toString() {
775 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + ")]";