2 * Sone - SoneImpl.java - Copyright © 2010–2016 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;
21 import static java.lang.String.format;
22 import static java.util.logging.Logger.getLogger;
24 import java.net.MalformedURLException;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
30 import java.util.concurrent.CopyOnWriteArraySet;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.PostReply;
41 import net.pterodactylus.sone.data.Profile;
42 import net.pterodactylus.sone.data.Reply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.SoneOptions;
45 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
46 import net.pterodactylus.sone.database.Database;
47 import net.pterodactylus.sone.freenet.wot.Identity;
48 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
50 import freenet.keys.FreenetURI;
52 import com.google.common.hash.Hasher;
53 import com.google.common.hash.Hashing;
56 * {@link Sone} implementation.
58 * Operations that modify the Sone need to synchronize on the Sone in question.
60 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62 public class SoneImpl implements Sone {
65 private static final Logger logger = getLogger(SoneImpl.class.getName());
68 private final Database database;
70 /** The ID of this Sone. */
71 private final String id;
73 /** Whether the Sone is local. */
74 private final boolean local;
76 /** The identity of this Sone. */
77 private final Identity identity;
79 /** The latest edition of the Sone. */
80 private volatile long latestEdition;
82 /** The time of the last inserted update. */
83 private volatile long time;
85 /** The status of this Sone. */
86 private volatile SoneStatus status = SoneStatus.unknown;
88 /** The profile of this Sone. */
89 private volatile Profile profile = new Profile(this);
91 /** The client used by the Sone. */
92 private volatile Client client;
94 /** Whether this Sone is known. */
95 private volatile boolean known;
98 private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
101 private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
103 /** The IDs of all liked posts. */
104 private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
106 /** The IDs of all liked replies. */
107 private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
109 /** The root album containing all albums. */
110 private final Album rootAlbum = new AlbumImpl(this);
112 /** Sone-specific options. */
113 private SoneOptions options = new DefaultSoneOptions();
116 * Creates a new Sone.
118 * @param database The database
120 * The identity of the Sone
122 * {@code true} if the Sone is a local Sone, {@code false} otherwise
124 public SoneImpl(Database database, Identity identity, boolean local) {
125 this.database = database;
126 this.id = identity.getId();
127 this.identity = identity;
136 * Returns the identity of this Sone.
138 * @return The identity of this Sone
141 public String getId() {
146 * Returns the identity of this Sone.
148 * @return The identity of this Sone
151 public Identity getIdentity() {
156 * Returns the name of this Sone.
158 * @return The name of this Sone
161 public String getName() {
162 return (identity != null) ? identity.getNickname() : null;
166 * Returns whether this Sone is a local Sone.
168 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
170 public boolean isLocal() {
175 * Returns the request URI of this Sone.
177 * @return The request URI of this Sone
180 public FreenetURI getRequestUri() {
182 return new FreenetURI(getIdentity().getRequestUri())
185 .setMetaString(new String[0])
186 .setSuggestedEdition(latestEdition);
187 } catch (MalformedURLException e) {
188 throw new IllegalStateException(
189 format("Identity %s's request URI is incorrect.",
195 * Returns the insert URI of this Sone.
197 * @return The insert URI of this Sone
200 public FreenetURI getInsertUri() {
205 return new FreenetURI(((OwnIdentity) getIdentity()).getInsertUri())
207 .setMetaString(new String[0])
208 .setSuggestedEdition(latestEdition);
209 } catch (MalformedURLException e) {
210 throw new IllegalStateException(format("Own identity %s's insert URI is incorrect.", getIdentity()), e);
215 * Returns the latest edition of this Sone.
217 * @return The latest edition of this Sone
219 public long getLatestEdition() {
220 return latestEdition;
224 * Sets the latest edition of this Sone. If the given latest edition is not
225 * greater than the current latest edition, the latest edition of this Sone is
228 * @param latestEdition
229 * The latest edition of this Sone
231 public void setLatestEdition(long latestEdition) {
232 if (!(latestEdition > this.latestEdition)) {
233 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
236 this.latestEdition = latestEdition;
240 * Return the time of the last inserted update of this Sone.
242 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
244 public long getTime() {
249 * Sets the time of the last inserted update of this Sone.
252 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
253 * @return This Sone (for method chaining)
256 public Sone setTime(long time) {
262 * Returns the status of this Sone.
264 * @return The status of this Sone
267 public SoneStatus getStatus() {
272 * Sets the new status of this Sone.
275 * The new status of this Sone
277 * @throws IllegalArgumentException
278 * if {@code status} is {@code null}
281 public Sone setStatus(@Nonnull SoneStatus status) {
282 this.status = checkNotNull(status, "status must not be null");
287 * Returns a copy of the profile. If you want to update values in the profile
288 * of this Sone, update the values in the returned {@link Profile} and use
289 * {@link #setProfile(Profile)} to change the profile in this Sone.
291 * @return A copy of the profile
294 public Profile getProfile() {
295 return new Profile(profile);
299 * Sets the profile of this Sone. A copy of the given profile is stored so that
300 * subsequent modifications of the given profile are not reflected in this
306 public void setProfile(@Nonnull Profile profile) {
307 this.profile = new Profile(profile);
311 * Returns the client used by this Sone.
313 * @return The client used by this Sone, or {@code null}
316 public Client getClient() {
321 * Sets the client used by this Sone.
324 * The client used by this Sone, or {@code null}
325 * @return This Sone (for method chaining)
328 public Sone setClient(@Nullable Client client) {
329 this.client = client;
334 * Returns whether this Sone is known.
336 * @return {@code true} if this Sone is known, {@code false} otherwise
338 public boolean isKnown() {
343 * Sets whether this Sone is known.
346 * {@code true} if this Sone is known, {@code false} otherwise
350 public Sone setKnown(boolean known) {
356 * Returns all friend Sones of this Sone.
358 * @return The friend Sones of this Sone
361 public Collection<String> getFriends() {
362 return database.getFriends(this);
366 * Returns whether this Sone has the given Sone as a friend Sone.
368 * @param friendSoneId
369 * The ID of the Sone to check for
370 * @return {@code true} if this Sone has the given Sone as a friend, {@code
373 public boolean hasFriend(@Nonnull String friendSoneId) {
374 return database.isFriend(this, friendSoneId);
378 * Returns the list of posts of this Sone, sorted by time, newest first.
380 * @return All posts of this Sone
383 public List<Post> getPosts() {
384 List<Post> sortedPosts;
385 synchronized (this) {
386 sortedPosts = new ArrayList<Post>(posts);
388 Collections.sort(sortedPosts, Post.NEWEST_FIRST);
393 * Sets all posts of this Sone at once.
396 * The new (and only) posts of this Sone
397 * @return This Sone (for method chaining)
400 public Sone setPosts(@Nonnull Collection<Post> posts) {
401 synchronized (this) {
403 this.posts.addAll(posts);
409 * Adds the given post to this Sone. The post will not be added if its {@link
410 * Post#getSone() Sone} is not this Sone.
415 public void addPost(@Nonnull Post post) {
416 if (post.getSone().equals(this) && posts.add(post)) {
417 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
422 * Removes the given post from this Sone.
427 public void removePost(@Nonnull Post post) {
428 if (post.getSone().equals(this)) {
434 * Returns all replies this Sone made.
436 * @return All replies this Sone made
439 public Set<PostReply> getReplies() {
440 return Collections.unmodifiableSet(replies);
444 * Sets all replies of this Sone at once.
447 * The new (and only) replies of this Sone
448 * @return This Sone (for method chaining)
451 public Sone setReplies(@Nonnull Collection<PostReply> replies) {
452 this.replies.clear();
453 this.replies.addAll(replies);
458 * Adds a reply to this Sone. If the given reply was not made by this Sone,
459 * nothing is added to this Sone.
464 public void addReply(@Nonnull PostReply reply) {
465 if (reply.getSone().equals(this)) {
471 * Removes a reply from this Sone.
474 * The reply to remove
476 public void removeReply(@Nonnull PostReply reply) {
477 if (reply.getSone().equals(this)) {
478 replies.remove(reply);
483 * Returns the IDs of all liked posts.
485 * @return All liked posts’ IDs
488 public Set<String> getLikedPostIds() {
489 return Collections.unmodifiableSet(likedPostIds);
493 * Sets the IDs of all liked posts.
495 * @param likedPostIds
496 * All liked posts’ IDs
497 * @return This Sone (for method chaining)
500 public Sone setLikePostIds(@Nonnull Set<String> likedPostIds) {
501 this.likedPostIds.clear();
502 this.likedPostIds.addAll(likedPostIds);
507 * Checks whether the given post ID is liked by this Sone.
511 * @return {@code true} if this Sone likes the given post, {@code false}
514 public boolean isLikedPostId(@Nonnull String postId) {
515 return likedPostIds.contains(postId);
519 * Adds the given post ID to the list of posts this Sone likes.
523 * @return This Sone (for method chaining)
526 public Sone addLikedPostId(@Nonnull String postId) {
527 likedPostIds.add(postId);
532 * Removes the given post ID from the list of posts this Sone likes.
536 * @return This Sone (for method chaining)
539 public Sone removeLikedPostId(@Nonnull String postId) {
540 likedPostIds.remove(postId);
545 * Returns the IDs of all liked replies.
547 * @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)
562 public Sone setLikeReplyIds(@Nonnull Set<String> likedReplyIds) {
563 this.likedReplyIds.clear();
564 this.likedReplyIds.addAll(likedReplyIds);
569 * Checks whether the given reply ID is liked by this Sone.
572 * The ID of the reply
573 * @return {@code true} if this Sone likes the given reply, {@code false}
576 public boolean isLikedReplyId(@Nonnull String replyId) {
577 return likedReplyIds.contains(replyId);
581 * Adds the given reply ID to the list of replies this Sone likes.
584 * The ID of the reply
585 * @return This Sone (for method chaining)
588 public Sone addLikedReplyId(@Nonnull String replyId) {
589 likedReplyIds.add(replyId);
594 * Removes the given post ID from the list of replies this Sone likes.
597 * The ID of the reply
598 * @return This Sone (for method chaining)
601 public Sone removeLikedReplyId(@Nonnull String replyId) {
602 likedReplyIds.remove(replyId);
607 * Returns the root album that contains all visible albums of this Sone.
609 * @return The root album of this Sone
612 public Album getRootAlbum() {
617 * Returns Sone-specific options.
619 * @return The options of this Sone
622 public SoneOptions getOptions() {
627 * Sets the options of this Sone.
630 * The options of this Sone
632 /* TODO - remove this method again, maybe add an option provider */
633 public void setOptions(@Nonnull SoneOptions options) {
634 this.options = options;
638 // FINGERPRINTABLE METHODS
643 public synchronized String getFingerprint() {
644 Hasher hash = Hashing.sha256().newHasher();
645 hash.putString(profile.getFingerprint());
647 hash.putString("Posts(");
648 for (Post post : getPosts()) {
649 hash.putString("Post(").putString(post.getId()).putString(")");
653 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
654 Collections.sort(replies, Reply.TIME_COMPARATOR);
655 hash.putString("Replies(");
656 for (PostReply reply : replies) {
657 hash.putString("Reply(").putString(reply.getId()).putString(")");
661 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
662 Collections.sort(likedPostIds);
663 hash.putString("LikedPosts(");
664 for (String likedPostId : likedPostIds) {
665 hash.putString("Post(").putString(likedPostId).putString(")");
669 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
670 Collections.sort(likedReplyIds);
671 hash.putString("LikedReplies(");
672 for (String likedReplyId : likedReplyIds) {
673 hash.putString("Reply(").putString(likedReplyId).putString(")");
677 hash.putString("Albums(");
678 for (Album album : rootAlbum.getAlbums()) {
679 if (!Album.NOT_EMPTY.apply(album)) {
682 hash.putString(album.getFingerprint());
686 return hash.hash().toString();
690 // INTERFACE Comparable<Sone>
695 public int compareTo(Sone sone) {
696 return NICE_NAME_COMPARATOR.compare(this, sone);
705 public int hashCode() {
706 return id.hashCode();
711 public boolean equals(Object object) {
712 if (!(object instanceof Sone)) {
715 return ((Sone) object).getId().equals(id);
720 public String toString() {
721 return getClass().getName() + "[identity=" + identity + ",posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";