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