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