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