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