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