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