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