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