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