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