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