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