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