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