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