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