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