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