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