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