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