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