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