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