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