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