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