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