Use unique IDs for images
[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 import javax.annotation.Nullable;
34
35 import net.pterodactylus.sone.data.Album;
36 import net.pterodactylus.sone.data.Client;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Profile;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.data.SoneOptions;
44 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
45 import net.pterodactylus.sone.database.Database;
46 import net.pterodactylus.sone.freenet.wot.Identity;
47 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
48
49 import com.google.common.base.Optional;
50 import com.google.common.base.Predicate;
51 import com.google.common.collect.FluentIterable;
52 import freenet.keys.FreenetURI;
53
54 import com.google.common.hash.Hasher;
55 import com.google.common.hash.Hashing;
56
57 /**
58  * {@link Sone} implementation.
59  * <p/>
60  * Operations that modify the Sone need to synchronize on the Sone in question.
61  *
62  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63  */
64 public class SoneImpl implements Sone {
65
66         /** The logger. */
67         private static final Logger logger = getLogger(SoneImpl.class.getName());
68
69         /** The database. */
70         private final Database database;
71
72         /** The ID of this Sone. */
73         private final String id;
74
75         /** Whether the Sone is local. */
76         private final boolean local;
77
78         /** The identity of this Sone. */
79         private final Identity identity;
80
81         /** The latest edition of the Sone. */
82         private volatile long latestEdition;
83
84         /** The time of the last inserted update. */
85         private volatile long time;
86
87         /** The status of this Sone. */
88         private volatile SoneStatus status = SoneStatus.unknown;
89
90         /** The profile of this Sone. */
91         private volatile Profile profile = new Profile(this);
92
93         /** The client used by the Sone. */
94         private volatile Client client;
95
96         /** Whether this Sone is known. */
97         private volatile boolean known;
98
99         /** All posts. */
100         private final Set<Post> posts = new CopyOnWriteArraySet<Post>();
101
102         /** All replies. */
103         private final Set<PostReply> replies = new CopyOnWriteArraySet<PostReply>();
104
105         /** The IDs of all liked posts. */
106         private final Set<String> likedPostIds = new CopyOnWriteArraySet<String>();
107
108         /** The IDs of all liked replies. */
109         private final Set<String> likedReplyIds = new CopyOnWriteArraySet<String>();
110
111         /** The root album containing all albums. */
112         private final Album rootAlbum = new AlbumImpl(this);
113
114         /** Sone-specific options. */
115         private SoneOptions options = new DefaultSoneOptions();
116
117         /**
118          * Creates a new Sone.
119          *
120          * @param database The database
121          * @param identity
122          *              The identity of the Sone
123          * @param local
124          *              {@code true} if the Sone is a local Sone, {@code false} otherwise
125          */
126         public SoneImpl(Database database, Identity identity, boolean local) {
127                 this.database = database;
128                 this.id = identity.getId();
129                 this.identity = identity;
130                 this.local = local;
131         }
132
133         //
134         // ACCESSORS
135         //
136
137         /**
138          * Returns the identity of this Sone.
139          *
140          * @return The identity of this Sone
141          */
142         public String getId() {
143                 return id;
144         }
145
146         /**
147          * Returns the identity of this Sone.
148          *
149          * @return The identity of this Sone
150          */
151         public Identity getIdentity() {
152                 return identity;
153         }
154
155         /**
156          * Returns the name of this Sone.
157          *
158          * @return The name of this Sone
159          */
160         public String getName() {
161                 return (identity != null) ? identity.getNickname() : null;
162         }
163
164         /**
165          * Returns whether this Sone is a local Sone.
166          *
167          * @return {@code true} if this Sone is a local Sone, {@code false} otherwise
168          */
169         public boolean isLocal() {
170                 return local;
171         }
172
173         /**
174          * Returns the request URI of this Sone.
175          *
176          * @return The request URI of this Sone
177          */
178         public FreenetURI getRequestUri() {
179                 try {
180                         return new FreenetURI(getIdentity().getRequestUri())
181                                         .setKeyType("USK")
182                                         .setDocName("Sone")
183                                         .setMetaString(new String[0])
184                                         .setSuggestedEdition(latestEdition);
185                 } catch (MalformedURLException e) {
186                         throw new IllegalStateException(
187                                         format("Identity %s's request URI is incorrect.",
188                                                         getIdentity()), e);
189                 }
190         }
191
192         /**
193          * Returns the insert URI of this Sone.
194          *
195          * @return The insert URI of this Sone
196          */
197         public FreenetURI getInsertUri() {
198                 if (!isLocal()) {
199                         return null;
200                 }
201                 try {
202                         return new FreenetURI(((OwnIdentity) getIdentity()).getInsertUri())
203                                         .setDocName("Sone")
204                                         .setMetaString(new String[0])
205                                         .setSuggestedEdition(latestEdition);
206                 } catch (MalformedURLException e) {
207                         throw new IllegalStateException(format("Own identity %s's insert URI is incorrect.", getIdentity()), e);
208                 }
209         }
210
211         /**
212          * Returns the latest edition of this Sone.
213          *
214          * @return The latest edition of this Sone
215          */
216         public long getLatestEdition() {
217                 return latestEdition;
218         }
219
220         /**
221          * Sets the latest edition of this Sone. If the given latest edition is not
222          * greater than the current latest edition, the latest edition of this Sone is
223          * not changed.
224          *
225          * @param latestEdition
226          *              The latest edition of this Sone
227          */
228         public void setLatestEdition(long latestEdition) {
229                 if (!(latestEdition > this.latestEdition)) {
230                         logger.log(Level.FINE, String.format("New latest edition %d is not greater than current latest edition %d!", latestEdition, this.latestEdition));
231                         return;
232                 }
233                 this.latestEdition = latestEdition;
234         }
235
236         /**
237          * Return the time of the last inserted update of this Sone.
238          *
239          * @return The time of the update (in milliseconds since Jan 1, 1970 UTC)
240          */
241         public long getTime() {
242                 return time;
243         }
244
245         /**
246          * Sets the time of the last inserted update of this Sone.
247          *
248          * @param time
249          *              The time of the update (in milliseconds since Jan 1, 1970 UTC)
250          * @return This Sone (for method chaining)
251          */
252         public Sone setTime(long time) {
253                 this.time = time;
254                 return this;
255         }
256
257         /**
258          * Returns the status of this Sone.
259          *
260          * @return The status of this Sone
261          */
262         public SoneStatus getStatus() {
263                 return status;
264         }
265
266         /**
267          * Sets the new status of this Sone.
268          *
269          * @param status
270          *              The new status of this Sone
271          * @return This Sone
272          * @throws IllegalArgumentException
273          *              if {@code status} is {@code null}
274          */
275         public Sone setStatus(SoneStatus status) {
276                 this.status = checkNotNull(status, "status must not be null");
277                 return this;
278         }
279
280         /**
281          * Returns a copy of the profile. If you want to update values in the profile
282          * of this Sone, update the values in the returned {@link Profile} and use
283          * {@link #setProfile(Profile)} to change the profile in this Sone.
284          *
285          * @return A copy of the profile
286          */
287         public Profile getProfile() {
288                 return new Profile(profile);
289         }
290
291         /**
292          * Sets the profile of this Sone. A copy of the given profile is stored so that
293          * subsequent modifications of the given profile are not reflected in this
294          * Sone!
295          *
296          * @param profile
297          *              The profile to set
298          */
299         public void setProfile(Profile profile) {
300                 this.profile = new Profile(profile);
301         }
302
303         /**
304          * Returns the client used by this Sone.
305          *
306          * @return The client used by this Sone, or {@code null}
307          */
308         public Client getClient() {
309                 return client;
310         }
311
312         /**
313          * Sets the client used by this Sone.
314          *
315          * @param client
316          *              The client used by this Sone, or {@code null}
317          * @return This Sone (for method chaining)
318          */
319         public Sone setClient(Client client) {
320                 this.client = client;
321                 return this;
322         }
323
324         /**
325          * Returns whether this Sone is known.
326          *
327          * @return {@code true} if this Sone is known, {@code false} otherwise
328          */
329         public boolean isKnown() {
330                 return known;
331         }
332
333         /**
334          * Sets whether this Sone is known.
335          *
336          * @param known
337          *              {@code true} if this Sone is known, {@code false} otherwise
338          * @return This Sone
339          */
340         public Sone setKnown(boolean known) {
341                 this.known = known;
342                 return this;
343         }
344
345         /**
346          * Returns all friend Sones of this Sone.
347          *
348          * @return The friend Sones of this Sone
349          */
350         public Collection<String> getFriends() {
351                 return database.getFriends(this);
352         }
353
354         /**
355          * Returns whether this Sone has the given Sone as a friend Sone.
356          *
357          * @param friendSoneId
358          *              The ID of the Sone to check for
359          * @return {@code true} if this Sone has the given Sone as a friend, {@code
360          *         false} otherwise
361          */
362         public boolean hasFriend(String friendSoneId) {
363                 return database.isFriend(this, friendSoneId);
364         }
365
366         /**
367          * Returns the list of posts of this Sone, sorted by time, newest first.
368          *
369          * @return All posts of this Sone
370          */
371         public List<Post> getPosts() {
372                 List<Post> sortedPosts;
373                 synchronized (this) {
374                         sortedPosts = new ArrayList<Post>(posts);
375                 }
376                 Collections.sort(sortedPosts, Post.TIME_COMPARATOR);
377                 return sortedPosts;
378         }
379
380         /**
381          * Sets all posts of this Sone at once.
382          *
383          * @param posts
384          *              The new (and only) posts of this Sone
385          * @return This Sone (for method chaining)
386          */
387         public Sone setPosts(Collection<Post> posts) {
388                 synchronized (this) {
389                         this.posts.clear();
390                         this.posts.addAll(posts);
391                 }
392                 return this;
393         }
394
395         /**
396          * Adds the given post to this Sone. The post will not be added if its {@link
397          * Post#getSone() Sone} is not this Sone.
398          *
399          * @param post
400          *              The post to add
401          */
402         public void addPost(Post post) {
403                 if (post.getSone().equals(this) && posts.add(post)) {
404                         logger.log(Level.FINEST, String.format("Adding %s to “%s”.", post, getName()));
405                 }
406         }
407
408         /**
409          * Removes the given post from this Sone.
410          *
411          * @param post
412          *              The post to remove
413          */
414         public void removePost(Post post) {
415                 if (post.getSone().equals(this)) {
416                         posts.remove(post);
417                 }
418         }
419
420         /**
421          * Returns all replies this Sone made.
422          *
423          * @return All replies this Sone made
424          */
425         public Set<PostReply> getReplies() {
426                 return Collections.unmodifiableSet(replies);
427         }
428
429         /**
430          * Sets all replies of this Sone at once.
431          *
432          * @param replies
433          *              The new (and only) replies of this Sone
434          * @return This Sone (for method chaining)
435          */
436         public Sone setReplies(Collection<PostReply> replies) {
437                 this.replies.clear();
438                 this.replies.addAll(replies);
439                 return this;
440         }
441
442         /**
443          * Adds a reply to this Sone. If the given reply was not made by this Sone,
444          * nothing is added to this Sone.
445          *
446          * @param reply
447          *              The reply to add
448          */
449         public void addReply(PostReply reply) {
450                 if (reply.getSone().equals(this)) {
451                         replies.add(reply);
452                 }
453         }
454
455         /**
456          * Removes a reply from this Sone.
457          *
458          * @param reply
459          *              The reply to remove
460          */
461         public void removeReply(PostReply reply) {
462                 if (reply.getSone().equals(this)) {
463                         replies.remove(reply);
464                 }
465         }
466
467         /**
468          * Returns the IDs of all liked posts.
469          *
470          * @return All liked posts’ IDs
471          */
472         public Set<String> getLikedPostIds() {
473                 return Collections.unmodifiableSet(likedPostIds);
474         }
475
476         /**
477          * Sets the IDs of all liked posts.
478          *
479          * @param likedPostIds
480          *              All liked posts’ IDs
481          * @return This Sone (for method chaining)
482          */
483         public Sone setLikePostIds(Set<String> likedPostIds) {
484                 this.likedPostIds.clear();
485                 this.likedPostIds.addAll(likedPostIds);
486                 return this;
487         }
488
489         /**
490          * Checks whether the given post ID is liked by this Sone.
491          *
492          * @param postId
493          *              The ID of the post
494          * @return {@code true} if this Sone likes the given post, {@code false}
495          *         otherwise
496          */
497         public boolean isLikedPostId(String postId) {
498                 return likedPostIds.contains(postId);
499         }
500
501         /**
502          * Adds the given post ID to the list of posts this Sone likes.
503          *
504          * @param postId
505          *              The ID of the post
506          * @return This Sone (for method chaining)
507          */
508         public Sone addLikedPostId(String postId) {
509                 likedPostIds.add(postId);
510                 return this;
511         }
512
513         /**
514          * Removes the given post ID from the list of posts this Sone likes.
515          *
516          * @param postId
517          *              The ID of the post
518          * @return This Sone (for method chaining)
519          */
520         public Sone removeLikedPostId(String postId) {
521                 likedPostIds.remove(postId);
522                 return this;
523         }
524
525         /**
526          * Returns the IDs of all liked replies.
527          *
528          * @return All liked replies’ IDs
529          */
530         public Set<String> getLikedReplyIds() {
531                 return Collections.unmodifiableSet(likedReplyIds);
532         }
533
534         /**
535          * Sets the IDs of all liked replies.
536          *
537          * @param likedReplyIds
538          *              All liked replies’ IDs
539          * @return This Sone (for method chaining)
540          */
541         public Sone setLikeReplyIds(Set<String> likedReplyIds) {
542                 this.likedReplyIds.clear();
543                 this.likedReplyIds.addAll(likedReplyIds);
544                 return this;
545         }
546
547         /**
548          * Checks whether the given reply ID is liked by this Sone.
549          *
550          * @param replyId
551          *              The ID of the reply
552          * @return {@code true} if this Sone likes the given reply, {@code false}
553          *         otherwise
554          */
555         public boolean isLikedReplyId(String replyId) {
556                 return likedReplyIds.contains(replyId);
557         }
558
559         /**
560          * Adds the given reply ID to the list of replies this Sone likes.
561          *
562          * @param replyId
563          *              The ID of the reply
564          * @return This Sone (for method chaining)
565          */
566         public Sone addLikedReplyId(String replyId) {
567                 likedReplyIds.add(replyId);
568                 return this;
569         }
570
571         /**
572          * Removes the given post ID from the list of replies this Sone likes.
573          *
574          * @param replyId
575          *              The ID of the reply
576          * @return This Sone (for method chaining)
577          */
578         public Sone removeLikedReplyId(String replyId) {
579                 likedReplyIds.remove(replyId);
580                 return this;
581         }
582
583         /**
584          * Returns the root album that contains all visible albums of this Sone.
585          *
586          * @return The root album of this Sone
587          */
588         public Album getRootAlbum() {
589                 return rootAlbum;
590         }
591
592         @Override
593         public Optional<Image> getImageByInternalId(final String internalId) {
594                 return FluentIterable.from(toAllImages.apply(this)).filter(new Predicate<Image>() {
595                         @Override
596                         public boolean apply(@Nullable Image input) {
597                                 return (input != null) && input.getInternalId().equals(internalId);
598                         }
599                 }).first();
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 + ",posts(" + posts.size() + "),replies(" + replies.size() + "),albums(" + getRootAlbum().getAlbums().size() + ")]";
707         }
708
709 }