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