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