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