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