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