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