Use dependency injection for SoneDownloader
[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.InsertionDelayChangedEvent;
55 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
56 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
57 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
58 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
59 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
60 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
61 import net.pterodactylus.sone.core.event.PostRemovedEvent;
62 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
63 import net.pterodactylus.sone.core.event.SoneLockedEvent;
64 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
65 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
66 import net.pterodactylus.sone.data.Album;
67 import net.pterodactylus.sone.data.Client;
68 import net.pterodactylus.sone.data.Image;
69 import net.pterodactylus.sone.data.Post;
70 import net.pterodactylus.sone.data.PostReply;
71 import net.pterodactylus.sone.data.Profile;
72 import net.pterodactylus.sone.data.Profile.Field;
73 import net.pterodactylus.sone.data.Reply;
74 import net.pterodactylus.sone.data.Sone;
75 import net.pterodactylus.sone.data.Sone.SoneStatus;
76 import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
77 import net.pterodactylus.sone.data.TemporaryImage;
78 import net.pterodactylus.sone.database.AlbumBuilder;
79 import net.pterodactylus.sone.database.Database;
80 import net.pterodactylus.sone.database.DatabaseException;
81 import net.pterodactylus.sone.database.ImageBuilder;
82 import net.pterodactylus.sone.database.PostBuilder;
83 import net.pterodactylus.sone.database.PostProvider;
84 import net.pterodactylus.sone.database.PostReplyBuilder;
85 import net.pterodactylus.sone.database.PostReplyProvider;
86 import net.pterodactylus.sone.database.SoneBuilder;
87 import net.pterodactylus.sone.database.SoneProvider;
88 import net.pterodactylus.sone.freenet.wot.Identity;
89 import net.pterodactylus.sone.freenet.wot.IdentityManager;
90 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
95 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
96 import net.pterodactylus.sone.main.SonePlugin;
97 import net.pterodactylus.util.config.Configuration;
98 import net.pterodactylus.util.config.ConfigurationException;
99 import net.pterodactylus.util.service.AbstractService;
100 import net.pterodactylus.util.thread.NamedThreadFactory;
101
102 import com.google.common.annotations.VisibleForTesting;
103 import com.google.common.base.Optional;
104 import com.google.common.collect.FluentIterable;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.Multimap;
107 import com.google.common.collect.Multimaps;
108 import com.google.common.eventbus.EventBus;
109 import com.google.common.eventbus.Subscribe;
110 import com.google.inject.Inject;
111 import com.google.inject.Singleton;
112 import kotlin.jvm.functions.Function1;
113
114 /**
115  * The Sone core.
116  *
117  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
118  */
119 @Singleton
120 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
121
122         /** The logger. */
123         private static final Logger logger = getLogger(Core.class.getName());
124
125         /** The start time. */
126         private final long startupTime = System.currentTimeMillis();
127
128         /** The preferences. */
129         private final Preferences preferences;
130
131         /** The event bus. */
132         private final EventBus eventBus;
133
134         /** The configuration. */
135         private final Configuration configuration;
136
137         /** Whether we’re currently saving the configuration. */
138         private boolean storingConfiguration = false;
139
140         /** The identity manager. */
141         private final IdentityManager identityManager;
142
143         /** Interface to freenet. */
144         private final FreenetInterface freenetInterface;
145
146         /** The Sone downloader. */
147         private final SoneDownloader soneDownloader;
148
149         /** The image inserter. */
150         private final ImageInserter imageInserter;
151
152         /** Sone downloader thread-pool. */
153         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
154
155         /** The update checker. */
156         private final UpdateChecker updateChecker;
157
158         /** The trust updater. */
159         private final WebOfTrustUpdater webOfTrustUpdater;
160
161         /** The times Sones were followed. */
162         private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163
164         /** Locked local Sones. */
165         /* synchronize on itself. */
166         private final Set<Sone> lockedSones = new HashSet<Sone>();
167
168         /** Sone inserters. */
169         /* synchronize access on this on sones. */
170         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171
172         /** Sone rescuers. */
173         /* synchronize access on this on sones. */
174         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175
176         /** All known Sones. */
177         private final Set<String> knownSones = new HashSet<String>();
178
179         /** The post database. */
180         private final Database database;
181
182         /** Trusted identities, sorted by own identities. */
183         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
184
185         /** All temporary images. */
186         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
187
188         /** Ticker for threads that mark own elements as known. */
189         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
190
191         /** The time the configuration was last touched. */
192         private volatile long lastConfigurationUpdate;
193
194         /**
195          * Creates a new core.
196          *
197          * @param configuration
198          *            The configuration of the core
199          * @param freenetInterface
200          *            The freenet interface
201          * @param identityManager
202          *            The identity manager
203          * @param webOfTrustUpdater
204          *            The WebOfTrust updater
205          * @param eventBus
206          *            The event bus
207          * @param database
208          *            The database
209          */
210         @Inject
211         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
212                 super("Sone Core");
213                 this.configuration = configuration;
214                 this.freenetInterface = freenetInterface;
215                 this.identityManager = identityManager;
216                 this.soneDownloader = soneDownloader;
217                 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
218                 this.updateChecker = updateChecker;
219                 this.webOfTrustUpdater = webOfTrustUpdater;
220                 this.eventBus = eventBus;
221                 this.database = database;
222                 preferences = new Preferences(eventBus);
223         }
224
225         @VisibleForTesting
226         protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
227                 super("Sone Core");
228                 this.configuration = configuration;
229                 this.freenetInterface = freenetInterface;
230                 this.identityManager = identityManager;
231                 this.soneDownloader = soneDownloader;
232                 this.imageInserter = imageInserter;
233                 this.updateChecker = updateChecker;
234                 this.webOfTrustUpdater = webOfTrustUpdater;
235                 this.eventBus = eventBus;
236                 this.database = database;
237                 preferences = new Preferences(eventBus);
238         }
239
240         //
241         // ACCESSORS
242         //
243
244         /**
245          * Returns the time Sone was started.
246          *
247          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
248          */
249         public long getStartupTime() {
250                 return startupTime;
251         }
252
253         /**
254          * Returns the options used by the core.
255          *
256          * @return The options of the core
257          */
258         public Preferences getPreferences() {
259                 return preferences;
260         }
261
262         /**
263          * Returns the identity manager used by the core.
264          *
265          * @return The identity manager
266          */
267         public IdentityManager getIdentityManager() {
268                 return identityManager;
269         }
270
271         /**
272          * Returns the update checker.
273          *
274          * @return The update checker
275          */
276         public UpdateChecker getUpdateChecker() {
277                 return updateChecker;
278         }
279
280         /**
281          * Returns the Sone rescuer for the given local Sone.
282          *
283          * @param sone
284          *            The local Sone to get the rescuer for
285          * @return The Sone rescuer for the given Sone
286          */
287         public SoneRescuer getSoneRescuer(Sone sone) {
288                 checkNotNull(sone, "sone must not be null");
289                 checkArgument(sone.isLocal(), "sone must be local");
290                 synchronized (soneRescuers) {
291                         SoneRescuer soneRescuer = soneRescuers.get(sone);
292                         if (soneRescuer == null) {
293                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
294                                 soneRescuers.put(sone, soneRescuer);
295                                 soneRescuer.start();
296                         }
297                         return soneRescuer;
298                 }
299         }
300
301         /**
302          * Returns whether the given Sone is currently locked.
303          *
304          * @param sone
305          *            The sone to check
306          * @return {@code true} if the Sone is locked, {@code false} if it is not
307          */
308         public boolean isLocked(Sone sone) {
309                 synchronized (lockedSones) {
310                         return lockedSones.contains(sone);
311                 }
312         }
313
314         public SoneBuilder soneBuilder() {
315                 return database.newSoneBuilder();
316         }
317
318         /**
319          * {@inheritDocs}
320          */
321         @Nonnull
322         @Override
323         public Collection<Sone> getSones() {
324                 return database.getSones();
325         }
326
327         @Nonnull
328         @Override
329         public Function1<String, Sone> getSoneLoader() {
330                 return database.getSoneLoader();
331         }
332
333         /**
334          * Returns the Sone with the given ID, regardless whether it’s local or
335          * remote.
336          *
337          * @param id
338          *            The ID of the Sone to get
339          * @return The Sone with the given ID, or {@code null} if there is no such
340          *         Sone
341          */
342         @Override
343         @Nullable
344         public Sone getSone(@Nonnull String id) {
345                 return database.getSone(id);
346         }
347
348         /**
349          * {@inheritDocs}
350          */
351         @Override
352         public Collection<Sone> getLocalSones() {
353                 return database.getLocalSones();
354         }
355
356         /**
357          * Returns the local Sone with the given ID, optionally creating a new Sone.
358          *
359          * @param id
360          *            The ID of the Sone
361          * @return The Sone with the given ID, or {@code null}
362          */
363         public Sone getLocalSone(String id) {
364                 Sone sone = database.getSone(id);
365                 if ((sone != null) && sone.isLocal()) {
366                         return sone;
367                 }
368                 return null;
369         }
370
371         /**
372          * {@inheritDocs}
373          */
374         @Override
375         public Collection<Sone> getRemoteSones() {
376                 return database.getRemoteSones();
377         }
378
379         /**
380          * Returns the remote Sone with the given ID.
381          *
382          *
383          * @param id
384          *            The ID of the remote Sone to get
385          * @return The Sone with the given ID
386          */
387         public Sone getRemoteSone(String id) {
388                 return database.getSone(id);
389         }
390
391         /**
392          * Returns whether the given Sone has been modified.
393          *
394          * @param sone
395          *            The Sone to check for modifications
396          * @return {@code true} if a modification has been detected in the Sone,
397          *         {@code false} otherwise
398          */
399         public boolean isModifiedSone(Sone sone) {
400                 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
401         }
402
403         /**
404          * Returns the time when the given was first followed by any local Sone.
405          *
406          * @param sone
407          *            The Sone to get the time for
408          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
409          *         been followed, or {@link Long#MAX_VALUE}
410          */
411         public long getSoneFollowingTime(Sone sone) {
412                 synchronized (soneFollowingTimes) {
413                         return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
414                 }
415         }
416
417         /**
418          * Returns a post builder.
419          *
420          * @return A new post builder
421          */
422         public PostBuilder postBuilder() {
423                 return database.newPostBuilder();
424         }
425
426         @Nullable
427         @Override
428         public Post getPost(@Nonnull String postId) {
429                 return database.getPost(postId);
430         }
431
432         /**
433          * {@inheritDocs}
434          */
435         @Override
436         public Collection<Post> getPosts(String soneId) {
437                 return database.getPosts(soneId);
438         }
439
440         /**
441          * {@inheritDoc}
442          */
443         @Override
444         public Collection<Post> getDirectedPosts(final String recipientId) {
445                 checkNotNull(recipientId, "recipient must not be null");
446                 return database.getDirectedPosts(recipientId);
447         }
448
449         /**
450          * Returns a post reply builder.
451          *
452          * @return A new post reply builder
453          */
454         public PostReplyBuilder postReplyBuilder() {
455                 return database.newPostReplyBuilder();
456         }
457
458         /**
459          * {@inheritDoc}
460          */
461         @Nullable
462         @Override
463         public 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);
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                 Image image = database.getImage(imageId);
579                 if (image != null) {
580                         return image;
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                 soneInserter.insertionDelayChanged(new InsertionDelayChangedEvent(preferences.getInsertionDelay()));
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                 String newLatestEdition = identity.getProperty("Sone.LatestEdition");
1716                 if (newLatestEdition != null) {
1717                         Long parsedNewLatestEdition = tryParse(newLatestEdition);
1718                         if (parsedNewLatestEdition != null) {
1719                                 sone.setLatestEdition(parsedNewLatestEdition);
1720                         }
1721                 }
1722                 soneDownloader.addSone(sone);
1723                 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1724         }
1725
1726         /**
1727          * Notifies the core that an {@link Identity} was removed.
1728          *
1729          * @param identityRemovedEvent
1730          *            The event
1731          */
1732         @Subscribe
1733         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1734                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1735                 Identity identity = identityRemovedEvent.identity();
1736                 trustedIdentities.remove(ownIdentity, identity);
1737                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1738                         if (trustedIdentity.getKey().equals(ownIdentity)) {
1739                                 continue;
1740                         }
1741                         if (trustedIdentity.getValue().contains(identity)) {
1742                                 return;
1743                         }
1744                 }
1745                 Sone sone = getSone(identity.getId());
1746                 if (sone == null) {
1747                         /* TODO - we don’t have the Sone anymore. should this happen? */
1748                         return;
1749                 }
1750                 for (PostReply postReply : sone.getReplies()) {
1751                         eventBus.post(new PostReplyRemovedEvent(postReply));
1752                 }
1753                 for (Post post : sone.getPosts()) {
1754                         eventBus.post(new PostRemovedEvent(post));
1755                 }
1756                 eventBus.post(new SoneRemovedEvent(sone));
1757                 database.removeSone(sone);
1758         }
1759
1760         /**
1761          * Deletes the temporary image.
1762          *
1763          * @param imageInsertFinishedEvent
1764          *            The event
1765          */
1766         @Subscribe
1767         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1768                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1769                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1770                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1771                 touchConfiguration();
1772         }
1773
1774         @VisibleForTesting
1775         class MarkPostKnown implements Runnable {
1776
1777                 private final Post post;
1778
1779                 public MarkPostKnown(Post post) {
1780                         this.post = post;
1781                 }
1782
1783                 @Override
1784                 public void run() {
1785                         markPostKnown(post);
1786                 }
1787
1788         }
1789
1790         @VisibleForTesting
1791         class MarkReplyKnown implements Runnable {
1792
1793                 private final PostReply postReply;
1794
1795                 public MarkReplyKnown(PostReply postReply) {
1796                         this.postReply = postReply;
1797                 }
1798
1799                 @Override
1800                 public void run() {
1801                         markReplyKnown(postReply);
1802                 }
1803
1804         }
1805
1806 }