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.freenet.wot.Identity;
43 import net.pterodactylus.util.logging.Logging;
45 import freenet.keys.FreenetURI;
47 import com.google.common.base.Optional;
48 import com.google.common.hash.Hasher;
49 import com.google.common.hash.Hashing;
52 * Dumb, store-everything-in-memory {@link Sone} implementation.
54 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56 public class DefaultSone implements Sone {
59 private static final Logger logger = Logging.getLogger(DefaultSone.class);
62 private final Database database;
64 /** The ID of this Sone. */
65 private final String id;
67 /** Whether the Sone is local. */
68 private final boolean local;
70 /** The identity of this Sone. */
71 private Identity identity;
73 /** The URI under which the Sone is stored in Freenet. */
74 private volatile FreenetURI requestUri;
76 /** The URI used to insert a new version of this Sone. */
77 /* This will be null for remote Sones! */
78 private volatile FreenetURI insertUri;
80 /** The latest edition of the Sone. */
81 private volatile long latestEdition;
83 /** The time of the last inserted update. */
84 private volatile long time;
86 /** The status of this Sone. */
87 private volatile SoneStatus status = SoneStatus.unknown;
89 /** The profile of this Sone. */
90 private volatile Profile profile = new Profile(this);
92 /** The client used by the Sone. */
93 private volatile Client client;
95 /** Whether this Sone is known. */
96 private volatile boolean known;
98 /** All friend Sones. */
99 private final Set<String> friendSones = new CopyOnWriteArraySet<String>();
102 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
105 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
107 /** The IDs of all liked posts. */
108 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
110 /** The IDs of all liked replies. */
111 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
113 /** The root album containing all albums. */
114 private final Album rootAlbum;
116 /** Sone-specific options. */
117 private Options options = new Options();
120 * Creates a new Sone.
125 * {@code true} if the Sone is a local Sone, {@code false} otherwise
127 public DefaultSone(Database database, String id, boolean local) {
128 this.database = database;
131 rootAlbum = new DefaultAlbumBuilder(database, this, null).randomId().build();
139 * Returns the identity of this Sone.
141 * @return The identity of this Sone
143 public String getId() {
148 * Returns the identity of this Sone.
150 * @return The identity of this Sone
152 public Identity getIdentity() {
157 * Sets the identity of this Sone. The {@link Identity#getId() ID} of the
158 * identity has to match this Sone’s {@link #getId()}.
161 * The identity of this Sone
162 * @return This Sone (for method chaining)
163 * @throws IllegalArgumentException
164 * if the ID of the identity does not match this Sone’s ID
166 public DefaultSone setIdentity(Identity identity) throws IllegalArgumentException {
167 if (!identity.getId().equals(id)) {
168 throw new IllegalArgumentException("Identity’s ID does not match Sone’s ID!");
170 this.identity = identity;
175 * Returns the name of this Sone.
177 * @return The name of this Sone
179 public String getName() {
180 return (identity != null) ? identity.getNickname() : null;
184 * Returns whether this Sone is a local Sone.
186 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
188 public boolean isLocal() {
193 * Returns the request URI of this Sone.
195 * @return The request URI of this Sone
197 public FreenetURI getRequestUri() {
198 return (requestUri != null) ? requestUri.setSuggestedEdition(latestEdition) : null;
202 * Sets the request URI of this Sone.
205 * The request URI of this Sone
206 * @return This Sone (for method chaining)
208 public Sone setRequestUri(FreenetURI requestUri) {
209 if (this.requestUri == null) {
210 this.requestUri = requestUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
213 if (!this.requestUri.equalsKeypair(requestUri)) {
214 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", requestUri, this.requestUri));
221 * Returns the insert URI of this Sone.
223 * @return The insert URI of this Sone
225 public FreenetURI getInsertUri() {
226 return (insertUri != null) ? insertUri.setSuggestedEdition(latestEdition) : null;
230 * Sets the insert URI of this Sone.
233 * The insert URI of this Sone
234 * @return This Sone (for method chaining)
236 public Sone setInsertUri(FreenetURI insertUri) {
237 if (this.insertUri == null) {
238 this.insertUri = insertUri.setKeyType("USK").setDocName("Sone").setMetaString(new String[0]);
241 if (!this.insertUri.equalsKeypair(insertUri)) {
242 logger.log(Level.WARNING, String.format("Request URI %s tried to overwrite %s!", insertUri, this.insertUri));
249 * Returns the latest edition of this Sone.
251 * @return The latest edition of this Sone
253 public long getLatestEdition() {
254 return latestEdition;
258 * Sets the latest edition of this Sone. If the given latest edition is not
259 * greater than the current latest edition, the latest edition of this Sone is
262 * @param latestEdition
263 * The latest edition of this Sone
265 public void setLatestEdition(long latestEdition) {
266 if (!(latestEdition > this.latestEdition)) {
267 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
270 this.latestEdition = latestEdition;
274 * Return the time of the last inserted update of this Sone.
276 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
278 public long getTime() {
283 * Sets the time of the last inserted update of this Sone.
286 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
287 * @return This Sone (for method chaining)
289 public Sone setTime(long time) {
295 * Returns the status of this Sone.
297 * @return The status of this Sone
299 public SoneStatus getStatus() {
304 * Sets the new status of this Sone.
307 * The new status of this Sone
309 * @throws IllegalArgumentException
310 * if {@code status} is {@code null}
312 public Sone setStatus(SoneStatus status) {
313 this.status = checkNotNull(status, "status must not be null");
318 * Returns a copy of the profile. If you want to update values in the profile
319 * of this Sone, update the values in the returned {@link Profile} and use
320 * {@link #setProfile(Profile)} to change the profile in this Sone.
322 * @return A copy of the profile
324 public Profile getProfile() {
325 return new Profile(profile);
329 * Sets the profile of this Sone. A copy of the given profile is stored so that
330 * subsequent modifications of the given profile are not reflected in this
336 public void setProfile(Profile profile) {
337 this.profile = new Profile(profile);
341 * Returns the client used by this Sone.
343 * @return The client used by this Sone, or {@code null}
345 public Client getClient() {
350 * Sets the client used by this Sone.
353 * The client used by this Sone, or {@code null}
354 * @return This Sone (for method chaining)
356 public Sone setClient(Client client) {
357 this.client = client;
362 * Returns whether this Sone is known.
364 * @return {@code true} if this Sone is known, {@code false} otherwise
366 public boolean isKnown() {
371 * Sets whether this Sone is known.
374 * {@code true} if this Sone is known, {@code false} otherwise
377 public Sone setKnown(boolean known) {
383 * Returns all friend Sones of this Sone.
385 * @return The friend Sones of this Sone
387 public List<String> getFriends() {
388 List<String> friends = new ArrayList<String>(friendSones);
393 * Returns whether this Sone has the given Sone as a friend Sone.
395 * @param friendSoneId
396 * The ID of the Sone to check for
397 * @return {@code true} if this Sone has the given Sone as a friend, {@code
400 public boolean hasFriend(String friendSoneId) {
401 return friendSones.contains(friendSoneId);
405 * Adds the given Sone as a friend Sone.
408 * The friend Sone to add
409 * @return This Sone (for method chaining)
411 public Sone addFriend(String friendSone) {
412 if (!friendSone.equals(id)) {
413 friendSones.add(friendSone);
419 * Removes the given Sone as a friend Sone.
421 * @param friendSoneId
422 * The ID of the friend Sone to remove
423 * @return This Sone (for method chaining)
425 public Sone removeFriend(String friendSoneId) {
426 friendSones.remove(friendSoneId);
431 * Returns the list of posts of this Sone, sorted by time, newest first.
433 * @return All posts of this Sone
435 public List<Post> getPosts() {
436 List<Post> sortedPosts;
437 synchronized (this) {
438 sortedPosts = new ArrayList<Post>(posts);
440 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
445 * Sets all posts of this Sone at once.
448 * The new (and only) posts of this Sone
449 * @return This Sone (for method chaining)
451 public Sone setPosts(Collection<Post> posts) {
452 synchronized (this) {
454 this.posts.addAll(posts);
460 * Adds the given post to this Sone. The post will not be added if its {@link
461 * Post#getSone() Sone} is not this Sone.
466 public void addPost(Post post) {
467 if (post.getSone().equals(this) && posts.add(post)) {
468 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
473 * Removes the given post from this Sone.
478 public void removePost(Post post) {
479 if (post.getSone().equals(this)) {
485 * Returns all replies this Sone made.
487 * @return All replies this Sone made
489 public Set<PostReply> getReplies() {
490 return Collections.unmodifiableSet(replies);
494 * Sets all replies of this Sone at once.
497 * The new (and only) replies of this Sone
498 * @return This Sone (for method chaining)
500 public Sone setReplies(Collection<PostReply> replies) {
501 this.replies.clear();
502 this.replies.addAll(replies);
507 * Adds a reply to this Sone. If the given reply was not made by this Sone,
508 * nothing is added to this Sone.
513 public void addReply(PostReply reply) {
514 if (reply.getSone().equals(this)) {
520 * Removes a reply from this Sone.
523 * The reply to remove
525 public void removeReply(PostReply reply) {
526 if (reply.getSone().equals(this)) {
527 replies.remove(reply);
532 * Returns the IDs of all liked posts.
534 * @return All liked posts’ IDs
536 public Set<String> getLikedPostIds() {
537 return Collections.unmodifiableSet(likedPostIds);
541 * Sets the IDs of all liked posts.
543 * @param likedPostIds
544 * All liked posts’ IDs
545 * @return This Sone (for method chaining)
547 public Sone setLikePostIds(Set<String> likedPostIds) {
548 this.likedPostIds.clear();
549 this.likedPostIds.addAll(likedPostIds);
554 * Checks whether the given post ID is liked by this Sone.
558 * @return {@code true} if this Sone likes the given post, {@code false}
561 public boolean isLikedPostId(String postId) {
562 return likedPostIds.contains(postId);
566 * Adds the given post ID to the list of posts this Sone likes.
570 * @return This Sone (for method chaining)
572 public Sone addLikedPostId(String postId) {
573 likedPostIds.add(postId);
578 * Removes the given post ID from the list of posts this Sone likes.
582 * @return This Sone (for method chaining)
584 public Sone removeLikedPostId(String postId) {
585 likedPostIds.remove(postId);
590 * Returns the IDs of all liked replies.
592 * @return All liked replies’ IDs
594 public Set<String> getLikedReplyIds() {
595 return Collections.unmodifiableSet(likedReplyIds);
599 * Sets the IDs of all liked replies.
601 * @param likedReplyIds
602 * All liked replies’ IDs
603 * @return This Sone (for method chaining)
605 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
606 this.likedReplyIds.clear();
607 this.likedReplyIds.addAll(likedReplyIds);
612 * Checks whether the given reply ID is liked by this Sone.
615 * The ID of the reply
616 * @return {@code true} if this Sone likes the given reply, {@code false}
619 public boolean isLikedReplyId(String replyId) {
620 return likedReplyIds.contains(replyId);
624 * Adds the given reply ID to the list of replies this Sone likes.
627 * The ID of the reply
628 * @return This Sone (for method chaining)
630 public Sone addLikedReplyId(String replyId) {
631 likedReplyIds.add(replyId);
636 * Removes the given post ID from the list of replies this Sone likes.
639 * The ID of the reply
640 * @return This Sone (for method chaining)
642 public Sone removeLikedReplyId(String replyId) {
643 likedReplyIds.remove(replyId);
648 * Returns the root album that contains all visible albums of this Sone.
650 * @return The root album of this Sone
652 public Album getRootAlbum() {
657 * Returns Sone-specific options.
659 * @return The options of this Sone
661 public Options getOptions() {
666 * Sets the options of this Sone.
669 * The options of this Sone
671 /* TODO - remove this method again, maybe add an option provider */
672 public void setOptions(Options options) {
673 this.options = options;
677 public AlbumBuilder newAlbumBuilder() {
678 return new DefaultAlbumBuilder(database, this, rootAlbum.getId());
681 public PostBuilder newPostBuilder() {
682 return new DefaultPostBuilder(database, getId()) {
684 public Post build(Optional<PostCreated> postCreated) {
685 Post post = super.build(postCreated);
686 database.storePost(post);
693 // FINGERPRINTABLE METHODS
698 public synchronized String getFingerprint() {
699 Hasher hash = Hashing.sha256().newHasher();
700 hash.putString(profile.getFingerprint());
702 hash.putString("Posts(");
703 for (Post post : getPosts()) {
704 hash.putString("Post(").putString(post.getId()).putString(")");
708 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
709 Collections.sort(replies, Reply.TIME_COMPARATOR);
710 hash.putString("Replies(");
711 for (PostReply reply : replies) {
712 hash.putString("Reply(").putString(reply.getId()).putString(")");
716 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
717 Collections.sort(likedPostIds);
718 hash.putString("LikedPosts(");
719 for (String likedPostId : likedPostIds) {
720 hash.putString("Post(").putString(likedPostId).putString(")");
724 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
725 Collections.sort(likedReplyIds);
726 hash.putString("LikedReplies(");
727 for (String likedReplyId : likedReplyIds) {
728 hash.putString("Reply(").putString(likedReplyId).putString(")");
732 hash.putString("Albums(");
733 for (Album album : rootAlbum.getAlbums()) {
734 if (!Album.NOT_EMPTY.apply(album)) {
737 hash.putString(album.getFingerprint());
741 return hash.hash().toString();
745 // INTERFACE Comparable<Sone>
750 public int compareTo(Sone sone) {
751 return NICE_NAME_COMPARATOR.compare(this, sone);
760 public int hashCode() {
761 return id.hashCode();
766 public boolean equals(Object object) {
767 if (!(object instanceof Sone)) {
770 return ((Sone) object).getId().equals(id);
775 public String toString() {
776 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() + ")]";