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