🔀 Merge branch 'release/v82'
[Sone.git] / 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.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("Sone.Core");
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, 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 = new UpdateChecker(eventBus, freenetInterface);
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                 sone.setLatestEdition(fromNullable(tryParse(ownIdentity.getProperty("Sone.LatestEdition"))).or(0L));
645                 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
646                 sone.setKnown(true);
647                 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
648                 eventBus.register(soneInserter);
649                 synchronized (soneInserters) {
650                         soneInserters.put(sone, soneInserter);
651                 }
652                 loadSone(sone);
653                 sone.setStatus(SoneStatus.idle);
654                 soneInserter.start();
655                 return sone;
656         }
657
658         /**
659          * Creates a new Sone for the given own identity.
660          *
661          * @param ownIdentity
662          *            The own identity to create a Sone for
663          * @return The created Sone
664          */
665         public Sone createSone(OwnIdentity ownIdentity) {
666                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
667                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
668                         return null;
669                 }
670                 Sone sone = addLocalSone(ownIdentity);
671
672                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
673                 touchConfiguration();
674                 return sone;
675         }
676
677         /**
678          * Adds the Sone of the given identity.
679          *
680          * @param identity
681          *            The identity whose Sone to add
682          * @return The added or already existing Sone
683          */
684         public Sone addRemoteSone(Identity identity) {
685                 if (identity == null) {
686                         logger.log(Level.WARNING, "Given Identity is null!");
687                         return null;
688                 }
689                 final Long latestEdition = tryParse(fromNullable(
690                                 identity.getProperty("Sone.LatestEdition")).or("0"));
691                 Optional<Sone> existingSone = getSone(identity.getId());
692                 if (existingSone.isPresent() && existingSone.get().isLocal()) {
693                         return existingSone.get();
694                 }
695                 boolean newSone = !existingSone.isPresent();
696                 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
697                 sone.setLatestEdition(latestEdition);
698                 if (newSone) {
699                         synchronized (knownSones) {
700                                 newSone = !knownSones.contains(sone.getId());
701                         }
702                         sone.setKnown(!newSone);
703                         if (newSone) {
704                                 eventBus.post(new NewSoneFoundEvent(sone));
705                                 for (Sone localSone : getLocalSones()) {
706                                         if (localSone.getOptions().isAutoFollow()) {
707                                                 followSone(localSone, sone.getId());
708                                         }
709                                 }
710                         }
711                 }
712                 database.storeSone(sone);
713                 soneDownloader.addSone(sone);
714                 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
715                 return sone;
716         }
717
718         /**
719          * Lets the given local Sone follow the Sone with the given ID.
720          *
721          * @param sone
722          *            The local Sone that should follow another Sone
723          * @param soneId
724          *            The ID of the Sone to follow
725          */
726         public void followSone(Sone sone, String soneId) {
727                 checkNotNull(sone, "sone must not be null");
728                 checkNotNull(soneId, "soneId must not be null");
729                 database.addFriend(sone, soneId);
730                 synchronized (soneFollowingTimes) {
731                         if (!soneFollowingTimes.containsKey(soneId)) {
732                                 long now = System.currentTimeMillis();
733                                 soneFollowingTimes.put(soneId, now);
734                                 Optional<Sone> followedSone = getSone(soneId);
735                                 if (!followedSone.isPresent()) {
736                                         return;
737                                 }
738                                 for (Post post : followedSone.get().getPosts()) {
739                                         if (post.getTime() < now) {
740                                                 markPostKnown(post);
741                                         }
742                                 }
743                                 for (PostReply reply : followedSone.get().getReplies()) {
744                                         if (reply.getTime() < now) {
745                                                 markReplyKnown(reply);
746                                         }
747                                 }
748                         }
749                 }
750                 touchConfiguration();
751         }
752
753         /**
754          * Lets the given local Sone unfollow the Sone with the given ID.
755          *
756          * @param sone
757          *            The local Sone that should unfollow another Sone
758          * @param soneId
759          *            The ID of the Sone being unfollowed
760          */
761         public void unfollowSone(Sone sone, String soneId) {
762                 checkNotNull(sone, "sone must not be null");
763                 checkNotNull(soneId, "soneId must not be null");
764                 database.removeFriend(sone, soneId);
765                 boolean unfollowedSoneStillFollowed = false;
766                 for (Sone localSone : getLocalSones()) {
767                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
768                 }
769                 if (!unfollowedSoneStillFollowed) {
770                         synchronized (soneFollowingTimes) {
771                                 soneFollowingTimes.remove(soneId);
772                         }
773                 }
774                 touchConfiguration();
775         }
776
777         /**
778          * Sets the trust value of the given origin Sone for the target Sone.
779          *
780          * @param origin
781          *            The origin Sone
782          * @param target
783          *            The target Sone
784          * @param trustValue
785          *            The trust value (from {@code -100} to {@code 100})
786          */
787         public void setTrust(Sone origin, Sone target, int trustValue) {
788                 checkNotNull(origin, "origin must not be null");
789                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
790                 checkNotNull(target, "target must not be null");
791                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
792                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
793         }
794
795         /**
796          * Removes any trust assignment for the given target Sone.
797          *
798          * @param origin
799          *            The trust origin
800          * @param target
801          *            The trust target
802          */
803         public void removeTrust(Sone origin, Sone target) {
804                 checkNotNull(origin, "origin must not be null");
805                 checkNotNull(target, "target must not be null");
806                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
807                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
808         }
809
810         /**
811          * Assigns the configured positive trust value for the given target.
812          *
813          * @param origin
814          *            The trust origin
815          * @param target
816          *            The trust target
817          */
818         public void trustSone(Sone origin, Sone target) {
819                 setTrust(origin, target, preferences.getPositiveTrust());
820         }
821
822         /**
823          * Assigns the configured negative trust value for the given target.
824          *
825          * @param origin
826          *            The trust origin
827          * @param target
828          *            The trust target
829          */
830         public void distrustSone(Sone origin, Sone target) {
831                 setTrust(origin, target, preferences.getNegativeTrust());
832         }
833
834         /**
835          * Removes the trust assignment for the given target.
836          *
837          * @param origin
838          *            The trust origin
839          * @param target
840          *            The trust target
841          */
842         public void untrustSone(Sone origin, Sone target) {
843                 removeTrust(origin, target);
844         }
845
846         /**
847          * Updates the stored Sone with the given Sone.
848          *
849          * @param sone
850          *            The updated Sone
851          */
852         public void updateSone(Sone sone) {
853                 updateSone(sone, false);
854         }
855
856         /**
857          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
858          * {@code true}, an older Sone than the current Sone can be given to restore
859          * an old state.
860          *
861          * @param sone
862          *            The Sone to update
863          * @param soneRescueMode
864          *            {@code true} if the stored Sone should be updated regardless
865          *            of the age of the given Sone
866          */
867         public void updateSone(final Sone sone, boolean soneRescueMode) {
868                 Optional<Sone> storedSone = getSone(sone.getId());
869                 if (storedSone.isPresent()) {
870                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
871                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
872                                 return;
873                         }
874                         List<Object> events =
875                                         collectEventsForChangesInSone(storedSone.get(), sone);
876                         database.storeSone(sone);
877                         for (Object event : events) {
878                                 eventBus.post(event);
879                         }
880                         sone.setOptions(storedSone.get().getOptions());
881                         sone.setKnown(storedSone.get().isKnown());
882                         sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
883                         if (sone.isLocal()) {
884                                 touchConfiguration();
885                         }
886                 }
887         }
888
889         private List<Object> collectEventsForChangesInSone(Sone oldSone,
890                         final Sone newSone) {
891                 final List<Object> events = new ArrayList<Object>();
892                 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
893                                 oldSone);
894                 soneChangeDetector.onNewPosts(new PostProcessor() {
895                         @Override
896                         public void processPost(Post post) {
897                                 if (post.getTime() < getSoneFollowingTime(newSone)) {
898                                         post.setKnown(true);
899                                 } else if (!post.isKnown()) {
900                                         events.add(new NewPostFoundEvent(post));
901                                 }
902                         }
903                 });
904                 soneChangeDetector.onRemovedPosts(new PostProcessor() {
905                         @Override
906                         public void processPost(Post post) {
907                                 events.add(new PostRemovedEvent(post));
908                         }
909                 });
910                 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
911                         @Override
912                         public void processPostReply(PostReply postReply) {
913                                 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
914                                         postReply.setKnown(true);
915                                 } else if (!postReply.isKnown()) {
916                                         events.add(new NewPostReplyFoundEvent(postReply));
917                                 }
918                         }
919                 });
920                 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
921                         @Override
922                         public void processPostReply(PostReply postReply) {
923                                 events.add(new PostReplyRemovedEvent(postReply));
924                         }
925                 });
926                 soneChangeDetector.detectChanges(newSone);
927                 return events;
928         }
929
930         /**
931          * Deletes the given Sone. This will remove the Sone from the
932          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
933          * remove the context from its identity.
934          *
935          * @param sone
936          *            The Sone to delete
937          */
938         public void deleteSone(Sone sone) {
939                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
940                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
941                         return;
942                 }
943                 if (!getLocalSones().contains(sone)) {
944                         logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
945                         return;
946                 }
947                 SoneInserter soneInserter = soneInserters.remove(sone);
948                 soneInserter.stop();
949                 database.removeSone(sone);
950                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
951                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
952                 try {
953                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
954                 } catch (ConfigurationException ce1) {
955                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
956                 }
957         }
958
959         /**
960          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
961          * known} before, a {@link MarkSoneKnownEvent} is fired.
962          *
963          * @param sone
964          *            The Sone to mark as known
965          */
966         public void markSoneKnown(Sone sone) {
967                 if (!sone.isKnown()) {
968                         sone.setKnown(true);
969                         synchronized (knownSones) {
970                                 knownSones.add(sone.getId());
971                         }
972                         eventBus.post(new MarkSoneKnownEvent(sone));
973                         touchConfiguration();
974                 }
975         }
976
977         /**
978          * Loads and updates the given Sone from the configuration. If any error is
979          * encountered, loading is aborted and the given Sone is not changed.
980          *
981          * @param sone
982          *            The Sone to load and update
983          */
984         public void loadSone(Sone sone) {
985                 if (!sone.isLocal()) {
986                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
987                         return;
988                 }
989                 logger.info(String.format("Loading local Sone: %s", sone));
990
991                 /* load Sone. */
992                 String sonePrefix = "Sone/" + sone.getId();
993                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
994                 if (soneTime == null) {
995                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
996                         return;
997                 }
998                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
999
1000                 /* load profile. */
1001                 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1002                 Profile profile = configurationSoneParser.parseProfile();
1003
1004                 /* load posts. */
1005                 Collection<Post> posts;
1006                 try {
1007                         posts = configurationSoneParser.parsePosts(database);
1008                 } catch (InvalidPostFound ipf) {
1009                         logger.log(Level.WARNING, "Invalid post found, aborting load!");
1010                         return;
1011                 }
1012
1013                 /* load replies. */
1014                 Collection<PostReply> replies;
1015                 try {
1016                         replies = configurationSoneParser.parsePostReplies(database);
1017                 } catch (InvalidPostReplyFound iprf) {
1018                         logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1019                         return;
1020                 }
1021
1022                 /* load post likes. */
1023                 Set<String> likedPostIds =
1024                                 configurationSoneParser.parseLikedPostIds();
1025
1026                 /* load reply likes. */
1027                 Set<String> likedReplyIds =
1028                                 configurationSoneParser.parseLikedPostReplyIds();
1029
1030                 /* load albums. */
1031                 List<Album> topLevelAlbums;
1032                 try {
1033                         topLevelAlbums =
1034                                         configurationSoneParser.parseTopLevelAlbums(database);
1035                 } catch (InvalidAlbumFound iaf) {
1036                         logger.log(Level.WARNING, "Invalid album found, aborting load!");
1037                         return;
1038                 } catch (InvalidParentAlbumFound ipaf) {
1039                         logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1040                                         ipaf.getAlbumParentId()));
1041                         return;
1042                 }
1043
1044                 /* load images. */
1045                 try {
1046                         configurationSoneParser.parseImages(database);
1047                 } catch (InvalidImageFound iif) {
1048                         logger.log(WARNING, "Invalid image found, aborting load!");
1049                         return;
1050                 } catch (InvalidParentAlbumFound ipaf) {
1051                         logger.log(Level.WARNING,
1052                                         format("Invalid album image (%s) encountered, aborting load!",
1053                                                         ipaf.getAlbumParentId()));
1054                         return;
1055                 }
1056
1057                 /* load avatar. */
1058                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1059                 if (avatarId != null) {
1060                         final Map<String, Image> images =
1061                                         configurationSoneParser.getImages();
1062                         profile.setAvatar(images.get(avatarId));
1063                 }
1064
1065                 /* load options. */
1066                 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1067                 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1068                 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1069                 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1070                 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1071                 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1072
1073                 /* if we’re still here, Sone was loaded successfully. */
1074                 synchronized (sone) {
1075                         sone.setTime(soneTime);
1076                         sone.setProfile(profile);
1077                         sone.setPosts(posts);
1078                         sone.setReplies(replies);
1079                         sone.setLikePostIds(likedPostIds);
1080                         sone.setLikeReplyIds(likedReplyIds);
1081                         for (Album album : sone.getRootAlbum().getAlbums()) {
1082                                 sone.getRootAlbum().removeAlbum(album);
1083                         }
1084                         for (Album album : topLevelAlbums) {
1085                                 sone.getRootAlbum().addAlbum(album);
1086                         }
1087                         database.storeSone(sone);
1088                         synchronized (soneInserters) {
1089                                 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1090                         }
1091                 }
1092                 for (Post post : posts) {
1093                         post.setKnown(true);
1094                 }
1095                 for (PostReply reply : replies) {
1096                         reply.setKnown(true);
1097                 }
1098
1099                 logger.info(String.format("Sone loaded successfully: %s", sone));
1100         }
1101
1102         /**
1103          * Creates a new post.
1104          *
1105          * @param sone
1106          *            The Sone that creates the post
1107          * @param recipient
1108          *            The recipient Sone, or {@code null} if this post does not have
1109          *            a recipient
1110          * @param text
1111          *            The text of the post
1112          * @return The created post
1113          */
1114         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1115                 checkNotNull(text, "text must not be null");
1116                 checkArgument(text.trim().length() > 0, "text must not be empty");
1117                 if (!sone.isLocal()) {
1118                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1119                         return null;
1120                 }
1121                 PostBuilder postBuilder = database.newPostBuilder();
1122                 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1123                 if (recipient.isPresent()) {
1124                         postBuilder.to(recipient.get().getId());
1125                 }
1126                 final Post post = postBuilder.build();
1127                 database.storePost(post);
1128                 eventBus.post(new NewPostFoundEvent(post));
1129                 sone.addPost(post);
1130                 touchConfiguration();
1131                 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1132                 return post;
1133         }
1134
1135         /**
1136          * Deletes the given post.
1137          *
1138          * @param post
1139          *            The post to delete
1140          */
1141         public void deletePost(Post post) {
1142                 if (!post.getSone().isLocal()) {
1143                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1144                         return;
1145                 }
1146                 database.removePost(post);
1147                 eventBus.post(new PostRemovedEvent(post));
1148                 markPostKnown(post);
1149                 touchConfiguration();
1150         }
1151
1152         /**
1153          * Marks the given post as known, if it is currently not a known post
1154          * (according to {@link Post#isKnown()}).
1155          *
1156          * @param post
1157          *            The post to mark as known
1158          */
1159         public void markPostKnown(Post post) {
1160                 post.setKnown(true);
1161                 eventBus.post(new MarkPostKnownEvent(post));
1162                 touchConfiguration();
1163                 for (PostReply reply : getReplies(post.getId())) {
1164                         markReplyKnown(reply);
1165                 }
1166         }
1167
1168         public void bookmarkPost(Post post) {
1169                 database.bookmarkPost(post);
1170         }
1171
1172         /**
1173          * Removes the given post from the bookmarks.
1174          *
1175          * @param post
1176          *            The post to unbookmark
1177          */
1178         public void unbookmarkPost(Post post) {
1179                 database.unbookmarkPost(post);
1180         }
1181
1182         /**
1183          * Creates a new reply.
1184          *
1185          * @param sone
1186          *            The Sone that creates the reply
1187          * @param post
1188          *            The post that this reply refers to
1189          * @param text
1190          *            The text of the reply
1191          * @return The created reply
1192          */
1193         public PostReply createReply(Sone sone, Post post, String text) {
1194                 checkNotNull(text, "text must not be null");
1195                 checkArgument(text.trim().length() > 0, "text must not be empty");
1196                 if (!sone.isLocal()) {
1197                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1198                         return null;
1199                 }
1200                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1201                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1202                 final PostReply reply = postReplyBuilder.build();
1203                 database.storePostReply(reply);
1204                 eventBus.post(new NewPostReplyFoundEvent(reply));
1205                 sone.addReply(reply);
1206                 touchConfiguration();
1207                 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1208                 return reply;
1209         }
1210
1211         /**
1212          * Deletes the given reply.
1213          *
1214          * @param reply
1215          *            The reply to delete
1216          */
1217         public void deleteReply(PostReply reply) {
1218                 Sone sone = reply.getSone();
1219                 if (!sone.isLocal()) {
1220                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1221                         return;
1222                 }
1223                 database.removePostReply(reply);
1224                 markReplyKnown(reply);
1225                 sone.removeReply(reply);
1226                 touchConfiguration();
1227         }
1228
1229         /**
1230          * Marks the given reply as known, if it is currently not a known reply
1231          * (according to {@link Reply#isKnown()}).
1232          *
1233          * @param reply
1234          *            The reply to mark as known
1235          */
1236         public void markReplyKnown(PostReply reply) {
1237                 boolean previouslyKnown = reply.isKnown();
1238                 reply.setKnown(true);
1239                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1240                 if (!previouslyKnown) {
1241                         touchConfiguration();
1242                 }
1243         }
1244
1245         /**
1246          * Creates a new album for the given Sone.
1247          *
1248          * @param sone
1249          *            The Sone to create the album for
1250          * @param parent
1251          *            The parent of the album (may be {@code null} to create a
1252          *            top-level album)
1253          * @return The new album
1254          */
1255         public Album createAlbum(Sone sone, Album parent) {
1256                 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1257                 database.storeAlbum(album);
1258                 parent.addAlbum(album);
1259                 return album;
1260         }
1261
1262         /**
1263          * Deletes the given album. The owner of the album has to be a local Sone,
1264          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1265          *
1266          * @param album
1267          *            The album to remove
1268          */
1269         public void deleteAlbum(Album album) {
1270                 checkNotNull(album, "album must not be null");
1271                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1272                 if (!album.isEmpty()) {
1273                         return;
1274                 }
1275                 album.getParent().removeAlbum(album);
1276                 database.removeAlbum(album);
1277                 touchConfiguration();
1278         }
1279
1280         /**
1281          * Creates a new image.
1282          *
1283          * @param sone
1284          *            The Sone creating the image
1285          * @param album
1286          *            The album the image will be inserted into
1287          * @param temporaryImage
1288          *            The temporary image to create the image from
1289          * @return The newly created image
1290          */
1291         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1292                 checkNotNull(sone, "sone must not be null");
1293                 checkNotNull(album, "album must not be null");
1294                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1295                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1296                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1297                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1298                 album.addImage(image);
1299                 database.storeImage(image);
1300                 imageInserter.insertImage(temporaryImage, image);
1301                 return image;
1302         }
1303
1304         /**
1305          * Deletes the given image. This method will also delete a matching
1306          * temporary image.
1307          *
1308          * @see #deleteTemporaryImage(String)
1309          * @param image
1310          *            The image to delete
1311          */
1312         public void deleteImage(Image image) {
1313                 checkNotNull(image, "image must not be null");
1314                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1315                 deleteTemporaryImage(image.getId());
1316                 image.getAlbum().removeImage(image);
1317                 database.removeImage(image);
1318                 touchConfiguration();
1319         }
1320
1321         /**
1322          * Creates a new temporary image.
1323          *
1324          * @param mimeType
1325          *            The MIME type of the temporary image
1326          * @param imageData
1327          *            The encoded data of the image
1328          * @return The temporary image
1329          */
1330         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1331                 TemporaryImage temporaryImage = new TemporaryImage();
1332                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1333                 synchronized (temporaryImages) {
1334                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1335                 }
1336                 return temporaryImage;
1337         }
1338
1339         /**
1340          * Deletes the temporary image with the given ID.
1341          *
1342          * @param imageId
1343          *            The ID of the temporary image to delete
1344          */
1345         public void deleteTemporaryImage(String imageId) {
1346                 checkNotNull(imageId, "imageId must not be null");
1347                 synchronized (temporaryImages) {
1348                         temporaryImages.remove(imageId);
1349                 }
1350                 Image image = getImage(imageId, false);
1351                 if (image != null) {
1352                         imageInserter.cancelImageInsert(image);
1353                 }
1354         }
1355
1356         /**
1357          * Notifies the core that the configuration, either of the core or of a
1358          * single local Sone, has changed, and that the configuration should be
1359          * saved.
1360          */
1361         public void touchConfiguration() {
1362                 lastConfigurationUpdate = System.currentTimeMillis();
1363         }
1364
1365         //
1366         // SERVICE METHODS
1367         //
1368
1369         /**
1370          * Starts the core.
1371          */
1372         @Override
1373         public void serviceStart() {
1374                 loadConfiguration();
1375                 updateChecker.start();
1376                 identityManager.start();
1377                 webOfTrustUpdater.init();
1378                 webOfTrustUpdater.start();
1379                 database.start();
1380         }
1381
1382         /**
1383          * {@inheritDoc}
1384          */
1385         @Override
1386         public void serviceRun() {
1387                 long lastSaved = System.currentTimeMillis();
1388                 while (!shouldStop()) {
1389                         sleep(1000);
1390                         long now = System.currentTimeMillis();
1391                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1392                                 for (Sone localSone : getLocalSones()) {
1393                                         saveSone(localSone);
1394                                 }
1395                                 saveConfiguration();
1396                                 lastSaved = now;
1397                         }
1398                 }
1399         }
1400
1401         /**
1402          * Stops the core.
1403          */
1404         @Override
1405         public void serviceStop() {
1406                 localElementTicker.shutdownNow();
1407                 synchronized (soneInserters) {
1408                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1409                                 soneInserter.getValue().stop();
1410                                 saveSone(soneInserter.getKey());
1411                         }
1412                 }
1413                 synchronized (soneRescuers) {
1414                         for (SoneRescuer soneRescuer : soneRescuers.values()) {
1415                                 soneRescuer.stop();
1416                         }
1417                 }
1418                 saveConfiguration();
1419                 database.stop();
1420                 webOfTrustUpdater.stop();
1421                 updateChecker.stop();
1422                 soneDownloader.stop();
1423                 soneDownloaders.shutdown();
1424                 identityManager.stop();
1425         }
1426
1427         //
1428         // PRIVATE METHODS
1429         //
1430
1431         /**
1432          * Saves the given Sone. This will persist all local settings for the given
1433          * Sone, such as the friends list and similar, private options.
1434          *
1435          * @param sone
1436          *            The Sone to save
1437          */
1438         private synchronized void saveSone(Sone sone) {
1439                 if (!sone.isLocal()) {
1440                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1441                         return;
1442                 }
1443                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1444                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1445                         return;
1446                 }
1447
1448                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1449                 try {
1450                         /* save Sone into configuration. */
1451                         String sonePrefix = "Sone/" + sone.getId();
1452                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1453                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1454
1455                         /* save profile. */
1456                         Profile profile = sone.getProfile();
1457                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1458                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1459                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1460                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1461                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1462                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1463                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1464
1465                         /* save profile fields. */
1466                         int fieldCounter = 0;
1467                         for (Field profileField : profile.getFields()) {
1468                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1469                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1470                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1471                         }
1472                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1473
1474                         /* save posts. */
1475                         int postCounter = 0;
1476                         for (Post post : sone.getPosts()) {
1477                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1478                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1479                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1480                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1481                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1482                         }
1483                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1484
1485                         /* save replies. */
1486                         int replyCounter = 0;
1487                         for (PostReply reply : sone.getReplies()) {
1488                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1489                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1490                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1491                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1492                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1493                         }
1494                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1495
1496                         /* save post likes. */
1497                         int postLikeCounter = 0;
1498                         for (String postId : sone.getLikedPostIds()) {
1499                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1500                         }
1501                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1502
1503                         /* save reply likes. */
1504                         int replyLikeCounter = 0;
1505                         for (String replyId : sone.getLikedReplyIds()) {
1506                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1507                         }
1508                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1509
1510                         /* save albums. first, collect in a flat structure, top-level first. */
1511                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1512
1513                         int albumCounter = 0;
1514                         for (Album album : albums) {
1515                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1516                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1517                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1518                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1519                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1520                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().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 }