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