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;
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;
33 import javax.annotation.Nullable;
35 import net.pterodactylus.sone.data.Album;
36 import net.pterodactylus.sone.data.Client;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Profile;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.data.SoneOptions;
44 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
45 import net.pterodactylus.sone.database.Database;
46 import net.pterodactylus.sone.freenet.wot.Identity;
47 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
49 import com.google.common.base.Optional;
50 import com.google.common.base.Predicate;
51 import com.google.common.collect.FluentIterable;
52 import freenet.keys.FreenetURI;
54 import com.google.common.hash.Hasher;
55 import com.google.common.hash.Hashing;
58 * {@link Sone} implementation.
60 * Operations that modify the Sone need to synchronize on the Sone in question.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public class SoneImpl implements Sone {
67 private static final Logger logger = getLogger(SoneImpl.class.getName());
70 private final Database database;
72 /** The ID of this Sone. */
73 private final String id;
75 /** Whether the Sone is local. */
76 private final boolean local;
78 /** The identity of this Sone. */
79 private final Identity identity;
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;
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 = new AlbumImpl(this);
114 /** Sone-specific options. */
115 private SoneOptions options = new DefaultSoneOptions();
118 * Creates a new Sone.
120 * @param database The database
122 * The identity of the Sone
124 * {@code true} if the Sone is a local Sone, {@code false} otherwise
126 public SoneImpl(Database database, Identity identity, boolean local) {
127 this.database = database;
128 this.id = identity.getId();
129 this.identity = identity;
138 * Returns the identity of this Sone.
140 * @return The identity of this Sone
142 public String getId() {
147 * Returns the identity of this Sone.
149 * @return The identity of this Sone
151 public Identity getIdentity() {
156 * Returns the name of this Sone.
158 * @return The name of this Sone
160 public String getName() {
161 return (identity != null) ? identity.getNickname() : null;
165 * Returns whether this Sone is a local Sone.
167 * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
169 public boolean isLocal() {
174 * Returns the request URI of this Sone.
176 * @return The request URI of this Sone
178 public FreenetURI getRequestUri() {
180 return new FreenetURI(getIdentity().getRequestUri())
183 .setMetaString(new String[0])
184 .setSuggestedEdition(latestEdition);
185 } catch (MalformedURLException e) {
186 throw new IllegalStateException(
187 format("Identity %s's request URI is incorrect.",
193 * Returns the insert URI of this Sone.
195 * @return The insert URI of this Sone
197 public FreenetURI getInsertUri() {
202 return new FreenetURI(((OwnIdentity) getIdentity()).getInsertUri())
204 .setMetaString(new String[0])
205 .setSuggestedEdition(latestEdition);
206 } catch (MalformedURLException e) {
207 throw new IllegalStateException(format("Own identity %s's insert URI is incorrect.", getIdentity()), e);
212 * Returns the latest edition of this Sone.
214 * @return The latest edition of this Sone
216 public long getLatestEdition() {
217 return latestEdition;
221 * Sets the latest edition of this Sone. If the given latest edition is not
222 * greater than the current latest edition, the latest edition of this Sone is
225 * @param latestEdition
226 * The latest edition of this Sone
228 public void setLatestEdition(long latestEdition) {
229 if (!(latestEdition > this.latestEdition)) {
230 logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
233 this.latestEdition = latestEdition;
237 * Return the time of the last inserted update of this Sone.
239 * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
241 public long getTime() {
246 * Sets the time of the last inserted update of this Sone.
249 * The time of the update (in milliseconds since Jan 1, 1970 UTC)
250 * @return This Sone (for method chaining)
252 public Sone setTime(long time) {
258 * Returns the status of this Sone.
260 * @return The status of this Sone
262 public SoneStatus getStatus() {
267 * Sets the new status of this Sone.
270 * The new status of this Sone
272 * @throws IllegalArgumentException
273 * if {@code status} is {@code null}
275 public Sone setStatus(SoneStatus status) {
276 this.status = checkNotNull(status, "status must not be null");
281 * Returns a copy of the profile. If you want to update values in the profile
282 * of this Sone, update the values in the returned {@link Profile} and use
283 * {@link #setProfile(Profile)} to change the profile in this Sone.
285 * @return A copy of the profile
287 public Profile getProfile() {
288 return new Profile(profile);
292 * Sets the profile of this Sone. A copy of the given profile is stored so that
293 * subsequent modifications of the given profile are not reflected in this
299 public void setProfile(Profile profile) {
300 this.profile = new Profile(profile);
304 * Returns the client used by this Sone.
306 * @return The client used by this Sone, or {@code null}
308 public Client getClient() {
313 * Sets the client used by this Sone.
316 * The client used by this Sone, or {@code null}
317 * @return This Sone (for method chaining)
319 public Sone setClient(Client client) {
320 this.client = client;
325 * Returns whether this Sone is known.
327 * @return {@code true} if this Sone is known, {@code false} otherwise
329 public boolean isKnown() {
334 * Sets whether this Sone is known.
337 * {@code true} if this Sone is known, {@code false} otherwise
340 public Sone setKnown(boolean known) {
346 * Returns all friend Sones of this Sone.
348 * @return The friend Sones of this Sone
350 public Collection<String> getFriends() {
351 return database.getFriends(this);
355 * Returns whether this Sone has the given Sone as a friend Sone.
357 * @param friendSoneId
358 * The ID of the Sone to check for
359 * @return {@code true} if this Sone has the given Sone as a friend, {@code
362 public boolean hasFriend(String friendSoneId) {
363 return database.isFriend(this, friendSoneId);
367 * Returns the list of posts of this Sone, sorted by time, newest first.
369 * @return All posts of this Sone
371 public List<Post> getPosts() {
372 List<Post> sortedPosts;
373 synchronized (this) {
374 sortedPosts = new ArrayList<Post>(posts);
376 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
381 * Sets all posts of this Sone at once.
384 * The new (and only) posts of this Sone
385 * @return This Sone (for method chaining)
387 public Sone setPosts(Collection<Post> posts) {
388 synchronized (this) {
390 this.posts.addAll(posts);
396 * Adds the given post to this Sone. The post will not be added if its {@link
397 * Post#getSone() Sone} is not this Sone.
402 public void addPost(Post post) {
403 if (post.getSone().equals(this) && posts.add(post)) {
404 logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
409 * Removes the given post from this Sone.
414 public void removePost(Post post) {
415 if (post.getSone().equals(this)) {
421 * Returns all replies this Sone made.
423 * @return All replies this Sone made
425 public Set<PostReply> getReplies() {
426 return Collections.unmodifiableSet(replies);
430 * Sets all replies of this Sone at once.
433 * The new (and only) replies of this Sone
434 * @return This Sone (for method chaining)
436 public Sone setReplies(Collection<PostReply> replies) {
437 this.replies.clear();
438 this.replies.addAll(replies);
443 * Adds a reply to this Sone. If the given reply was not made by this Sone,
444 * nothing is added to this Sone.
449 public void addReply(PostReply reply) {
450 if (reply.getSone().equals(this)) {
456 * Removes a reply from this Sone.
459 * The reply to remove
461 public void removeReply(PostReply reply) {
462 if (reply.getSone().equals(this)) {
463 replies.remove(reply);
468 * Returns the IDs of all liked posts.
470 * @return All liked posts’ IDs
472 public Set<String> getLikedPostIds() {
473 return Collections.unmodifiableSet(likedPostIds);
477 * Sets the IDs of all liked posts.
479 * @param likedPostIds
480 * All liked posts’ IDs
481 * @return This Sone (for method chaining)
483 public Sone setLikePostIds(Set<String> likedPostIds) {
484 this.likedPostIds.clear();
485 this.likedPostIds.addAll(likedPostIds);
490 * Checks whether the given post ID is liked by this Sone.
494 * @return {@code true} if this Sone likes the given post, {@code false}
497 public boolean isLikedPostId(String postId) {
498 return likedPostIds.contains(postId);
502 * Adds the given post ID to the list of posts this Sone likes.
506 * @return This Sone (for method chaining)
508 public Sone addLikedPostId(String postId) {
509 likedPostIds.add(postId);
514 * Removes the given post ID from the list of posts this Sone likes.
518 * @return This Sone (for method chaining)
520 public Sone removeLikedPostId(String postId) {
521 likedPostIds.remove(postId);
526 * Returns the IDs of all liked replies.
528 * @return All liked replies’ IDs
530 public Set<String> getLikedReplyIds() {
531 return Collections.unmodifiableSet(likedReplyIds);
535 * Sets the IDs of all liked replies.
537 * @param likedReplyIds
538 * All liked replies’ IDs
539 * @return This Sone (for method chaining)
541 public Sone setLikeReplyIds(Set<String> likedReplyIds) {
542 this.likedReplyIds.clear();
543 this.likedReplyIds.addAll(likedReplyIds);
548 * Checks whether the given reply ID is liked by this Sone.
551 * The ID of the reply
552 * @return {@code true} if this Sone likes the given reply, {@code false}
555 public boolean isLikedReplyId(String replyId) {
556 return likedReplyIds.contains(replyId);
560 * Adds the given reply ID to the list of replies this Sone likes.
563 * The ID of the reply
564 * @return This Sone (for method chaining)
566 public Sone addLikedReplyId(String replyId) {
567 likedReplyIds.add(replyId);
572 * Removes the given post ID from the list of replies this Sone likes.
575 * The ID of the reply
576 * @return This Sone (for method chaining)
578 public Sone removeLikedReplyId(String replyId) {
579 likedReplyIds.remove(replyId);
584 * Returns the root album that contains all visible albums of this Sone.
586 * @return The root album of this Sone
588 public Album getRootAlbum() {
593 public Optional<Image> getImageByInternalId(final String internalId) {
594 return FluentIterable.from(toAllImages.apply(this)).filter(new Predicate<Image>() {
596 public boolean apply(@Nullable Image input) {
597 return (input != null) && input.getInternalId().equals(internalId);
603 * Returns Sone-specific options.
605 * @return The options of this Sone
607 public SoneOptions getOptions() {
612 * Sets the options of this Sone.
615 * The options of this Sone
617 /* TODO - remove this method again, maybe add an option provider */
618 public void setOptions(SoneOptions options) {
619 this.options = options;
623 // FINGERPRINTABLE METHODS
628 public synchronized String getFingerprint() {
629 Hasher hash = Hashing.sha256().newHasher();
630 hash.putString(profile.getFingerprint());
632 hash.putString("Posts(");
633 for (Post post : getPosts()) {
634 hash.putString("Post(").putString(post.getId()).putString(")");
638 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
639 Collections.sort(replies, Reply.TIME_COMPARATOR);
640 hash.putString("Replies(");
641 for (PostReply reply : replies) {
642 hash.putString("Reply(").putString(reply.getId()).putString(")");
646 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
647 Collections.sort(likedPostIds);
648 hash.putString("LikedPosts(");
649 for (String likedPostId : likedPostIds) {
650 hash.putString("Post(").putString(likedPostId).putString(")");
654 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
655 Collections.sort(likedReplyIds);
656 hash.putString("LikedReplies(");
657 for (String likedReplyId : likedReplyIds) {
658 hash.putString("Reply(").putString(likedReplyId).putString(")");
662 hash.putString("Albums(");
663 for (Album album : rootAlbum.getAlbums()) {
664 if (!Album.NOT_EMPTY.apply(album)) {
667 hash.putString(album.getFingerprint());
671 return hash.hash().toString();
675 // INTERFACE Comparable<Sone>
680 public int compareTo(Sone sone) {
681 return NICE_NAME_COMPARATOR.compare(this, sone);
690 public int hashCode() {
691 return id.hashCode();
696 public boolean equals(Object object) {
697 if (!(object instanceof Sone)) {
700 return ((Sone) object).getId().equals(id);
705 public String toString() {
706 return getClass().getName() + "[identity=" + identity + ",posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";