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