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