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