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