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