Add class to set FCP interface access level from an option.
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010–2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
24
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Set;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.TimeUnit;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
40
41 import net.pterodactylus.sone.core.Options.DefaultOption;
42 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.data.SoneImpl;
67 import net.pterodactylus.sone.data.TemporaryImage;
68 import net.pterodactylus.sone.database.Database;
69 import net.pterodactylus.sone.database.DatabaseException;
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.SoneProvider;
75 import net.pterodactylus.sone.fcp.FcpInterface;
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.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
92
93 import com.google.common.base.Optional;
94 import com.google.common.base.Predicates;
95 import com.google.common.collect.FluentIterable;
96 import com.google.common.collect.HashMultimap;
97 import com.google.common.collect.ImmutableSet;
98 import com.google.common.collect.Multimap;
99 import com.google.common.collect.Multimaps;
100 import com.google.common.eventbus.EventBus;
101 import com.google.common.eventbus.Subscribe;
102 import com.google.inject.Inject;
103
104 import freenet.keys.FreenetURI;
105
106 /**
107  * The Sone core.
108  *
109  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
110  */
111 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
112
113         /** The logger. */
114         private static final Logger logger = Logging.getLogger(Core.class);
115
116         /** The start time. */
117         private final long startupTime = System.currentTimeMillis();
118
119         /** The options. */
120         private final Options options = new Options();
121
122         /** The preferences. */
123         private final Preferences preferences = new Preferences(options);
124
125         /** The event bus. */
126         private final EventBus eventBus;
127
128         /** The configuration. */
129         private final Configuration configuration;
130
131         /** Whether we’re currently saving the configuration. */
132         private boolean storingConfiguration = false;
133
134         /** The identity manager. */
135         private final IdentityManager identityManager;
136
137         /** Interface to freenet. */
138         private final FreenetInterface freenetInterface;
139
140         /** The Sone downloader. */
141         private final SoneDownloader soneDownloader;
142
143         /** The image inserter. */
144         private final ImageInserter imageInserter;
145
146         /** Sone downloader thread-pool. */
147         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
148
149         /** The update checker. */
150         private final UpdateChecker updateChecker;
151
152         /** The trust updater. */
153         private final WebOfTrustUpdater webOfTrustUpdater;
154
155         /** The FCP interface. */
156         private volatile FcpInterface fcpInterface;
157
158         /** The times Sones were followed. */
159         private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
160
161         /** Locked local Sones. */
162         /* synchronize on itself. */
163         private final Set<Sone> lockedSones = new HashSet<Sone>();
164
165         /** Sone inserters. */
166         /* synchronize access on this on sones. */
167         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
168
169         /** Sone rescuers. */
170         /* synchronize access on this on sones. */
171         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
172
173         /** All Sones. */
174         /* synchronize access on this on itself. */
175         private final Map<String, Sone> sones = new HashMap<String, Sone>();
176
177         /** All known Sones. */
178         private final Set<String> knownSones = new HashSet<String>();
179
180         /** The post database. */
181         private final Database database;
182
183         /** All bookmarked posts. */
184         /* synchronize access on itself. */
185         private final Set<String> bookmarkedPosts = new HashSet<String>();
186
187         /** Trusted identities, sorted by own identities. */
188         private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
189
190         /** All temporary images. */
191         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
192
193         /** Ticker for threads that mark own elements as known. */
194         private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
195
196         /** The time the configuration was last touched. */
197         private volatile long lastConfigurationUpdate;
198
199         /**
200          * Creates a new core.
201          *
202          * @param configuration
203          *            The configuration of the core
204          * @param freenetInterface
205          *            The freenet interface
206          * @param identityManager
207          *            The identity manager
208          * @param webOfTrustUpdater
209          *            The WebOfTrust updater
210          * @param eventBus
211          *            The event bus
212          * @param database
213          *            The database
214          */
215         @Inject
216         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
217                 super("Sone Core");
218                 this.configuration = configuration;
219                 this.freenetInterface = freenetInterface;
220                 this.identityManager = identityManager;
221                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
222                 this.imageInserter = new ImageInserter(freenetInterface);
223                 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
224                 this.webOfTrustUpdater = webOfTrustUpdater;
225                 this.eventBus = eventBus;
226                 this.database = database;
227         }
228
229         //
230         // ACCESSORS
231         //
232
233         /**
234          * Returns the time Sone was started.
235          *
236          * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
237          */
238         public long getStartupTime() {
239                 return startupTime;
240         }
241
242         /**
243          * Returns the options used by the core.
244          *
245          * @return The options of the core
246          */
247         public Preferences getPreferences() {
248                 return preferences;
249         }
250
251         /**
252          * Returns the identity manager used by the core.
253          *
254          * @return The identity manager
255          */
256         public IdentityManager getIdentityManager() {
257                 return identityManager;
258         }
259
260         /**
261          * Returns the update checker.
262          *
263          * @return The update checker
264          */
265         public UpdateChecker getUpdateChecker() {
266                 return updateChecker;
267         }
268
269         /**
270          * Sets the FCP interface to use.
271          *
272          * @param fcpInterface
273          *            The FCP interface to use
274          */
275         public void setFcpInterface(FcpInterface fcpInterface) {
276                 this.fcpInterface = fcpInterface;
277         }
278
279         /**
280          * Returns the Sone rescuer for the given local Sone.
281          *
282          * @param sone
283          *            The local Sone to get the rescuer for
284          * @return The Sone rescuer for the given Sone
285          */
286         public SoneRescuer getSoneRescuer(Sone sone) {
287                 checkNotNull(sone, "sone must not be null");
288                 checkArgument(sone.isLocal(), "sone must be local");
289                 synchronized (sones) {
290                         SoneRescuer soneRescuer = soneRescuers.get(sone);
291                         if (soneRescuer == null) {
292                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
293                                 soneRescuers.put(sone, soneRescuer);
294                                 soneRescuer.start();
295                         }
296                         return soneRescuer;
297                 }
298         }
299
300         /**
301          * Returns whether the given Sone is currently locked.
302          *
303          * @param sone
304          *            The sone to check
305          * @return {@code true} if the Sone is locked, {@code false} if it is not
306          */
307         public boolean isLocked(Sone sone) {
308                 synchronized (lockedSones) {
309                         return lockedSones.contains(sone);
310                 }
311         }
312
313         /**
314          * {@inheritDocs}
315          */
316         @Override
317         public Collection<Sone> getSones() {
318                 synchronized (sones) {
319                         return ImmutableSet.copyOf(sones.values());
320                 }
321         }
322
323         /**
324          * Returns the Sone with the given ID, regardless whether it’s local or
325          * remote.
326          *
327          * @param id
328          *            The ID of the Sone to get
329          * @return The Sone with the given ID, or {@code null} if there is no such
330          *         Sone
331          */
332         @Override
333         public Optional<Sone> getSone(String id) {
334                 synchronized (sones) {
335                         return Optional.fromNullable(sones.get(id));
336                 }
337         }
338
339         /**
340          * {@inheritDocs}
341          */
342         @Override
343         public Collection<Sone> getLocalSones() {
344                 synchronized (sones) {
345                         return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
346                 }
347         }
348
349         /**
350          * Returns the local Sone with the given ID, optionally creating a new Sone.
351          *
352          * @param id
353          *            The ID of the Sone
354          * @param create
355          *            {@code true} to create a new Sone if none exists,
356          *            {@code false} to return null if none exists
357          * @return The Sone with the given ID, or {@code null}
358          */
359         public Sone getLocalSone(String id, boolean create) {
360                 synchronized (sones) {
361                         Sone sone = sones.get(id);
362                         if ((sone == null) && create) {
363                                 sone = new SoneImpl(id, true);
364                                 sones.put(id, sone);
365                         }
366                         if ((sone != null) && !sone.isLocal()) {
367                                 sone = new SoneImpl(id, true);
368                                 sones.put(id, sone);
369                         }
370                         return sone;
371                 }
372         }
373
374         /**
375          * {@inheritDocs}
376          */
377         @Override
378         public Collection<Sone> getRemoteSones() {
379                 synchronized (sones) {
380                         return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
381                 }
382         }
383
384         /**
385          * Returns the remote Sone with the given ID.
386          *
387          * @param id
388          *            The ID of the remote Sone to get
389          * @param create
390          *            {@code true} to always create a Sone, {@code false} to return
391          *            {@code null} if no Sone with the given ID exists
392          * @return The Sone with the given ID
393          */
394         public Sone getRemoteSone(String id, boolean create) {
395                 synchronized (sones) {
396                         Sone sone = sones.get(id);
397                         if ((sone == null) && create && (id != null) && (id.length() == 43)) {
398                                 sone = new SoneImpl(id, false);
399                                 sones.put(id, sone);
400                         }
401                         return sone;
402                 }
403         }
404
405         /**
406          * Returns whether the given Sone has been modified.
407          *
408          * @param sone
409          *            The Sone to check for modifications
410          * @return {@code true} if a modification has been detected in the Sone,
411          *         {@code false} otherwise
412          */
413         public boolean isModifiedSone(Sone sone) {
414                 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
415         }
416
417         /**
418          * Returns the time when the given was first followed by any local Sone.
419          *
420          * @param sone
421          *            The Sone to get the time for
422          * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
423          *         been followed, or {@link Long#MAX_VALUE}
424          */
425         public long getSoneFollowingTime(Sone sone) {
426                 synchronized (soneFollowingTimes) {
427                         return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
428                 }
429         }
430
431         /**
432          * Returns whether the target Sone is trusted by the origin Sone.
433          *
434          * @param origin
435          *            The origin Sone
436          * @param target
437          *            The target Sone
438          * @return {@code true} if the target Sone is trusted by the origin Sone
439          */
440         public boolean isSoneTrusted(Sone origin, Sone target) {
441                 checkNotNull(origin, "origin must not be null");
442                 checkNotNull(target, "target must not be null");
443                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
444                 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
445         }
446
447         /**
448          * Returns a post builder.
449          *
450          * @return A new post builder
451          */
452         public PostBuilder postBuilder() {
453                 return database.newPostBuilder();
454         }
455
456         /**
457          * {@inheritDoc}
458          */
459         @Override
460         public Optional<Post> getPost(String postId) {
461                 return database.getPost(postId);
462         }
463
464         /**
465          * {@inheritDocs}
466          */
467         @Override
468         public Collection<Post> getPosts(String soneId) {
469                 return database.getPosts(soneId);
470         }
471
472         /**
473          * {@inheritDoc}
474          */
475         @Override
476         public Collection<Post> getDirectedPosts(final String recipientId) {
477                 checkNotNull(recipientId, "recipient must not be null");
478                 return database.getDirectedPosts(recipientId);
479         }
480
481         /**
482          * Returns a post reply builder.
483          *
484          * @return A new post reply builder
485          */
486         public PostReplyBuilder postReplyBuilder() {
487                 return database.newPostReplyBuilder();
488         }
489
490         /**
491          * {@inheritDoc}
492          */
493         @Override
494         public Optional<PostReply> getPostReply(String replyId) {
495                 return database.getPostReply(replyId);
496         }
497
498         /**
499          * {@inheritDoc}
500          */
501         @Override
502         public List<PostReply> getReplies(final String postId) {
503                 return database.getReplies(postId);
504         }
505
506         /**
507          * Returns all Sones that have liked the given post.
508          *
509          * @param post
510          *            The post to get the liking Sones for
511          * @return The Sones that like the given post
512          */
513         public Set<Sone> getLikes(Post post) {
514                 Set<Sone> sones = new HashSet<Sone>();
515                 for (Sone sone : getSones()) {
516                         if (sone.getLikedPostIds().contains(post.getId())) {
517                                 sones.add(sone);
518                         }
519                 }
520                 return sones;
521         }
522
523         /**
524          * Returns all Sones that have liked the given reply.
525          *
526          * @param reply
527          *            The reply to get the liking Sones for
528          * @return The Sones that like the given reply
529          */
530         public Set<Sone> getLikes(PostReply reply) {
531                 Set<Sone> sones = new HashSet<Sone>();
532                 for (Sone sone : getSones()) {
533                         if (sone.getLikedReplyIds().contains(reply.getId())) {
534                                 sones.add(sone);
535                         }
536                 }
537                 return sones;
538         }
539
540         /**
541          * Returns whether the given post is bookmarked.
542          *
543          * @param post
544          *            The post to check
545          * @return {@code true} if the given post is bookmarked, {@code false}
546          *         otherwise
547          */
548         public boolean isBookmarked(Post post) {
549                 return isPostBookmarked(post.getId());
550         }
551
552         /**
553          * Returns whether the post with the given ID is bookmarked.
554          *
555          * @param id
556          *            The ID of the post to check
557          * @return {@code true} if the post with the given ID is bookmarked,
558          *         {@code false} otherwise
559          */
560         public boolean isPostBookmarked(String id) {
561                 synchronized (bookmarkedPosts) {
562                         return bookmarkedPosts.contains(id);
563                 }
564         }
565
566         /**
567          * Returns all currently known bookmarked posts.
568          *
569          * @return All bookmarked posts
570          */
571         public Set<Post> getBookmarkedPosts() {
572                 Set<Post> posts = new HashSet<Post>();
573                 synchronized (bookmarkedPosts) {
574                         for (String bookmarkedPostId : bookmarkedPosts) {
575                                 Optional<Post> post = getPost(bookmarkedPostId);
576                                 if (post.isPresent()) {
577                                         posts.add(post.get());
578                                 }
579                         }
580                 }
581                 return posts;
582         }
583
584         /**
585          * Returns the album with the given ID, creating a new album if no album
586          * with the given ID can be found.
587          *
588          * @param albumId
589          *            The ID of the album
590          * @return The album with the given ID
591          */
592         public Album getAlbum(String albumId) {
593                 return getAlbum(albumId, true);
594         }
595
596         /**
597          * Returns the album with the given ID, optionally creating a new album if
598          * an album with the given ID can not be found.
599          *
600          * @param albumId
601          *            The ID of the album
602          * @param create
603          *            {@code true} to create a new album if none exists for the
604          *            given ID
605          * @return The album with the given ID, or {@code null} if no album with the
606          *         given ID exists and {@code create} is {@code false}
607          */
608         public Album getAlbum(String albumId, boolean create) {
609                 Optional<Album> album = database.getAlbum(albumId);
610                 if (album.isPresent()) {
611                         return album.get();
612                 }
613                 if (!create) {
614                         return null;
615                 }
616                 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
617                 database.storeAlbum(newAlbum);
618                 return newAlbum;
619         }
620
621         /**
622          * Returns the image with the given ID, creating it if necessary.
623          *
624          * @param imageId
625          *            The ID of the image
626          * @return The image with the given ID
627          */
628         public Image getImage(String imageId) {
629                 return getImage(imageId, true);
630         }
631
632         /**
633          * Returns the image with the given ID, optionally creating it if it does
634          * not exist.
635          *
636          * @param imageId
637          *            The ID of the image
638          * @param create
639          *            {@code true} to create an image if none exists with the given
640          *            ID
641          * @return The image with the given ID, or {@code null} if none exists and
642          *         none was created
643          */
644         public Image getImage(String imageId, boolean create) {
645                 Optional<Image> image = database.getImage(imageId);
646                 if (image.isPresent()) {
647                         return image.get();
648                 }
649                 if (!create) {
650                         return null;
651                 }
652                 Image newImage = database.newImageBuilder().withId(imageId).build();
653                 database.storeImage(newImage);
654                 return newImage;
655         }
656
657         /**
658          * Returns the temporary image with the given ID.
659          *
660          * @param imageId
661          *            The ID of the temporary image
662          * @return The temporary image, or {@code null} if there is no temporary
663          *         image with the given ID
664          */
665         public TemporaryImage getTemporaryImage(String imageId) {
666                 synchronized (temporaryImages) {
667                         return temporaryImages.get(imageId);
668                 }
669         }
670
671         //
672         // ACTIONS
673         //
674
675         /**
676          * Locks the given Sone. A locked Sone will not be inserted by
677          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
678          * again.
679          *
680          * @param sone
681          *            The sone to lock
682          */
683         public void lockSone(Sone sone) {
684                 synchronized (lockedSones) {
685                         if (lockedSones.add(sone)) {
686                                 eventBus.post(new SoneLockedEvent(sone));
687                         }
688                 }
689         }
690
691         /**
692          * Unlocks the given Sone.
693          *
694          * @see #lockSone(Sone)
695          * @param sone
696          *            The sone to unlock
697          */
698         public void unlockSone(Sone sone) {
699                 synchronized (lockedSones) {
700                         if (lockedSones.remove(sone)) {
701                                 eventBus.post(new SoneUnlockedEvent(sone));
702                         }
703                 }
704         }
705
706         /**
707          * Adds a local Sone from the given own identity.
708          *
709          * @param ownIdentity
710          *            The own identity to create a Sone from
711          * @return The added (or already existing) Sone
712          */
713         public Sone addLocalSone(OwnIdentity ownIdentity) {
714                 if (ownIdentity == null) {
715                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
716                         return null;
717                 }
718                 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
719                 synchronized (sones) {
720                         final Sone sone;
721                         try {
722                                 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
723                         } catch (MalformedURLException mue1) {
724                                 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
725                                 return null;
726                         }
727                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
728                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
729                         sone.setKnown(true);
730                         /* TODO - load posts ’n stuff */
731                         sones.put(ownIdentity.getId(), sone);
732                         final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
733                         soneInserters.put(sone, soneInserter);
734                         sone.setStatus(SoneStatus.idle);
735                         loadSone(sone);
736                         soneInserter.start();
737                         return sone;
738                 }
739         }
740
741         /**
742          * Creates a new Sone for the given own identity.
743          *
744          * @param ownIdentity
745          *            The own identity to create a Sone for
746          * @return The created Sone
747          */
748         public Sone createSone(OwnIdentity ownIdentity) {
749                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
750                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
751                         return null;
752                 }
753                 Sone sone = addLocalSone(ownIdentity);
754                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
755                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
756                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
757                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
758                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
759                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
760
761                 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
762                 touchConfiguration();
763                 return sone;
764         }
765
766         /**
767          * Adds the Sone of the given identity.
768          *
769          * @param identity
770          *            The identity whose Sone to add
771          * @return The added or already existing Sone
772          */
773         public Sone addRemoteSone(Identity identity) {
774                 if (identity == null) {
775                         logger.log(Level.WARNING, "Given Identity is null!");
776                         return null;
777                 }
778                 synchronized (sones) {
779                         final Sone sone = getRemoteSone(identity.getId(), true);
780                         if (sone.isLocal()) {
781                                 return sone;
782                         }
783                         sone.setIdentity(identity);
784                         boolean newSone = sone.getRequestUri() == null;
785                         sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
786                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
787                         if (newSone) {
788                                 synchronized (knownSones) {
789                                         newSone = !knownSones.contains(sone.getId());
790                                 }
791                                 sone.setKnown(!newSone);
792                                 if (newSone) {
793                                         eventBus.post(new NewSoneFoundEvent(sone));
794                                         for (Sone localSone : getLocalSones()) {
795                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
796                                                         followSone(localSone, sone.getId());
797                                                 }
798                                         }
799                                 }
800                         }
801                         soneDownloader.addSone(sone);
802                         soneDownloaders.execute(new Runnable() {
803
804                                 @Override
805                                 @SuppressWarnings("synthetic-access")
806                                 public void run() {
807                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
808                                 }
809
810                         });
811                         return sone;
812                 }
813         }
814
815         /**
816          * Lets the given local Sone follow the Sone with the given ID.
817          *
818          * @param sone
819          *            The local Sone that should follow another Sone
820          * @param soneId
821          *            The ID of the Sone to follow
822          */
823         public void followSone(Sone sone, String soneId) {
824                 checkNotNull(sone, "sone must not be null");
825                 checkNotNull(soneId, "soneId must not be null");
826                 sone.addFriend(soneId);
827                 synchronized (soneFollowingTimes) {
828                         if (!soneFollowingTimes.containsKey(soneId)) {
829                                 long now = System.currentTimeMillis();
830                                 soneFollowingTimes.put(soneId, now);
831                                 Optional<Sone> followedSone = getSone(soneId);
832                                 if (!followedSone.isPresent()) {
833                                         return;
834                                 }
835                                 for (Post post : followedSone.get().getPosts()) {
836                                         if (post.getTime() < now) {
837                                                 markPostKnown(post);
838                                         }
839                                 }
840                                 for (PostReply reply : followedSone.get().getReplies()) {
841                                         if (reply.getTime() < now) {
842                                                 markReplyKnown(reply);
843                                         }
844                                 }
845                         }
846                 }
847                 touchConfiguration();
848         }
849
850         /**
851          * Lets the given local Sone unfollow the Sone with the given ID.
852          *
853          * @param sone
854          *            The local Sone that should unfollow another Sone
855          * @param soneId
856          *            The ID of the Sone being unfollowed
857          */
858         public void unfollowSone(Sone sone, String soneId) {
859                 checkNotNull(sone, "sone must not be null");
860                 checkNotNull(soneId, "soneId must not be null");
861                 sone.removeFriend(soneId);
862                 boolean unfollowedSoneStillFollowed = false;
863                 for (Sone localSone : getLocalSones()) {
864                         unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
865                 }
866                 if (!unfollowedSoneStillFollowed) {
867                         synchronized (soneFollowingTimes) {
868                                 soneFollowingTimes.remove(soneId);
869                         }
870                 }
871                 touchConfiguration();
872         }
873
874         /**
875          * Sets the trust value of the given origin Sone for the target Sone.
876          *
877          * @param origin
878          *            The origin Sone
879          * @param target
880          *            The target Sone
881          * @param trustValue
882          *            The trust value (from {@code -100} to {@code 100})
883          */
884         public void setTrust(Sone origin, Sone target, int trustValue) {
885                 checkNotNull(origin, "origin must not be null");
886                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
887                 checkNotNull(target, "target must not be null");
888                 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
889                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
890         }
891
892         /**
893          * Removes any trust assignment for the given target Sone.
894          *
895          * @param origin
896          *            The trust origin
897          * @param target
898          *            The trust target
899          */
900         public void removeTrust(Sone origin, Sone target) {
901                 checkNotNull(origin, "origin must not be null");
902                 checkNotNull(target, "target must not be null");
903                 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
904                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
905         }
906
907         /**
908          * Assigns the configured positive trust value for the given target.
909          *
910          * @param origin
911          *            The trust origin
912          * @param target
913          *            The trust target
914          */
915         public void trustSone(Sone origin, Sone target) {
916                 setTrust(origin, target, preferences.getPositiveTrust());
917         }
918
919         /**
920          * Assigns the configured negative trust value for the given target.
921          *
922          * @param origin
923          *            The trust origin
924          * @param target
925          *            The trust target
926          */
927         public void distrustSone(Sone origin, Sone target) {
928                 setTrust(origin, target, preferences.getNegativeTrust());
929         }
930
931         /**
932          * Removes the trust assignment for the given target.
933          *
934          * @param origin
935          *            The trust origin
936          * @param target
937          *            The trust target
938          */
939         public void untrustSone(Sone origin, Sone target) {
940                 removeTrust(origin, target);
941         }
942
943         /**
944          * Updates the stored Sone with the given Sone.
945          *
946          * @param sone
947          *            The updated Sone
948          */
949         public void updateSone(Sone sone) {
950                 updateSone(sone, false);
951         }
952
953         /**
954          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
955          * {@code true}, an older Sone than the current Sone can be given to restore
956          * an old state.
957          *
958          * @param sone
959          *            The Sone to update
960          * @param soneRescueMode
961          *            {@code true} if the stored Sone should be updated regardless
962          *            of the age of the given Sone
963          */
964         public void updateSone(Sone sone, boolean soneRescueMode) {
965                 Optional<Sone> storedSone = getSone(sone.getId());
966                 if (storedSone.isPresent()) {
967                         if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
968                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
969                                 return;
970                         }
971                         /* find removed posts. */
972                         Collection<Post> removedPosts = new ArrayList<Post>();
973                         Collection<Post> newPosts = new ArrayList<Post>();
974                         Collection<Post> existingPosts = database.getPosts(sone.getId());
975                         for (Post oldPost : existingPosts) {
976                                 if (!sone.getPosts().contains(oldPost)) {
977                                         removedPosts.add(oldPost);
978                                 }
979                         }
980                         /* find new posts. */
981                         for (Post newPost : sone.getPosts()) {
982                                 if (existingPosts.contains(newPost)) {
983                                         continue;
984                                 }
985                                 if (newPost.getTime() < getSoneFollowingTime(sone)) {
986                                         newPost.setKnown(true);
987                                 } else if (!newPost.isKnown()) {
988                                         newPosts.add(newPost);
989                                 }
990                         }
991                         /* store posts. */
992                         database.storePosts(sone, sone.getPosts());
993                         Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
994                         Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
995                         if (!soneRescueMode) {
996                                 for (PostReply reply : storedSone.get().getReplies()) {
997                                         if (!sone.getReplies().contains(reply)) {
998                                                 removedPostReplies.add(reply);
999                                         }
1000                                 }
1001                         }
1002                         Set<PostReply> storedReplies = storedSone.get().getReplies();
1003                         for (PostReply reply : sone.getReplies()) {
1004                                 if (storedReplies.contains(reply)) {
1005                                         continue;
1006                                 }
1007                                 if (reply.getTime() < getSoneFollowingTime(sone)) {
1008                                         reply.setKnown(true);
1009                                 } else if (!reply.isKnown()) {
1010                                         newPostReplies.add(reply);
1011                                 }
1012                         }
1013                         database.storePostReplies(sone, sone.getReplies());
1014                         for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1015                                 database.removeAlbum(album);
1016                                 for (Image image : album.getImages()) {
1017                                         database.removeImage(image);
1018                                 }
1019                         }
1020                         for (Post removedPost : removedPosts) {
1021                                 eventBus.post(new PostRemovedEvent(removedPost));
1022                         }
1023                         for (Post newPost : newPosts) {
1024                                 eventBus.post(new NewPostFoundEvent(newPost));
1025                         }
1026                         for (PostReply removedPostReply : removedPostReplies) {
1027                                 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1028                         }
1029                         for (PostReply newPostReply : newPostReplies) {
1030                                 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1031                         }
1032                         for (Album album : sone.getRootAlbum().getAlbums()) {
1033                                 database.storeAlbum(album);
1034                                 for (Image image : album.getImages()) {
1035                                         database.storeImage(image);
1036                                 }
1037                         }
1038                         synchronized (sones) {
1039                                 sone.setOptions(storedSone.get().getOptions());
1040                                 sone.setKnown(storedSone.get().isKnown());
1041                                 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1042                                 if (sone.isLocal()) {
1043                                         soneInserters.get(storedSone.get()).setSone(sone);
1044                                         touchConfiguration();
1045                                 }
1046                                 sones.put(sone.getId(), sone);
1047                         }
1048                 }
1049         }
1050
1051         /**
1052          * Deletes the given Sone. This will remove the Sone from the
1053          * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1054          * remove the context from its identity.
1055          *
1056          * @param sone
1057          *            The Sone to delete
1058          */
1059         public void deleteSone(Sone sone) {
1060                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1061                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1062                         return;
1063                 }
1064                 synchronized (sones) {
1065                         if (!getLocalSones().contains(sone)) {
1066                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1067                                 return;
1068                         }
1069                         sones.remove(sone.getId());
1070                         SoneInserter soneInserter = soneInserters.remove(sone);
1071                         soneInserter.stop();
1072                 }
1073                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1074                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1075                 try {
1076                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1077                 } catch (ConfigurationException ce1) {
1078                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1079                 }
1080         }
1081
1082         /**
1083          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1084          * known} before, a {@link MarkSoneKnownEvent} is fired.
1085          *
1086          * @param sone
1087          *            The Sone to mark as known
1088          */
1089         public void markSoneKnown(Sone sone) {
1090                 if (!sone.isKnown()) {
1091                         sone.setKnown(true);
1092                         synchronized (knownSones) {
1093                                 knownSones.add(sone.getId());
1094                         }
1095                         eventBus.post(new MarkSoneKnownEvent(sone));
1096                         touchConfiguration();
1097                 }
1098         }
1099
1100         /**
1101          * Loads and updates the given Sone from the configuration. If any error is
1102          * encountered, loading is aborted and the given Sone is not changed.
1103          *
1104          * @param sone
1105          *            The Sone to load and update
1106          */
1107         public void loadSone(Sone sone) {
1108                 if (!sone.isLocal()) {
1109                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1110                         return;
1111                 }
1112                 logger.info(String.format("Loading local Sone: %s", sone));
1113
1114                 /* initialize options. */
1115                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1116                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1117                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1118                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1119                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1120                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1121
1122                 /* load Sone. */
1123                 String sonePrefix = "Sone/" + sone.getId();
1124                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1125                 if (soneTime == null) {
1126                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1127                         return;
1128                 }
1129                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1130
1131                 /* load profile. */
1132                 Profile profile = new Profile(sone);
1133                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1134                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1135                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1136                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1137                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1138                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1139
1140                 /* load profile fields. */
1141                 while (true) {
1142                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1143                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1144                         if (fieldName == null) {
1145                                 break;
1146                         }
1147                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1148                         profile.addField(fieldName).setValue(fieldValue);
1149                 }
1150
1151                 /* load posts. */
1152                 Set<Post> posts = new HashSet<Post>();
1153                 while (true) {
1154                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1155                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1156                         if (postId == null) {
1157                                 break;
1158                         }
1159                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1160                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1161                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1162                         if ((postTime == 0) || (postText == null)) {
1163                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1164                                 return;
1165                         }
1166                         PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1167                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1168                                 postBuilder.to(postRecipientId);
1169                         }
1170                         posts.add(postBuilder.build());
1171                 }
1172
1173                 /* load replies. */
1174                 Set<PostReply> replies = new HashSet<PostReply>();
1175                 while (true) {
1176                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1177                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1178                         if (replyId == null) {
1179                                 break;
1180                         }
1181                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1182                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1183                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1184                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1185                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1186                                 return;
1187                         }
1188                         PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1189                         replies.add(postReplyBuilder.build());
1190                 }
1191
1192                 /* load post likes. */
1193                 Set<String> likedPostIds = new HashSet<String>();
1194                 while (true) {
1195                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1196                         if (likedPostId == null) {
1197                                 break;
1198                         }
1199                         likedPostIds.add(likedPostId);
1200                 }
1201
1202                 /* load reply likes. */
1203                 Set<String> likedReplyIds = new HashSet<String>();
1204                 while (true) {
1205                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1206                         if (likedReplyId == null) {
1207                                 break;
1208                         }
1209                         likedReplyIds.add(likedReplyId);
1210                 }
1211
1212                 /* load friends. */
1213                 Set<String> friends = new HashSet<String>();
1214                 while (true) {
1215                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1216                         if (friendId == null) {
1217                                 break;
1218                         }
1219                         friends.add(friendId);
1220                 }
1221
1222                 /* load albums. */
1223                 List<Album> topLevelAlbums = new ArrayList<Album>();
1224                 int albumCounter = 0;
1225                 while (true) {
1226                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1227                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1228                         if (albumId == null) {
1229                                 break;
1230                         }
1231                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1232                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1233                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1234                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1235                         if ((albumTitle == null) || (albumDescription == null)) {
1236                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1237                                 return;
1238                         }
1239                         Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1240                         if (albumParentId != null) {
1241                                 Album parentAlbum = getAlbum(albumParentId, false);
1242                                 if (parentAlbum == null) {
1243                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1244                                         return;
1245                                 }
1246                                 parentAlbum.addAlbum(album);
1247                         } else {
1248                                 if (!topLevelAlbums.contains(album)) {
1249                                         topLevelAlbums.add(album);
1250                                 }
1251                         }
1252                 }
1253
1254                 /* load images. */
1255                 int imageCounter = 0;
1256                 while (true) {
1257                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1258                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1259                         if (imageId == null) {
1260                                 break;
1261                         }
1262                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1263                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1264                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1265                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1266                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1267                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1268                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1269                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1270                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1271                                 return;
1272                         }
1273                         Album album = getAlbum(albumId, false);
1274                         if (album == null) {
1275                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1276                                 return;
1277                         }
1278                         Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1279                         album.addImage(image);
1280                 }
1281
1282                 /* load avatar. */
1283                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1284                 if (avatarId != null) {
1285                         profile.setAvatar(getImage(avatarId, false));
1286                 }
1287
1288                 /* load options. */
1289                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1290                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1291                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1292                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1293                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1294                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1295
1296                 /* if we’re still here, Sone was loaded successfully. */
1297                 synchronized (sone) {
1298                         sone.setTime(soneTime);
1299                         sone.setProfile(profile);
1300                         sone.setPosts(posts);
1301                         sone.setReplies(replies);
1302                         sone.setLikePostIds(likedPostIds);
1303                         sone.setLikeReplyIds(likedReplyIds);
1304                         for (String friendId : friends) {
1305                                 followSone(sone, friendId);
1306                         }
1307                         for (Album album : sone.getRootAlbum().getAlbums()) {
1308                                 sone.getRootAlbum().removeAlbum(album);
1309                         }
1310                         for (Album album : topLevelAlbums) {
1311                                 sone.getRootAlbum().addAlbum(album);
1312                         }
1313                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1314                 }
1315                 synchronized (knownSones) {
1316                         for (String friend : friends) {
1317                                 knownSones.add(friend);
1318                         }
1319                 }
1320                 database.storePosts(sone, posts);
1321                 for (Post post : posts) {
1322                         post.setKnown(true);
1323                 }
1324                 database.storePostReplies(sone, replies);
1325                 for (PostReply reply : replies) {
1326                         reply.setKnown(true);
1327                 }
1328
1329                 logger.info(String.format("Sone loaded successfully: %s", sone));
1330         }
1331
1332         /**
1333          * Creates a new post.
1334          *
1335          * @param sone
1336          *            The Sone that creates the post
1337          * @param text
1338          *            The text of the post
1339          * @return The created post
1340          */
1341         public Post createPost(Sone sone, String text) {
1342                 return createPost(sone, System.currentTimeMillis(), text);
1343         }
1344
1345         /**
1346          * Creates a new post.
1347          *
1348          * @param sone
1349          *            The Sone that creates the post
1350          * @param time
1351          *            The time of the post
1352          * @param text
1353          *            The text of the post
1354          * @return The created post
1355          */
1356         public Post createPost(Sone sone, long time, String text) {
1357                 return createPost(sone, null, time, text);
1358         }
1359
1360         /**
1361          * Creates a new post.
1362          *
1363          * @param sone
1364          *            The Sone that creates the post
1365          * @param recipient
1366          *            The recipient Sone, or {@code null} if this post does not have
1367          *            a recipient
1368          * @param text
1369          *            The text of the post
1370          * @return The created post
1371          */
1372         public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1373                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1374         }
1375
1376         /**
1377          * Creates a new post.
1378          *
1379          * @param sone
1380          *            The Sone that creates the post
1381          * @param recipient
1382          *            The recipient Sone, or {@code null} if this post does not have
1383          *            a recipient
1384          * @param time
1385          *            The time of the post
1386          * @param text
1387          *            The text of the post
1388          * @return The created post
1389          */
1390         public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1391                 checkNotNull(text, "text must not be null");
1392                 checkArgument(text.trim().length() > 0, "text must not be empty");
1393                 if (!sone.isLocal()) {
1394                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1395                         return null;
1396                 }
1397                 PostBuilder postBuilder = database.newPostBuilder();
1398                 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1399                 if (recipient.isPresent()) {
1400                         postBuilder.to(recipient.get().getId());
1401                 }
1402                 final Post post = postBuilder.build();
1403                 database.storePost(post);
1404                 eventBus.post(new NewPostFoundEvent(post));
1405                 sone.addPost(post);
1406                 touchConfiguration();
1407                 localElementTicker.schedule(new Runnable() {
1408
1409                         /**
1410                          * {@inheritDoc}
1411                          */
1412                         @Override
1413                         public void run() {
1414                                 markPostKnown(post);
1415                         }
1416                 }, 10, TimeUnit.SECONDS);
1417                 return post;
1418         }
1419
1420         /**
1421          * Deletes the given post.
1422          *
1423          * @param post
1424          *            The post to delete
1425          */
1426         public void deletePost(Post post) {
1427                 if (!post.getSone().isLocal()) {
1428                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1429                         return;
1430                 }
1431                 database.removePost(post);
1432                 eventBus.post(new PostRemovedEvent(post));
1433                 markPostKnown(post);
1434                 touchConfiguration();
1435         }
1436
1437         /**
1438          * Marks the given post as known, if it is currently not a known post
1439          * (according to {@link Post#isKnown()}).
1440          *
1441          * @param post
1442          *            The post to mark as known
1443          */
1444         public void markPostKnown(Post post) {
1445                 post.setKnown(true);
1446                 eventBus.post(new MarkPostKnownEvent(post));
1447                 touchConfiguration();
1448                 for (PostReply reply : getReplies(post.getId())) {
1449                         markReplyKnown(reply);
1450                 }
1451         }
1452
1453         /**
1454          * Bookmarks the given post.
1455          *
1456          * @param post
1457          *            The post to bookmark
1458          */
1459         public void bookmark(Post post) {
1460                 bookmarkPost(post.getId());
1461         }
1462
1463         /**
1464          * Bookmarks the post with the given ID.
1465          *
1466          * @param id
1467          *            The ID of the post to bookmark
1468          */
1469         public void bookmarkPost(String id) {
1470                 synchronized (bookmarkedPosts) {
1471                         bookmarkedPosts.add(id);
1472                 }
1473         }
1474
1475         /**
1476          * Removes the given post from the bookmarks.
1477          *
1478          * @param post
1479          *            The post to unbookmark
1480          */
1481         public void unbookmark(Post post) {
1482                 unbookmarkPost(post.getId());
1483         }
1484
1485         /**
1486          * Removes the post with the given ID from the bookmarks.
1487          *
1488          * @param id
1489          *            The ID of the post to unbookmark
1490          */
1491         public void unbookmarkPost(String id) {
1492                 synchronized (bookmarkedPosts) {
1493                         bookmarkedPosts.remove(id);
1494                 }
1495         }
1496
1497         /**
1498          * Creates a new reply.
1499          *
1500          * @param sone
1501          *            The Sone that creates the reply
1502          * @param post
1503          *            The post that this reply refers to
1504          * @param text
1505          *            The text of the reply
1506          * @return The created reply
1507          */
1508         public PostReply createReply(Sone sone, Post post, String text) {
1509                 checkNotNull(text, "text must not be null");
1510                 checkArgument(text.trim().length() > 0, "text must not be empty");
1511                 if (!sone.isLocal()) {
1512                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1513                         return null;
1514                 }
1515                 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1516                 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1517                 final PostReply reply = postReplyBuilder.build();
1518                 database.storePostReply(reply);
1519                 eventBus.post(new NewPostReplyFoundEvent(reply));
1520                 sone.addReply(reply);
1521                 touchConfiguration();
1522                 localElementTicker.schedule(new Runnable() {
1523
1524                         /**
1525                          * {@inheritDoc}
1526                          */
1527                         @Override
1528                         public void run() {
1529                                 markReplyKnown(reply);
1530                         }
1531                 }, 10, TimeUnit.SECONDS);
1532                 return reply;
1533         }
1534
1535         /**
1536          * Deletes the given reply.
1537          *
1538          * @param reply
1539          *            The reply to delete
1540          */
1541         public void deleteReply(PostReply reply) {
1542                 Sone sone = reply.getSone();
1543                 if (!sone.isLocal()) {
1544                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1545                         return;
1546                 }
1547                 database.removePostReply(reply);
1548                 markReplyKnown(reply);
1549                 sone.removeReply(reply);
1550                 touchConfiguration();
1551         }
1552
1553         /**
1554          * Marks the given reply as known, if it is currently not a known reply
1555          * (according to {@link Reply#isKnown()}).
1556          *
1557          * @param reply
1558          *            The reply to mark as known
1559          */
1560         public void markReplyKnown(PostReply reply) {
1561                 boolean previouslyKnown = reply.isKnown();
1562                 reply.setKnown(true);
1563                 eventBus.post(new MarkPostReplyKnownEvent(reply));
1564                 if (!previouslyKnown) {
1565                         touchConfiguration();
1566                 }
1567         }
1568
1569         /**
1570          * Creates a new top-level album for the given Sone.
1571          *
1572          * @param sone
1573          *            The Sone to create the album for
1574          * @return The new album
1575          */
1576         public Album createAlbum(Sone sone) {
1577                 return createAlbum(sone, sone.getRootAlbum());
1578         }
1579
1580         /**
1581          * Creates a new album for the given Sone.
1582          *
1583          * @param sone
1584          *            The Sone to create the album for
1585          * @param parent
1586          *            The parent of the album (may be {@code null} to create a
1587          *            top-level album)
1588          * @return The new album
1589          */
1590         public Album createAlbum(Sone sone, Album parent) {
1591                 Album album = database.newAlbumBuilder().randomId().build();
1592                 database.storeAlbum(album);
1593                 album.setSone(sone);
1594                 parent.addAlbum(album);
1595                 return album;
1596         }
1597
1598         /**
1599          * Deletes the given album. The owner of the album has to be a local Sone,
1600          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1601          *
1602          * @param album
1603          *            The album to remove
1604          */
1605         public void deleteAlbum(Album album) {
1606                 checkNotNull(album, "album must not be null");
1607                 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1608                 if (!album.isEmpty()) {
1609                         return;
1610                 }
1611                 album.getParent().removeAlbum(album);
1612                 database.removeAlbum(album);
1613                 touchConfiguration();
1614         }
1615
1616         /**
1617          * Creates a new image.
1618          *
1619          * @param sone
1620          *            The Sone creating the image
1621          * @param album
1622          *            The album the image will be inserted into
1623          * @param temporaryImage
1624          *            The temporary image to create the image from
1625          * @return The newly created image
1626          */
1627         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1628                 checkNotNull(sone, "sone must not be null");
1629                 checkNotNull(album, "album must not be null");
1630                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1631                 checkArgument(sone.isLocal(), "sone must be a local Sone");
1632                 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1633                 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1634                 album.addImage(image);
1635                 database.storeImage(image);
1636                 imageInserter.insertImage(temporaryImage, image);
1637                 return image;
1638         }
1639
1640         /**
1641          * Deletes the given image. This method will also delete a matching
1642          * temporary image.
1643          *
1644          * @see #deleteTemporaryImage(TemporaryImage)
1645          * @param image
1646          *            The image to delete
1647          */
1648         public void deleteImage(Image image) {
1649                 checkNotNull(image, "image must not be null");
1650                 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1651                 deleteTemporaryImage(image.getId());
1652                 image.getAlbum().removeImage(image);
1653                 database.removeImage(image);
1654                 touchConfiguration();
1655         }
1656
1657         /**
1658          * Creates a new temporary image.
1659          *
1660          * @param mimeType
1661          *            The MIME type of the temporary image
1662          * @param imageData
1663          *            The encoded data of the image
1664          * @return The temporary image
1665          */
1666         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1667                 TemporaryImage temporaryImage = new TemporaryImage();
1668                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1669                 synchronized (temporaryImages) {
1670                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1671                 }
1672                 return temporaryImage;
1673         }
1674
1675         /**
1676          * Deletes the given temporary image.
1677          *
1678          * @param temporaryImage
1679          *            The temporary image to delete
1680          */
1681         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1682                 checkNotNull(temporaryImage, "temporaryImage must not be null");
1683                 deleteTemporaryImage(temporaryImage.getId());
1684         }
1685
1686         /**
1687          * Deletes the temporary image with the given ID.
1688          *
1689          * @param imageId
1690          *            The ID of the temporary image to delete
1691          */
1692         public void deleteTemporaryImage(String imageId) {
1693                 checkNotNull(imageId, "imageId must not be null");
1694                 synchronized (temporaryImages) {
1695                         temporaryImages.remove(imageId);
1696                 }
1697                 Image image = getImage(imageId, false);
1698                 if (image != null) {
1699                         imageInserter.cancelImageInsert(image);
1700                 }
1701         }
1702
1703         /**
1704          * Notifies the core that the configuration, either of the core or of a
1705          * single local Sone, has changed, and that the configuration should be
1706          * saved.
1707          */
1708         public void touchConfiguration() {
1709                 lastConfigurationUpdate = System.currentTimeMillis();
1710         }
1711
1712         //
1713         // SERVICE METHODS
1714         //
1715
1716         /**
1717          * Starts the core.
1718          */
1719         @Override
1720         public void serviceStart() {
1721                 loadConfiguration();
1722                 updateChecker.start();
1723                 identityManager.start();
1724                 webOfTrustUpdater.init();
1725                 webOfTrustUpdater.start();
1726                 database.start();
1727         }
1728
1729         /**
1730          * {@inheritDoc}
1731          */
1732         @Override
1733         public void serviceRun() {
1734                 long lastSaved = System.currentTimeMillis();
1735                 while (!shouldStop()) {
1736                         sleep(1000);
1737                         long now = System.currentTimeMillis();
1738                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1739                                 for (Sone localSone : getLocalSones()) {
1740                                         saveSone(localSone);
1741                                 }
1742                                 saveConfiguration();
1743                                 lastSaved = now;
1744                         }
1745                 }
1746         }
1747
1748         /**
1749          * Stops the core.
1750          */
1751         @Override
1752         public void serviceStop() {
1753                 localElementTicker.shutdownNow();
1754                 synchronized (sones) {
1755                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1756                                 soneInserter.getValue().stop();
1757                                 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1758                         }
1759                 }
1760                 saveConfiguration();
1761                 database.stop();
1762                 webOfTrustUpdater.stop();
1763                 updateChecker.stop();
1764                 soneDownloader.stop();
1765                 soneDownloaders.shutdown();
1766                 identityManager.stop();
1767         }
1768
1769         //
1770         // PRIVATE METHODS
1771         //
1772
1773         /**
1774          * Saves the given Sone. This will persist all local settings for the given
1775          * Sone, such as the friends list and similar, private options.
1776          *
1777          * @param sone
1778          *            The Sone to save
1779          */
1780         private synchronized void saveSone(Sone sone) {
1781                 if (!sone.isLocal()) {
1782                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1783                         return;
1784                 }
1785                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1786                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1787                         return;
1788                 }
1789
1790                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1791                 try {
1792                         /* save Sone into configuration. */
1793                         String sonePrefix = "Sone/" + sone.getId();
1794                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1795                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1796
1797                         /* save profile. */
1798                         Profile profile = sone.getProfile();
1799                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1800                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1801                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1802                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1803                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1804                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1805                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1806
1807                         /* save profile fields. */
1808                         int fieldCounter = 0;
1809                         for (Field profileField : profile.getFields()) {
1810                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1811                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1812                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1813                         }
1814                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1815
1816                         /* save posts. */
1817                         int postCounter = 0;
1818                         for (Post post : sone.getPosts()) {
1819                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1820                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1821                                 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1822                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1823                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1824                         }
1825                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1826
1827                         /* save replies. */
1828                         int replyCounter = 0;
1829                         for (PostReply reply : sone.getReplies()) {
1830                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1831                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1832                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1833                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1834                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1835                         }
1836                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1837
1838                         /* save post likes. */
1839                         int postLikeCounter = 0;
1840                         for (String postId : sone.getLikedPostIds()) {
1841                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1842                         }
1843                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1844
1845                         /* save reply likes. */
1846                         int replyLikeCounter = 0;
1847                         for (String replyId : sone.getLikedReplyIds()) {
1848                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1849                         }
1850                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1851
1852                         /* save friends. */
1853                         int friendCounter = 0;
1854                         for (String friendId : sone.getFriends()) {
1855                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1856                         }
1857                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1858
1859                         /* save albums. first, collect in a flat structure, top-level first. */
1860                         List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1861
1862                         int albumCounter = 0;
1863                         for (Album album : albums) {
1864                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1865                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1866                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1867                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1868                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1869                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1870                         }
1871                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1872
1873                         /* save images. */
1874                         int imageCounter = 0;
1875                         for (Album album : albums) {
1876                                 for (Image image : album.getImages()) {
1877                                         if (!image.isInserted()) {
1878                                                 continue;
1879                                         }
1880                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1881                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1882                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1883                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1884                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1885                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1886                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1887                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1888                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1889                                 }
1890                         }
1891                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1892
1893                         /* save options. */
1894                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1895                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1896                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1897                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1898                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1899                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1900
1901                         configuration.save();
1902
1903                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1904
1905                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1906                 } catch (ConfigurationException ce1) {
1907                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1908                 }
1909         }
1910
1911         /**
1912          * Saves the current options.
1913          */
1914         private void saveConfiguration() {
1915                 synchronized (configuration) {
1916                         if (storingConfiguration) {
1917                                 logger.log(Level.FINE, "Already storing configuration…");
1918                                 return;
1919                         }
1920                         storingConfiguration = true;
1921                 }
1922
1923                 /* store the options first. */
1924                 try {
1925                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1926                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1927                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1928                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1929                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1930                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1931                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1932                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1933                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1934                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1935                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1936                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1937
1938                         /* save known Sones. */
1939                         int soneCounter = 0;
1940                         synchronized (knownSones) {
1941                                 for (String knownSoneId : knownSones) {
1942                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1943                                 }
1944                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1945                         }
1946
1947                         /* save Sone following times. */
1948                         soneCounter = 0;
1949                         synchronized (soneFollowingTimes) {
1950                                 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1951                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1952                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1953                                         ++soneCounter;
1954                                 }
1955                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1956                         }
1957
1958                         /* save known posts. */
1959                         database.save();
1960
1961                         /* save bookmarked posts. */
1962                         int bookmarkedPostCounter = 0;
1963                         synchronized (bookmarkedPosts) {
1964                                 for (String bookmarkedPostId : bookmarkedPosts) {
1965                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1966                                 }
1967                         }
1968                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1969
1970                         /* now save it. */
1971                         configuration.save();
1972
1973                 } catch (ConfigurationException ce1) {
1974                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1975                 } catch (DatabaseException de1) {
1976                         logger.log(Level.SEVERE, "Could not save database!", de1);
1977                 } finally {
1978                         synchronized (configuration) {
1979                                 storingConfiguration = false;
1980                         }
1981                 }
1982         }
1983
1984         /**
1985          * Loads the configuration.
1986          */
1987         private void loadConfiguration() {
1988                 /* create options. */
1989                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1990                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1991                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1992                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1993                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1994                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1995                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1996                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1997                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1998                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1999                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
2000
2001                 loadConfigurationValue("InsertionDelay");
2002                 loadConfigurationValue("PostsPerPage");
2003                 loadConfigurationValue("ImagesPerPage");
2004                 loadConfigurationValue("CharactersPerPost");
2005                 loadConfigurationValue("PostCutOffLength");
2006                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2007                 loadConfigurationValue("PositiveTrust");
2008                 loadConfigurationValue("NegativeTrust");
2009                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2010                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2011                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2012
2013                 /* load known Sones. */
2014                 int soneCounter = 0;
2015                 while (true) {
2016                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2017                         if (knownSoneId == null) {
2018                                 break;
2019                         }
2020                         synchronized (knownSones) {
2021                                 knownSones.add(knownSoneId);
2022                         }
2023                 }
2024
2025                 /* load Sone following times. */
2026                 soneCounter = 0;
2027                 while (true) {
2028                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2029                         if (soneId == null) {
2030                                 break;
2031                         }
2032                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2033                         synchronized (soneFollowingTimes) {
2034                                 soneFollowingTimes.put(soneId, time);
2035                         }
2036                         ++soneCounter;
2037                 }
2038
2039                 /* load bookmarked posts. */
2040                 int bookmarkedPostCounter = 0;
2041                 while (true) {
2042                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2043                         if (bookmarkedPostId == null) {
2044                                 break;
2045                         }
2046                         synchronized (bookmarkedPosts) {
2047                                 bookmarkedPosts.add(bookmarkedPostId);
2048                         }
2049                 }
2050
2051         }
2052
2053         /**
2054          * Loads an {@link Integer} configuration value for the option with the
2055          * given name, logging validation failures.
2056          *
2057          * @param optionName
2058          *            The name of the option to load
2059          */
2060         private void loadConfigurationValue(String optionName) {
2061                 try {
2062                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2063                 } catch (IllegalArgumentException iae1) {
2064                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2065                 }
2066         }
2067
2068         /**
2069          * Notifies the core that a new {@link OwnIdentity} was added.
2070          *
2071          * @param ownIdentityAddedEvent
2072          *            The event
2073          */
2074         @Subscribe
2075         public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2076                 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2077                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2078                 if (ownIdentity.hasContext("Sone")) {
2079                         addLocalSone(ownIdentity);
2080                 }
2081         }
2082
2083         /**
2084          * Notifies the core that an {@link OwnIdentity} was removed.
2085          *
2086          * @param ownIdentityRemovedEvent
2087          *            The event
2088          */
2089         @Subscribe
2090         public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2091                 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2092                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2093                 trustedIdentities.removeAll(ownIdentity);
2094         }
2095
2096         /**
2097          * Notifies the core that a new {@link Identity} was added.
2098          *
2099          * @param identityAddedEvent
2100          *            The event
2101          */
2102         @Subscribe
2103         public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2104                 Identity identity = identityAddedEvent.identity();
2105                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2106                 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2107                 addRemoteSone(identity);
2108         }
2109
2110         /**
2111          * Notifies the core that an {@link Identity} was updated.
2112          *
2113          * @param identityUpdatedEvent
2114          *            The event
2115          */
2116         @Subscribe
2117         public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2118                 final Identity identity = identityUpdatedEvent.identity();
2119                 soneDownloaders.execute(new Runnable() {
2120
2121                         @Override
2122                         @SuppressWarnings("synthetic-access")
2123                         public void run() {
2124                                 Sone sone = getRemoteSone(identity.getId(), false);
2125                                 if (sone.isLocal()) {
2126                                         return;
2127                                 }
2128                                 sone.setIdentity(identity);
2129                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2130                                 soneDownloader.addSone(sone);
2131                                 soneDownloader.fetchSone(sone);
2132                         }
2133                 });
2134         }
2135
2136         /**
2137          * Notifies the core that an {@link Identity} was removed.
2138          *
2139          * @param identityRemovedEvent
2140          *            The event
2141          */
2142         @Subscribe
2143         public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2144                 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2145                 Identity identity = identityRemovedEvent.identity();
2146                 trustedIdentities.remove(ownIdentity, identity);
2147                 boolean foundIdentity = false;
2148                 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2149                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2150                                 continue;
2151                         }
2152                         if (trustedIdentity.getValue().contains(identity)) {
2153                                 foundIdentity = true;
2154                         }
2155                 }
2156                 if (foundIdentity) {
2157                         /* some local identity still trusts this identity, don’t remove. */
2158                         return;
2159                 }
2160                 Optional<Sone> sone = getSone(identity.getId());
2161                 if (!sone.isPresent()) {
2162                         /* TODO - we don’t have the Sone anymore. should this happen? */
2163                         return;
2164                 }
2165                 database.removePosts(sone.get());
2166                 for (Post post : sone.get().getPosts()) {
2167                         eventBus.post(new PostRemovedEvent(post));
2168                 }
2169                 database.removePostReplies(sone.get());
2170                 for (PostReply reply : sone.get().getReplies()) {
2171                         eventBus.post(new PostReplyRemovedEvent(reply));
2172                 }
2173                 synchronized (sones) {
2174                         sones.remove(identity.getId());
2175                 }
2176                 eventBus.post(new SoneRemovedEvent(sone.get()));
2177         }
2178
2179         /**
2180          * Deletes the temporary image.
2181          *
2182          * @param imageInsertFinishedEvent
2183          *            The event
2184          */
2185         @Subscribe
2186         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2187                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2188                 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2189                 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2190                 touchConfiguration();
2191         }
2192
2193 }