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