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