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