9b46988e50b3519e2eeaec832b0a239234677024
[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.LocalSone;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.PostReply;
39 import net.pterodactylus.sone.data.Profile;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.SoneOptions;
43 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
44 import net.pterodactylus.sone.database.Database;
45 import net.pterodactylus.sone.freenet.wot.Identity;
46 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
47
48 import freenet.keys.FreenetURI;
49
50 import com.google.common.hash.Hasher;
51 import com.google.common.hash.Hashing;
52
53 /**
54  * {@link Sone} implementation.
55  * <p/>
56  * Operations that modify the Sone need to synchronize on the Sone in question.
57  *
58  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59  */
60 public class SoneImpl implements LocalSone {
61
62         /** The logger. */
63         private static final Logger logger = getLogger("Sone.Data");
64
65         /** The database. */
66         private final Database database;
67
68         /** The ID of this Sone. */
69         private final String id;
70
71         /** Whether the Sone is local. */
72         private final boolean local;
73
74         /** The identity of this Sone. */
75         private final Identity identity;
76
77         /** The latest edition of the Sone. */
78         private volatile long latestEdition;
79
80         /** The time of the last inserted update. */
81         private final long time;
82
83         /** The status of this Sone. */
84         private volatile SoneStatus status = SoneStatus.unknown;
85
86         /** The profile of this Sone. */
87         private volatile Profile profile = new Profile(this);
88
89         /** The client used by the Sone. */
90         private volatile Client client;
91
92         /** Whether this Sone is known. */
93         private volatile boolean known;
94
95         /** All posts. */
96         private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
97
98         /** All replies. */
99         private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
100
101         /** The IDs of all liked posts. */
102         private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
103
104         /** The IDs of all liked replies. */
105         private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
106
107         /** The root album containing all albums. */
108         private final Album rootAlbum = new AlbumImpl(this);
109
110         /** Sone-specific options. */
111         private SoneOptions options = new DefaultSoneOptions();
112
113         /**
114          * Creates a new Sone.
115          *
116          * @param database The database
117          * @param identity
118          *              The identity of the Sone
119          * @param local
120          *              {@code true} if the Sone is a local Sone, {@code false} otherwise
121          */
122         public SoneImpl(Database database, Identity identity, boolean local, long time) {
123                 this.database = database;
124                 this.id = identity.getId();
125                 this.identity = identity;
126                 this.local = local;
127                 this.time = time;
128         }
129
130         //
131         // ACCESSORS
132         //
133
134         /**
135          * Returns the identity of this Sone.
136          *
137          * @return The identity of this Sone
138          */
139         public String getId() {
140                 return id;
141         }
142
143         /**
144          * Returns the identity of this Sone.
145          *
146          * @return The identity of this Sone
147          */
148         public Identity getIdentity() {
149                 return identity;
150         }
151
152         /**
153          * Returns the name of this Sone.
154          *
155          * @return The name of this Sone
156          */
157         public String getName() {
158                 return (identity != null) ? identity.getNickname() : null;
159         }
160
161         /**
162          * Returns whether this Sone is a local Sone.
163          *
164          * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
165          */
166         public boolean isLocal() {
167                 return local;
168         }
169
170         /**
171          * Returns the request URI of this Sone.
172          *
173          * @return The request URI of this Sone
174          */
175         public FreenetURI getRequestUri() {
176                 try {
177                         return new FreenetURI(getIdentity().getRequestUri())
178                                         .setKeyType("USK")
179                                         .setDocName("Sone")
180                                         .setMetaString(new String[0])
181                                         .setSuggestedEdition(latestEdition);
182                 } catch (MalformedURLException e) {
183                         throw new IllegalStateException(
184                                         format("Identity %s's request URI is incorrect.",
185                                                         getIdentity()), e);
186                 }
187         }
188
189         /**
190          * Returns the insert URI of this Sone.
191          *
192          * @return The insert URI of this Sone
193          */
194         public FreenetURI getInsertUri() {
195                 if (!isLocal()) {
196                         return null;
197                 }
198                 try {
199                         return new FreenetURI(((OwnIdentity) getIdentity()).getInsertUri())
200                                         .setDocName("Sone")
201                                         .setMetaString(new String[0])
202                                         .setSuggestedEdition(latestEdition);
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                 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 Collection<String> getFriends() {
347                 return database.getFriends(this);
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 database.isFriend(this, friendSoneId);
360         }
361
362         /**
363          * Returns the list of posts of this Sone, sorted by time, newest first.
364          *
365          * @return All posts of this Sone
366          */
367         public List<Post> getPosts() {
368                 List<Post> sortedPosts;
369                 synchronized (this) {
370                         sortedPosts = new ArrayList<Post>(posts);
371                 }
372                 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
373                 return sortedPosts;
374         }
375
376         /**
377          * Sets all posts of this Sone at once.
378          *
379          * @param posts
380          *              The new (and only) posts of this Sone
381          * @return This Sone (for method chaining)
382          */
383         public Sone setPosts(Collection<Post> posts) {
384                 synchronized (this) {
385                         this.posts.clear();
386                         this.posts.addAll(posts);
387                 }
388                 return this;
389         }
390
391         /**
392          * Adds the given post to this Sone. The post will not be added if its {@link
393          * Post#getSone() Sone} is not this Sone.
394          *
395          * @param post
396          *              The post to add
397          */
398         public void addPost(Post post) {
399                 if (post.getSone().equals(this) && posts.add(post)) {
400                         logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
401                 }
402         }
403
404         /**
405          * Removes the given post from this Sone.
406          *
407          * @param post
408          *              The post to remove
409          */
410         public void removePost(Post post) {
411                 if (post.getSone().equals(this)) {
412                         posts.remove(post);
413                 }
414         }
415
416         /**
417          * Returns all replies this Sone made.
418          *
419          * @return All replies this Sone made
420          */
421         public Set<PostReply> getReplies() {
422                 return Collections.unmodifiableSet(replies);
423         }
424
425         /**
426          * Sets all replies of this Sone at once.
427          *
428          * @param replies
429          *              The new (and only) replies of this Sone
430          * @return This Sone (for method chaining)
431          */
432         public Sone setReplies(Collection<PostReply> replies) {
433                 this.replies.clear();
434                 this.replies.addAll(replies);
435                 return this;
436         }
437
438         /**
439          * Adds a reply to this Sone. If the given reply was not made by this Sone,
440          * nothing is added to this Sone.
441          *
442          * @param reply
443          *              The reply to add
444          */
445         public void addReply(PostReply reply) {
446                 if (reply.getSone().equals(this)) {
447                         replies.add(reply);
448                 }
449         }
450
451         /**
452          * Removes a reply from this Sone.
453          *
454          * @param reply
455          *              The reply to remove
456          */
457         public void removeReply(PostReply reply) {
458                 if (reply.getSone().equals(this)) {
459                         replies.remove(reply);
460                 }
461         }
462
463         /**
464          * Returns the IDs of all liked posts.
465          *
466          * @return All liked posts’ IDs
467          */
468         public Set<String> getLikedPostIds() {
469                 return Collections.unmodifiableSet(likedPostIds);
470         }
471
472         /**
473          * Sets the IDs of all liked posts.
474          *
475          * @param likedPostIds
476          *              All liked posts’ IDs
477          * @return This Sone (for method chaining)
478          */
479         public Sone setLikePostIds(Set<String> likedPostIds) {
480                 this.likedPostIds.clear();
481                 this.likedPostIds.addAll(likedPostIds);
482                 return this;
483         }
484
485         /**
486          * Checks whether the given post ID is liked by this Sone.
487          *
488          * @param postId
489          *              The ID of the post
490          * @return {@code true} if this Sone likes the given post, {@code false}
491          *         otherwise
492          */
493         public boolean isLikedPostId(String postId) {
494                 return likedPostIds.contains(postId);
495         }
496
497         /**
498          * Adds the given post ID to the list of posts this Sone likes.
499          *
500          * @param postId
501          *              The ID of the post
502          * @return This Sone (for method chaining)
503          */
504         public Sone addLikedPostId(String postId) {
505                 likedPostIds.add(postId);
506                 return this;
507         }
508
509         /**
510          * Removes the given post ID from the list of posts this Sone likes.
511          *
512          * @param postId
513          *              The ID of the post
514          * @return This Sone (for method chaining)
515          */
516         public Sone removeLikedPostId(String postId) {
517                 likedPostIds.remove(postId);
518                 return this;
519         }
520
521         /**
522          * Returns the IDs of all liked replies.
523          *
524          * @return All liked replies’ IDs
525          */
526         public Set<String> getLikedReplyIds() {
527                 return Collections.unmodifiableSet(likedReplyIds);
528         }
529
530         /**
531          * Sets the IDs of all liked replies.
532          *
533          * @param likedReplyIds
534          *              All liked replies’ IDs
535          * @return This Sone (for method chaining)
536          */
537         public Sone setLikeReplyIds(Set<String> likedReplyIds) {
538                 this.likedReplyIds.clear();
539                 this.likedReplyIds.addAll(likedReplyIds);
540                 return this;
541         }
542
543         /**
544          * Checks whether the given reply ID is liked by this Sone.
545          *
546          * @param replyId
547          *              The ID of the reply
548          * @return {@code true} if this Sone likes the given reply, {@code false}
549          *         otherwise
550          */
551         public boolean isLikedReplyId(String replyId) {
552                 return likedReplyIds.contains(replyId);
553         }
554
555         /**
556          * Adds the given reply ID to the list of replies this Sone likes.
557          *
558          * @param replyId
559          *              The ID of the reply
560          * @return This Sone (for method chaining)
561          */
562         public Sone addLikedReplyId(String replyId) {
563                 likedReplyIds.add(replyId);
564                 return this;
565         }
566
567         /**
568          * Removes the given post ID from the list of replies this Sone likes.
569          *
570          * @param replyId
571          *              The ID of the reply
572          * @return This Sone (for method chaining)
573          */
574         public Sone removeLikedReplyId(String replyId) {
575                 likedReplyIds.remove(replyId);
576                 return this;
577         }
578
579         /**
580          * Returns the root album that contains all visible albums of this Sone.
581          *
582          * @return The root album of this Sone
583          */
584         public Album getRootAlbum() {
585                 return rootAlbum;
586         }
587
588         /**
589          * Returns Sone-specific options.
590          *
591          * @return The options of this Sone
592          */
593         public SoneOptions getOptions() {
594                 return options;
595         }
596
597         /**
598          * Sets the options of this Sone.
599          *
600          * @param options
601          *              The options of this Sone
602          */
603         /* TODO - remove this method again, maybe add an option provider */
604         public void setOptions(SoneOptions options) {
605                 this.options = options;
606         }
607
608         //
609         // FINGERPRINTABLE METHODS
610         //
611
612         /** {@inheritDoc} */
613         @Override
614         public synchronized String getFingerprint() {
615                 Hasher hash = Hashing.sha256().newHasher();
616                 hash.putString(profile.getFingerprint());
617
618                 hash.putString("Posts(");
619                 for (Post post : getPosts()) {
620                         hash.putString("Post(").putString(post.getId()).putString(")");
621                 }
622                 hash.putString(")");
623
624                 List<PostReply> replies = new ArrayList<PostReply>(getReplies());
625                 Collections.sort(replies, Reply.TIME_COMPARATOR);
626                 hash.putString("Replies(");
627                 for (PostReply reply : replies) {
628                         hash.putString("Reply(").putString(reply.getId()).putString(")");
629                 }
630                 hash.putString(")");
631
632                 List<String> likedPostIds = new ArrayList<String>(getLikedPostIds());
633                 Collections.sort(likedPostIds);
634                 hash.putString("LikedPosts(");
635                 for (String likedPostId : likedPostIds) {
636                         hash.putString("Post(").putString(likedPostId).putString(")");
637                 }
638                 hash.putString(")");
639
640                 List<String> likedReplyIds = new ArrayList<String>(getLikedReplyIds());
641                 Collections.sort(likedReplyIds);
642                 hash.putString("LikedReplies(");
643                 for (String likedReplyId : likedReplyIds) {
644                         hash.putString("Reply(").putString(likedReplyId).putString(")");
645                 }
646                 hash.putString(")");
647
648                 hash.putString("Albums(");
649                 for (Album album : rootAlbum.getAlbums()) {
650                         if (!Album.NOT_EMPTY.apply(album)) {
651                                 continue;
652                         }
653                         hash.putString(album.getFingerprint());
654                 }
655                 hash.putString(")");
656
657                 return hash.hash().toString();
658         }
659
660         //
661         // INTERFACE Comparable<Sone>
662         //
663
664         /** {@inheritDoc} */
665         @Override
666         public int compareTo(Sone sone) {
667                 return NICE_NAME_COMPARATOR.compare(this, sone);
668         }
669
670         //
671         // OBJECT METHODS
672         //
673
674         /** {@inheritDoc} */
675         @Override
676         public int hashCode() {
677                 return id.hashCode();
678         }
679
680         /** {@inheritDoc} */
681         @Override
682         public boolean equals(Object object) {
683                 if (!(object instanceof Sone)) {
684                         return false;
685                 }
686                 return ((Sone) object).getId().equals(id);
687         }
688
689         /** {@inheritDoc} */
690         @Override
691         public String toString() {
692                 return getClass().getName() + "[identity=" + identity + ",posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";
693         }
694
695 }