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