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