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