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