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