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