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