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