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