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