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