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