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.database.PostBuilder;
42 import net.pterodactylus.sone.database.PostReplyBuilder;
43 import net.pterodactylus.sone.freenet.wot.Identity;
44 import net.pterodactylus.util.logging.Logging;
46 import freenet.keys.FreenetURI;
48 import com.google.common.base.Optional;
49 import com.google.common.hash.Hasher;
50 import com.google.common.hash.Hashing;
53 * Dumb, store-everything-in-memory {@link Sone} implementation.
55 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57 public class DefaultSone implements Sone {
60 private static final Logger logger = Logging.getLogger(DefaultSone.class);
63 private final Database database;
65 /** The ID of this Sone. */
66 private final String id;
68 /** Whether the Sone is local. */
69 private final boolean local;
71 /** The identity of this Sone. */
72 private Identity identity;
74 /** The URI under which the Sone is stored in Freenet. */
75 private volatile FreenetURI requestUri;
77 /** The URI used to insert a new version of this Sone. */
78 /* This will be null for remote Sones! */
79 private volatile FreenetURI insertUri;
81 /** The latest edition of the Sone. */
82 private volatile long latestEdition;
84 /** The time of the last inserted update. */
85 private volatile long time;
87 /** The status of this Sone. */
88 private volatile SoneStatus status = SoneStatus.unknown;
90 /** The profile of this Sone. */
91 private volatile Profile profile = new Profile(this);
93 /** The client used by the Sone. */
94 private volatile Client client;
96 /** Whether this Sone is known. */
97 private volatile boolean known;
99 /** All friend Sones. */
100 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
103 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
106 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
108 /** The IDs of all liked posts. */
109 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
111 /** The IDs of all liked replies. */
112 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
114 /** The root album containing all albums. */
115 private final Album rootAlbum;
117 /** Sone-specific options. */
118 private Options options = new Options();
121 * Creates a new Sone.
126 * {@code true} if the Sone is a local Sone, {@code false} otherwise
128 public DefaultSone(Database database, String id, boolean local) {
129 this.database = database;
132 rootAlbum = new DefaultAlbumBuilder(database, this, null).build();
140 * Returns the identity of this Sone.
142 * @return The identity of this Sone
144 public String getId() {
149 * Returns the identity of this Sone.
151 * @return The identity of this Sone
153 public Identity getIdentity() {
158 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
159 * identity has to match this Sone’s {@link #getId()}.
162 * The identity of this Sone
163 * @return This Sone (for method chaining)
164 * @throws IllegalArgumentException
165 * if the ID of the identity does not match this Sone’s ID
167 public DefaultSone setIdentity(Identity identity) throws IllegalArgumentException {
168 if (!identity.getId().equals(id)) {
169 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
171 this.identity = identity;
176 * Returns the name of this Sone.
178 * @return The name of this Sone
180 public String getName() {
181 return (identity != null) ? identity.getNickname() : null;
185 * Returns whether this Sone is a local Sone.
187 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
189 public boolean isLocal() {
194 * Returns the request URI of this Sone.
196 * @return The request URI of this Sone
198 public FreenetURI getRequestUri() {
199 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
203 * Sets the request URI of this Sone.
206 * The request URI of this Sone
207 * @return This Sone (for method chaining)
209 public Sone setRequestUri(FreenetURI requestUri) {
210 if (this.requestUri == null) {
211 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
214 if (!this.requestUri.equalsKeypair(requestUri)) {
215 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
222 * Returns the insert URI of this Sone.
224 * @return The insert URI of this Sone
226 public FreenetURI getInsertUri() {
227 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
231 * Sets the insert URI of this Sone.
234 * The insert URI of this Sone
235 * @return This Sone (for method chaining)
237 public Sone setInsertUri(FreenetURI insertUri) {
238 if (this.insertUri == null) {
239 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
242 if (!this.insertUri.equalsKeypair(insertUri)) {
243 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
250 * Returns the latest edition of this Sone.
252 * @return The latest edition of this Sone
254 public long getLatestEdition() {
255 return latestEdition;
259 * Sets the latest edition of this Sone. If the given latest edition is not
260 * greater than the current latest edition, the latest edition of this Sone is
263 * @param latestEdition
264 * The latest edition of this Sone
266 public void setLatestEdition(long latestEdition) {
267 if (!(latestEdition > this.latestEdition)) {
268 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
271 this.latestEdition = latestEdition;
275 * Return the time of the last inserted update of this Sone.
277 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
279 public long getTime() {
284 * Sets the time of the last inserted update of this Sone.
287 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
288 * @return This Sone (for method chaining)
290 public Sone setTime(long time) {
296 * Returns the status of this Sone.
298 * @return The status of this Sone
300 public SoneStatus getStatus() {
305 * Sets the new status of this Sone.
308 * The new status of this Sone
310 * @throws IllegalArgumentException
311 * if {@code status} is {@code null}
313 public Sone setStatus(SoneStatus status) {
314 this.status = checkNotNull(status, "status must not be null");
319 * Returns a copy of the profile. If you want to update values in the profile
320 * of this Sone, update the values in the returned {@link Profile} and use
321 * {@link #setProfile(Profile)} to change the profile in this Sone.
323 * @return A copy of the profile
325 public Profile getProfile() {
326 return new Profile(profile);
330 * Sets the profile of this Sone. A copy of the given profile is stored so that
331 * subsequent modifications of the given profile are not reflected in this
337 public void setProfile(Profile profile) {
338 this.profile = new Profile(profile);
342 * Returns the client used by this Sone.
344 * @return The client used by this Sone, or {@code null}
346 public Client getClient() {
351 * Sets the client used by this Sone.
354 * The client used by this Sone, or {@code null}
355 * @return This Sone (for method chaining)
357 public Sone setClient(Client client) {
358 this.client = client;
363 * Returns whether this Sone is known.
365 * @return {@code true} if this Sone is known, {@code false} otherwise
367 public boolean isKnown() {
372 * Sets whether this Sone is known.
375 * {@code true} if this Sone is known, {@code false} otherwise
378 public Sone setKnown(boolean known) {
384 * Returns all friend Sones of this Sone.
386 * @return The friend Sones of this Sone
388 public List<String> getFriends() {
389 List<String> friends = new ArrayList<String>(friendSones);
394 * Returns whether this Sone has the given Sone as a friend Sone.
396 * @param friendSoneId
397 * The ID of the Sone to check for
398 * @return {@code true} if this Sone has the given Sone as a friend, {@code
401 public boolean hasFriend(String friendSoneId) {
402 return friendSones.contains(friendSoneId);
406 * Adds the given Sone as a friend Sone.
409 * The friend Sone to add
410 * @return This Sone (for method chaining)
412 public Sone addFriend(String friendSone) {
413 if (!friendSone.equals(id)) {
414 friendSones.add(friendSone);
420 * Removes the given Sone as a friend Sone.
422 * @param friendSoneId
423 * The ID of the friend Sone to remove
424 * @return This Sone (for method chaining)
426 public Sone removeFriend(String friendSoneId) {
427 friendSones.remove(friendSoneId);
432 * Returns the list of posts of this Sone, sorted by time, newest first.
434 * @return All posts of this Sone
436 public List<Post> getPosts() {
437 List<Post> sortedPosts;
438 synchronized (this) {
439 sortedPosts = new ArrayList<Post>(posts);
441 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
446 * Sets all posts of this Sone at once.
449 * The new (and only) posts of this Sone
450 * @return This Sone (for method chaining)
452 public Sone setPosts(Collection<Post> posts) {
453 synchronized (this) {
455 this.posts.addAll(posts);
461 * Adds the given post to this Sone. The post will not be added if its {@link
462 * Post#getSone() Sone} is not this Sone.
467 public void addPost(Post post) {
468 if (post.getSone().equals(this) && posts.add(post)) {
469 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
474 * Removes the given post from this Sone.
479 public void removePost(Post post) {
480 if (post.getSone().equals(this)) {
486 * Returns all replies this Sone made.
488 * @return All replies this Sone made
490 public Set<PostReply> getReplies() {
491 return Collections.unmodifiableSet(replies);
495 * Sets all replies of this Sone at once.
498 * The new (and only) replies of this Sone
499 * @return This Sone (for method chaining)
501 public Sone setReplies(Collection<PostReply> replies) {
502 this.replies.clear();
503 this.replies.addAll(replies);
508 * Adds a reply to this Sone. If the given reply was not made by this Sone,
509 * nothing is added to this Sone.
514 public void addReply(PostReply reply) {
515 if (reply.getSone().equals(this)) {
521 * Removes a reply from this Sone.
524 * The reply to remove
526 public void removeReply(PostReply reply) {
527 if (reply.getSone().equals(this)) {
528 replies.remove(reply);
533 * Returns the IDs of all liked posts.
535 * @return All liked posts’ IDs
537 public Set<String> getLikedPostIds() {
538 return Collections.unmodifiableSet(likedPostIds);
542 * Sets the IDs of all liked posts.
544 * @param likedPostIds
545 * All liked posts’ IDs
546 * @return This Sone (for method chaining)
548 public Sone setLikePostIds(Set<String> likedPostIds) {
549 this.likedPostIds.clear();
550 this.likedPostIds.addAll(likedPostIds);
555 * Checks whether the given post ID is liked by this Sone.
559 * @return {@code true} if this Sone likes the given post, {@code false}
562 public boolean isLikedPostId(String postId) {
563 return likedPostIds.contains(postId);
567 * Adds the given post ID to the list of posts this Sone likes.
571 * @return This Sone (for method chaining)
573 public Sone addLikedPostId(String postId) {
574 likedPostIds.add(postId);
579 * Removes the given post ID from the list of posts this Sone likes.
583 * @return This Sone (for method chaining)
585 public Sone removeLikedPostId(String postId) {
586 likedPostIds.remove(postId);
591 * Returns the IDs of all liked replies.
593 * @return All liked replies’ IDs
595 public Set<String> getLikedReplyIds() {
596 return Collections.unmodifiableSet(likedReplyIds);
600 * Sets the IDs of all liked replies.
602 * @param likedReplyIds
603 * All liked replies’ IDs
604 * @return This Sone (for method chaining)
606 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
607 this.likedReplyIds.clear();
608 this.likedReplyIds.addAll(likedReplyIds);
613 * Checks whether the given reply ID is liked by this Sone.
616 * The ID of the reply
617 * @return {@code true} if this Sone likes the given reply, {@code false}
620 public boolean isLikedReplyId(String replyId) {
621 return likedReplyIds.contains(replyId);
625 * Adds the given reply ID to the list of replies this Sone likes.
628 * The ID of the reply
629 * @return This Sone (for method chaining)
631 public Sone addLikedReplyId(String replyId) {
632 likedReplyIds.add(replyId);
637 * Removes the given post ID from the list of replies this Sone likes.
640 * The ID of the reply
641 * @return This Sone (for method chaining)
643 public Sone removeLikedReplyId(String replyId) {
644 likedReplyIds.remove(replyId);
649 * Returns the root album that contains all visible albums of this Sone.
651 * @return The root album of this Sone
653 public Album getRootAlbum() {
658 * Returns Sone-specific options.
660 * @return The options of this Sone
662 public Options getOptions() {
667 * Sets the options of this Sone.
670 * The options of this Sone
672 /* TODO - remove this method again, maybe add an option provider */
673 public void setOptions(Options options) {
674 this.options = options;
678 public AlbumBuilder newAlbumBuilder() {
679 return new DefaultAlbumBuilder(database, this, rootAlbum.getId());
682 public PostBuilder newPostBuilder() {
683 return new DefaultPostBuilder(database, getId()) {
685 public Post build(Optional<PostCreated> postCreated) {
686 Post post = super.build(postCreated);
687 database.storePost(post);
694 public PostReplyBuilder newPostReplyBuilder(String postId) throws IllegalStateException {
695 return new DefaultPostReplyBuilder(database, getId(), postId) {
697 public PostReply build(Optional<PostReplyCreated> postReplyCreated) {
698 PostReply postReply = super.build(postReplyCreated);
699 database.storePostReply(postReply);
706 // FINGERPRINTABLE METHODS
711 public synchronized String getFingerprint() {
712 Hasher hash = Hashing.sha256().newHasher();
713 hash.putString(profile.getFingerprint());
715 hash.putString("Posts(");
716 for (Post post : getPosts()) {
717 hash.putString("Post(").putString(post.getId()).putString(")");
721 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
722 Collections.sort(replies, Reply.TIME_COMPARATOR);
723 hash.putString("Replies(");
724 for (PostReply reply : replies) {
725 hash.putString("Reply(").putString(reply.getId()).putString(")");
729 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
730 Collections.sort(likedPostIds);
731 hash.putString("LikedPosts(");
732 for (String likedPostId : likedPostIds) {
733 hash.putString("Post(").putString(likedPostId).putString(")");
737 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
738 Collections.sort(likedReplyIds);
739 hash.putString("LikedReplies(");
740 for (String likedReplyId : likedReplyIds) {
741 hash.putString("Reply(").putString(likedReplyId).putString(")");
745 hash.putString("Albums(");
746 for (Album album : rootAlbum.getAlbums()) {
747 if (!Album.NOT_EMPTY.apply(album)) {
750 hash.putString(album.getFingerprint());
754 return hash.hash().toString();
758 // INTERFACE Comparable<Sone>
763 public int compareTo(Sone sone) {
764 return NICE_NAME_COMPARATOR.compare(this, sone);
773 public int hashCode() {
774 return id.hashCode();
779 public boolean equals(Object object) {
780 if (!(object instanceof Sone)) {
783 return ((Sone) object).getId().equals(id);
788 public String toString() {
789 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() + ")]";