Replace Sone provider interface with Kotlin version
[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         @Override
463         public Optional<PostReply> getPostReply(String replyId) {
464                 return database.getPostReply(replyId);
465         }
466
467         /**
468          * {@inheritDoc}
469          */
470         @Override
471         public List<PostReply> getReplies(final String postId) {
472                 return database.getReplies(postId);
473         }
474
475         /**
476          * Returns all Sones that have liked the given post.
477          *
478          * @param post
479          *            The post to get the liking Sones for
480          * @return The Sones that like the given post
481          */
482         public Set<Sone> getLikes(Post post) {
483                 Set<Sone> sones = new HashSet<Sone>();
484                 for (Sone sone : getSones()) {
485                         if (sone.getLikedPostIds().contains(post.getId())) {
486                                 sones.add(sone);
487                         }
488                 }
489                 return sones;
490         }
491
492         /**
493          * Returns all Sones that have liked the given reply.
494          *
495          * @param reply
496          *            The reply to get the liking Sones for
497          * @return The Sones that like the given reply
498          */
499         public Set<Sone> getLikes(PostReply reply) {
500                 Set<Sone> sones = new HashSet<Sone>();
501                 for (Sone sone : getSones()) {
502                         if (sone.getLikedReplyIds().contains(reply.getId())) {
503                                 sones.add(sone);
504                         }
505                 }
506                 return sones;
507         }
508
509         /**
510          * Returns whether the given post is bookmarked.
511          *
512          * @param post
513          *            The post to check
514          * @return {@code true} if the given post is bookmarked, {@code false}
515          *         otherwise
516          */
517         public boolean isBookmarked(Post post) {
518                 return database.isPostBookmarked(post);
519         }
520
521         /**
522          * Returns all currently known bookmarked posts.
523          *
524          * @return All bookmarked posts
525          */
526         public Set<Post> getBookmarkedPosts() {
527                 return database.getBookmarkedPosts();
528         }
529
530         public AlbumBuilder albumBuilder() {
531                 return database.newAlbumBuilder();
532         }
533
534         /**
535          * Returns the album with the given ID, optionally creating a new album if
536          * an album with the given ID can not be found.
537          *
538          * @param albumId
539          *            The ID of the album
540          * @return The album with the given ID, or {@code null} if no album with the
541          *         given ID exists
542          */
543         @Nullable
544         public Album getAlbum(@Nonnull String albumId) {
545                 return database.getAlbum(albumId).orNull();
546         }
547
548         public ImageBuilder imageBuilder() {
549                 return database.newImageBuilder();
550         }
551
552         /**
553          * Returns the image with the given ID, creating it if necessary.
554          *
555          * @param imageId
556          *            The ID of the image
557          * @return The image with the given ID
558          */
559         @Nullable
560         public Image getImage(String imageId) {
561                 return getImage(imageId, true);
562         }
563
564         /**
565          * Returns the image with the given ID, optionally creating it if it does
566          * not exist.
567          *
568          * @param imageId
569          *            The ID of the image
570          * @param create
571          *            {@code true} to create an image if none exists with the given
572          *            ID
573          * @return The image with the given ID, or {@code null} if none exists and
574          *         none was created
575          */
576         @Nullable
577         public Image getImage(String imageId, boolean create) {
578                 Optional<Image> image = database.getImage(imageId);
579                 if (image.isPresent()) {
580                         return image.get();
581                 }
582                 if (!create) {
583                         return null;
584                 }
585                 Image newImage = database.newImageBuilder().withId(imageId).build();
586                 database.storeImage(newImage);
587                 return newImage;
588         }
589
590         /**
591          * Returns the temporary image with the given ID.
592          *
593          * @param imageId
594          *            The ID of the temporary image
595          * @return The temporary image, or {@code null} if there is no temporary
596          *         image with the given ID
597          */
598         public TemporaryImage getTemporaryImage(String imageId) {
599                 synchronized (temporaryImages) {
600                         return temporaryImages.get(imageId);
601                 }
602         }
603
604         //
605         // ACTIONS
606         //
607
608         /**
609          * Locks the given Sone. A locked Sone will not be inserted by
610          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
611          * again.
612          *
613          * @param sone
614          *            The sone to lock
615          */
616         public void lockSone(Sone sone) {
617                 synchronized (lockedSones) {
618                         if (lockedSones.add(sone)) {
619                                 eventBus.post(new SoneLockedEvent(sone));
620                         }
621                 }
622         }
623
624         /**
625          * Unlocks the given Sone.
626          *
627          * @see #lockSone(Sone)
628          * @param sone
629          *            The sone to unlock
630          */
631         public void unlockSone(Sone sone) {
632                 synchronized (lockedSones) {
633                         if (lockedSones.remove(sone)) {
634                                 eventBus.post(new SoneUnlockedEvent(sone));
635                         }
636                 }
637         }
638
639         /**
640          * Adds a local Sone from the given own identity.
641          *
642          * @param ownIdentity
643          *            The own identity to create a Sone from
644          * @return The added (or already existing) Sone
645          */
646         public Sone addLocalSone(OwnIdentity ownIdentity) {
647                 if (ownIdentity == null) {
648                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
649                         return null;
650                 }
651                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
652                 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
653                 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
654                 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
655                 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
656                 sone.setKnown(true);
657                 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
658                 eventBus.register(soneInserter);
659                 synchronized (soneInserters) {
660                         soneInserters.put(sone, soneInserter);
661                 }
662                 loadSone(sone);
663                 database.storeSone(sone);
664                 sone.setStatus(SoneStatus.idle);
665                 soneInserter.start();
666                 return sone;
667         }
668
669         /**
670          * Creates a new Sone for the given own identity.
671          *
672          * @param ownIdentity
673          *            The own identity to create a Sone for
674          * @return The created Sone
675          */
676         public Sone createSone(OwnIdentity ownIdentity) {
677                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
678                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
679                         return null;
680                 }
681                 Sone sone = addLocalSone(ownIdentity);
682
683                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
684                 touchConfiguration();
685                 return sone;
686         }
687
688         /**
689          * Adds the Sone of the given identity.
690          *
691          * @param identity
692          *            The identity whose Sone to add
693          * @return The added or already existing Sone
694          */
695         public Sone addRemoteSone(Identity identity) {
696                 if (identity == null) {
697                         logger.log(Level.WARNING, "Given Identity is null!");
698                         return null;
699                 }
700                 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
701                 long latestEdition = fromNullable(tryParse(property)).or(0L);
702                 Sone existingSone = getSone(identity.getId());
703                 if ((existingSone != null )&& existingSone.isLocal()) {
704                         return existingSone;
705                 }
706                 boolean newSone = existingSone == null;
707                 Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
708                 sone.setLatestEdition(latestEdition);
709                 if (newSone) {
710                         synchronized (knownSones) {
711                                 newSone = !knownSones.contains(sone.getId());
712                         }
713                         sone.setKnown(!newSone);
714                         if (newSone) {
715                                 eventBus.post(new NewSoneFoundEvent(sone));
716                                 for (Sone localSone : getLocalSones()) {
717                                         if (localSone.getOptions().isAutoFollow()) {
718                                                 followSone(localSone, sone.getId());
719                                         }
720                                 }
721                         }
722                 }
723                 database.storeSone(sone);
724                 soneDownloader.addSone(sone);
725                 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
726                 return sone;
727         }
728
729         /**
730          * Lets the given local Sone follow the Sone with the given ID.
731          *
732          * @param sone
733          *            The local Sone that should follow another Sone
734          * @param soneId
735          *            The ID of the Sone to follow
736          */
737         public void followSone(Sone sone, String soneId) {
738                 checkNotNull(sone, "sone must not be null");
739                 checkNotNull(soneId, "soneId must not be null");
740                 database.addFriend(sone, soneId);
741                 synchronized (soneFollowingTimes) {
742                         if (!soneFollowingTimes.containsKey(soneId)) {
743                                 long now = System.currentTimeMillis();
744                                 soneFollowingTimes.put(soneId, now);
745                                 Sone followedSone = getSone(soneId);
746                                 if (followedSone == null) {
747                                         return;
748                                 }
749                                 for (Post post : followedSone.getPosts()) {
750                                         if (post.getTime() < now) {
751                                                 markPostKnown(post);
752                                         }
753                                 }
754                                 for (PostReply reply : followedSone.getReplies()) {
755                                         if (reply.getTime() < now) {
756                                                 markReplyKnown(reply);
757                                         }
758                                 }
759                         }
760                 }
761                 touchConfiguration();
762         }
763
764         /**
765          * Lets the given local Sone unfollow the Sone with the given ID.
766          *
767          * @param sone
768          *            The local Sone that should unfollow another Sone
769          * @param soneId
770          *            The ID of the Sone being unfollowed
771          */
772         public void unfollowSone(Sone sone, String soneId) {
773                 checkNotNull(sone, "sone must not be null");
774                 checkNotNull(soneId, "soneId must not be null");
775                 database.removeFriend(sone, soneId);
776                 boolean unfollowedSoneStillFollowed = false;
777                 for (Sone localSone : getLocalSones()) {
778                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
779                 }
780                 if (!unfollowedSoneStillFollowed) {
781                         synchronized (soneFollowingTimes) {
782                                 soneFollowingTimes.remove(soneId);
783                         }
784                 }
785                 touchConfiguration();
786         }
787
788         /**
789          * Sets the trust value of the given origin Sone for the target Sone.
790          *
791          * @param origin
792          *            The origin Sone
793          * @param target
794          *            The target Sone
795          * @param trustValue
796          *            The trust value (from {@code -100} to {@code 100})
797          */
798         public void setTrust(Sone origin, Sone target, int trustValue) {
799                 checkNotNull(origin, "origin must not be null");
800                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
801                 checkNotNull(target, "target must not be null");
802                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
803                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
804         }
805
806         /**
807          * Removes any trust assignment for the given target Sone.
808          *
809          * @param origin
810          *            The trust origin
811          * @param target
812          *            The trust target
813          */
814         public void removeTrust(Sone origin, Sone target) {
815                 checkNotNull(origin, "origin must not be null");
816                 checkNotNull(target, "target must not be null");
817                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
818                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
819         }
820
821         /**
822          * Assigns the configured positive trust value for the given target.
823          *
824          * @param origin
825          *            The trust origin
826          * @param target
827          *            The trust target
828          */
829         public void trustSone(Sone origin, Sone target) {
830                 setTrust(origin, target, preferences.getPositiveTrust());
831         }
832
833         /**
834          * Assigns the configured negative trust value for the given target.
835          *
836          * @param origin
837          *            The trust origin
838          * @param target
839          *            The trust target
840          */
841         public void distrustSone(Sone origin, Sone target) {
842                 setTrust(origin, target, preferences.getNegativeTrust());
843         }
844
845         /**
846          * Removes the trust assignment for the given target.
847          *
848          * @param origin
849          *            The trust origin
850          * @param target
851          *            The trust target
852          */
853         public void untrustSone(Sone origin, Sone target) {
854                 removeTrust(origin, target);
855         }
856
857         /**
858          * Updates the stored Sone with the given Sone.
859          *
860          * @param sone
861          *            The updated Sone
862          */
863         public void updateSone(Sone sone) {
864                 updateSone(sone, false);
865         }
866
867         /**
868          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
869          * {@code true}, an older Sone than the current Sone can be given to restore
870          * an old state.
871          *
872          * @param sone
873          *            The Sone to update
874          * @param soneRescueMode
875          *            {@code true} if the stored Sone should be updated regardless
876          *            of the age of the given Sone
877          */
878         public void updateSone(final Sone sone, boolean soneRescueMode) {
879                 Sone storedSone = getSone(sone.getId());
880                 if (storedSone != null) {
881                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
882                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
883                                 return;
884                         }
885                         List<Object> events =
886                                         collectEventsForChangesInSone(storedSone, sone);
887                         database.storeSone(sone);
888                         for (Object event : events) {
889                                 eventBus.post(event);
890                         }
891                         sone.setOptions(storedSone.getOptions());
892                         sone.setKnown(storedSone.isKnown());
893                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
894                         if (sone.isLocal()) {
895                                 touchConfiguration();
896                         }
897                 }
898         }
899
900         private List<Object> collectEventsForChangesInSone(Sone oldSone,
901                         final Sone newSone) {
902                 final List<Object> events = new ArrayList<Object>();
903                 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
904                                 oldSone);
905                 soneChangeDetector.onNewPosts(new PostProcessor() {
906                         @Override
907                         public void processPost(Post post) {
908                                 if (post.getTime() < getSoneFollowingTime(newSone)) {
909                                         post.setKnown(true);
910                                 } else if (!post.isKnown()) {
911                                         events.add(new NewPostFoundEvent(post));
912                                 }
913                         }
914                 });
915                 soneChangeDetector.onRemovedPosts(new PostProcessor() {
916                         @Override
917                         public void processPost(Post post) {
918                                 events.add(new PostRemovedEvent(post));
919                         }
920                 });
921                 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
922                         @Override
923                         public void processPostReply(PostReply postReply) {
924                                 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
925                                         postReply.setKnown(true);
926                                 } else if (!postReply.isKnown()) {
927                                         events.add(new NewPostReplyFoundEvent(postReply));
928                                 }
929                         }
930                 });
931                 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
932                         @Override
933                         public void processPostReply(PostReply postReply) {
934                                 events.add(new PostReplyRemovedEvent(postReply));
935                         }
936                 });
937                 soneChangeDetector.detectChanges(newSone);
938                 return events;
939         }
940
941         /**
942          * Deletes the given Sone. This will remove the Sone from the
943          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
944          * remove the context from its identity.
945          *
946          * @param sone
947          *            The Sone to delete
948          */
949         public void deleteSone(Sone sone) {
950                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
951                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
952                         return;
953                 }
954                 if (!getLocalSones().contains(sone)) {
955                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
956                         return;
957                 }
958                 SoneInserter soneInserter = soneInserters.remove(sone);
959                 soneInserter.stop();
960                 database.removeSone(sone);
961                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
962                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
963                 try {
964                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
965                 } catch (ConfigurationException ce1) {
966                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
967                 }
968         }
969
970         /**
971          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
972          * known} before, a {@link MarkSoneKnownEvent} is fired.
973          *
974          * @param sone
975          *            The Sone to mark as known
976          */
977         public void markSoneKnown(Sone sone) {
978                 if (!sone.isKnown()) {
979                         sone.setKnown(true);
980                         synchronized (knownSones) {
981                                 knownSones.add(sone.getId());
982                         }
983                         eventBus.post(new MarkSoneKnownEvent(sone));
984                         touchConfiguration();
985                 }
986         }
987
988         /**
989          * Loads and updates the given Sone from the configuration. If any error is
990          * encountered, loading is aborted and the given Sone is not changed.
991          *
992          * @param sone
993          *            The Sone to load and update
994          */
995         public void loadSone(Sone sone) {
996                 if (!sone.isLocal()) {
997                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
998                         return;
999                 }
1000                 logger.info(String.format("Loading local Sone: %s", sone));
1001
1002                 /* load Sone. */
1003                 String sonePrefix = "Sone/" + sone.getId();
1004                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1005                 if (soneTime == null) {
1006                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1007                         return;
1008                 }
1009                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1010
1011                 /* load profile. */
1012                 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1013                 Profile profile = configurationSoneParser.parseProfile();
1014
1015                 /* load posts. */
1016                 Collection<Post> posts;
1017                 try {
1018                         posts = configurationSoneParser.parsePosts(database);
1019                 } catch (InvalidPostFound ipf) {
1020                         logger.log(Level.WARNING, "Invalid post found, aborting load!");
1021                         return;
1022                 }
1023
1024                 /* load replies. */
1025                 Collection<PostReply> replies;
1026                 try {
1027                         replies = configurationSoneParser.parsePostReplies(database);
1028                 } catch (InvalidPostReplyFound iprf) {
1029                         logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1030                         return;
1031                 }
1032
1033                 /* load post likes. */
1034                 Set<String> likedPostIds =
1035                                 configurationSoneParser.parseLikedPostIds();
1036
1037                 /* load reply likes. */
1038                 Set<String> likedReplyIds =
1039                                 configurationSoneParser.parseLikedPostReplyIds();
1040
1041                 /* load albums. */
1042                 List<Album> topLevelAlbums;
1043                 try {
1044                         topLevelAlbums =
1045                                         configurationSoneParser.parseTopLevelAlbums(database);
1046                 } catch (InvalidAlbumFound iaf) {
1047                         logger.log(Level.WARNING, "Invalid album found, aborting load!");
1048                         return;
1049                 } catch (InvalidParentAlbumFound ipaf) {
1050                         logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1051                                         ipaf.getAlbumParentId()));
1052                         return;
1053                 }
1054
1055                 /* load images. */
1056                 try {
1057                         configurationSoneParser.parseImages(database);
1058                 } catch (InvalidImageFound iif) {
1059                         logger.log(WARNING, "Invalid image found, aborting load!");
1060                         return;
1061                 } catch (InvalidParentAlbumFound ipaf) {
1062                         logger.log(Level.WARNING,
1063                                         format("Invalid album image (%s) encountered, aborting load!",
1064                                                         ipaf.getAlbumParentId()));
1065                         return;
1066                 }
1067
1068                 /* load avatar. */
1069                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1070                 if (avatarId != null) {
1071                         final Map<String, Image> images =
1072                                         configurationSoneParser.getImages();
1073                         profile.setAvatar(images.get(avatarId));
1074                 }
1075
1076                 /* load options. */
1077                 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1078                 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1079                 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1080                 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1081                 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1082                 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1083                 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1084
1085                 /* if we’re still here, Sone was loaded successfully. */
1086                 synchronized (sone) {
1087                         sone.setTime(soneTime);
1088                         sone.setProfile(profile);
1089                         sone.setPosts(posts);
1090                         sone.setReplies(replies);
1091                         sone.setLikePostIds(likedPostIds);
1092                         sone.setLikeReplyIds(likedReplyIds);
1093                         for (Album album : sone.getRootAlbum().getAlbums()) {
1094                                 sone.getRootAlbum().removeAlbum(album);
1095                         }
1096                         for (Album album : topLevelAlbums) {
1097                                 sone.getRootAlbum().addAlbum(album);
1098                         }
1099                         synchronized (soneInserters) {
1100                                 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
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                 synchronized (soneRescuers) {
1425                         for (SoneRescuer soneRescuer : soneRescuers.values()) {
1426                                 soneRescuer.stop();
1427                         }
1428                 }
1429                 saveConfiguration();
1430                 database.stop();
1431                 webOfTrustUpdater.stop();
1432                 updateChecker.stop();
1433                 soneDownloader.stop();
1434                 soneDownloaders.shutdown();
1435                 identityManager.stop();
1436         }
1437
1438         //
1439         // PRIVATE METHODS
1440         //
1441
1442         /**
1443          * Saves the given Sone. This will persist all local settings for the given
1444          * Sone, such as the friends list and similar, private options.
1445          *
1446          * @param sone
1447          *            The Sone to save
1448          */
1449         private synchronized void saveSone(Sone sone) {
1450                 if (!sone.isLocal()) {
1451                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1452                         return;
1453                 }
1454                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1455                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1456                         return;
1457                 }
1458
1459                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1460                 try {
1461                         /* save Sone into configuration. */
1462                         String sonePrefix = "Sone/" + sone.getId();
1463                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1464                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1465
1466                         /* save profile. */
1467                         Profile profile = sone.getProfile();
1468                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1469                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1470                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1471                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1472                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1473                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1474                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1475
1476                         /* save profile fields. */
1477                         int fieldCounter = 0;
1478                         for (Field profileField : profile.getFields()) {
1479                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1480                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1481                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1482                         }
1483                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1484
1485                         /* save posts. */
1486                         int postCounter = 0;
1487                         for (Post post : sone.getPosts()) {
1488                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1489                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1490                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1491                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1492                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1493                         }
1494                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1495
1496                         /* save replies. */
1497                         int replyCounter = 0;
1498                         for (PostReply reply : sone.getReplies()) {
1499                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1500                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1501                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1502                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1503                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1504                         }
1505                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1506
1507                         /* save post likes. */
1508                         int postLikeCounter = 0;
1509                         for (String postId : sone.getLikedPostIds()) {
1510                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1511                         }
1512                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1513
1514                         /* save reply likes. */
1515                         int replyLikeCounter = 0;
1516                         for (String replyId : sone.getLikedReplyIds()) {
1517                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1518                         }
1519                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1520
1521                         /* save albums. first, collect in a flat structure, top-level first. */
1522                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1523
1524                         int albumCounter = 0;
1525                         for (Album album : albums) {
1526                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1527                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1528                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1529                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1530                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1531                         }
1532                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1533
1534                         /* save images. */
1535                         int imageCounter = 0;
1536                         for (Album album : albums) {
1537                                 for (Image image : album.getImages()) {
1538                                         if (!image.isInserted()) {
1539                                                 continue;
1540                                         }
1541                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1542                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1543                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1544                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1545                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1546                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1547                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1548                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1549                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1550                                 }
1551                         }
1552                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1553
1554                         /* save options. */
1555                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1556                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1557                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1558                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1559                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1560                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1561                         configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1562
1563                         configuration.save();
1564
1565                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1566
1567                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1568                 } catch (ConfigurationException ce1) {
1569                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1570                 }
1571         }
1572
1573         /**
1574          * Saves the current options.
1575          */
1576         private void saveConfiguration() {
1577                 synchronized (configuration) {
1578                         if (storingConfiguration) {
1579                                 logger.log(Level.FINE, "Already storing configuration…");
1580                                 return;
1581                         }
1582                         storingConfiguration = true;
1583                 }
1584
1585                 /* store the options first. */
1586                 try {
1587                         preferences.saveTo(configuration);
1588
1589                         /* save known Sones. */
1590                         int soneCounter = 0;
1591                         synchronized (knownSones) {
1592                                 for (String knownSoneId : knownSones) {
1593                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1594                                 }
1595                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1596                         }
1597
1598                         /* save Sone following times. */
1599                         soneCounter = 0;
1600                         synchronized (soneFollowingTimes) {
1601                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1602                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1603                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1604                                         ++soneCounter;
1605                                 }
1606                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1607                         }
1608
1609                         /* save known posts. */
1610                         database.save();
1611
1612                         /* now save it. */
1613                         configuration.save();
1614
1615                 } catch (ConfigurationException ce1) {
1616                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1617                 } catch (DatabaseException de1) {
1618                         logger.log(Level.SEVERE, "Could not save database!", de1);
1619                 } finally {
1620                         synchronized (configuration) {
1621                                 storingConfiguration = false;
1622                         }
1623                 }
1624         }
1625
1626         /**
1627          * Loads the configuration.
1628          */
1629         private void loadConfiguration() {
1630                 new PreferencesLoader(preferences).loadFrom(configuration);
1631
1632                 /* load known Sones. */
1633                 int soneCounter = 0;
1634                 while (true) {
1635                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1636                         if (knownSoneId == null) {
1637                                 break;
1638                         }
1639                         synchronized (knownSones) {
1640                                 knownSones.add(knownSoneId);
1641                         }
1642                 }
1643
1644                 /* load Sone following times. */
1645                 soneCounter = 0;
1646                 while (true) {
1647                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1648                         if (soneId == null) {
1649                                 break;
1650                         }
1651                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1652                         synchronized (soneFollowingTimes) {
1653                                 soneFollowingTimes.put(soneId, time);
1654                         }
1655                         ++soneCounter;
1656                 }
1657         }
1658
1659         /**
1660          * Notifies the core that a new {@link OwnIdentity} was added.
1661          *
1662          * @param ownIdentityAddedEvent
1663          *            The event
1664          */
1665         @Subscribe
1666         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1667                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1668                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1669                 if (ownIdentity.hasContext("Sone")) {
1670                         addLocalSone(ownIdentity);
1671                 }
1672         }
1673
1674         /**
1675          * Notifies the core that an {@link OwnIdentity} was removed.
1676          *
1677          * @param ownIdentityRemovedEvent
1678          *            The event
1679          */
1680         @Subscribe
1681         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1682                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1683                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1684                 trustedIdentities.removeAll(ownIdentity);
1685         }
1686
1687         /**
1688          * Notifies the core that a new {@link Identity} was added.
1689          *
1690          * @param identityAddedEvent
1691          *            The event
1692          */
1693         @Subscribe
1694         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1695                 Identity identity = identityAddedEvent.identity();
1696                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1697                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1698                 addRemoteSone(identity);
1699         }
1700
1701         /**
1702          * Notifies the core that an {@link Identity} was updated.
1703          *
1704          * @param identityUpdatedEvent
1705          *            The event
1706          */
1707         @Subscribe
1708         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1709                 Identity identity = identityUpdatedEvent.identity();
1710                 final Sone sone = getRemoteSone(identity.getId());
1711                 if (sone.isLocal()) {
1712                         return;
1713                 }
1714                 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1715                 soneDownloader.addSone(sone);
1716                 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1717         }
1718
1719         /**
1720          * Notifies the core that an {@link Identity} was removed.
1721          *
1722          * @param identityRemovedEvent
1723          *            The event
1724          */
1725         @Subscribe
1726         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1727                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1728                 Identity identity = identityRemovedEvent.identity();
1729                 trustedIdentities.remove(ownIdentity, identity);
1730                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1731                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1732                                 continue;
1733                         }
1734                         if (trustedIdentity.getValue().contains(identity)) {
1735                                 return;
1736                         }
1737                 }
1738                 Sone sone = getSone(identity.getId());
1739                 if (sone == null) {
1740                         /* TODO - we don’t have the Sone anymore. should this happen? */
1741                         return;
1742                 }
1743                 for (PostReply postReply : sone.getReplies()) {
1744                         eventBus.post(new PostReplyRemovedEvent(postReply));
1745                 }
1746                 for (Post post : sone.getPosts()) {
1747                         eventBus.post(new PostRemovedEvent(post));
1748                 }
1749                 eventBus.post(new SoneRemovedEvent(sone));
1750                 database.removeSone(sone);
1751         }
1752
1753         /**
1754          * Deletes the temporary image.
1755          *
1756          * @param imageInsertFinishedEvent
1757          *            The event
1758          */
1759         @Subscribe
1760         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1761                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1762                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1763                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1764                 touchConfiguration();
1765         }
1766
1767         @VisibleForTesting
1768         class MarkPostKnown implements Runnable {
1769
1770                 private final Post post;
1771
1772                 public MarkPostKnown(Post post) {
1773                         this.post = post;
1774                 }
1775
1776                 @Override
1777                 public void run() {
1778                         markPostKnown(post);
1779                 }
1780
1781         }
1782
1783         @VisibleForTesting
1784         class MarkReplyKnown implements Runnable {
1785
1786                 private final PostReply postReply;
1787
1788                 public MarkReplyKnown(PostReply postReply) {
1789                         this.postReply = postReply;
1790                 }
1791
1792                 @Override
1793                 public void run() {
1794                         markReplyKnown(postReply);
1795                 }
1796
1797         }
1798
1799 }