Merge branch 'release-0.9.7'
[Sone.git] / src / main / java / net / pterodactylus / sone / data / impl / SoneImpl.java
1 /*
2  * Sone - SoneImpl.java - Copyright © 2010–2016 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.data.impl;
19
20 import static com.google.common.base.Preconditions.checkNotNull;
21 import static java.lang.String.format;
22 import static java.util.logging.Logger.getLogger;
23
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;
29 import java.util.Set;
30 import java.util.concurrent.CopyOnWriteArraySet;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
36
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;
49
50 import freenet.keys.FreenetURI;
51
52 import com.google.common.hash.Hasher;
53 import com.google.common.hash.Hashing;
54
55 /**
56  * {@link Sone} implementation.
57  * <p/>
58  * Operations that modify the Sone need to synchronize on the Sone in question.
59  *
60  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61  */
62 public class SoneImpl implements Sone {
63
64         /** The logger. */
65         private static final Logger logger = getLogger(SoneImpl.class.getName());
66
67         /** The database. */
68         private final Database database;
69
70         /** The ID of this Sone. */
71         private final String id;
72
73         /** Whether the Sone is local. */
74         private final boolean local;
75
76         /** The identity of this Sone. */
77         private final Identity identity;
78
79         /** The latest edition of the Sone. */
80         private volatile long latestEdition;
81
82         /** The time of the last inserted update. */
83         private volatile long time;
84
85         /** The status of this Sone. */
86         private volatile SoneStatus status = SoneStatus.unknown;
87
88         /** The profile of this Sone. */
89         private volatile Profile profile = new Profile(this);
90
91         /** The client used by the Sone. */
92         private volatile Client client;
93
94         /** Whether this Sone is known. */
95         private volatile boolean known;
96
97         /** All posts. */
98         private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
99
100         /** All replies. */
101         private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
102
103         /** The IDs of all liked posts. */
104         private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
105
106         /** The IDs of all liked replies. */
107         private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
108
109         /** The root album containing all albums. */
110         private final Album rootAlbum = new AlbumImpl(this);
111
112         /** Sone-specific options. */
113         private SoneOptions options = new DefaultSoneOptions();
114
115         /**
116          * Creates a new Sone.
117          *
118          * @param database The database
119          * @param identity
120          *              The identity of the Sone
121          * @param local
122          *              {@code true} if the Sone is a local Sone, {@code false} otherwise
123          */
124         public SoneImpl(Database database, Identity identity, boolean local) {
125                 this.database = database;
126                 this.id = identity.getId();
127                 this.identity = identity;
128                 this.local = local;
129         }
130
131         //
132         // ACCESSORS
133         //
134
135         /**
136          * Returns the identity of this Sone.
137          *
138          * @return The identity of this Sone
139          */
140         @Nonnull
141         public String getId() {
142                 return id;
143         }
144
145         /**
146          * Returns the identity of this Sone.
147          *
148          * @return The identity of this Sone
149          */
150         @Nonnull
151         public Identity getIdentity() {
152                 return identity;
153         }
154
155         /**
156          * Returns the name of this Sone.
157          *
158          * @return The name of this Sone
159          */
160         @Nonnull
161         public String getName() {
162                 return (identity != null) ? identity.getNickname() : null;
163         }
164
165         /**
166          * Returns whether this Sone is a local Sone.
167          *
168          * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
169          */
170         public boolean isLocal() {
171                 return local;
172         }
173
174         /**
175          * Returns the request URI of this Sone.
176          *
177          * @return The request URI of this Sone
178          */
179         @Nonnull
180         public FreenetURI getRequestUri() {
181                 try {
182                         return new FreenetURI(getIdentity().getRequestUri())
183                                         .setKeyType("USK")
184                                         .setDocName("Sone")
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.",
190                                                         getIdentity()), e);
191                 }
192         }
193
194         /**
195          * Returns the insert URI of this Sone.
196          *
197          * @return The insert URI of this Sone
198          */
199         @Nullable
200         public FreenetURI getInsertUri() {
201                 if (!isLocal()) {
202                         return null;
203                 }
204                 try {
205                         return new FreenetURI(((OwnIdentity) getIdentity()).getInsertUri())
206                                         .setDocName("Sone")
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);
211                 }
212         }
213
214         /**
215          * Returns the latest edition of this Sone.
216          *
217          * @return The latest edition of this Sone
218          */
219         public long getLatestEdition() {
220                 return latestEdition;
221         }
222
223         /**
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
226          * not changed.
227          *
228          * @param latestEdition
229          *              The latest edition of this Sone
230          */
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));
234                         return;
235                 }
236                 this.latestEdition = latestEdition;
237         }
238
239         /**
240          * Return the time of the last inserted update of this Sone.
241          *
242          * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
243          */
244         public long getTime() {
245                 return time;
246         }
247
248         /**
249          * Sets the time of the last inserted update of this Sone.
250          *
251          * @param time
252          *              The time of the update (in milliseconds since Jan 1, 1970 UTC)
253          * @return This Sone (for method chaining)
254          */
255         @Nonnull
256         public Sone setTime(long time) {
257                 this.time = time;
258                 return this;
259         }
260
261         /**
262          * Returns the status of this Sone.
263          *
264          * @return The status of this Sone
265          */
266         @Nonnull
267         public SoneStatus getStatus() {
268                 return status;
269         }
270
271         /**
272          * Sets the new status of this Sone.
273          *
274          * @param status
275          *              The new status of this Sone
276          * @return This Sone
277          * @throws IllegalArgumentException
278          *              if {@code status} is {@code null}
279          */
280         @Nonnull
281         public Sone setStatus(@Nonnull SoneStatus status) {
282                 this.status = checkNotNull(status, "status must not be null");
283                 return this;
284         }
285
286         /**
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.
290          *
291          * @return A copy of the profile
292          */
293         @Nonnull
294         public Profile getProfile() {
295                 return new Profile(profile);
296         }
297
298         /**
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
301          * Sone!
302          *
303          * @param profile
304          *              The profile to set
305          */
306         public void setProfile(@Nonnull Profile profile) {
307                 this.profile = new Profile(profile);
308         }
309
310         /**
311          * Returns the client used by this Sone.
312          *
313          * @return The client used by this Sone, or {@code null}
314          */
315         @Nullable
316         public Client getClient() {
317                 return client;
318         }
319
320         /**
321          * Sets the client used by this Sone.
322          *
323          * @param client
324          *              The client used by this Sone, or {@code null}
325          * @return This Sone (for method chaining)
326          */
327         @Nonnull
328         public Sone setClient(@Nullable Client client) {
329                 this.client = client;
330                 return this;
331         }
332
333         /**
334          * Returns whether this Sone is known.
335          *
336          * @return {@code true} if this Sone is known, {@code false} otherwise
337          */
338         public boolean isKnown() {
339                 return known;
340         }
341
342         /**
343          * Sets whether this Sone is known.
344          *
345          * @param known
346          *              {@code true} if this Sone is known, {@code false} otherwise
347          * @return This Sone
348          */
349         @Nonnull
350         public Sone setKnown(boolean known) {
351                 this.known = known;
352                 return this;
353         }
354
355         /**
356          * Returns all friend Sones of this Sone.
357          *
358          * @return The friend Sones of this Sone
359          */
360         @Nonnull
361         public Collection<String> getFriends() {
362                 return database.getFriends(this);
363         }
364
365         /**
366          * Returns whether this Sone has the given Sone as a friend Sone.
367          *
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
371          *         false} otherwise
372          */
373         public boolean hasFriend(@Nonnull String friendSoneId) {
374                 return database.isFriend(this, friendSoneId);
375         }
376
377         /**
378          * Returns the list of posts of this Sone, sorted by time, newest first.
379          *
380          * @return All posts of this Sone
381          */
382         @Nonnull
383         public List<Post> getPosts() {
384                 List<Post> sortedPosts;
385                 synchronized (this) {
386                         sortedPosts = new ArrayList<Post>(posts);
387                 }
388                 Collections.sort(sortedPosts, Post.NEWEST_FIRST);
389                 return sortedPosts;
390         }
391
392         /**
393          * Sets all posts of this Sone at once.
394          *
395          * @param posts
396          *              The new (and only) posts of this Sone
397          * @return This Sone (for method chaining)
398          */
399         @Nonnull
400         public Sone setPosts(@Nonnull Collection<Post> posts) {
401                 synchronized (this) {
402                         this.posts.clear();
403                         this.posts.addAll(posts);
404                 }
405                 return this;
406         }
407
408         /**
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.
411          *
412          * @param post
413          *              The post to add
414          */
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()));
418                 }
419         }
420
421         /**
422          * Removes the given post from this Sone.
423          *
424          * @param post
425          *              The post to remove
426          */
427         public void removePost(@Nonnull Post post) {
428                 if (post.getSone().equals(this)) {
429                         posts.remove(post);
430                 }
431         }
432
433         /**
434          * Returns all replies this Sone made.
435          *
436          * @return All replies this Sone made
437          */
438         @Nonnull
439         public Set<PostReply> getReplies() {
440                 return Collections.unmodifiableSet(replies);
441         }
442
443         /**
444          * Sets all replies of this Sone at once.
445          *
446          * @param replies
447          *              The new (and only) replies of this Sone
448          * @return This Sone (for method chaining)
449          */
450         @Nonnull
451         public Sone setReplies(@Nonnull Collection<PostReply> replies) {
452                 this.replies.clear();
453                 this.replies.addAll(replies);
454                 return this;
455         }
456
457         /**
458          * Adds a reply to this Sone. If the given reply was not made by this Sone,
459          * nothing is added to this Sone.
460          *
461          * @param reply
462          *              The reply to add
463          */
464         public void addReply(@Nonnull PostReply reply) {
465                 if (reply.getSone().equals(this)) {
466                         replies.add(reply);
467                 }
468         }
469
470         /**
471          * Removes a reply from this Sone.
472          *
473          * @param reply
474          *              The reply to remove
475          */
476         public void removeReply(@Nonnull PostReply reply) {
477                 if (reply.getSone().equals(this)) {
478                         replies.remove(reply);
479                 }
480         }
481
482         /**
483          * Returns the IDs of all liked posts.
484          *
485          * @return All liked posts’ IDs
486          */
487         @Nonnull
488         public Set<String> getLikedPostIds() {
489                 return Collections.unmodifiableSet(likedPostIds);
490         }
491
492         /**
493          * Sets the IDs of all liked posts.
494          *
495          * @param likedPostIds
496          *              All liked posts’ IDs
497          * @return This Sone (for method chaining)
498          */
499         @Nonnull
500         public Sone setLikePostIds(@Nonnull Set<String> likedPostIds) {
501                 this.likedPostIds.clear();
502                 this.likedPostIds.addAll(likedPostIds);
503                 return this;
504         }
505
506         /**
507          * Checks whether the given post ID is liked by this Sone.
508          *
509          * @param postId
510          *              The ID of the post
511          * @return {@code true} if this Sone likes the given post, {@code false}
512          *         otherwise
513          */
514         public boolean isLikedPostId(@Nonnull String postId) {
515                 return likedPostIds.contains(postId);
516         }
517
518         /**
519          * Adds the given post ID to the list of posts this Sone likes.
520          *
521          * @param postId
522          *              The ID of the post
523          * @return This Sone (for method chaining)
524          */
525         @Nonnull
526         public Sone addLikedPostId(@Nonnull String postId) {
527                 likedPostIds.add(postId);
528                 return this;
529         }
530
531         /**
532          * Removes the given post ID from the list of posts this Sone likes.
533          *
534          * @param postId
535          *              The ID of the post
536          */
537         public void removeLikedPostId(@Nonnull String postId) {
538                 likedPostIds.remove(postId);
539         }
540
541         /**
542          * Returns the IDs of all liked replies.
543          *
544          * @return All liked replies’ IDs
545          */
546         @Nonnull
547         public Set<String> getLikedReplyIds() {
548                 return Collections.unmodifiableSet(likedReplyIds);
549         }
550
551         /**
552          * Sets the IDs of all liked replies.
553          *
554          * @param likedReplyIds
555          *              All liked replies’ IDs
556          * @return This Sone (for method chaining)
557          */
558         @Nonnull
559         public Sone setLikeReplyIds(@Nonnull Set<String> likedReplyIds) {
560                 this.likedReplyIds.clear();
561                 this.likedReplyIds.addAll(likedReplyIds);
562                 return this;
563         }
564
565         /**
566          * Checks whether the given reply ID is liked by this Sone.
567          *
568          * @param replyId
569          *              The ID of the reply
570          * @return {@code true} if this Sone likes the given reply, {@code false}
571          *         otherwise
572          */
573         public boolean isLikedReplyId(@Nonnull String replyId) {
574                 return likedReplyIds.contains(replyId);
575         }
576
577         /**
578          * Adds the given reply ID to the list of replies this Sone likes.
579          *
580          * @param replyId
581          *              The ID of the reply
582          * @return This Sone (for method chaining)
583          */
584         @Nonnull
585         public Sone addLikedReplyId(@Nonnull String replyId) {
586                 likedReplyIds.add(replyId);
587                 return this;
588         }
589
590         /**
591          * Removes the given post ID from the list of replies this Sone likes.
592          *
593          * @param replyId
594          *              The ID of the reply
595          */
596         public void removeLikedReplyId(@Nonnull String replyId) {
597                 likedReplyIds.remove(replyId);
598         }
599
600         /**
601          * Returns the root album that contains all visible albums of this Sone.
602          *
603          * @return The root album of this Sone
604          */
605         @Nonnull
606         public Album getRootAlbum() {
607                 return rootAlbum;
608         }
609
610         /**
611          * Returns Sone-specific options.
612          *
613          * @return The options of this Sone
614          */
615         @Nonnull
616         public SoneOptions getOptions() {
617                 return options;
618         }
619
620         /**
621          * Sets the options of this Sone.
622          *
623          * @param options
624          *              The options of this Sone
625          */
626         /* TODO - remove this method again, maybe add an option provider */
627         public void setOptions(@Nonnull SoneOptions options) {
628                 this.options = options;
629         }
630
631         //
632         // FINGERPRINTABLE METHODS
633         //
634
635         /** {@inheritDoc} */
636         @Override
637         public synchronized String getFingerprint() {
638                 Hasher hash = Hashing.sha256().newHasher();
639                 hash.putString(profile.getFingerprint());
640
641                 hash.putString("Posts(");
642                 for (Post post : getPosts()) {
643                         hash.putString("Post(").putString(post.getId()).putString(")");
644                 }
645                 hash.putString(")");
646
647                 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
648                 Collections.sort(replies, Reply.TIME_COMPARATOR);
649                 hash.putString("Replies(");
650                 for (PostReply reply : replies) {
651                         hash.putString("Reply(").putString(reply.getId()).putString(")");
652                 }
653                 hash.putString(")");
654
655                 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
656                 Collections.sort(likedPostIds);
657                 hash.putString("LikedPosts(");
658                 for (String likedPostId : likedPostIds) {
659                         hash.putString("Post(").putString(likedPostId).putString(")");
660                 }
661                 hash.putString(")");
662
663                 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
664                 Collections.sort(likedReplyIds);
665                 hash.putString("LikedReplies(");
666                 for (String likedReplyId : likedReplyIds) {
667                         hash.putString("Reply(").putString(likedReplyId).putString(")");
668                 }
669                 hash.putString(")");
670
671                 hash.putString("Albums(");
672                 for (Album album : rootAlbum.getAlbums()) {
673                         if (!Album.NOT_EMPTY.apply(album)) {
674                                 continue;
675                         }
676                         hash.putString(album.getFingerprint());
677                 }
678                 hash.putString(")");
679
680                 return hash.hash().toString();
681         }
682
683         //
684         // INTERFACE Comparable<Sone>
685         //
686
687         /** {@inheritDoc} */
688         @Override
689         public int compareTo(Sone sone) {
690                 return NICE_NAME_COMPARATOR.compare(this, sone);
691         }
692
693         //
694         // OBJECT METHODS
695         //
696
697         /** {@inheritDoc} */
698         @Override
699         public int hashCode() {
700                 return id.hashCode();
701         }
702
703         /** {@inheritDoc} */
704         @Override
705         public boolean equals(Object object) {
706                 if (!(object instanceof Sone)) {
707                         return false;
708                 }
709                 return ((Sone) object).getId().equals(id);
710         }
711
712         /** {@inheritDoc} */
713         @Override
714         public String toString() {
715                 return getClass().getName() + "[identity=" + identity + ",posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";
716         }
717
718 }