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