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