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