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