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