5ce01fe3df96b3f766c572746e17e6e4009cfa2c
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2013 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.core;
19
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39
40 import net.pterodactylus.sone.core.Options.DefaultOption;
41 import net.pterodactylus.sone.core.Options.Option;
42 import net.pterodactylus.sone.core.Options.OptionWatcher;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostBuilder;
60 import net.pterodactylus.sone.data.PostBuilderFactory;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.data.impl.PostReplyImpl;
70 import net.pterodactylus.sone.fcp.FcpInterface;
71 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
72 import net.pterodactylus.sone.freenet.wot.Identity;
73 import net.pterodactylus.sone.freenet.wot.IdentityManager;
74 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
75 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
76 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
77 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
80 import net.pterodactylus.sone.main.SonePlugin;
81 import net.pterodactylus.sone.utils.IntegerRangePredicate;
82 import net.pterodactylus.util.config.Configuration;
83 import net.pterodactylus.util.config.ConfigurationException;
84 import net.pterodactylus.util.logging.Logging;
85 import net.pterodactylus.util.number.Numbers;
86 import net.pterodactylus.util.service.AbstractService;
87 import net.pterodactylus.util.thread.NamedThreadFactory;
88
89 import com.google.common.base.Predicate;
90 import com.google.common.base.Predicates;
91 import com.google.common.collect.Collections2;
92 import com.google.common.eventbus.EventBus;
93 import com.google.common.eventbus.Subscribe;
94 import com.google.inject.Inject;
95
96 import freenet.keys.FreenetURI;
97
98 /**
99  * The Sone core.
100  *
101  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
102  */
103 public class Core extends AbstractService implements SoneProvider, PostProvider {
104
105         /** The logger. */
106         private static final Logger logger = Logging.getLogger(Core.class);
107
108         /** The start time. */
109         private final long startupTime = System.currentTimeMillis();
110
111         /** The options. */
112         private final Options options = new Options();
113
114         /** The preferences. */
115         private final Preferences preferences = new Preferences(options);
116
117         /** The event bus. */
118         private final EventBus eventBus;
119
120         /** The configuration. */
121         private Configuration configuration;
122
123         /** Whether we’re currently saving the configuration. */
124         private boolean storingConfiguration = false;
125
126         /** The identity manager. */
127         private final IdentityManager identityManager;
128
129         /** Interface to freenet. */
130         private final FreenetInterface freenetInterface;
131
132         /** The Sone downloader. */
133         private final SoneDownloader soneDownloader;
134
135         /** The image inserter. */
136         private final ImageInserter imageInserter;
137
138         /** Sone downloader thread-pool. */
139         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
140
141         /** The update checker. */
142         private final UpdateChecker updateChecker;
143
144         /** The trust updater. */
145         private final WebOfTrustUpdater webOfTrustUpdater;
146
147         /** The FCP interface. */
148         private volatile FcpInterface fcpInterface;
149
150         /** The times Sones were followed. */
151         private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
152
153         /** Locked local Sones. */
154         /* synchronize on itself. */
155         private final Set<Sone> lockedSones = new HashSet<Sone>();
156
157         /** Sone inserters. */
158         /* synchronize access on this on sones. */
159         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
160
161         /** Sone rescuers. */
162         /* synchronize access on this on sones. */
163         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
164
165         /** All Sones. */
166         /* synchronize access on this on itself. */
167         private final Map<String, Sone> sones = new HashMap<String, Sone>();
168
169         /** All known Sones. */
170         private final Set<String> knownSones = new HashSet<String>();
171
172         /** The post builder. */
173         private final PostBuilderFactory postBuilderFactory;
174
175         /** All posts. */
176         private final Map<String, Post> posts = new HashMap<String, Post>();
177
178         /** All known posts. */
179         private final Set<String> knownPosts = new HashSet<String>();
180
181         /** All replies. */
182         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
183
184         /** All known replies. */
185         private final Set<String> knownReplies = new HashSet<String>();
186
187         /** All bookmarked posts. */
188         /* synchronize access on itself. */
189         private final Set<String> bookmarkedPosts = new HashSet<String>();
190
191         /** Trusted identities, sorted by own identities. */
192         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
193
194         /** All known albums. */
195         private final Map<String, Album> albums = new HashMap<String, Album>();
196
197         /** All known images. */
198         private final Map<String, Image> images = new HashMap<String, Image>();
199
200         /** All temporary images. */
201         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
202
203         /** Ticker for threads that mark own elements as known. */
204         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
205
206         /** The time the configuration was last touched. */
207         private volatile long lastConfigurationUpdate;
208
209         /**
210          * Creates a new core.
211          *
212          * @param configuration
213          *            The configuration of the core
214          * @param freenetInterface
215          *            The freenet interface
216          * @param identityManager
217          *            The identity manager
218          * @param webOfTrustUpdater
219          *            The WebOfTrust updater
220          * @param eventBus
221          *            The event bus
222          * @param postBuilderFactory
223          *            The post builder
224          */
225         @Inject
226         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory) {
227                 super("Sone Core");
228                 this.configuration = configuration;
229                 this.freenetInterface = freenetInterface;
230                 this.identityManager = identityManager;
231                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
232                 this.imageInserter = new ImageInserter(freenetInterface);
233                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
234                 this.webOfTrustUpdater = webOfTrustUpdater;
235                 this.eventBus = eventBus;
236                 this.postBuilderFactory = postBuilderFactory;
237         }
238
239         //
240         // ACCESSORS
241         //
242
243         /**
244          * Returns the time Sone was started.
245          *
246          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
247          */
248         public long getStartupTime() {
249                 return startupTime;
250         }
251
252         /**
253          * Sets the configuration to use. This will automatically save the current
254          * configuration to the given configuration.
255          *
256          * @param configuration
257          *            The new configuration to use
258          */
259         public void setConfiguration(Configuration configuration) {
260                 this.configuration = configuration;
261                 touchConfiguration();
262         }
263
264         /**
265          * Returns the options used by the core.
266          *
267          * @return The options of the core
268          */
269         public Preferences getPreferences() {
270                 return preferences;
271         }
272
273         /**
274          * Returns the identity manager used by the core.
275          *
276          * @return The identity manager
277          */
278         public IdentityManager getIdentityManager() {
279                 return identityManager;
280         }
281
282         /**
283          * Returns the update checker.
284          *
285          * @return The update checker
286          */
287         public UpdateChecker getUpdateChecker() {
288                 return updateChecker;
289         }
290
291         /**
292          * Sets the FCP interface to use.
293          *
294          * @param fcpInterface
295          *            The FCP interface to use
296          */
297         public void setFcpInterface(FcpInterface fcpInterface) {
298                 this.fcpInterface = fcpInterface;
299         }
300
301         /**
302          * Returns the Sone rescuer for the given local Sone.
303          *
304          * @param sone
305          *            The local Sone to get the rescuer for
306          * @return The Sone rescuer for the given Sone
307          */
308         public SoneRescuer getSoneRescuer(Sone sone) {
309                 checkNotNull(sone, "sone must not be null");
310                 checkArgument(sone.isLocal(), "sone must be local");
311                 synchronized (sones) {
312                         SoneRescuer soneRescuer = soneRescuers.get(sone);
313                         if (soneRescuer == null) {
314                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
315                                 soneRescuers.put(sone, soneRescuer);
316                                 soneRescuer.start();
317                         }
318                         return soneRescuer;
319                 }
320         }
321
322         /**
323          * Returns whether the given Sone is currently locked.
324          *
325          * @param sone
326          *            The sone to check
327          * @return {@code true} if the Sone is locked, {@code false} if it is not
328          */
329         public boolean isLocked(Sone sone) {
330                 synchronized (lockedSones) {
331                         return lockedSones.contains(sone);
332                 }
333         }
334
335         /**
336          * Returns all Sones, remote and local.
337          *
338          * @return All Sones
339          */
340         public Set<Sone> getSones() {
341                 return new HashSet<Sone>(sones.values());
342         }
343
344         /**
345          * Returns the Sone with the given ID, regardless whether it’s local or
346          * remote.
347          *
348          * @param id
349          *            The ID of the Sone to get
350          * @return The Sone with the given ID, or {@code null} if there is no such
351          *         Sone
352          */
353         public Sone getSone(String id) {
354                 return getSone(id, true);
355         }
356
357         /**
358          * Returns the Sone with the given ID, regardless whether it’s local or
359          * remote.
360          *
361          * @param id
362          *            The ID of the Sone to get
363          * @param create
364          *            {@code true} to create a new Sone if none exists,
365          *            {@code false} to return {@code null} if a Sone with the given
366          *            ID does not exist
367          * @return The Sone with the given ID, or {@code null} if there is no such
368          *         Sone
369          */
370         @Override
371         public Sone getSone(String id, boolean create) {
372                 synchronized (sones) {
373                         if (!sones.containsKey(id) && create) {
374                                 Sone sone = new Sone(id, false);
375                                 sones.put(id, sone);
376                         }
377                         return sones.get(id);
378                 }
379         }
380
381         /**
382          * Checks whether the core knows a Sone with the given ID.
383          *
384          * @param id
385          *            The ID of the Sone
386          * @return {@code true} if there is a Sone with the given ID, {@code false}
387          *         otherwise
388          */
389         public boolean hasSone(String id) {
390                 synchronized (sones) {
391                         return sones.containsKey(id);
392                 }
393         }
394
395         /**
396          * Returns all local Sones.
397          *
398          * @return All local Sones
399          */
400         public Collection<Sone> getLocalSones() {
401                 synchronized (sones) {
402                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
403
404                                 @Override
405                                 public boolean apply(Sone sone) {
406                                         return sone.isLocal();
407                                 }
408                         });
409                 }
410         }
411
412         /**
413          * Returns the local Sone with the given ID, optionally creating a new Sone.
414          *
415          * @param id
416          *            The ID of the Sone
417          * @param create
418          *            {@code true} to create a new Sone if none exists,
419          *            {@code false} to return null if none exists
420          * @return The Sone with the given ID, or {@code null}
421          */
422         public Sone getLocalSone(String id, boolean create) {
423                 synchronized (sones) {
424                         Sone sone = sones.get(id);
425                         if ((sone == null) && create) {
426                                 sone = new Sone(id, true);
427                                 sones.put(id, sone);
428                         }
429                         if ((sone != null) && !sone.isLocal()) {
430                                 sone = new Sone(id, true);
431                                 sones.put(id, sone);
432                         }
433                         return sone;
434                 }
435         }
436
437         /**
438          * Returns all remote Sones.
439          *
440          * @return All remote Sones
441          */
442         public Collection<Sone> getRemoteSones() {
443                 synchronized (sones) {
444                         return Collections2.filter(sones.values(), new Predicate<Sone>() {
445
446                                 @Override
447                                 public boolean apply(Sone sone) {
448                                         return !sone.isLocal();
449                                 }
450                         });
451                 }
452         }
453
454         /**
455          * Returns the remote Sone with the given ID.
456          *
457          * @param id
458          *            The ID of the remote Sone to get
459          * @param create
460          *            {@code true} to always create a Sone, {@code false} to return
461          *            {@code null} if no Sone with the given ID exists
462          * @return The Sone with the given ID
463          */
464         public Sone getRemoteSone(String id, boolean create) {
465                 synchronized (sones) {
466                         Sone sone = sones.get(id);
467                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
468                                 sone = new Sone(id, false);
469                                 sones.put(id, sone);
470                         }
471                         return sone;
472                 }
473         }
474
475         /**
476          * Returns whether the given Sone has been modified.
477          *
478          * @param sone
479          *            The Sone to check for modifications
480          * @return {@code true} if a modification has been detected in the Sone,
481          *         {@code false} otherwise
482          */
483         public boolean isModifiedSone(Sone sone) {
484                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
485         }
486
487         /**
488          * Returns the time when the given was first followed by any local Sone.
489          *
490          * @param sone
491          *            The Sone to get the time for
492          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
493          *         been followed, or {@link Long#MAX_VALUE}
494          */
495         public long getSoneFollowingTime(Sone sone) {
496                 synchronized (soneFollowingTimes) {
497                         if (soneFollowingTimes.containsKey(sone)) {
498                                 return soneFollowingTimes.get(sone);
499                         }
500                         return Long.MAX_VALUE;
501                 }
502         }
503
504         /**
505          * Returns whether the target Sone is trusted by the origin Sone.
506          *
507          * @param origin
508          *            The origin Sone
509          * @param target
510          *            The target Sone
511          * @return {@code true} if the target Sone is trusted by the origin Sone
512          */
513         public boolean isSoneTrusted(Sone origin, Sone target) {
514                 checkNotNull(origin, "origin must not be null");
515                 checkNotNull(target, "target must not be null");
516                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
517                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
518         }
519
520         /**
521          * Returns a post builder.
522          *
523          * @return A new post builder
524          */
525         public PostBuilder postBuilder() {
526                 return postBuilderFactory.newPostBuilder();
527         }
528
529         /**
530          * {@inheritDoc}
531          */
532         @Override
533         public Post getPost(String postId) {
534                 synchronized (posts) {
535                         return posts.get(postId);
536                 }
537         }
538
539         /**
540          * Returns all posts that have the given Sone as recipient.
541          *
542          * @see Post#getRecipient()
543          * @param recipient
544          *            The recipient of the posts
545          * @return All posts that have the given Sone as recipient
546          */
547         public Set<Post> getDirectedPosts(Sone recipient) {
548                 checkNotNull(recipient, "recipient must not be null");
549                 Set<Post> directedPosts = new HashSet<Post>();
550                 synchronized (posts) {
551                         for (Post post : posts.values()) {
552                                 if (recipient.equals(post.getRecipient())) {
553                                         directedPosts.add(post);
554                                 }
555                         }
556                 }
557                 return directedPosts;
558         }
559
560         /**
561          * Returns the reply with the given ID.
562          *
563          * @param replyId
564          *            The ID of the reply to get
565          * @return The reply, or {@code null} if there is no such reply
566          */
567         public PostReply getPostReply(String replyId) {
568                 synchronized (replies) {
569                         return replies.get(replyId);
570                 }
571         }
572
573         /**
574          * Returns all replies for the given post, order ascending by time.
575          *
576          * @param post
577          *            The post to get all replies for
578          * @return All replies for the given post
579          */
580         public List<PostReply> getReplies(Post post) {
581                 Set<Sone> sones = getSones();
582                 List<PostReply> replies = new ArrayList<PostReply>();
583                 for (Sone sone : sones) {
584                         for (PostReply reply : sone.getReplies()) {
585                                 if (reply.getPost().equals(post)) {
586                                         replies.add(reply);
587                                 }
588                         }
589                 }
590                 Collections.sort(replies, Reply.TIME_COMPARATOR);
591                 return replies;
592         }
593
594         /**
595          * Returns all Sones that have liked the given post.
596          *
597          * @param post
598          *            The post to get the liking Sones for
599          * @return The Sones that like the given post
600          */
601         public Set<Sone> getLikes(Post post) {
602                 Set<Sone> sones = new HashSet<Sone>();
603                 for (Sone sone : getSones()) {
604                         if (sone.getLikedPostIds().contains(post.getId())) {
605                                 sones.add(sone);
606                         }
607                 }
608                 return sones;
609         }
610
611         /**
612          * Returns all Sones that have liked the given reply.
613          *
614          * @param reply
615          *            The reply to get the liking Sones for
616          * @return The Sones that like the given reply
617          */
618         public Set<Sone> getLikes(PostReply reply) {
619                 Set<Sone> sones = new HashSet<Sone>();
620                 for (Sone sone : getSones()) {
621                         if (sone.getLikedReplyIds().contains(reply.getId())) {
622                                 sones.add(sone);
623                         }
624                 }
625                 return sones;
626         }
627
628         /**
629          * Returns whether the given post is bookmarked.
630          *
631          * @param post
632          *            The post to check
633          * @return {@code true} if the given post is bookmarked, {@code false}
634          *         otherwise
635          */
636         public boolean isBookmarked(Post post) {
637                 return isPostBookmarked(post.getId());
638         }
639
640         /**
641          * Returns whether the post with the given ID is bookmarked.
642          *
643          * @param id
644          *            The ID of the post to check
645          * @return {@code true} if the post with the given ID is bookmarked,
646          *         {@code false} otherwise
647          */
648         public boolean isPostBookmarked(String id) {
649                 synchronized (bookmarkedPosts) {
650                         return bookmarkedPosts.contains(id);
651                 }
652         }
653
654         /**
655          * Returns all currently known bookmarked posts.
656          *
657          * @return All bookmarked posts
658          */
659         public Set<Post> getBookmarkedPosts() {
660                 Set<Post> posts = new HashSet<Post>();
661                 synchronized (bookmarkedPosts) {
662                         for (String bookmarkedPostId : bookmarkedPosts) {
663                                 Post post = getPost(bookmarkedPostId);
664                                 if (post != null) {
665                                         posts.add(post);
666                                 }
667                         }
668                 }
669                 return posts;
670         }
671
672         /**
673          * Returns the album with the given ID, creating a new album if no album
674          * with the given ID can be found.
675          *
676          * @param albumId
677          *            The ID of the album
678          * @return The album with the given ID
679          */
680         public Album getAlbum(String albumId) {
681                 return getAlbum(albumId, true);
682         }
683
684         /**
685          * Returns the album with the given ID, optionally creating a new album if
686          * an album with the given ID can not be found.
687          *
688          * @param albumId
689          *            The ID of the album
690          * @param create
691          *            {@code true} to create a new album if none exists for the
692          *            given ID
693          * @return The album with the given ID, or {@code null} if no album with the
694          *         given ID exists and {@code create} is {@code false}
695          */
696         public Album getAlbum(String albumId, boolean create) {
697                 synchronized (albums) {
698                         Album album = albums.get(albumId);
699                         if (create && (album == null)) {
700                                 album = new Album(albumId);
701                                 albums.put(albumId, album);
702                         }
703                         return album;
704                 }
705         }
706
707         /**
708          * Returns the image with the given ID, creating it if necessary.
709          *
710          * @param imageId
711          *            The ID of the image
712          * @return The image with the given ID
713          */
714         public Image getImage(String imageId) {
715                 return getImage(imageId, true);
716         }
717
718         /**
719          * Returns the image with the given ID, optionally creating it if it does
720          * not exist.
721          *
722          * @param imageId
723          *            The ID of the image
724          * @param create
725          *            {@code true} to create an image if none exists with the given
726          *            ID
727          * @return The image with the given ID, or {@code null} if none exists and
728          *         none was created
729          */
730         public Image getImage(String imageId, boolean create) {
731                 synchronized (images) {
732                         Image image = images.get(imageId);
733                         if (create && (image == null)) {
734                                 image = new Image(imageId);
735                                 images.put(imageId, image);
736                         }
737                         return image;
738                 }
739         }
740
741         /**
742          * Returns the temporary image with the given ID.
743          *
744          * @param imageId
745          *            The ID of the temporary image
746          * @return The temporary image, or {@code null} if there is no temporary
747          *         image with the given ID
748          */
749         public TemporaryImage getTemporaryImage(String imageId) {
750                 synchronized (temporaryImages) {
751                         return temporaryImages.get(imageId);
752                 }
753         }
754
755         //
756         // ACTIONS
757         //
758
759         /**
760          * Locks the given Sone. A locked Sone will not be inserted by
761          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
762          * again.
763          *
764          * @param sone
765          *            The sone to lock
766          */
767         public void lockSone(Sone sone) {
768                 synchronized (lockedSones) {
769                         if (lockedSones.add(sone)) {
770                                 eventBus.post(new SoneLockedEvent(sone));
771                         }
772                 }
773         }
774
775         /**
776          * Unlocks the given Sone.
777          *
778          * @see #lockSone(Sone)
779          * @param sone
780          *            The sone to unlock
781          */
782         public void unlockSone(Sone sone) {
783                 synchronized (lockedSones) {
784                         if (lockedSones.remove(sone)) {
785                                 eventBus.post(new SoneUnlockedEvent(sone));
786                         }
787                 }
788         }
789
790         /**
791          * Adds a local Sone from the given own identity.
792          *
793          * @param ownIdentity
794          *            The own identity to create a Sone from
795          * @return The added (or already existing) Sone
796          */
797         public Sone addLocalSone(OwnIdentity ownIdentity) {
798                 if (ownIdentity == null) {
799                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
800                         return null;
801                 }
802                 synchronized (sones) {
803                         final Sone sone;
804                         try {
805                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
806                         } catch (MalformedURLException mue1) {
807                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
808                                 return null;
809                         }
810                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
811                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
812                         sone.setKnown(true);
813                         /* TODO - load posts ’n stuff */
814                         sones.put(ownIdentity.getId(), sone);
815                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
816                         soneInserters.put(sone, soneInserter);
817                         sone.setStatus(SoneStatus.idle);
818                         loadSone(sone);
819                         soneInserter.start();
820                         return sone;
821                 }
822         }
823
824         /**
825          * Creates a new Sone for the given own identity.
826          *
827          * @param ownIdentity
828          *            The own identity to create a Sone for
829          * @return The created Sone
830          */
831         public Sone createSone(OwnIdentity ownIdentity) {
832                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
833                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
834                         return null;
835                 }
836                 Sone sone = addLocalSone(ownIdentity);
837                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
838                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
839                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
840                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
841                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
842                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
843
844                 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
845                 touchConfiguration();
846                 return sone;
847         }
848
849         /**
850          * Adds the Sone of the given identity.
851          *
852          * @param identity
853          *            The identity whose Sone to add
854          * @return The added or already existing Sone
855          */
856         public Sone addRemoteSone(Identity identity) {
857                 if (identity == null) {
858                         logger.log(Level.WARNING, "Given Identity is null!");
859                         return null;
860                 }
861                 synchronized (sones) {
862                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
863                         boolean newSone = sone.getRequestUri() == null;
864                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
865                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
866                         if (newSone) {
867                                 synchronized (knownSones) {
868                                         newSone = !knownSones.contains(sone.getId());
869                                 }
870                                 sone.setKnown(!newSone);
871                                 if (newSone) {
872                                         eventBus.post(new NewSoneFoundEvent(sone));
873                                         for (Sone localSone : getLocalSones()) {
874                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
875                                                         followSone(localSone, sone);
876                                                 }
877                                         }
878                                 }
879                         }
880                         soneDownloader.addSone(sone);
881                         soneDownloaders.execute(new Runnable() {
882
883                                 @Override
884                                 @SuppressWarnings("synthetic-access")
885                                 public void run() {
886                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
887                                 }
888
889                         });
890                         return sone;
891                 }
892         }
893
894         /**
895          * Lets the given local Sone follow the Sone with the given ID.
896          *
897          * @param sone
898          *            The local Sone that should follow another Sone
899          * @param soneId
900          *            The ID of the Sone to follow
901          */
902         public void followSone(Sone sone, String soneId) {
903                 checkNotNull(sone, "sone must not be null");
904                 checkNotNull(soneId, "soneId must not be null");
905                 Sone followedSone = getSone(soneId, true);
906                 if (followedSone == null) {
907                         logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
908                         return;
909                 }
910                 followSone(sone, getSone(soneId));
911         }
912
913         /**
914          * Lets the given local Sone follow the other given Sone. If the given Sone
915          * was not followed by any local Sone before, this will mark all elements of
916          * the followed Sone as read that have been created before the current
917          * moment.
918          *
919          * @param sone
920          *            The local Sone that should follow the other Sone
921          * @param followedSone
922          *            The Sone that should be followed
923          */
924         public void followSone(Sone sone, Sone followedSone) {
925                 checkNotNull(sone, "sone must not be null");
926                 checkNotNull(followedSone, "followedSone must not be null");
927                 sone.addFriend(followedSone.getId());
928                 synchronized (soneFollowingTimes) {
929                         if (!soneFollowingTimes.containsKey(followedSone)) {
930                                 long now = System.currentTimeMillis();
931                                 soneFollowingTimes.put(followedSone, now);
932                                 for (Post post : followedSone.getPosts()) {
933                                         if (post.getTime() < now) {
934                                                 markPostKnown(post);
935                                         }
936                                 }
937                                 for (PostReply reply : followedSone.getReplies()) {
938                                         if (reply.getTime() < now) {
939                                                 markReplyKnown(reply);
940                                         }
941                                 }
942                         }
943                 }
944                 touchConfiguration();
945         }
946
947         /**
948          * Lets the given local Sone unfollow the Sone with the given ID.
949          *
950          * @param sone
951          *            The local Sone that should unfollow another Sone
952          * @param soneId
953          *            The ID of the Sone being unfollowed
954          */
955         public void unfollowSone(Sone sone, String soneId) {
956                 checkNotNull(sone, "sone must not be null");
957                 checkNotNull(soneId, "soneId must not be null");
958                 unfollowSone(sone, getSone(soneId, false));
959         }
960
961         /**
962          * Lets the given local Sone unfollow the other given Sone. If the given
963          * local Sone is the last local Sone that followed the given Sone, its
964          * following time will be removed.
965          *
966          * @param sone
967          *            The local Sone that should unfollow another Sone
968          * @param unfollowedSone
969          *            The Sone being unfollowed
970          */
971         public void unfollowSone(Sone sone, Sone unfollowedSone) {
972                 checkNotNull(sone, "sone must not be null");
973                 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
974                 sone.removeFriend(unfollowedSone.getId());
975                 boolean unfollowedSoneStillFollowed = false;
976                 for (Sone localSone : getLocalSones()) {
977                         unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
978                 }
979                 if (!unfollowedSoneStillFollowed) {
980                         synchronized (soneFollowingTimes) {
981                                 soneFollowingTimes.remove(unfollowedSone);
982                         }
983                 }
984                 touchConfiguration();
985         }
986
987         /**
988          * Sets the trust value of the given origin Sone for the target Sone.
989          *
990          * @param origin
991          *            The origin Sone
992          * @param target
993          *            The target Sone
994          * @param trustValue
995          *            The trust value (from {@code -100} to {@code 100})
996          */
997         public void setTrust(Sone origin, Sone target, int trustValue) {
998                 checkNotNull(origin, "origin must not be null");
999                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1000                 checkNotNull(target, "target must not be null");
1001                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1002                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1003         }
1004
1005         /**
1006          * Removes any trust assignment for the given target Sone.
1007          *
1008          * @param origin
1009          *            The trust origin
1010          * @param target
1011          *            The trust target
1012          */
1013         public void removeTrust(Sone origin, Sone target) {
1014                 checkNotNull(origin, "origin must not be null");
1015                 checkNotNull(target, "target must not be null");
1016                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1017                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1018         }
1019
1020         /**
1021          * Assigns the configured positive trust value for the given target.
1022          *
1023          * @param origin
1024          *            The trust origin
1025          * @param target
1026          *            The trust target
1027          */
1028         public void trustSone(Sone origin, Sone target) {
1029                 setTrust(origin, target, preferences.getPositiveTrust());
1030         }
1031
1032         /**
1033          * Assigns the configured negative trust value for the given target.
1034          *
1035          * @param origin
1036          *            The trust origin
1037          * @param target
1038          *            The trust target
1039          */
1040         public void distrustSone(Sone origin, Sone target) {
1041                 setTrust(origin, target, preferences.getNegativeTrust());
1042         }
1043
1044         /**
1045          * Removes the trust assignment for the given target.
1046          *
1047          * @param origin
1048          *            The trust origin
1049          * @param target
1050          *            The trust target
1051          */
1052         public void untrustSone(Sone origin, Sone target) {
1053                 removeTrust(origin, target);
1054         }
1055
1056         /**
1057          * Updates the stored Sone with the given Sone.
1058          *
1059          * @param sone
1060          *            The updated Sone
1061          */
1062         public void updateSone(Sone sone) {
1063                 updateSone(sone, false);
1064         }
1065
1066         /**
1067          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1068          * {@code true}, an older Sone than the current Sone can be given to restore
1069          * an old state.
1070          *
1071          * @param sone
1072          *            The Sone to update
1073          * @param soneRescueMode
1074          *            {@code true} if the stored Sone should be updated regardless
1075          *            of the age of the given Sone
1076          */
1077         public void updateSone(Sone sone, boolean soneRescueMode) {
1078                 if (hasSone(sone.getId())) {
1079                         Sone storedSone = getSone(sone.getId());
1080                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1081                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1082                                 return;
1083                         }
1084                         synchronized (posts) {
1085                                 if (!soneRescueMode) {
1086                                         for (Post post : storedSone.getPosts()) {
1087                                                 posts.remove(post.getId());
1088                                                 if (!sone.getPosts().contains(post)) {
1089                                                         eventBus.post(new PostRemovedEvent(post));
1090                                                 }
1091                                         }
1092                                 }
1093                                 List<Post> storedPosts = storedSone.getPosts();
1094                                 synchronized (knownPosts) {
1095                                         for (Post post : sone.getPosts()) {
1096                                                 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1097                                                 postBuilder.copyPost(post).from(storedSone);
1098                                                 Post newPost = postBuilder.build().setKnown(knownPosts.contains(post.getId()));
1099                                                 if (!storedPosts.contains(newPost)) {
1100                                                         if (newPost.getTime() < getSoneFollowingTime(sone)) {
1101                                                                 knownPosts.add(newPost.getId());
1102                                                                 newPost.setKnown(true);
1103                                                         } else if (!knownPosts.contains(newPost.getId())) {
1104                                                                 eventBus.post(new NewPostFoundEvent(newPost));
1105                                                         }
1106                                                 }
1107                                                 posts.put(newPost.getId(), newPost);
1108                                         }
1109                                 }
1110                         }
1111                         synchronized (replies) {
1112                                 if (!soneRescueMode) {
1113                                         for (PostReply reply : storedSone.getReplies()) {
1114                                                 replies.remove(reply.getId());
1115                                                 if (!sone.getReplies().contains(reply)) {
1116                                                         eventBus.post(new PostReplyRemovedEvent(reply));
1117                                                 }
1118                                         }
1119                                 }
1120                                 Set<PostReply> storedReplies = storedSone.getReplies();
1121                                 synchronized (knownReplies) {
1122                                         for (PostReply reply : sone.getReplies()) {
1123                                                 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1124                                                 if (!storedReplies.contains(reply)) {
1125                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1126                                                                 knownReplies.add(reply.getId());
1127                                                                 reply.setKnown(true);
1128                                                         } else if (!knownReplies.contains(reply.getId())) {
1129                                                                 eventBus.post(new NewPostReplyFoundEvent(reply));
1130                                                         }
1131                                                 }
1132                                                 replies.put(reply.getId(), reply);
1133                                         }
1134                                 }
1135                         }
1136                         synchronized (albums) {
1137                                 synchronized (images) {
1138                                         for (Album album : storedSone.getAlbums()) {
1139                                                 albums.remove(album.getId());
1140                                                 for (Image image : album.getImages()) {
1141                                                         images.remove(image.getId());
1142                                                 }
1143                                         }
1144                                         for (Album album : sone.getAlbums()) {
1145                                                 albums.put(album.getId(), album);
1146                                                 for (Image image : album.getImages()) {
1147                                                         images.put(image.getId(), image);
1148                                                 }
1149                                         }
1150                                 }
1151                         }
1152                         synchronized (storedSone) {
1153                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1154                                         storedSone.setTime(sone.getTime());
1155                                 }
1156                                 storedSone.setClient(sone.getClient());
1157                                 storedSone.setProfile(sone.getProfile());
1158                                 if (soneRescueMode) {
1159                                         for (Post post : sone.getPosts()) {
1160                                                 storedSone.addPost(post);
1161                                         }
1162                                         for (PostReply reply : sone.getReplies()) {
1163                                                 storedSone.addReply(reply);
1164                                         }
1165                                         for (String likedPostId : sone.getLikedPostIds()) {
1166                                                 storedSone.addLikedPostId(likedPostId);
1167                                         }
1168                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1169                                                 storedSone.addLikedReplyId(likedReplyId);
1170                                         }
1171                                         for (Album album : sone.getAlbums()) {
1172                                                 storedSone.addAlbum(album);
1173                                         }
1174                                 } else {
1175                                         storedSone.setPosts(sone.getPosts());
1176                                         storedSone.setReplies(sone.getReplies());
1177                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1178                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1179                                         storedSone.setAlbums(sone.getAlbums());
1180                                 }
1181                                 storedSone.setLatestEdition(sone.getLatestEdition());
1182                         }
1183                 }
1184         }
1185
1186         /**
1187          * Deletes the given Sone. This will remove the Sone from the
1188          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1189          * remove the context from its identity.
1190          *
1191          * @param sone
1192          *            The Sone to delete
1193          */
1194         public void deleteSone(Sone sone) {
1195                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1196                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1197                         return;
1198                 }
1199                 synchronized (sones) {
1200                         if (!getLocalSones().contains(sone)) {
1201                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1202                                 return;
1203                         }
1204                         sones.remove(sone.getId());
1205                         SoneInserter soneInserter = soneInserters.remove(sone);
1206                         soneInserter.stop();
1207                 }
1208                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1209                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1210                 try {
1211                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1212                 } catch (ConfigurationException ce1) {
1213                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1214                 }
1215         }
1216
1217         /**
1218          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1219          * known} before, a {@link MarkSoneKnownEvent} is fired.
1220          *
1221          * @param sone
1222          *            The Sone to mark as known
1223          */
1224         public void markSoneKnown(Sone sone) {
1225                 if (!sone.isKnown()) {
1226                         sone.setKnown(true);
1227                         synchronized (knownSones) {
1228                                 knownSones.add(sone.getId());
1229                         }
1230                         eventBus.post(new MarkSoneKnownEvent(sone));
1231                         touchConfiguration();
1232                 }
1233         }
1234
1235         /**
1236          * Loads and updates the given Sone from the configuration. If any error is
1237          * encountered, loading is aborted and the given Sone is not changed.
1238          *
1239          * @param sone
1240          *            The Sone to load and update
1241          */
1242         public void loadSone(Sone sone) {
1243                 if (!sone.isLocal()) {
1244                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1245                         return;
1246                 }
1247
1248                 /* initialize options. */
1249                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1250                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1251                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1252                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1253                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1254                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1255
1256                 /* load Sone. */
1257                 String sonePrefix = "Sone/" + sone.getId();
1258                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1259                 if (soneTime == null) {
1260                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1261                         return;
1262                 }
1263                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1264
1265                 /* load profile. */
1266                 Profile profile = new Profile(sone);
1267                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1268                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1269                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1270                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1271                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1272                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1273
1274                 /* load profile fields. */
1275                 while (true) {
1276                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1277                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1278                         if (fieldName == null) {
1279                                 break;
1280                         }
1281                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1282                         profile.addField(fieldName).setValue(fieldValue);
1283                 }
1284
1285                 /* load posts. */
1286                 Set<Post> posts = new HashSet<Post>();
1287                 while (true) {
1288                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1289                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1290                         if (postId == null) {
1291                                 break;
1292                         }
1293                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1294                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1295                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1296                         if ((postTime == 0) || (postText == null)) {
1297                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1298                                 return;
1299                         }
1300                         PostBuilder postBuilder = postBuilderFactory.newPostBuilder().withId(postId).from(sone).withTime(postTime).withText(postText);
1301                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1302                                 postBuilder.to(getSone(postRecipientId));
1303                         }
1304                         posts.add(postBuilder.build());
1305                 }
1306
1307                 /* load replies. */
1308                 Set<PostReply> replies = new HashSet<PostReply>();
1309                 while (true) {
1310                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1311                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1312                         if (replyId == null) {
1313                                 break;
1314                         }
1315                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1316                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1317                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1318                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1319                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1320                                 return;
1321                         }
1322                         replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1323                 }
1324
1325                 /* load post likes. */
1326                 Set<String> likedPostIds = new HashSet<String>();
1327                 while (true) {
1328                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1329                         if (likedPostId == null) {
1330                                 break;
1331                         }
1332                         likedPostIds.add(likedPostId);
1333                 }
1334
1335                 /* load reply likes. */
1336                 Set<String> likedReplyIds = new HashSet<String>();
1337                 while (true) {
1338                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1339                         if (likedReplyId == null) {
1340                                 break;
1341                         }
1342                         likedReplyIds.add(likedReplyId);
1343                 }
1344
1345                 /* load friends. */
1346                 Set<String> friends = new HashSet<String>();
1347                 while (true) {
1348                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1349                         if (friendId == null) {
1350                                 break;
1351                         }
1352                         friends.add(friendId);
1353                 }
1354
1355                 /* load albums. */
1356                 List<Album> topLevelAlbums = new ArrayList<Album>();
1357                 int albumCounter = 0;
1358                 while (true) {
1359                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1360                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1361                         if (albumId == null) {
1362                                 break;
1363                         }
1364                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1365                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1366                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1367                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1368                         if ((albumTitle == null) || (albumDescription == null)) {
1369                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1370                                 return;
1371                         }
1372                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1373                         if (albumParentId != null) {
1374                                 Album parentAlbum = getAlbum(albumParentId, false);
1375                                 if (parentAlbum == null) {
1376                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1377                                         return;
1378                                 }
1379                                 parentAlbum.addAlbum(album);
1380                         } else {
1381                                 if (!topLevelAlbums.contains(album)) {
1382                                         topLevelAlbums.add(album);
1383                                 }
1384                         }
1385                 }
1386
1387                 /* load images. */
1388                 int imageCounter = 0;
1389                 while (true) {
1390                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1391                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1392                         if (imageId == null) {
1393                                 break;
1394                         }
1395                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1396                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1397                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1398                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1399                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1400                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1401                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1402                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1403                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1404                                 return;
1405                         }
1406                         Album album = getAlbum(albumId, false);
1407                         if (album == null) {
1408                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1409                                 return;
1410                         }
1411                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1412                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1413                         album.addImage(image);
1414                 }
1415
1416                 /* load avatar. */
1417                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1418                 if (avatarId != null) {
1419                         profile.setAvatar(getImage(avatarId, false));
1420                 }
1421
1422                 /* load options. */
1423                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1424                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1425                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1426                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1427                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1428                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1429
1430                 /* if we’re still here, Sone was loaded successfully. */
1431                 synchronized (sone) {
1432                         sone.setTime(soneTime);
1433                         sone.setProfile(profile);
1434                         sone.setPosts(posts);
1435                         sone.setReplies(replies);
1436                         sone.setLikePostIds(likedPostIds);
1437                         sone.setLikeReplyIds(likedReplyIds);
1438                         for (String friendId : friends) {
1439                                 followSone(sone, friendId);
1440                         }
1441                         sone.setAlbums(topLevelAlbums);
1442                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1443                 }
1444                 synchronized (knownSones) {
1445                         for (String friend : friends) {
1446                                 knownSones.add(friend);
1447                         }
1448                 }
1449                 synchronized (knownPosts) {
1450                         for (Post post : posts) {
1451                                 knownPosts.add(post.getId());
1452                         }
1453                 }
1454                 synchronized (knownReplies) {
1455                         for (PostReply reply : replies) {
1456                                 knownReplies.add(reply.getId());
1457                         }
1458                 }
1459         }
1460
1461         /**
1462          * Creates a new post.
1463          *
1464          * @param sone
1465          *            The Sone that creates the post
1466          * @param text
1467          *            The text of the post
1468          * @return The created post
1469          */
1470         public Post createPost(Sone sone, String text) {
1471                 return createPost(sone, System.currentTimeMillis(), text);
1472         }
1473
1474         /**
1475          * Creates a new post.
1476          *
1477          * @param sone
1478          *            The Sone that creates the post
1479          * @param time
1480          *            The time of the post
1481          * @param text
1482          *            The text of the post
1483          * @return The created post
1484          */
1485         public Post createPost(Sone sone, long time, String text) {
1486                 return createPost(sone, null, time, text);
1487         }
1488
1489         /**
1490          * Creates a new post.
1491          *
1492          * @param sone
1493          *            The Sone that creates the post
1494          * @param recipient
1495          *            The recipient Sone, or {@code null} if this post does not have
1496          *            a recipient
1497          * @param text
1498          *            The text of the post
1499          * @return The created post
1500          */
1501         public Post createPost(Sone sone, Sone recipient, String text) {
1502                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1503         }
1504
1505         /**
1506          * Creates a new post.
1507          *
1508          * @param sone
1509          *            The Sone that creates the post
1510          * @param recipient
1511          *            The recipient Sone, or {@code null} if this post does not have
1512          *            a recipient
1513          * @param time
1514          *            The time of the post
1515          * @param text
1516          *            The text of the post
1517          * @return The created post
1518          */
1519         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1520                 checkNotNull(text, "text must not be null");
1521                 checkArgument(text.trim().length() > 0, "text must not be empty");
1522                 if (!sone.isLocal()) {
1523                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1524                         return null;
1525                 }
1526                 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1527                 postBuilder.from(sone).randomId().withTime(time).withText(text.trim());
1528                 if (recipient != null) {
1529                         postBuilder.to(recipient);
1530                 }
1531                 final Post post = postBuilder.build();
1532                 synchronized (posts) {
1533                         posts.put(post.getId(), post);
1534                 }
1535                 eventBus.post(new NewPostFoundEvent(post));
1536                 sone.addPost(post);
1537                 touchConfiguration();
1538                 localElementTicker.schedule(new Runnable() {
1539
1540                         /**
1541                          * {@inheritDoc}
1542                          */
1543                         @Override
1544                         public void run() {
1545                                 markPostKnown(post);
1546                         }
1547                 }, 10, TimeUnit.SECONDS);
1548                 return post;
1549         }
1550
1551         /**
1552          * Deletes the given post.
1553          *
1554          * @param post
1555          *            The post to delete
1556          */
1557         public void deletePost(Post post) {
1558                 if (!post.getSone().isLocal()) {
1559                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1560                         return;
1561                 }
1562                 post.getSone().removePost(post);
1563                 synchronized (posts) {
1564                         posts.remove(post.getId());
1565                 }
1566                 eventBus.post(new PostRemovedEvent(post));
1567                 markPostKnown(post);
1568                 touchConfiguration();
1569         }
1570
1571         /**
1572          * Marks the given post as known, if it is currently not a known post
1573          * (according to {@link Post#isKnown()}).
1574          *
1575          * @param post
1576          *            The post to mark as known
1577          */
1578         public void markPostKnown(Post post) {
1579                 post.setKnown(true);
1580                 synchronized (knownPosts) {
1581                         eventBus.post(new MarkPostKnownEvent(post));
1582                         if (knownPosts.add(post.getId())) {
1583                                 touchConfiguration();
1584                         }
1585                 }
1586                 for (PostReply reply : getReplies(post)) {
1587                         markReplyKnown(reply);
1588                 }
1589         }
1590
1591         /**
1592          * Bookmarks the given post.
1593          *
1594          * @param post
1595          *            The post to bookmark
1596          */
1597         public void bookmark(Post post) {
1598                 bookmarkPost(post.getId());
1599         }
1600
1601         /**
1602          * Bookmarks the post with the given ID.
1603          *
1604          * @param id
1605          *            The ID of the post to bookmark
1606          */
1607         public void bookmarkPost(String id) {
1608                 synchronized (bookmarkedPosts) {
1609                         bookmarkedPosts.add(id);
1610                 }
1611         }
1612
1613         /**
1614          * Removes the given post from the bookmarks.
1615          *
1616          * @param post
1617          *            The post to unbookmark
1618          */
1619         public void unbookmark(Post post) {
1620                 unbookmarkPost(post.getId());
1621         }
1622
1623         /**
1624          * Removes the post with the given ID from the bookmarks.
1625          *
1626          * @param id
1627          *            The ID of the post to unbookmark
1628          */
1629         public void unbookmarkPost(String id) {
1630                 synchronized (bookmarkedPosts) {
1631                         bookmarkedPosts.remove(id);
1632                 }
1633         }
1634
1635         /**
1636          * Creates a new reply.
1637          *
1638          * @param sone
1639          *            The Sone that creates the reply
1640          * @param post
1641          *            The post that this reply refers to
1642          * @param text
1643          *            The text of the reply
1644          * @return The created reply
1645          */
1646         public PostReply createReply(Sone sone, Post post, String text) {
1647                 return createReply(sone, post, System.currentTimeMillis(), text);
1648         }
1649
1650         /**
1651          * Creates a new reply.
1652          *
1653          * @param sone
1654          *            The Sone that creates the reply
1655          * @param post
1656          *            The post that this reply refers to
1657          * @param time
1658          *            The time of the reply
1659          * @param text
1660          *            The text of the reply
1661          * @return The created reply
1662          */
1663         public PostReply createReply(Sone sone, Post post, long time, String text) {
1664                 checkNotNull(text, "text must not be null");
1665                 checkArgument(text.trim().length() > 0, "text must not be empty");
1666                 if (!sone.isLocal()) {
1667                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1668                         return null;
1669                 }
1670                 final PostReply reply = new PostReplyImpl(sone, post, System.currentTimeMillis(), text.trim());
1671                 synchronized (replies) {
1672                         replies.put(reply.getId(), reply);
1673                 }
1674                 synchronized (knownReplies) {
1675                         eventBus.post(new NewPostReplyFoundEvent(reply));
1676                 }
1677                 sone.addReply(reply);
1678                 touchConfiguration();
1679                 localElementTicker.schedule(new Runnable() {
1680
1681                         /**
1682                          * {@inheritDoc}
1683                          */
1684                         @Override
1685                         public void run() {
1686                                 markReplyKnown(reply);
1687                         }
1688                 }, 10, TimeUnit.SECONDS);
1689                 return reply;
1690         }
1691
1692         /**
1693          * Deletes the given reply.
1694          *
1695          * @param reply
1696          *            The reply to delete
1697          */
1698         public void deleteReply(PostReply reply) {
1699                 Sone sone = reply.getSone();
1700                 if (!sone.isLocal()) {
1701                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1702                         return;
1703                 }
1704                 synchronized (replies) {
1705                         replies.remove(reply.getId());
1706                 }
1707                 synchronized (knownReplies) {
1708                         markReplyKnown(reply);
1709                         knownReplies.remove(reply.getId());
1710                 }
1711                 sone.removeReply(reply);
1712                 touchConfiguration();
1713         }
1714
1715         /**
1716          * Marks the given reply as known, if it is currently not a known reply
1717          * (according to {@link Reply#isKnown()}).
1718          *
1719          * @param reply
1720          *            The reply to mark as known
1721          */
1722         public void markReplyKnown(PostReply reply) {
1723                 reply.setKnown(true);
1724                 synchronized (knownReplies) {
1725                         eventBus.post(new MarkPostReplyKnownEvent(reply));
1726                         if (knownReplies.add(reply.getId())) {
1727                                 touchConfiguration();
1728                         }
1729                 }
1730         }
1731
1732         /**
1733          * Creates a new top-level album for the given Sone.
1734          *
1735          * @param sone
1736          *            The Sone to create the album for
1737          * @return The new album
1738          */
1739         public Album createAlbum(Sone sone) {
1740                 return createAlbum(sone, null);
1741         }
1742
1743         /**
1744          * Creates a new album for the given Sone.
1745          *
1746          * @param sone
1747          *            The Sone to create the album for
1748          * @param parent
1749          *            The parent of the album (may be {@code null} to create a
1750          *            top-level album)
1751          * @return The new album
1752          */
1753         public Album createAlbum(Sone sone, Album parent) {
1754                 Album album = new Album();
1755                 synchronized (albums) {
1756                         albums.put(album.getId(), album);
1757                 }
1758                 album.setSone(sone);
1759                 if (parent != null) {
1760                         parent.addAlbum(album);
1761                 } else {
1762                         sone.addAlbum(album);
1763                 }
1764                 return album;
1765         }
1766
1767         /**
1768          * Deletes the given album. The owner of the album has to be a local Sone,
1769          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1770          *
1771          * @param album
1772          *            The album to remove
1773          */
1774         public void deleteAlbum(Album album) {
1775                 checkNotNull(album, "album must not be null");
1776                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1777                 if (!album.isEmpty()) {
1778                         return;
1779                 }
1780                 if (album.getParent() == null) {
1781                         album.getSone().removeAlbum(album);
1782                 } else {
1783                         album.getParent().removeAlbum(album);
1784                 }
1785                 synchronized (albums) {
1786                         albums.remove(album.getId());
1787                 }
1788                 touchConfiguration();
1789         }
1790
1791         /**
1792          * Creates a new image.
1793          *
1794          * @param sone
1795          *            The Sone creating the image
1796          * @param album
1797          *            The album the image will be inserted into
1798          * @param temporaryImage
1799          *            The temporary image to create the image from
1800          * @return The newly created image
1801          */
1802         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1803                 checkNotNull(sone, "sone must not be null");
1804                 checkNotNull(album, "album must not be null");
1805                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1806                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1807                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1808                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1809                 album.addImage(image);
1810                 synchronized (images) {
1811                         images.put(image.getId(), image);
1812                 }
1813                 imageInserter.insertImage(temporaryImage, image);
1814                 return image;
1815         }
1816
1817         /**
1818          * Deletes the given image. This method will also delete a matching
1819          * temporary image.
1820          *
1821          * @see #deleteTemporaryImage(TemporaryImage)
1822          * @param image
1823          *            The image to delete
1824          */
1825         public void deleteImage(Image image) {
1826                 checkNotNull(image, "image must not be null");
1827                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1828                 deleteTemporaryImage(image.getId());
1829                 image.getAlbum().removeImage(image);
1830                 synchronized (images) {
1831                         images.remove(image.getId());
1832                 }
1833                 touchConfiguration();
1834         }
1835
1836         /**
1837          * Creates a new temporary image.
1838          *
1839          * @param mimeType
1840          *            The MIME type of the temporary image
1841          * @param imageData
1842          *            The encoded data of the image
1843          * @return The temporary image
1844          */
1845         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1846                 TemporaryImage temporaryImage = new TemporaryImage();
1847                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1848                 synchronized (temporaryImages) {
1849                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1850                 }
1851                 return temporaryImage;
1852         }
1853
1854         /**
1855          * Deletes the given temporary image.
1856          *
1857          * @param temporaryImage
1858          *            The temporary image to delete
1859          */
1860         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1861                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1862                 deleteTemporaryImage(temporaryImage.getId());
1863         }
1864
1865         /**
1866          * Deletes the temporary image with the given ID.
1867          *
1868          * @param imageId
1869          *            The ID of the temporary image to delete
1870          */
1871         public void deleteTemporaryImage(String imageId) {
1872                 checkNotNull(imageId, "imageId must not be null");
1873                 synchronized (temporaryImages) {
1874                         temporaryImages.remove(imageId);
1875                 }
1876                 Image image = getImage(imageId, false);
1877                 if (image != null) {
1878                         imageInserter.cancelImageInsert(image);
1879                 }
1880         }
1881
1882         /**
1883          * Notifies the core that the configuration, either of the core or of a
1884          * single local Sone, has changed, and that the configuration should be
1885          * saved.
1886          */
1887         public void touchConfiguration() {
1888                 lastConfigurationUpdate = System.currentTimeMillis();
1889         }
1890
1891         //
1892         // SERVICE METHODS
1893         //
1894
1895         /**
1896          * Starts the core.
1897          */
1898         @Override
1899         public void serviceStart() {
1900                 loadConfiguration();
1901                 updateChecker.start();
1902                 identityManager.start();
1903                 webOfTrustUpdater.init();
1904                 webOfTrustUpdater.start();
1905         }
1906
1907         /**
1908          * {@inheritDoc}
1909          */
1910         @Override
1911         public void serviceRun() {
1912                 long lastSaved = System.currentTimeMillis();
1913                 while (!shouldStop()) {
1914                         sleep(1000);
1915                         long now = System.currentTimeMillis();
1916                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1917                                 for (Sone localSone : getLocalSones()) {
1918                                         saveSone(localSone);
1919                                 }
1920                                 saveConfiguration();
1921                                 lastSaved = now;
1922                         }
1923                 }
1924         }
1925
1926         /**
1927          * Stops the core.
1928          */
1929         @Override
1930         public void serviceStop() {
1931                 localElementTicker.shutdownNow();
1932                 synchronized (sones) {
1933                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1934                                 soneInserter.getValue().stop();
1935                                 saveSone(soneInserter.getKey());
1936                         }
1937                 }
1938                 saveConfiguration();
1939                 webOfTrustUpdater.stop();
1940                 updateChecker.stop();
1941                 soneDownloader.stop();
1942                 identityManager.stop();
1943         }
1944
1945         //
1946         // PRIVATE METHODS
1947         //
1948
1949         /**
1950          * Saves the given Sone. This will persist all local settings for the given
1951          * Sone, such as the friends list and similar, private options.
1952          *
1953          * @param sone
1954          *            The Sone to save
1955          */
1956         private synchronized void saveSone(Sone sone) {
1957                 if (!sone.isLocal()) {
1958                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1959                         return;
1960                 }
1961                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1962                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1963                         return;
1964                 }
1965
1966                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1967                 try {
1968                         /* save Sone into configuration. */
1969                         String sonePrefix = "Sone/" + sone.getId();
1970                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1971                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1972
1973                         /* save profile. */
1974                         Profile profile = sone.getProfile();
1975                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1976                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1977                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1978                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1979                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1980                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1981                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1982
1983                         /* save profile fields. */
1984                         int fieldCounter = 0;
1985                         for (Field profileField : profile.getFields()) {
1986                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1987                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1988                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1989                         }
1990                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1991
1992                         /* save posts. */
1993                         int postCounter = 0;
1994                         for (Post post : sone.getPosts()) {
1995                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1996                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1997                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1998                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1999                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2000                         }
2001                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2002
2003                         /* save replies. */
2004                         int replyCounter = 0;
2005                         for (PostReply reply : sone.getReplies()) {
2006                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2007                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2008                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2009                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2010                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2011                         }
2012                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2013
2014                         /* save post likes. */
2015                         int postLikeCounter = 0;
2016                         for (String postId : sone.getLikedPostIds()) {
2017                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2018                         }
2019                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2020
2021                         /* save reply likes. */
2022                         int replyLikeCounter = 0;
2023                         for (String replyId : sone.getLikedReplyIds()) {
2024                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2025                         }
2026                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2027
2028                         /* save friends. */
2029                         int friendCounter = 0;
2030                         for (String friendId : sone.getFriends()) {
2031                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2032                         }
2033                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2034
2035                         /* save albums. first, collect in a flat structure, top-level first. */
2036                         List<Album> albums = sone.getAllAlbums();
2037
2038                         int albumCounter = 0;
2039                         for (Album album : albums) {
2040                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2041                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2042                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2043                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2044                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2045                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2046                         }
2047                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2048
2049                         /* save images. */
2050                         int imageCounter = 0;
2051                         for (Album album : albums) {
2052                                 for (Image image : album.getImages()) {
2053                                         if (!image.isInserted()) {
2054                                                 continue;
2055                                         }
2056                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2057                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2058                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2059                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2060                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2061                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2062                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2063                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2064                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2065                                 }
2066                         }
2067                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2068
2069                         /* save options. */
2070                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2071                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2072                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2073                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2074                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2075                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2076
2077                         configuration.save();
2078
2079                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2080
2081                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2082                 } catch (ConfigurationException ce1) {
2083                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2084                 }
2085         }
2086
2087         /**
2088          * Saves the current options.
2089          */
2090         private void saveConfiguration() {
2091                 synchronized (configuration) {
2092                         if (storingConfiguration) {
2093                                 logger.log(Level.FINE, "Already storing configuration…");
2094                                 return;
2095                         }
2096                         storingConfiguration = true;
2097                 }
2098
2099                 /* store the options first. */
2100                 try {
2101                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2102                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2103                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2104                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2105                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2106                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2107                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2108                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2109                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2110                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2111                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2112                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2113
2114                         /* save known Sones. */
2115                         int soneCounter = 0;
2116                         synchronized (knownSones) {
2117                                 for (String knownSoneId : knownSones) {
2118                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2119                                 }
2120                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2121                         }
2122
2123                         /* save Sone following times. */
2124                         soneCounter = 0;
2125                         synchronized (soneFollowingTimes) {
2126                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2127                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2128                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2129                                         ++soneCounter;
2130                                 }
2131                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2132                         }
2133
2134                         /* save known posts. */
2135                         int postCounter = 0;
2136                         synchronized (knownPosts) {
2137                                 for (String knownPostId : knownPosts) {
2138                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2139                                 }
2140                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2141                         }
2142
2143                         /* save known replies. */
2144                         int replyCounter = 0;
2145                         synchronized (knownReplies) {
2146                                 for (String knownReplyId : knownReplies) {
2147                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2148                                 }
2149                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2150                         }
2151
2152                         /* save bookmarked posts. */
2153                         int bookmarkedPostCounter = 0;
2154                         synchronized (bookmarkedPosts) {
2155                                 for (String bookmarkedPostId : bookmarkedPosts) {
2156                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2157                                 }
2158                         }
2159                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2160
2161                         /* now save it. */
2162                         configuration.save();
2163
2164                 } catch (ConfigurationException ce1) {
2165                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2166                 } finally {
2167                         synchronized (configuration) {
2168                                 storingConfiguration = false;
2169                         }
2170                 }
2171         }
2172
2173         /**
2174          * Loads the configuration.
2175          */
2176         @SuppressWarnings("unchecked")
2177         private void loadConfiguration() {
2178                 /* create options. */
2179                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2180
2181                         @Override
2182                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2183                                 SoneInserter.setInsertionDelay(newValue);
2184                         }
2185
2186                 }));
2187                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2188                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2189                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2190                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2191                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2192                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2193                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2194                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2195                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2196
2197                         @Override
2198                         @SuppressWarnings("synthetic-access")
2199                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2200                                 fcpInterface.setActive(newValue);
2201                         }
2202                 }));
2203                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2204
2205                         @Override
2206                         @SuppressWarnings("synthetic-access")
2207                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2208                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2209                         }
2210
2211                 }));
2212
2213                 loadConfigurationValue("InsertionDelay");
2214                 loadConfigurationValue("PostsPerPage");
2215                 loadConfigurationValue("ImagesPerPage");
2216                 loadConfigurationValue("CharactersPerPost");
2217                 loadConfigurationValue("PostCutOffLength");
2218                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2219                 loadConfigurationValue("PositiveTrust");
2220                 loadConfigurationValue("NegativeTrust");
2221                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2222                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2223                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2224
2225                 /* load known Sones. */
2226                 int soneCounter = 0;
2227                 while (true) {
2228                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2229                         if (knownSoneId == null) {
2230                                 break;
2231                         }
2232                         synchronized (knownSones) {
2233                                 knownSones.add(knownSoneId);
2234                         }
2235                 }
2236
2237                 /* load Sone following times. */
2238                 soneCounter = 0;
2239                 while (true) {
2240                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2241                         if (soneId == null) {
2242                                 break;
2243                         }
2244                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2245                         Sone followedSone = getSone(soneId);
2246                         if (followedSone == null) {
2247                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2248                         } else {
2249                                 synchronized (soneFollowingTimes) {
2250                                         soneFollowingTimes.put(getSone(soneId), time);
2251                                 }
2252                         }
2253                         ++soneCounter;
2254                 }
2255
2256                 /* load known posts. */
2257                 int postCounter = 0;
2258                 while (true) {
2259                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2260                         if (knownPostId == null) {
2261                                 break;
2262                         }
2263                         synchronized (knownPosts) {
2264                                 knownPosts.add(knownPostId);
2265                         }
2266                 }
2267
2268                 /* load known replies. */
2269                 int replyCounter = 0;
2270                 while (true) {
2271                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2272                         if (knownReplyId == null) {
2273                                 break;
2274                         }
2275                         synchronized (knownReplies) {
2276                                 knownReplies.add(knownReplyId);
2277                         }
2278                 }
2279
2280                 /* load bookmarked posts. */
2281                 int bookmarkedPostCounter = 0;
2282                 while (true) {
2283                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2284                         if (bookmarkedPostId == null) {
2285                                 break;
2286                         }
2287                         synchronized (bookmarkedPosts) {
2288                                 bookmarkedPosts.add(bookmarkedPostId);
2289                         }
2290                 }
2291
2292         }
2293
2294         /**
2295          * Loads an {@link Integer} configuration value for the option with the
2296          * given name, logging validation failures.
2297          *
2298          * @param optionName
2299          *            The name of the option to load
2300          */
2301         private void loadConfigurationValue(String optionName) {
2302                 try {
2303                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2304                 } catch (IllegalArgumentException iae1) {
2305                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2306                 }
2307         }
2308
2309         /**
2310          * Generate a Sone URI from the given URI and latest edition.
2311          *
2312          * @param uriString
2313          *            The URI to derive the Sone URI from
2314          * @return The derived URI
2315          */
2316         private static FreenetURI getSoneUri(String uriString) {
2317                 try {
2318                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2319                         return uri;
2320                 } catch (MalformedURLException mue1) {
2321                         logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2322                         return null;
2323                 }
2324         }
2325
2326         /**
2327          * Notifies the core that a new {@link OwnIdentity} was added.
2328          *
2329          * @param ownIdentityAddedEvent
2330          *            The event
2331          */
2332         @Subscribe
2333         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2334                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2335                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2336                 if (ownIdentity.hasContext("Sone")) {
2337                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2338                         addLocalSone(ownIdentity);
2339                 }
2340         }
2341
2342         /**
2343          * Notifies the core that an {@link OwnIdentity} was removed.
2344          *
2345          * @param ownIdentityRemovedEvent
2346          *            The event
2347          */
2348         @Subscribe
2349         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2350                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2351                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2352                 trustedIdentities.remove(ownIdentity);
2353         }
2354
2355         /**
2356          * Notifies the core that a new {@link Identity} was added.
2357          *
2358          * @param identityAddedEvent
2359          *            The event
2360          */
2361         @Subscribe
2362         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2363                 Identity identity = identityAddedEvent.identity();
2364                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2365                 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2366                 addRemoteSone(identity);
2367         }
2368
2369         /**
2370          * Notifies the core that an {@link Identity} was updated.
2371          *
2372          * @param identityUpdatedEvent
2373          *            The event
2374          */
2375         @Subscribe
2376         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2377                 final Identity identity = identityUpdatedEvent.identity();
2378                 soneDownloaders.execute(new Runnable() {
2379
2380                         @Override
2381                         @SuppressWarnings("synthetic-access")
2382                         public void run() {
2383                                 Sone sone = getRemoteSone(identity.getId(), false);
2384                                 sone.setIdentity(identity);
2385                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2386                                 soneDownloader.addSone(sone);
2387                                 soneDownloader.fetchSone(sone);
2388                         }
2389                 });
2390         }
2391
2392         /**
2393          * Notifies the core that an {@link Identity} was removed.
2394          *
2395          * @param identityRemovedEvent
2396          *            The event
2397          */
2398         @Subscribe
2399         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2400                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2401                 Identity identity = identityRemovedEvent.identity();
2402                 trustedIdentities.get(ownIdentity).remove(identity);
2403                 boolean foundIdentity = false;
2404                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2405                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2406                                 continue;
2407                         }
2408                         if (trustedIdentity.getValue().contains(identity)) {
2409                                 foundIdentity = true;
2410                         }
2411                 }
2412                 if (foundIdentity) {
2413                         /* some local identity still trusts this identity, don’t remove. */
2414                         return;
2415                 }
2416                 Sone sone = getSone(identity.getId(), false);
2417                 if (sone == null) {
2418                         /* TODO - we don’t have the Sone anymore. should this happen? */
2419                         return;
2420                 }
2421                 synchronized (posts) {
2422                         synchronized (knownPosts) {
2423                                 for (Post post : sone.getPosts()) {
2424                                         posts.remove(post.getId());
2425                                         eventBus.post(new PostRemovedEvent(post));
2426                                 }
2427                         }
2428                 }
2429                 synchronized (replies) {
2430                         synchronized (knownReplies) {
2431                                 for (PostReply reply : sone.getReplies()) {
2432                                         replies.remove(reply.getId());
2433                                         eventBus.post(new PostReplyRemovedEvent(reply));
2434                                 }
2435                         }
2436                 }
2437                 synchronized (sones) {
2438                         sones.remove(identity.getId());
2439                 }
2440                 eventBus.post(new SoneRemovedEvent(sone));
2441         }
2442
2443         /**
2444          * Deletes the temporary image.
2445          *
2446          * @param imageInsertFinishedEvent
2447          *            The event
2448          */
2449         @Subscribe
2450         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2451                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2452                 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2453                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2454                 touchConfiguration();
2455         }
2456
2457 }