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