2 * Sone - SoneImpl.java - Copyright © 2010–2013 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.impl;
20 import static com.google.common.base.Preconditions.checkNotNull;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
27 import java.util.concurrent.CopyOnWriteArraySet;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.core.Options;
32 import net.pterodactylus.sone.data.Album;
33 import net.pterodactylus.sone.data.Client;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.PostReply;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.database.AlbumBuilder;
40 import net.pterodactylus.sone.database.Database;
41 import net.pterodactylus.sone.freenet.wot.Identity;
42 import net.pterodactylus.util.logging.Logging;
44 import freenet.keys.FreenetURI;
46 import com.google.common.hash.Hasher;
47 import com.google.common.hash.Hashing;
50 * Dumb, store-everything-in-memory {@link Sone} implementation.
52 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54 public class DefaultSone implements Sone {
57 private static final Logger logger = Logging.getLogger(DefaultSone.class);
60 private final Database database;
62 /** The ID of this Sone. */
63 private final String id;
65 /** Whether the Sone is local. */
66 private final boolean local;
68 /** The identity of this Sone. */
69 private Identity identity;
71 /** The URI under which the Sone is stored in Freenet. */
72 private volatile FreenetURI requestUri;
74 /** The URI used to insert a new version of this Sone. */
75 /* This will be null for remote Sones! */
76 private volatile FreenetURI insertUri;
78 /** The latest edition of the Sone. */
79 private volatile long latestEdition;
81 /** The time of the last inserted update. */
82 private volatile long time;
84 /** The status of this Sone. */
85 private volatile SoneStatus status = SoneStatus.unknown;
87 /** The profile of this Sone. */
88 private volatile Profile profile = new Profile(this);
90 /** The client used by the Sone. */
91 private volatile Client client;
93 /** Whether this Sone is known. */
94 private volatile boolean known;
96 /** All friend Sones. */
97 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
100 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
103 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
105 /** The IDs of all liked posts. */
106 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
108 /** The IDs of all liked replies. */
109 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
111 /** The root album containing all albums. */
112 private final Album rootAlbum;
114 /** Sone-specific options. */
115 private Options options = new Options();
118 * Creates a new Sone.
123 * {@code true} if the Sone is a local Sone, {@code false} otherwise
125 public DefaultSone(Database database, String id, boolean local) {
126 this.database = database;
129 rootAlbum = new DefaultAlbumBuilder(database, this, null).randomId().build();
137 * Returns the identity of this Sone.
139 * @return The identity of this Sone
141 public String getId() {
146 * Returns the identity of this Sone.
148 * @return The identity of this Sone
150 public Identity getIdentity() {
155 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
156 * identity has to match this Sone’s {@link #getId()}.
159 * The identity of this Sone
160 * @return This Sone (for method chaining)
161 * @throws IllegalArgumentException
162 * if the ID of the identity does not match this Sone’s ID
164 public DefaultSone setIdentity(Identity identity) throws IllegalArgumentException {
165 if (!identity.getId().equals(id)) {
166 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
168 this.identity = identity;
173 * Returns the name of this Sone.
175 * @return The name of this Sone
177 public String getName() {
178 return (identity != null) ? identity.getNickname() : null;
182 * Returns whether this Sone is a local Sone.
184 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
186 public boolean isLocal() {
191 * Returns the request URI of this Sone.
193 * @return The request URI of this Sone
195 public FreenetURI getRequestUri() {
196 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
200 * Sets the request URI of this Sone.
203 * The request URI of this Sone
204 * @return This Sone (for method chaining)
206 public Sone setRequestUri(FreenetURI requestUri) {
207 if (this.requestUri == null) {
208 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
211 if (!this.requestUri.equalsKeypair(requestUri)) {
212 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
219 * Returns the insert URI of this Sone.
221 * @return The insert URI of this Sone
223 public FreenetURI getInsertUri() {
224 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
228 * Sets the insert URI of this Sone.
231 * The insert URI of this Sone
232 * @return This Sone (for method chaining)
234 public Sone setInsertUri(FreenetURI insertUri) {
235 if (this.insertUri == null) {
236 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
239 if (!this.insertUri.equalsKeypair(insertUri)) {
240 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
247 * Returns the latest edition of this Sone.
249 * @return The latest edition of this Sone
251 public long getLatestEdition() {
252 return latestEdition;
256 * Sets the latest edition of this Sone. If the given latest edition is not
257 * greater than the current latest edition, the latest edition of this Sone is
260 * @param latestEdition
261 * The latest edition of this Sone
263 public void setLatestEdition(long latestEdition) {
264 if (!(latestEdition > this.latestEdition)) {
265 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
268 this.latestEdition = latestEdition;
272 * Return the time of the last inserted update of this Sone.
274 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
276 public long getTime() {
281 * Sets the time of the last inserted update of this Sone.
284 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
285 * @return This Sone (for method chaining)
287 public Sone setTime(long time) {
293 * Returns the status of this Sone.
295 * @return The status of this Sone
297 public SoneStatus getStatus() {
302 * Sets the new status of this Sone.
305 * The new status of this Sone
307 * @throws IllegalArgumentException
308 * if {@code status} is {@code null}
310 public Sone setStatus(SoneStatus status) {
311 this.status = checkNotNull(status, "status must not be null");
316 * Returns a copy of the profile. If you want to update values in the profile
317 * of this Sone, update the values in the returned {@link Profile} and use
318 * {@link #setProfile(Profile)} to change the profile in this Sone.
320 * @return A copy of the profile
322 public Profile getProfile() {
323 return new Profile(profile);
327 * Sets the profile of this Sone. A copy of the given profile is stored so that
328 * subsequent modifications of the given profile are not reflected in this
334 public void setProfile(Profile profile) {
335 this.profile = new Profile(profile);
339 * Returns the client used by this Sone.
341 * @return The client used by this Sone, or {@code null}
343 public Client getClient() {
348 * Sets the client used by this Sone.
351 * The client used by this Sone, or {@code null}
352 * @return This Sone (for method chaining)
354 public Sone setClient(Client client) {
355 this.client = client;
360 * Returns whether this Sone is known.
362 * @return {@code true} if this Sone is known, {@code false} otherwise
364 public boolean isKnown() {
369 * Sets whether this Sone is known.
372 * {@code true} if this Sone is known, {@code false} otherwise
375 public Sone setKnown(boolean known) {
381 * Returns all friend Sones of this Sone.
383 * @return The friend Sones of this Sone
385 public List<String> getFriends() {
386 List<String> friends = new ArrayList<String>(friendSones);
391 * Returns whether this Sone has the given Sone as a friend Sone.
393 * @param friendSoneId
394 * The ID of the Sone to check for
395 * @return {@code true} if this Sone has the given Sone as a friend, {@code
398 public boolean hasFriend(String friendSoneId) {
399 return friendSones.contains(friendSoneId);
403 * Adds the given Sone as a friend Sone.
406 * The friend Sone to add
407 * @return This Sone (for method chaining)
409 public Sone addFriend(String friendSone) {
410 if (!friendSone.equals(id)) {
411 friendSones.add(friendSone);
417 * Removes the given Sone as a friend Sone.
419 * @param friendSoneId
420 * The ID of the friend Sone to remove
421 * @return This Sone (for method chaining)
423 public Sone removeFriend(String friendSoneId) {
424 friendSones.remove(friendSoneId);
429 * Returns the list of posts of this Sone, sorted by time, newest first.
431 * @return All posts of this Sone
433 public List<Post> getPosts() {
434 List<Post> sortedPosts;
435 synchronized (this) {
436 sortedPosts = new ArrayList<Post>(posts);
438 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
443 * Sets all posts of this Sone at once.
446 * The new (and only) posts of this Sone
447 * @return This Sone (for method chaining)
449 public Sone setPosts(Collection<Post> posts) {
450 synchronized (this) {
452 this.posts.addAll(posts);
458 * Adds the given post to this Sone. The post will not be added if its {@link
459 * Post#getSone() Sone} is not this Sone.
464 public void addPost(Post post) {
465 if (post.getSone().equals(this) && posts.add(post)) {
466 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
471 * Removes the given post from this Sone.
476 public void removePost(Post post) {
477 if (post.getSone().equals(this)) {
483 * Returns all replies this Sone made.
485 * @return All replies this Sone made
487 public Set<PostReply> getReplies() {
488 return Collections.unmodifiableSet(replies);
492 * Sets all replies of this Sone at once.
495 * The new (and only) replies of this Sone
496 * @return This Sone (for method chaining)
498 public Sone setReplies(Collection<PostReply> replies) {
499 this.replies.clear();
500 this.replies.addAll(replies);
505 * Adds a reply to this Sone. If the given reply was not made by this Sone,
506 * nothing is added to this Sone.
511 public void addReply(PostReply reply) {
512 if (reply.getSone().equals(this)) {
518 * Removes a reply from this Sone.
521 * The reply to remove
523 public void removeReply(PostReply reply) {
524 if (reply.getSone().equals(this)) {
525 replies.remove(reply);
530 * Returns the IDs of all liked posts.
532 * @return All liked posts’ IDs
534 public Set<String> getLikedPostIds() {
535 return Collections.unmodifiableSet(likedPostIds);
539 * Sets the IDs of all liked posts.
541 * @param likedPostIds
542 * All liked posts’ IDs
543 * @return This Sone (for method chaining)
545 public Sone setLikePostIds(Set<String> likedPostIds) {
546 this.likedPostIds.clear();
547 this.likedPostIds.addAll(likedPostIds);
552 * Checks whether the given post ID is liked by this Sone.
556 * @return {@code true} if this Sone likes the given post, {@code false}
559 public boolean isLikedPostId(String postId) {
560 return likedPostIds.contains(postId);
564 * Adds the given post ID to the list of posts this Sone likes.
568 * @return This Sone (for method chaining)
570 public Sone addLikedPostId(String postId) {
571 likedPostIds.add(postId);
576 * Removes the given post ID from the list of posts this Sone likes.
580 * @return This Sone (for method chaining)
582 public Sone removeLikedPostId(String postId) {
583 likedPostIds.remove(postId);
588 * Returns the IDs of all liked replies.
590 * @return All liked replies’ IDs
592 public Set<String> getLikedReplyIds() {
593 return Collections.unmodifiableSet(likedReplyIds);
597 * Sets the IDs of all liked replies.
599 * @param likedReplyIds
600 * All liked replies’ IDs
601 * @return This Sone (for method chaining)
603 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
604 this.likedReplyIds.clear();
605 this.likedReplyIds.addAll(likedReplyIds);
610 * Checks whether the given reply ID is liked by this Sone.
613 * The ID of the reply
614 * @return {@code true} if this Sone likes the given reply, {@code false}
617 public boolean isLikedReplyId(String replyId) {
618 return likedReplyIds.contains(replyId);
622 * Adds the given reply ID to the list of replies this Sone likes.
625 * The ID of the reply
626 * @return This Sone (for method chaining)
628 public Sone addLikedReplyId(String replyId) {
629 likedReplyIds.add(replyId);
634 * Removes the given post ID from the list of replies this Sone likes.
637 * The ID of the reply
638 * @return This Sone (for method chaining)
640 public Sone removeLikedReplyId(String replyId) {
641 likedReplyIds.remove(replyId);
646 * Returns the root album that contains all visible albums of this Sone.
648 * @return The root album of this Sone
650 public Album getRootAlbum() {
655 * Returns Sone-specific options.
657 * @return The options of this Sone
659 public Options getOptions() {
664 * Sets the options of this Sone.
667 * The options of this Sone
669 /* TODO - remove this method again, maybe add an option provider */
670 public void setOptions(Options options) {
671 this.options = options;
675 public AlbumBuilder newAlbumBuilder() {
676 return new DefaultAlbumBuilder(database, this, rootAlbum.getId());
680 // FINGERPRINTABLE METHODS
685 public synchronized String getFingerprint() {
686 Hasher hash = Hashing.sha256().newHasher();
687 hash.putString(profile.getFingerprint());
689 hash.putString("Posts(");
690 for (Post post : getPosts()) {
691 hash.putString("Post(").putString(post.getId()).putString(")");
695 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
696 Collections.sort(replies, Reply.TIME_COMPARATOR);
697 hash.putString("Replies(");
698 for (PostReply reply : replies) {
699 hash.putString("Reply(").putString(reply.getId()).putString(")");
703 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
704 Collections.sort(likedPostIds);
705 hash.putString("LikedPosts(");
706 for (String likedPostId : likedPostIds) {
707 hash.putString("Post(").putString(likedPostId).putString(")");
711 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
712 Collections.sort(likedReplyIds);
713 hash.putString("LikedReplies(");
714 for (String likedReplyId : likedReplyIds) {
715 hash.putString("Reply(").putString(likedReplyId).putString(")");
719 hash.putString("Albums(");
720 for (Album album : rootAlbum.getAlbums()) {
721 if (!Album.NOT_EMPTY.apply(album)) {
724 hash.putString(album.getFingerprint());
728 return hash.hash().toString();
732 // INTERFACE Comparable<Sone>
737 public int compareTo(Sone sone) {
738 return NICE_NAME_COMPARATOR.compare(this, sone);
747 public int hashCode() {
748 return id.hashCode();
753 public boolean equals(Object object) {
754 if (!(object instanceof Sone)) {
757 return ((Sone) object).getId().equals(id);
762 public String toString() {
763 return getClass().getName() + "[identity=" + identity + ",requestUri=" + requestUri + ",insertUri(" + String.valueOf(insertUri).length() + "),friends(" + friendSones.size() + "),posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";