Extract an interface out of Sone.
[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.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().setSone(this);
103
104         /** Sone-specific options. */
105         private Options options = new Options();
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                 List<String> friends = new ArrayList<String>(friendSones);
375                 return friends;
376         }
377
378         /**
379          * Returns whether this Sone has the given Sone as a friend Sone.
380          *
381          * @param friendSoneId
382          *              The ID of the Sone to check for
383          * @return {@code true} if this Sone has the given Sone as a friend, {@code
384          *         false} otherwise
385          */
386         public boolean hasFriend(String friendSoneId) {
387                 return friendSones.contains(friendSoneId);
388         }
389
390         /**
391          * Adds the given Sone as a friend Sone.
392          *
393          * @param friendSone
394          *              The friend Sone to add
395          * @return This Sone (for method chaining)
396          */
397         public Sone addFriend(String friendSone) {
398                 if (!friendSone.equals(id)) {
399                         friendSones.add(friendSone);
400                 }
401                 return this;
402         }
403
404         /**
405          * Removes the given Sone as a friend Sone.
406          *
407          * @param friendSoneId
408          *              The ID of the friend Sone to remove
409          * @return This Sone (for method chaining)
410          */
411         public Sone removeFriend(String friendSoneId) {
412                 friendSones.remove(friendSoneId);
413                 return this;
414         }
415
416         /**
417          * Returns the list of posts of this Sone, sorted by time, newest first.
418          *
419          * @return All posts of this Sone
420          */
421         public List<Post> getPosts() {
422                 List<Post> sortedPosts;
423                 synchronized (this) {
424                         sortedPosts = new ArrayList<Post>(posts);
425                 }
426                 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
427                 return sortedPosts;
428         }
429
430         /**
431          * Sets all posts of this Sone at once.
432          *
433          * @param posts
434          *              The new (and only) posts of this Sone
435          * @return This Sone (for method chaining)
436          */
437         public Sone setPosts(Collection<Post> posts) {
438                 synchronized (this) {
439                         this.posts.clear();
440                         this.posts.addAll(posts);
441                 }
442                 return this;
443         }
444
445         /**
446          * Adds the given post to this Sone. The post will not be added if its {@link
447          * Post#getSone() Sone} is not this Sone.
448          *
449          * @param post
450          *              The post to add
451          */
452         public void addPost(Post post) {
453                 if (post.getSone().equals(this) && posts.add(post)) {
454                         logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
455                 }
456         }
457
458         /**
459          * Removes the given post from this Sone.
460          *
461          * @param post
462          *              The post to remove
463          */
464         public void removePost(Post post) {
465                 if (post.getSone().equals(this)) {
466                         posts.remove(post);
467                 }
468         }
469
470         /**
471          * Returns all replies this Sone made.
472          *
473          * @return All replies this Sone made
474          */
475         public Set<PostReply> getReplies() {
476                 return Collections.unmodifiableSet(replies);
477         }
478
479         /**
480          * Sets all replies of this Sone at once.
481          *
482          * @param replies
483          *              The new (and only) replies of this Sone
484          * @return This Sone (for method chaining)
485          */
486         public Sone setReplies(Collection<PostReply> replies) {
487                 this.replies.clear();
488                 this.replies.addAll(replies);
489                 return this;
490         }
491
492         /**
493          * Adds a reply to this Sone. If the given reply was not made by this Sone,
494          * nothing is added to this Sone.
495          *
496          * @param reply
497          *              The reply to add
498          */
499         public void addReply(PostReply reply) {
500                 if (reply.getSone().equals(this)) {
501                         replies.add(reply);
502                 }
503         }
504
505         /**
506          * Removes a reply from this Sone.
507          *
508          * @param reply
509          *              The reply to remove
510          */
511         public void removeReply(PostReply reply) {
512                 if (reply.getSone().equals(this)) {
513                         replies.remove(reply);
514                 }
515         }
516
517         /**
518          * Returns the IDs of all liked posts.
519          *
520          * @return All liked posts’ IDs
521          */
522         public Set<String> getLikedPostIds() {
523                 return Collections.unmodifiableSet(likedPostIds);
524         }
525
526         /**
527          * Sets the IDs of all liked posts.
528          *
529          * @param likedPostIds
530          *              All liked posts’ IDs
531          * @return This Sone (for method chaining)
532          */
533         public Sone setLikePostIds(Set<String> likedPostIds) {
534                 this.likedPostIds.clear();
535                 this.likedPostIds.addAll(likedPostIds);
536                 return this;
537         }
538
539         /**
540          * Checks whether the given post ID is liked by this Sone.
541          *
542          * @param postId
543          *              The ID of the post
544          * @return {@code true} if this Sone likes the given post, {@code false}
545          *         otherwise
546          */
547         public boolean isLikedPostId(String postId) {
548                 return likedPostIds.contains(postId);
549         }
550
551         /**
552          * Adds the given post ID to the list of posts this Sone likes.
553          *
554          * @param postId
555          *              The ID of the post
556          * @return This Sone (for method chaining)
557          */
558         public Sone addLikedPostId(String postId) {
559                 likedPostIds.add(postId);
560                 return this;
561         }
562
563         /**
564          * Removes the given post ID from the list of posts this Sone likes.
565          *
566          * @param postId
567          *              The ID of the post
568          * @return This Sone (for method chaining)
569          */
570         public Sone removeLikedPostId(String postId) {
571                 likedPostIds.remove(postId);
572                 return this;
573         }
574
575         /**
576          * Returns the IDs of all liked replies.
577          *
578          * @return All liked replies’ IDs
579          */
580         public Set<String> getLikedReplyIds() {
581                 return Collections.unmodifiableSet(likedReplyIds);
582         }
583
584         /**
585          * Sets the IDs of all liked replies.
586          *
587          * @param likedReplyIds
588          *              All liked replies’ IDs
589          * @return This Sone (for method chaining)
590          */
591         public Sone setLikeReplyIds(Set<String> likedReplyIds) {
592                 this.likedReplyIds.clear();
593                 this.likedReplyIds.addAll(likedReplyIds);
594                 return this;
595         }
596
597         /**
598          * Checks whether the given reply ID is liked by this Sone.
599          *
600          * @param replyId
601          *              The ID of the reply
602          * @return {@code true} if this Sone likes the given reply, {@code false}
603          *         otherwise
604          */
605         public boolean isLikedReplyId(String replyId) {
606                 return likedReplyIds.contains(replyId);
607         }
608
609         /**
610          * Adds the given reply ID to the list of replies this Sone likes.
611          *
612          * @param replyId
613          *              The ID of the reply
614          * @return This Sone (for method chaining)
615          */
616         public Sone addLikedReplyId(String replyId) {
617                 likedReplyIds.add(replyId);
618                 return this;
619         }
620
621         /**
622          * Removes the given post ID from the list of replies this Sone likes.
623          *
624          * @param replyId
625          *              The ID of the reply
626          * @return This Sone (for method chaining)
627          */
628         public Sone removeLikedReplyId(String replyId) {
629                 likedReplyIds.remove(replyId);
630                 return this;
631         }
632
633         /**
634          * Returns the root album that contains all visible albums of this Sone.
635          *
636          * @return The root album of this Sone
637          */
638         public Album getRootAlbum() {
639                 return rootAlbum;
640         }
641
642         /**
643          * Returns Sone-specific options.
644          *
645          * @return The options of this Sone
646          */
647         public Options getOptions() {
648                 return options;
649         }
650
651         /**
652          * Sets the options of this Sone.
653          *
654          * @param options
655          *              The options of this Sone
656          */
657         /* TODO - remove this method again, maybe add an option provider */
658         public void setOptions(Options options) {
659                 this.options = options;
660         }
661
662         //
663         // FINGERPRINTABLE METHODS
664         //
665
666         /** {@inheritDoc} */
667         @Override
668         public synchronized String getFingerprint() {
669                 Hasher hash = Hashing.sha256().newHasher();
670                 hash.putString(profile.getFingerprint());
671
672                 hash.putString("Posts(");
673                 for (Post post : getPosts()) {
674                         hash.putString("Post(").putString(post.getId()).putString(")");
675                 }
676                 hash.putString(")");
677
678                 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
679                 Collections.sort(replies, Reply.TIME_COMPARATOR);
680                 hash.putString("Replies(");
681                 for (PostReply reply : replies) {
682                         hash.putString("Reply(").putString(reply.getId()).putString(")");
683                 }
684                 hash.putString(")");
685
686                 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
687                 Collections.sort(likedPostIds);
688                 hash.putString("LikedPosts(");
689                 for (String likedPostId : likedPostIds) {
690                         hash.putString("Post(").putString(likedPostId).putString(")");
691                 }
692                 hash.putString(")");
693
694                 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
695                 Collections.sort(likedReplyIds);
696                 hash.putString("LikedReplies(");
697                 for (String likedReplyId : likedReplyIds) {
698                         hash.putString("Reply(").putString(likedReplyId).putString(")");
699                 }
700                 hash.putString(")");
701
702                 hash.putString("Albums(");
703                 for (Album album : rootAlbum.getAlbums()) {
704                         if (!Album.NOT_EMPTY.apply(album)) {
705                                 continue;
706                         }
707                         hash.putString(album.getFingerprint());
708                 }
709                 hash.putString(")");
710
711                 return hash.hash().toString();
712         }
713
714         //
715         // INTERFACE Comparable<Sone>
716         //
717
718         /** {@inheritDoc} */
719         @Override
720         public int compareTo(Sone sone) {
721                 return NICE_NAME_COMPARATOR.compare(this, sone);
722         }
723
724         //
725         // OBJECT METHODS
726         //
727
728         /** {@inheritDoc} */
729         @Override
730         public int hashCode() {
731                 return id.hashCode();
732         }
733
734         /** {@inheritDoc} */
735         @Override
736         public boolean equals(Object object) {
737                 if (!(object instanceof Sone)) {
738                         return false;
739                 }
740                 return ((Sone) object).getId().equals(id);
741         }
742
743         /** {@inheritDoc} */
744         @Override
745         public String toString() {
746                 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() + ")]";
747         }
748
749 }