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