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