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