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