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