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