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