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