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