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