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