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