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