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