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