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