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