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