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