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