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