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