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