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