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