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