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