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