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