ca08ae1a9195639eef8e9bfd69cdb8633cc85105
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2020 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.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static java.util.logging.Logger.getLogger;
27 import static net.pterodactylus.sone.data.AlbumsKt.getAllImages;
28
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Set;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.TimeUnit;
41 import java.util.concurrent.atomic.*;
42 import java.util.logging.Level;
43 import java.util.logging.Logger;
44
45 import javax.annotation.Nonnull;
46 import javax.annotation.Nullable;
47
48 import com.codahale.metrics.*;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
51 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
52 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
53 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
54 import net.pterodactylus.sone.core.event.*;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
66 import net.pterodactylus.sone.data.TemporaryImage;
67 import net.pterodactylus.sone.database.AlbumBuilder;
68 import net.pterodactylus.sone.database.Database;
69 import net.pterodactylus.sone.database.DatabaseException;
70 import net.pterodactylus.sone.database.ImageBuilder;
71 import net.pterodactylus.sone.database.PostBuilder;
72 import net.pterodactylus.sone.database.PostProvider;
73 import net.pterodactylus.sone.database.PostReplyBuilder;
74 import net.pterodactylus.sone.database.PostReplyProvider;
75 import net.pterodactylus.sone.database.SoneBuilder;
76 import net.pterodactylus.sone.database.SoneProvider;
77 import net.pterodactylus.sone.freenet.wot.Identity;
78 import net.pterodactylus.sone.freenet.wot.IdentityManager;
79 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
85 import net.pterodactylus.sone.main.SonePlugin;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.service.AbstractService;
89 import net.pterodactylus.util.thread.NamedThreadFactory;
90
91 import com.google.common.annotations.VisibleForTesting;
92 import com.google.common.base.Stopwatch;
93 import com.google.common.collect.FluentIterable;
94 import com.google.common.collect.HashMultimap;
95 import com.google.common.collect.Multimap;
96 import com.google.common.collect.Multimaps;
97 import com.google.common.eventbus.EventBus;
98 import com.google.common.eventbus.Subscribe;
99 import com.google.inject.Inject;
100 import com.google.inject.Singleton;
101 import kotlin.jvm.functions.Function1;
102
103 /**
104  * The Sone core.
105  */
106 @Singleton
107 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
108
109         /** The logger. */
110         private static final Logger logger = getLogger(Core.class.getName());
111
112         /** The start time. */
113         private final long startupTime = System.currentTimeMillis();
114
115         private final AtomicBoolean debug = new AtomicBoolean(false);
116
117         /** The preferences. */
118         private final Preferences preferences;
119
120         /** The event bus. */
121         private final EventBus eventBus;
122
123         /** The configuration. */
124         private final Configuration configuration;
125
126         /** Whether we’re currently saving the configuration. */
127         private boolean storingConfiguration = false;
128
129         /** The identity manager. */
130         private final IdentityManager identityManager;
131
132         /** Interface to freenet. */
133         private final FreenetInterface freenetInterface;
134
135         /** The Sone downloader. */
136         private final SoneDownloader soneDownloader;
137
138         /** The image inserter. */
139         private final ImageInserter imageInserter;
140
141         /** Sone downloader thread-pool. */
142         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
143
144         /** The update checker. */
145         private final UpdateChecker updateChecker;
146
147         /** The trust updater. */
148         private final WebOfTrustUpdater webOfTrustUpdater;
149
150         /** Locked local Sones. */
151         /* synchronize on itself. */
152         private final Set<Sone> lockedSones = new HashSet<>();
153
154         /** Sone inserters. */
155         /* synchronize access on this on sones. */
156         private final Map<Sone, SoneInserter> soneInserters = new HashMap<>();
157
158         /** Sone rescuers. */
159         /* synchronize access on this on sones. */
160         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<>();
161
162         /** All known Sones. */
163         private final Set<String> knownSones = new HashSet<>();
164
165         /** The post database. */
166         private final Database database;
167
168         /** Trusted identities, sorted by own identities. */
169         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
170
171         /** All temporary images. */
172         private final Map<String, TemporaryImage> temporaryImages = new HashMap<>();
173
174         /** Ticker for threads that mark own elements as known. */
175         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
176
177         /** The time the configuration was last touched. */
178         private volatile long lastConfigurationUpdate;
179
180         private final MetricRegistry metricRegistry;
181         private final Histogram configurationSaveTimeHistogram;
182
183         @Inject
184         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database, MetricRegistry metricRegistry) {
185                 super("Sone Core");
186                 this.configuration = configuration;
187                 this.freenetInterface = freenetInterface;
188                 this.identityManager = identityManager;
189                 this.soneDownloader = soneDownloader;
190                 this.imageInserter = imageInserter;
191                 this.updateChecker = updateChecker;
192                 this.webOfTrustUpdater = webOfTrustUpdater;
193                 this.eventBus = eventBus;
194                 this.database = database;
195                 this.metricRegistry = metricRegistry;
196                 preferences = new Preferences(eventBus);
197                 this.configurationSaveTimeHistogram = metricRegistry.histogram("configuration.save.duration", () -> new Histogram(new ExponentiallyDecayingReservoir(3000, 0)));
198         }
199
200         //
201         // ACCESSORS
202         //
203
204         /**
205          * Returns the time Sone was started.
206          *
207          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
208          */
209         public long getStartupTime() {
210                 return startupTime;
211         }
212
213         @Nonnull
214         public boolean getDebug() {
215                 return debug.get();
216         }
217
218         public void setDebug() {
219                 debug.set(true);
220                 eventBus.post(new DebugActivatedEvent());
221         }
222
223         /**
224          * Returns the options used by the core.
225          *
226          * @return The options of the core
227          */
228         public Preferences getPreferences() {
229                 return preferences;
230         }
231
232         /**
233          * Returns the identity manager used by the core.
234          *
235          * @return The identity manager
236          */
237         public IdentityManager getIdentityManager() {
238                 return identityManager;
239         }
240
241         /**
242          * Returns the update checker.
243          *
244          * @return The update checker
245          */
246         public UpdateChecker getUpdateChecker() {
247                 return updateChecker;
248         }
249
250         /**
251          * Returns the Sone rescuer for the given local Sone.
252          *
253          * @param sone
254          *            The local Sone to get the rescuer for
255          * @return The Sone rescuer for the given Sone
256          */
257         public SoneRescuer getSoneRescuer(Sone sone) {
258                 checkNotNull(sone, "sone must not be null");
259                 checkArgument(sone.isLocal(), "sone must be local");
260                 synchronized (soneRescuers) {
261                         SoneRescuer soneRescuer = soneRescuers.get(sone);
262                         if (soneRescuer == null) {
263                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
264                                 soneRescuers.put(sone, soneRescuer);
265                                 soneRescuer.start();
266                         }
267                         return soneRescuer;
268                 }
269         }
270
271         /**
272          * Returns whether the given Sone is currently locked.
273          *
274          * @param sone
275          *            The sone to check
276          * @return {@code true} if the Sone is locked, {@code false} if it is not
277          */
278         public boolean isLocked(Sone sone) {
279                 synchronized (lockedSones) {
280                         return lockedSones.contains(sone);
281                 }
282         }
283
284         public SoneBuilder soneBuilder() {
285                 return database.newSoneBuilder();
286         }
287
288         /**
289          * {@inheritDocs}
290          */
291         @Nonnull
292         @Override
293         public Collection<Sone> getSones() {
294                 return database.getSones();
295         }
296
297         @Nonnull
298         @Override
299         public Function1<String, Sone> getSoneLoader() {
300                 return database.getSoneLoader();
301         }
302
303         /**
304          * Returns the Sone with the given ID, regardless whether it’s local or
305          * remote.
306          *
307          * @param id
308          *            The ID of the Sone to get
309          * @return The Sone with the given ID, or {@code null} if there is no such
310          *         Sone
311          */
312         @Override
313         @Nullable
314         public Sone getSone(@Nonnull String id) {
315                 return database.getSone(id);
316         }
317
318         /**
319          * {@inheritDocs}
320          */
321         @Override
322         public Collection<Sone> getLocalSones() {
323                 return database.getLocalSones();
324         }
325
326         /**
327          * Returns the local Sone with the given ID, optionally creating a new Sone.
328          *
329          * @param id
330          *            The ID of the Sone
331          * @return The Sone with the given ID, or {@code null}
332          */
333         public Sone getLocalSone(String id) {
334                 Sone sone = database.getSone(id);
335                 if ((sone != null) && sone.isLocal()) {
336                         return sone;
337                 }
338                 return null;
339         }
340
341         /**
342          * {@inheritDocs}
343          */
344         @Override
345         public Collection<Sone> getRemoteSones() {
346                 return database.getRemoteSones();
347         }
348
349         /**
350          * Returns the remote Sone with the given ID.
351          *
352          *
353          * @param id
354          *            The ID of the remote Sone to get
355          * @return The Sone with the given ID
356          */
357         public Sone getRemoteSone(String id) {
358                 return database.getSone(id);
359         }
360
361         /**
362          * Returns whether the given Sone has been modified.
363          *
364          * @param sone
365          *            The Sone to check for modifications
366          * @return {@code true} if a modification has been detected in the Sone,
367          *         {@code false} otherwise
368          */
369         public boolean isModifiedSone(Sone sone) {
370                 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
371         }
372
373         /**
374          * Returns a post builder.
375          *
376          * @return A new post builder
377          */
378         public PostBuilder postBuilder() {
379                 return database.newPostBuilder();
380         }
381
382         @Nullable
383         @Override
384         public Post getPost(@Nonnull String postId) {
385                 return database.getPost(postId);
386         }
387
388         /**
389          * {@inheritDocs}
390          */
391         @Override
392         public Collection<Post> getPosts(String soneId) {
393                 return database.getPosts(soneId);
394         }
395
396         /**
397          * {@inheritDoc}
398          */
399         @Override
400         public Collection<Post> getDirectedPosts(final String recipientId) {
401                 checkNotNull(recipientId, "recipient must not be null");
402                 return database.getDirectedPosts(recipientId);
403         }
404
405         /**
406          * Returns a post reply builder.
407          *
408          * @return A new post reply builder
409          */
410         public PostReplyBuilder postReplyBuilder() {
411                 return database.newPostReplyBuilder();
412         }
413
414         /**
415          * {@inheritDoc}
416          */
417         @Nullable
418         @Override
419         public PostReply getPostReply(String replyId) {
420                 return database.getPostReply(replyId);
421         }
422
423         /**
424          * {@inheritDoc}
425          */
426         @Override
427         public List<PostReply> getReplies(final String postId) {
428                 return database.getReplies(postId);
429         }
430
431         /**
432          * Returns all Sones that have liked the given post.
433          *
434          * @param post
435          *            The post to get the liking Sones for
436          * @return The Sones that like the given post
437          */
438         public Set<Sone> getLikes(Post post) {
439                 Set<Sone> sones = new HashSet<>();
440                 for (Sone sone : getSones()) {
441                         if (sone.getLikedPostIds().contains(post.getId())) {
442                                 sones.add(sone);
443                         }
444                 }
445                 return sones;
446         }
447
448         /**
449          * Returns all Sones that have liked the given reply.
450          *
451          * @param reply
452          *            The reply to get the liking Sones for
453          * @return The Sones that like the given reply
454          */
455         public Set<Sone> getLikes(PostReply reply) {
456                 Set<Sone> sones = new HashSet<>();
457                 for (Sone sone : getSones()) {
458                         if (sone.getLikedReplyIds().contains(reply.getId())) {
459                                 sones.add(sone);
460                         }
461                 }
462                 return sones;
463         }
464
465         /**
466          * Returns whether the given post is bookmarked.
467          *
468          * @param post
469          *            The post to check
470          * @return {@code true} if the given post is bookmarked, {@code false}
471          *         otherwise
472          */
473         public boolean isBookmarked(Post post) {
474                 return database.isPostBookmarked(post);
475         }
476
477         /**
478          * Returns all currently known bookmarked posts.
479          *
480          * @return All bookmarked posts
481          */
482         public Set<Post> getBookmarkedPosts() {
483                 return database.getBookmarkedPosts();
484         }
485
486         public AlbumBuilder albumBuilder() {
487                 return database.newAlbumBuilder();
488         }
489
490         /**
491          * Returns the album with the given ID, optionally creating a new album if
492          * an album with the given ID can not be found.
493          *
494          * @param albumId
495          *            The ID of the album
496          * @return The album with the given ID, or {@code null} if no album with the
497          *         given ID exists
498          */
499         @Nullable
500         public Album getAlbum(@Nonnull String albumId) {
501                 return database.getAlbum(albumId);
502         }
503
504         public ImageBuilder imageBuilder() {
505                 return database.newImageBuilder();
506         }
507
508         /**
509          * Returns the image with the given ID, creating it if necessary.
510          *
511          * @param imageId
512          *            The ID of the image
513          * @return The image with the given ID
514          */
515         @Nullable
516         public Image getImage(String imageId) {
517                 return getImage(imageId, true);
518         }
519
520         /**
521          * Returns the image with the given ID, optionally creating it if it does
522          * not exist.
523          *
524          * @param imageId
525          *            The ID of the image
526          * @param create
527          *            {@code true} to create an image if none exists with the given
528          *            ID
529          * @return The image with the given ID, or {@code null} if none exists and
530          *         none was created
531          */
532         @Nullable
533         public Image getImage(String imageId, boolean create) {
534                 Image image = database.getImage(imageId);
535                 if (image != null) {
536                         return image;
537                 }
538                 if (!create) {
539                         return null;
540                 }
541                 Image newImage = database.newImageBuilder().withId(imageId).build();
542                 database.storeImage(newImage);
543                 return newImage;
544         }
545
546         /**
547          * Returns the temporary image with the given ID.
548          *
549          * @param imageId
550          *            The ID of the temporary image
551          * @return The temporary image, or {@code null} if there is no temporary
552          *         image with the given ID
553          */
554         public TemporaryImage getTemporaryImage(String imageId) {
555                 synchronized (temporaryImages) {
556                         return temporaryImages.get(imageId);
557                 }
558         }
559
560         //
561         // ACTIONS
562         //
563
564         /**
565          * Locks the given Sone. A locked Sone will not be inserted by
566          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
567          * again.
568          *
569          * @param sone
570          *            The sone to lock
571          */
572         public void lockSone(Sone sone) {
573                 synchronized (lockedSones) {
574                         if (lockedSones.add(sone)) {
575                                 eventBus.post(new SoneLockedEvent(sone));
576                         }
577                 }
578         }
579
580         /**
581          * Unlocks the given Sone.
582          *
583          * @see #lockSone(Sone)
584          * @param sone
585          *            The sone to unlock
586          */
587         public void unlockSone(Sone sone) {
588                 synchronized (lockedSones) {
589                         if (lockedSones.remove(sone)) {
590                                 eventBus.post(new SoneUnlockedEvent(sone));
591                         }
592                 }
593         }
594
595         /**
596          * Adds a local Sone from the given own identity.
597          *
598          * @param ownIdentity
599          *            The own identity to create a Sone from
600          * @return The added (or already existing) Sone
601          */
602         public Sone addLocalSone(OwnIdentity ownIdentity) {
603                 if (ownIdentity == null) {
604                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
605                         return null;
606                 }
607                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
608                 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
609                 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
610                 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
611                 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
612                 sone.setKnown(true);
613                 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, metricRegistry, ownIdentity.getId());
614                 soneInserter.insertionDelayChanged(new InsertionDelayChangedEvent(preferences.getInsertionDelay()));
615                 eventBus.register(soneInserter);
616                 synchronized (soneInserters) {
617                         soneInserters.put(sone, soneInserter);
618                 }
619                 loadSone(sone);
620                 database.storeSone(sone);
621                 sone.setStatus(SoneStatus.idle);
622                 if (sone.getPosts().isEmpty() && sone.getReplies().isEmpty() && getAllImages(sone.getRootAlbum()).isEmpty()) {
623                         // dirty hack
624                         lockSone(sone);
625                         eventBus.post(new SoneLockedOnStartup(sone));
626                 }
627                 soneInserter.start();
628                 return sone;
629         }
630
631         /**
632          * Creates a new Sone for the given own identity.
633          *
634          * @param ownIdentity
635          *            The own identity to create a Sone for
636          * @return The created Sone
637          */
638         public Sone createSone(OwnIdentity ownIdentity) {
639                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
640                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
641                         return null;
642                 }
643                 Sone sone = addLocalSone(ownIdentity);
644
645                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
646                 touchConfiguration();
647                 return sone;
648         }
649
650         /**
651          * Adds the Sone of the given identity.
652          *
653          * @param identity
654          *            The identity whose Sone to add
655          * @return The added or already existing Sone
656          */
657         public Sone addRemoteSone(Identity identity) {
658                 if (identity == null) {
659                         logger.log(Level.WARNING, "Given Identity is null!");
660                         return null;
661                 }
662                 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
663                 long latestEdition = fromNullable(tryParse(property)).or(0L);
664                 Sone existingSone = getSone(identity.getId());
665                 if ((existingSone != null )&& existingSone.isLocal()) {
666                         return existingSone;
667                 }
668                 boolean newSone = existingSone == null;
669                 Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
670                 sone.setLatestEdition(latestEdition);
671                 if (newSone) {
672                         synchronized (knownSones) {
673                                 newSone = !knownSones.contains(sone.getId());
674                         }
675                         sone.setKnown(!newSone);
676                         if (newSone) {
677                                 eventBus.post(new NewSoneFoundEvent(sone));
678                                 for (Sone localSone : getLocalSones()) {
679                                         if (localSone.getOptions().isAutoFollow()) {
680                                                 followSone(localSone, sone.getId());
681                                         }
682                                 }
683                         }
684                 }
685                 database.storeSone(sone);
686                 soneDownloader.addSone(sone);
687                 soneDownloaders.execute(soneDownloader.fetchSoneAsUskAction(sone));
688                 return sone;
689         }
690
691         /**
692          * Lets the given local Sone follow the Sone with the given ID.
693          *
694          * @param sone
695          *            The local Sone that should follow another Sone
696          * @param soneId
697          *            The ID of the Sone to follow
698          */
699         public void followSone(Sone sone, String soneId) {
700                 checkNotNull(sone, "sone must not be null");
701                 checkNotNull(soneId, "soneId must not be null");
702                 database.addFriend(sone, soneId);
703                 @SuppressWarnings("ConstantConditions") // we just followed, this can’t be null.
704                 long now = database.getFollowingTime(soneId);
705                 Sone followedSone = getSone(soneId);
706                 if (followedSone == null) {
707                         return;
708                 }
709                 for (Post post : followedSone.getPosts()) {
710                         if (post.getTime() < now) {
711                                 markPostKnown(post);
712                         }
713                 }
714                 for (PostReply reply : followedSone.getReplies()) {
715                         if (reply.getTime() < now) {
716                                 markReplyKnown(reply);
717                         }
718                 }
719                 touchConfiguration();
720         }
721
722         /**
723          * Lets the given local Sone unfollow the Sone with the given ID.
724          *
725          * @param sone
726          *            The local Sone that should unfollow another Sone
727          * @param soneId
728          *            The ID of the Sone being unfollowed
729          */
730         public void unfollowSone(Sone sone, String soneId) {
731                 checkNotNull(sone, "sone must not be null");
732                 checkNotNull(soneId, "soneId must not be null");
733                 database.removeFriend(sone, soneId);
734                 touchConfiguration();
735         }
736
737         /**
738          * Updates the stored Sone with the given Sone.
739          *
740          * @param sone
741          *            The updated Sone
742          */
743         public void updateSone(Sone sone) {
744                 updateSone(sone, false);
745         }
746
747         /**
748          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
749          * {@code true}, an older Sone than the current Sone can be given to restore
750          * an old state.
751          *
752          * @param sone
753          *            The Sone to update
754          * @param soneRescueMode
755          *            {@code true} if the stored Sone should be updated regardless
756          *            of the age of the given Sone
757          */
758         public void updateSone(final Sone sone, boolean soneRescueMode) {
759                 Sone storedSone = getSone(sone.getId());
760                 if (storedSone != null) {
761                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
762                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
763                                 return;
764                         }
765                         List<Object> events =
766                                         collectEventsForChangesInSone(storedSone, sone);
767                         database.storeSone(sone);
768                         for (Object event : events) {
769                                 eventBus.post(event);
770                         }
771                         sone.setOptions(storedSone.getOptions());
772                         sone.setKnown(storedSone.isKnown());
773                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
774                         if (sone.isLocal()) {
775                                 touchConfiguration();
776                         }
777                 }
778         }
779
780         private List<Object> collectEventsForChangesInSone(Sone oldSone, Sone newSone) {
781                 List<Object> events = new ArrayList<>();
782                 SoneComparison soneComparison = new SoneComparison(oldSone, newSone);
783                 for (Post newPost : soneComparison.getNewPosts()) {
784                         if (newPost.getSone().equals(newSone)) {
785                                 newPost.setKnown(true);
786                         } else if (newPost.getTime() < database.getFollowingTime(newSone.getId())) {
787                                 newPost.setKnown(true);
788                         } else if (!newPost.isKnown()) {
789                                 events.add(new NewPostFoundEvent(newPost));
790                         }
791                 }
792                 for (Post post : soneComparison.getRemovedPosts()) {
793                         events.add(new PostRemovedEvent(post));
794                 }
795                 for (PostReply postReply : soneComparison.getNewPostReplies()) {
796                         if (postReply.getSone().equals(newSone)) {
797                                 postReply.setKnown(true);
798                         } else if (postReply.getTime() < database.getFollowingTime(newSone.getId())) {
799                                 postReply.setKnown(true);
800                         } else if (!postReply.isKnown()) {
801                                 events.add(new NewPostReplyFoundEvent(postReply));
802                         }
803                 }
804                 for (PostReply postReply : soneComparison.getRemovedPostReplies()) {
805                         events.add(new PostReplyRemovedEvent(postReply));
806                 }
807                 return events;
808         }
809
810         /**
811          * Deletes the given Sone. This will remove the Sone from the
812          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
813          * remove the context from its identity.
814          *
815          * @param sone
816          *            The Sone to delete
817          */
818         public void deleteSone(Sone sone) {
819                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
820                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
821                         return;
822                 }
823                 if (!getLocalSones().contains(sone)) {
824                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
825                         return;
826                 }
827                 SoneInserter soneInserter = soneInserters.remove(sone);
828                 soneInserter.stop();
829                 database.removeSone(sone);
830                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
831                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
832                 try {
833                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
834                 } catch (ConfigurationException ce1) {
835                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
836                 }
837         }
838
839         /**
840          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
841          * known} before, a {@link MarkSoneKnownEvent} is fired.
842          *
843          * @param sone
844          *            The Sone to mark as known
845          */
846         public void markSoneKnown(Sone sone) {
847                 if (!sone.isKnown()) {
848                         sone.setKnown(true);
849                         synchronized (knownSones) {
850                                 knownSones.add(sone.getId());
851                         }
852                         eventBus.post(new MarkSoneKnownEvent(sone));
853                         touchConfiguration();
854                 }
855         }
856
857         /**
858          * Loads and updates the given Sone from the configuration. If any error is
859          * encountered, loading is aborted and the given Sone is not changed.
860          *
861          * @param sone
862          *            The Sone to load and update
863          */
864         public void loadSone(Sone sone) {
865                 if (!sone.isLocal()) {
866                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
867                         return;
868                 }
869                 logger.info(String.format("Loading local Sone: %s", sone));
870
871                 /* load Sone. */
872                 String sonePrefix = "Sone/" + sone.getId();
873                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
874                 if (soneTime == null) {
875                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
876                         return;
877                 }
878                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
879
880                 /* load profile. */
881                 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
882                 Profile profile = configurationSoneParser.parseProfile();
883
884                 /* load posts. */
885                 Collection<Post> posts;
886                 try {
887                         posts = configurationSoneParser.parsePosts(database);
888                 } catch (InvalidPostFound ipf) {
889                         logger.log(Level.WARNING, "Invalid post found, aborting load!");
890                         return;
891                 }
892
893                 /* load replies. */
894                 Collection<PostReply> replies;
895                 try {
896                         replies = configurationSoneParser.parsePostReplies(database);
897                 } catch (InvalidPostReplyFound iprf) {
898                         logger.log(Level.WARNING, "Invalid reply found, aborting load!");
899                         return;
900                 }
901
902                 /* load post likes. */
903                 Set<String> likedPostIds =
904                                 configurationSoneParser.parseLikedPostIds();
905
906                 /* load reply likes. */
907                 Set<String> likedReplyIds =
908                                 configurationSoneParser.parseLikedPostReplyIds();
909
910                 /* load albums. */
911                 List<Album> topLevelAlbums;
912                 try {
913                         topLevelAlbums =
914                                         configurationSoneParser.parseTopLevelAlbums(database);
915                 } catch (InvalidAlbumFound iaf) {
916                         logger.log(Level.WARNING, "Invalid album found, aborting load!");
917                         return;
918                 } catch (InvalidParentAlbumFound ipaf) {
919                         logger.log(Level.WARNING, format("Invalid parent album ID: %s",
920                                         ipaf.getAlbumParentId()));
921                         return;
922                 }
923
924                 /* load images. */
925                 try {
926                         configurationSoneParser.parseImages(database);
927                 } catch (InvalidImageFound iif) {
928                         logger.log(WARNING, "Invalid image found, aborting load!");
929                         return;
930                 } catch (InvalidParentAlbumFound ipaf) {
931                         logger.log(Level.WARNING,
932                                         format("Invalid album image (%s) encountered, aborting load!",
933                                                         ipaf.getAlbumParentId()));
934                         return;
935                 }
936
937                 /* load avatar. */
938                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
939                 if (avatarId != null) {
940                         final Map<String, Image> images =
941                                         configurationSoneParser.getImages();
942                         profile.setAvatar(images.get(avatarId));
943                 }
944
945                 /* load options. */
946                 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
947                 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
948                 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
949                 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
950                 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
951                 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
952                 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
953
954                 /* if we’re still here, Sone was loaded successfully. */
955                 synchronized (sone) {
956                         sone.setTime(soneTime);
957                         sone.setProfile(profile);
958                         sone.setPosts(posts);
959                         sone.setReplies(replies);
960                         sone.setLikePostIds(likedPostIds);
961                         sone.setLikeReplyIds(likedReplyIds);
962                         for (Album album : sone.getRootAlbum().getAlbums()) {
963                                 sone.getRootAlbum().removeAlbum(album);
964                         }
965                         for (Album album : topLevelAlbums) {
966                                 sone.getRootAlbum().addAlbum(album);
967                         }
968                         synchronized (soneInserters) {
969                                 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
970                         }
971                 }
972                 for (Post post : posts) {
973                         post.setKnown(true);
974                 }
975                 for (PostReply reply : replies) {
976                         reply.setKnown(true);
977                 }
978
979                 logger.info(String.format("Sone loaded successfully: %s", sone));
980         }
981
982         /**
983          * Creates a new post.
984          *
985          * @param sone
986          *            The Sone that creates the post
987          * @param recipient
988          *            The recipient Sone, or {@code null} if this post does not have
989          *            a recipient
990          * @param text
991          *            The text of the post
992          * @return The created post
993          */
994         public Post createPost(Sone sone, @Nullable Sone recipient, String text) {
995                 checkNotNull(text, "text must not be null");
996                 checkArgument(text.trim().length() > 0, "text must not be empty");
997                 if (!sone.isLocal()) {
998                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
999                         return null;
1000                 }
1001                 PostBuilder postBuilder = database.newPostBuilder();
1002                 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1003                 if (recipient != null) {
1004                         postBuilder.to(recipient.getId());
1005                 }
1006                 final Post post = postBuilder.build();
1007                 database.storePost(post);
1008                 eventBus.post(new NewPostFoundEvent(post));
1009                 sone.addPost(post);
1010                 touchConfiguration();
1011                 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1012                 return post;
1013         }
1014
1015         /**
1016          * Deletes the given post.
1017          *
1018          * @param post
1019          *            The post to delete
1020          */
1021         public void deletePost(Post post) {
1022                 if (!post.getSone().isLocal()) {
1023                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1024                         return;
1025                 }
1026                 database.removePost(post);
1027                 eventBus.post(new PostRemovedEvent(post));
1028                 markPostKnown(post);
1029                 touchConfiguration();
1030         }
1031
1032         /**
1033          * Marks the given post as known, if it is currently not a known post
1034          * (according to {@link Post#isKnown()}).
1035          *
1036          * @param post
1037          *            The post to mark as known
1038          */
1039         public void markPostKnown(Post post) {
1040                 post.setKnown(true);
1041                 eventBus.post(new MarkPostKnownEvent(post));
1042                 touchConfiguration();
1043                 for (PostReply reply : getReplies(post.getId())) {
1044                         markReplyKnown(reply);
1045                 }
1046         }
1047
1048         public void bookmarkPost(Post post) {
1049                 database.bookmarkPost(post);
1050         }
1051
1052         /**
1053          * Removes the given post from the bookmarks.
1054          *
1055          * @param post
1056          *            The post to unbookmark
1057          */
1058         public void unbookmarkPost(Post post) {
1059                 database.unbookmarkPost(post);
1060         }
1061
1062         /**
1063          * Creates a new reply.
1064          *
1065          * @param sone
1066          *            The Sone that creates the reply
1067          * @param post
1068          *            The post that this reply refers to
1069          * @param text
1070          *            The text of the reply
1071          * @return The created reply
1072          */
1073         public PostReply createReply(Sone sone, Post post, String text) {
1074                 checkNotNull(text, "text must not be null");
1075                 checkArgument(text.trim().length() > 0, "text must not be empty");
1076                 if (!sone.isLocal()) {
1077                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1078                         return null;
1079                 }
1080                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1081                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1082                 final PostReply reply = postReplyBuilder.build();
1083                 database.storePostReply(reply);
1084                 eventBus.post(new NewPostReplyFoundEvent(reply));
1085                 sone.addReply(reply);
1086                 touchConfiguration();
1087                 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1088                 return reply;
1089         }
1090
1091         /**
1092          * Deletes the given reply.
1093          *
1094          * @param reply
1095          *            The reply to delete
1096          */
1097         public void deleteReply(PostReply reply) {
1098                 Sone sone = reply.getSone();
1099                 if (!sone.isLocal()) {
1100                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1101                         return;
1102                 }
1103                 database.removePostReply(reply);
1104                 markReplyKnown(reply);
1105                 sone.removeReply(reply);
1106                 touchConfiguration();
1107         }
1108
1109         /**
1110          * Marks the given reply as known, if it is currently not a known reply
1111          * (according to {@link Reply#isKnown()}).
1112          *
1113          * @param reply
1114          *            The reply to mark as known
1115          */
1116         public void markReplyKnown(PostReply reply) {
1117                 boolean previouslyKnown = reply.isKnown();
1118                 reply.setKnown(true);
1119                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1120                 if (!previouslyKnown) {
1121                         touchConfiguration();
1122                 }
1123         }
1124
1125         /**
1126          * Creates a new album for the given Sone.
1127          *
1128          * @param sone
1129          *            The Sone to create the album for
1130          * @param parent
1131          *            The parent of the album (may be {@code null} to create a
1132          *            top-level album)
1133          * @return The new album
1134          */
1135         public Album createAlbum(Sone sone, Album parent) {
1136                 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1137                 database.storeAlbum(album);
1138                 parent.addAlbum(album);
1139                 return album;
1140         }
1141
1142         /**
1143          * Deletes the given album. The owner of the album has to be a local Sone,
1144          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1145          *
1146          * @param album
1147          *            The album to remove
1148          */
1149         public void deleteAlbum(Album album) {
1150                 checkNotNull(album, "album must not be null");
1151                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1152                 if (!album.isEmpty()) {
1153                         return;
1154                 }
1155                 album.getParent().removeAlbum(album);
1156                 database.removeAlbum(album);
1157                 touchConfiguration();
1158         }
1159
1160         /**
1161          * Creates a new image.
1162          *
1163          * @param sone
1164          *            The Sone creating the image
1165          * @param album
1166          *            The album the image will be inserted into
1167          * @param temporaryImage
1168          *            The temporary image to create the image from
1169          * @return The newly created image
1170          */
1171         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1172                 checkNotNull(sone, "sone must not be null");
1173                 checkNotNull(album, "album must not be null");
1174                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1175                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1176                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1177                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1178                 album.addImage(image);
1179                 database.storeImage(image);
1180                 imageInserter.insertImage(temporaryImage, image);
1181                 return image;
1182         }
1183
1184         /**
1185          * Deletes the given image. This method will also delete a matching
1186          * temporary image.
1187          *
1188          * @see #deleteTemporaryImage(String)
1189          * @param image
1190          *            The image to delete
1191          */
1192         public void deleteImage(Image image) {
1193                 checkNotNull(image, "image must not be null");
1194                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1195                 deleteTemporaryImage(image.getId());
1196                 image.getAlbum().removeImage(image);
1197                 database.removeImage(image);
1198                 touchConfiguration();
1199         }
1200
1201         /**
1202          * Creates a new temporary image.
1203          *
1204          * @param mimeType
1205          *            The MIME type of the temporary image
1206          * @param imageData
1207          *            The encoded data of the image
1208          * @return The temporary image
1209          */
1210         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1211                 TemporaryImage temporaryImage = new TemporaryImage();
1212                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1213                 synchronized (temporaryImages) {
1214                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1215                 }
1216                 return temporaryImage;
1217         }
1218
1219         /**
1220          * Deletes the temporary image with the given ID.
1221          *
1222          * @param imageId
1223          *            The ID of the temporary image to delete
1224          */
1225         public void deleteTemporaryImage(String imageId) {
1226                 checkNotNull(imageId, "imageId must not be null");
1227                 synchronized (temporaryImages) {
1228                         temporaryImages.remove(imageId);
1229                 }
1230                 Image image = getImage(imageId, false);
1231                 if (image != null) {
1232                         imageInserter.cancelImageInsert(image);
1233                 }
1234         }
1235
1236         /**
1237          * Notifies the core that the configuration, either of the core or of a
1238          * single local Sone, has changed, and that the configuration should be
1239          * saved.
1240          */
1241         public void touchConfiguration() {
1242                 lastConfigurationUpdate = System.currentTimeMillis();
1243         }
1244
1245         //
1246         // SERVICE METHODS
1247         //
1248
1249         /**
1250          * Starts the core.
1251          */
1252         @Override
1253         public void serviceStart() {
1254                 loadConfiguration();
1255                 updateChecker.start();
1256                 identityManager.start();
1257                 webOfTrustUpdater.init();
1258                 webOfTrustUpdater.start();
1259                 database.startAsync();
1260         }
1261
1262         /**
1263          * {@inheritDoc}
1264          */
1265         @Override
1266         public void serviceRun() {
1267                 long lastSaved = System.currentTimeMillis();
1268                 while (!shouldStop()) {
1269                         sleep(1000);
1270                         long now = System.currentTimeMillis();
1271                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1272                                 for (Sone localSone : getLocalSones()) {
1273                                         saveSone(localSone);
1274                                 }
1275                                 saveConfiguration();
1276                                 lastSaved = now;
1277                         }
1278                 }
1279         }
1280
1281         /**
1282          * Stops the core.
1283          */
1284         @Override
1285         public void serviceStop() {
1286                 localElementTicker.shutdownNow();
1287                 synchronized (soneInserters) {
1288                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1289                                 soneInserter.getValue().stop();
1290                                 Sone latestSone = getLocalSone(soneInserter.getKey().getId());
1291                                 saveSone(latestSone);
1292                         }
1293                 }
1294                 synchronized (soneRescuers) {
1295                         for (SoneRescuer soneRescuer : soneRescuers.values()) {
1296                                 soneRescuer.stop();
1297                         }
1298                 }
1299                 saveConfiguration();
1300                 database.stopAsync();
1301                 webOfTrustUpdater.stop();
1302                 updateChecker.stop();
1303                 soneDownloader.stop();
1304                 soneDownloaders.shutdown();
1305                 identityManager.stop();
1306         }
1307
1308         //
1309         // PRIVATE METHODS
1310         //
1311
1312         /**
1313          * Saves the given Sone. This will persist all local settings for the given
1314          * Sone, such as the friends list and similar, private options.
1315          *
1316          * @param sone
1317          *            The Sone to save
1318          */
1319         private synchronized void saveSone(Sone sone) {
1320                 if (!sone.isLocal()) {
1321                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1322                         return;
1323                 }
1324                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1325                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1326                         return;
1327                 }
1328
1329                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1330                 try {
1331                         /* save Sone into configuration. */
1332                         String sonePrefix = "Sone/" + sone.getId();
1333                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1334                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1335
1336                         /* save profile. */
1337                         Profile profile = sone.getProfile();
1338                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1339                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1340                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1341                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1342                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1343                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1344                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1345
1346                         /* save profile fields. */
1347                         int fieldCounter = 0;
1348                         for (Field profileField : profile.getFields()) {
1349                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1350                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1351                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1352                         }
1353                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1354
1355                         /* save posts. */
1356                         int postCounter = 0;
1357                         for (Post post : sone.getPosts()) {
1358                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1359                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1360                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1361                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1362                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1363                         }
1364                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1365
1366                         /* save replies. */
1367                         int replyCounter = 0;
1368                         for (PostReply reply : sone.getReplies()) {
1369                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1370                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1371                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1372                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1373                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1374                         }
1375                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1376
1377                         /* save post likes. */
1378                         int postLikeCounter = 0;
1379                         for (String postId : sone.getLikedPostIds()) {
1380                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1381                         }
1382                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1383
1384                         /* save reply likes. */
1385                         int replyLikeCounter = 0;
1386                         for (String replyId : sone.getLikedReplyIds()) {
1387                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1388                         }
1389                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1390
1391                         /* save albums. first, collect in a flat structure, top-level first. */
1392                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1393
1394                         int albumCounter = 0;
1395                         for (Album album : albums) {
1396                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1397                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1398                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1399                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1400                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1401                         }
1402                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1403
1404                         /* save images. */
1405                         int imageCounter = 0;
1406                         for (Album album : albums) {
1407                                 for (Image image : album.getImages()) {
1408                                         if (!image.isInserted()) {
1409                                                 continue;
1410                                         }
1411                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1412                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1413                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1414                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1415                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1416                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1417                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1418                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1419                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1420                                 }
1421                         }
1422                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1423
1424                         /* save options. */
1425                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1426                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1427                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1428                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1429                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1430                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1431                         configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1432
1433                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1434
1435                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1436                 } catch (ConfigurationException ce1) {
1437                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1438                 }
1439         }
1440
1441         /**
1442          * Saves the current options.
1443          */
1444         private void saveConfiguration() {
1445                 synchronized (configuration) {
1446                         if (storingConfiguration) {
1447                                 logger.log(Level.FINE, "Already storing configuration…");
1448                                 return;
1449                         }
1450                         storingConfiguration = true;
1451                 }
1452
1453                 /* store the options first. */
1454                 try {
1455                         preferences.saveTo(configuration);
1456
1457                         /* save known Sones. */
1458                         int soneCounter = 0;
1459                         synchronized (knownSones) {
1460                                 for (String knownSoneId : knownSones) {
1461                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1462                                 }
1463                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1464                         }
1465
1466                         /* save known posts. */
1467                         database.save();
1468
1469                         /* now save it. */
1470                         Stopwatch stopwatch = Stopwatch.createStarted();
1471                         configuration.save();
1472                         configurationSaveTimeHistogram.update(stopwatch.elapsed(TimeUnit.MICROSECONDS));
1473
1474                 } catch (ConfigurationException ce1) {
1475                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1476                 } catch (DatabaseException de1) {
1477                         logger.log(Level.SEVERE, "Could not save database!", de1);
1478                 } finally {
1479                         synchronized (configuration) {
1480                                 storingConfiguration = false;
1481                         }
1482                 }
1483         }
1484
1485         /**
1486          * Loads the configuration.
1487          */
1488         private void loadConfiguration() {
1489                 new PreferencesLoader(preferences).loadFrom(configuration);
1490
1491                 /* load known Sones. */
1492                 int soneCounter = 0;
1493                 while (true) {
1494                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1495                         if (knownSoneId == null) {
1496                                 break;
1497                         }
1498                         synchronized (knownSones) {
1499                                 knownSones.add(knownSoneId);
1500                         }
1501                 }
1502         }
1503
1504         /**
1505          * Notifies the core that a new {@link OwnIdentity} was added.
1506          *
1507          * @param ownIdentityAddedEvent
1508          *            The event
1509          */
1510         @Subscribe
1511         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1512                 OwnIdentity ownIdentity = ownIdentityAddedEvent.getOwnIdentity();
1513                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1514                 if (ownIdentity.hasContext("Sone")) {
1515                         addLocalSone(ownIdentity);
1516                 }
1517         }
1518
1519         /**
1520          * Notifies the core that an {@link OwnIdentity} was removed.
1521          *
1522          * @param ownIdentityRemovedEvent
1523          *            The event
1524          */
1525         @Subscribe
1526         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1527                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.getOwnIdentity();
1528                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1529                 trustedIdentities.removeAll(ownIdentity);
1530         }
1531
1532         /**
1533          * Notifies the core that a new {@link Identity} was added.
1534          *
1535          * @param identityAddedEvent
1536          *            The event
1537          */
1538         @Subscribe
1539         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1540                 Identity identity = identityAddedEvent.getIdentity();
1541                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1542                 trustedIdentities.put(identityAddedEvent.getOwnIdentity(), identity);
1543                 addRemoteSone(identity);
1544         }
1545
1546         /**
1547          * Notifies the core that an {@link Identity} was updated.
1548          *
1549          * @param identityUpdatedEvent
1550          *            The event
1551          */
1552         @Subscribe
1553         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1554                 Identity identity = identityUpdatedEvent.getIdentity();
1555                 final Sone sone = getRemoteSone(identity.getId());
1556                 if (sone.isLocal()) {
1557                         return;
1558                 }
1559                 String newLatestEdition = identity.getProperty("Sone.LatestEdition");
1560                 if (newLatestEdition != null) {
1561                         Long parsedNewLatestEdition = tryParse(newLatestEdition);
1562                         if (parsedNewLatestEdition != null) {
1563                                 sone.setLatestEdition(parsedNewLatestEdition);
1564                         }
1565                 }
1566                 soneDownloader.addSone(sone);
1567                 soneDownloaders.execute(soneDownloader.fetchSoneAsSskAction(sone));
1568         }
1569
1570         /**
1571          * Notifies the core that an {@link Identity} was removed.
1572          *
1573          * @param identityRemovedEvent
1574          *            The event
1575          */
1576         @Subscribe
1577         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1578                 OwnIdentity ownIdentity = identityRemovedEvent.getOwnIdentity();
1579                 Identity identity = identityRemovedEvent.getIdentity();
1580                 trustedIdentities.remove(ownIdentity, identity);
1581                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1582                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1583                                 continue;
1584                         }
1585                         if (trustedIdentity.getValue().contains(identity)) {
1586                                 return;
1587                         }
1588                 }
1589                 Sone sone = getSone(identity.getId());
1590                 if (sone == null) {
1591                         /* TODO - we don’t have the Sone anymore. should this happen? */
1592                         return;
1593                 }
1594                 for (PostReply postReply : sone.getReplies()) {
1595                         eventBus.post(new PostReplyRemovedEvent(postReply));
1596                 }
1597                 for (Post post : sone.getPosts()) {
1598                         eventBus.post(new PostRemovedEvent(post));
1599                 }
1600                 eventBus.post(new SoneRemovedEvent(sone));
1601                 database.removeSone(sone);
1602         }
1603
1604         /**
1605          * Deletes the temporary image.
1606          *
1607          * @param imageInsertFinishedEvent
1608          *            The event
1609          */
1610         @Subscribe
1611         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1612                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.getImage(), imageInsertFinishedEvent.getResultingUri()));
1613                 imageInsertFinishedEvent.getImage().modify().setKey(imageInsertFinishedEvent.getResultingUri().toString()).update();
1614                 deleteTemporaryImage(imageInsertFinishedEvent.getImage().getId());
1615                 touchConfiguration();
1616         }
1617
1618         @VisibleForTesting
1619         class MarkPostKnown implements Runnable {
1620
1621                 private final Post post;
1622
1623                 public MarkPostKnown(Post post) {
1624                         this.post = post;
1625                 }
1626
1627                 @Override
1628                 public void run() {
1629                         markPostKnown(post);
1630                 }
1631
1632         }
1633
1634         @VisibleForTesting
1635         class MarkReplyKnown implements Runnable {
1636
1637                 private final PostReply postReply;
1638
1639                 public MarkReplyKnown(PostReply postReply) {
1640                         this.postReply = postReply;
1641                 }
1642
1643                 @Override
1644                 public void run() {
1645                         markReplyKnown(postReply);
1646                 }
1647
1648         }
1649
1650 }