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