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