Merge remote-tracking branch 'beak/next' into next
[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.main.SonePlugin;
57 import net.pterodactylus.util.config.Configuration;
58 import net.pterodactylus.util.config.ConfigurationException;
59 import net.pterodactylus.util.logging.Logging;
60 import net.pterodactylus.util.number.Numbers;
61 import net.pterodactylus.util.service.AbstractService;
62 import net.pterodactylus.util.thread.Ticker;
63 import net.pterodactylus.util.validation.EqualityValidator;
64 import net.pterodactylus.util.validation.IntegerRangeValidator;
65 import net.pterodactylus.util.validation.OrValidator;
66 import net.pterodactylus.util.validation.Validation;
67 import net.pterodactylus.util.version.Version;
68 import freenet.keys.FreenetURI;
69
70 /**
71  * The Sone core.
72  *
73  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
74  */
75 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
76
77         /** The logger. */
78         private static final Logger logger = Logging.getLogger(Core.class);
79
80         /** The options. */
81         private final Options options = new Options();
82
83         /** The preferences. */
84         private final Preferences preferences = new Preferences(options);
85
86         /** The core listener manager. */
87         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
88
89         /** The configuration. */
90         private Configuration configuration;
91
92         /** Whether we’re currently saving the configuration. */
93         private boolean storingConfiguration = false;
94
95         /** The identity manager. */
96         private final IdentityManager identityManager;
97
98         /** Interface to freenet. */
99         private final FreenetInterface freenetInterface;
100
101         /** The Sone downloader. */
102         private final SoneDownloader soneDownloader;
103
104         /** The image inserter. */
105         private final ImageInserter imageInserter;
106
107         /** Sone downloader thread-pool. */
108         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
109
110         /** The update checker. */
111         private final UpdateChecker updateChecker;
112
113         /** The trust updater. */
114         private final WebOfTrustUpdater webOfTrustUpdater;
115
116         /** The FCP interface. */
117         private volatile FcpInterface fcpInterface;
118
119         /** The times Sones were followed. */
120         private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
121
122         /** Locked local Sones. */
123         /* synchronize on itself. */
124         private final Set<Sone> lockedSones = new HashSet<Sone>();
125
126         /** Sone inserters. */
127         /* synchronize access on this on localSones. */
128         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
129
130         /** Sone rescuers. */
131         /* synchronize access on this on localSones. */
132         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
133
134         /** All local Sones. */
135         /* synchronize access on this on itself. */
136         private final Map<String, Sone> localSones = new HashMap<String, Sone>();
137
138         /** All remote Sones. */
139         /* synchronize access on this on itself. */
140         private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
141
142         /** All known Sones. */
143         private final Set<String> knownSones = new HashSet<String>();
144
145         /** All posts. */
146         private final Map<String, Post> posts = new HashMap<String, Post>();
147
148         /** All known posts. */
149         private final Set<String> knownPosts = new HashSet<String>();
150
151         /** All replies. */
152         private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
153
154         /** All known replies. */
155         private final Set<String> knownReplies = new HashSet<String>();
156
157         /** All bookmarked posts. */
158         /* synchronize access on itself. */
159         private final Set<String> bookmarkedPosts = new HashSet<String>();
160
161         /** Trusted identities, sorted by own identities. */
162         private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
163
164         /** All known albums. */
165         private final Map<String, Album> albums = new HashMap<String, Album>();
166
167         /** All known images. */
168         private final Map<String, Image> images = new HashMap<String, Image>();
169
170         /** All temporary images. */
171         private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
172
173         /** Ticker for threads that mark own elements as known. */
174         private final Ticker localElementTicker = new Ticker();
175
176         /** The time the configuration was last touched. */
177         private volatile long lastConfigurationUpdate;
178
179         /**
180          * Creates a new core.
181          *
182          * @param configuration
183          *            The configuration of the core
184          * @param freenetInterface
185          *            The freenet interface
186          * @param identityManager
187          *            The identity manager
188          * @param webOfTrustUpdater
189          *            The WebOfTrust updater
190          */
191         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
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.webOfTrustUpdater = webOfTrustUpdater;
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                 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
893                         logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
894                         return null;
895                 }
896                 Sone sone = addLocalSone(ownIdentity);
897                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
898                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
899                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
900                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
901                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
902                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
903
904                 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
905                 touchConfiguration();
906                 return sone;
907         }
908
909         /**
910          * Adds the Sone of the given identity.
911          *
912          * @param identity
913          *            The identity whose Sone to add
914          * @return The added or already existing Sone
915          */
916         public Sone addRemoteSone(Identity identity) {
917                 if (identity == null) {
918                         logger.log(Level.WARNING, "Given Identity is null!");
919                         return null;
920                 }
921                 synchronized (remoteSones) {
922                         final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
923                         boolean newSone = sone.getRequestUri() == null;
924                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
925                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
926                         if (newSone) {
927                                 synchronized (knownSones) {
928                                         newSone = !knownSones.contains(sone.getId());
929                                 }
930                                 sone.setKnown(!newSone);
931                                 if (newSone) {
932                                         coreListenerManager.fireNewSoneFound(sone);
933                                         for (Sone localSone : getLocalSones()) {
934                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
935                                                         followSone(localSone, sone);
936                                                 }
937                                         }
938                                 }
939                         }
940                         soneDownloader.addSone(sone);
941                         soneDownloaders.execute(new Runnable() {
942
943                                 @Override
944                                 @SuppressWarnings("synthetic-access")
945                                 public void run() {
946                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
947                                 }
948
949                         });
950                         return sone;
951                 }
952         }
953
954         /**
955          * Lets the given local Sone follow the Sone with the given ID.
956          *
957          * @param sone
958          *            The local Sone that should follow another Sone
959          * @param soneId
960          *            The ID of the Sone to follow
961          */
962         public void followSone(Sone sone, String soneId) {
963                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
964                 Sone followedSone = getSone(soneId, true);
965                 if (followedSone == null) {
966                         logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
967                         return;
968                 }
969                 followSone(sone, getSone(soneId));
970         }
971
972         /**
973          * Lets the given local Sone follow the other given Sone. If the given Sone
974          * was not followed by any local Sone before, this will mark all elements of
975          * the followed Sone as read that have been created before the current
976          * moment.
977          *
978          * @param sone
979          *            The local Sone that should follow the other Sone
980          * @param followedSone
981          *            The Sone that should be followed
982          */
983         public void followSone(Sone sone, Sone followedSone) {
984                 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
985                 sone.addFriend(followedSone.getId());
986                 synchronized (soneFollowingTimes) {
987                         if (!soneFollowingTimes.containsKey(followedSone)) {
988                                 long now = System.currentTimeMillis();
989                                 soneFollowingTimes.put(followedSone, now);
990                                 for (Post post : followedSone.getPosts()) {
991                                         if (post.getTime() < now) {
992                                                 markPostKnown(post);
993                                         }
994                                 }
995                                 for (PostReply reply : followedSone.getReplies()) {
996                                         if (reply.getTime() < now) {
997                                                 markReplyKnown(reply);
998                                         }
999                                 }
1000                         }
1001                 }
1002                 touchConfiguration();
1003         }
1004
1005         /**
1006          * Lets the given local Sone unfollow the Sone with the given ID.
1007          *
1008          * @param sone
1009          *            The local Sone that should unfollow another Sone
1010          * @param soneId
1011          *            The ID of the Sone being unfollowed
1012          */
1013         public void unfollowSone(Sone sone, String soneId) {
1014                 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1015                 unfollowSone(sone, getSone(soneId, false));
1016         }
1017
1018         /**
1019          * Lets the given local Sone unfollow the other given Sone. If the given
1020          * local Sone is the last local Sone that followed the given Sone, its
1021          * following time will be removed.
1022          *
1023          * @param sone
1024          *            The local Sone that should unfollow another Sone
1025          * @param unfollowedSone
1026          *            The Sone being unfollowed
1027          */
1028         public void unfollowSone(Sone sone, Sone unfollowedSone) {
1029                 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1030                 sone.removeFriend(unfollowedSone.getId());
1031                 boolean unfollowedSoneStillFollowed = false;
1032                 for (Sone localSone : getLocalSones()) {
1033                         unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1034                 }
1035                 if (!unfollowedSoneStillFollowed) {
1036                         synchronized (soneFollowingTimes) {
1037                                 soneFollowingTimes.remove(unfollowedSone);
1038                         }
1039                 }
1040                 touchConfiguration();
1041         }
1042
1043         /**
1044          * Sets the trust value of the given origin Sone for the target Sone.
1045          *
1046          * @param origin
1047          *            The origin Sone
1048          * @param target
1049          *            The target Sone
1050          * @param trustValue
1051          *            The trust value (from {@code -100} to {@code 100})
1052          */
1053         public void setTrust(Sone origin, Sone target, int trustValue) {
1054                 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();
1055                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1056         }
1057
1058         /**
1059          * Removes any trust assignment for the given target Sone.
1060          *
1061          * @param origin
1062          *            The trust origin
1063          * @param target
1064          *            The trust target
1065          */
1066         public void removeTrust(Sone origin, Sone target) {
1067                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1068                 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1069         }
1070
1071         /**
1072          * Assigns the configured positive trust value for the given target.
1073          *
1074          * @param origin
1075          *            The trust origin
1076          * @param target
1077          *            The trust target
1078          */
1079         public void trustSone(Sone origin, Sone target) {
1080                 setTrust(origin, target, preferences.getPositiveTrust());
1081         }
1082
1083         /**
1084          * Assigns the configured negative trust value for the given target.
1085          *
1086          * @param origin
1087          *            The trust origin
1088          * @param target
1089          *            The trust target
1090          */
1091         public void distrustSone(Sone origin, Sone target) {
1092                 setTrust(origin, target, preferences.getNegativeTrust());
1093         }
1094
1095         /**
1096          * Removes the trust assignment for the given target.
1097          *
1098          * @param origin
1099          *            The trust origin
1100          * @param target
1101          *            The trust target
1102          */
1103         public void untrustSone(Sone origin, Sone target) {
1104                 removeTrust(origin, target);
1105         }
1106
1107         /**
1108          * Updates the stored Sone with the given Sone.
1109          *
1110          * @param sone
1111          *            The updated Sone
1112          */
1113         public void updateSone(Sone sone) {
1114                 updateSone(sone, false);
1115         }
1116
1117         /**
1118          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1119          * {@code true}, an older Sone than the current Sone can be given to restore
1120          * an old state.
1121          *
1122          * @param sone
1123          *            The Sone to update
1124          * @param soneRescueMode
1125          *            {@code true} if the stored Sone should be updated regardless
1126          *            of the age of the given Sone
1127          */
1128         public void updateSone(Sone sone, boolean soneRescueMode) {
1129                 if (hasSone(sone.getId())) {
1130                         Sone storedSone = getSone(sone.getId());
1131                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1132                                 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1133                                 return;
1134                         }
1135                         synchronized (posts) {
1136                                 if (!soneRescueMode) {
1137                                         for (Post post : storedSone.getPosts()) {
1138                                                 posts.remove(post.getId());
1139                                                 if (!sone.getPosts().contains(post)) {
1140                                                         coreListenerManager.firePostRemoved(post);
1141                                                 }
1142                                         }
1143                                 }
1144                                 List<Post> storedPosts = storedSone.getPosts();
1145                                 synchronized (knownPosts) {
1146                                         for (Post post : sone.getPosts()) {
1147                                                 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1148                                                 if (!storedPosts.contains(post)) {
1149                                                         if (post.getTime() < getSoneFollowingTime(sone)) {
1150                                                                 knownPosts.add(post.getId());
1151                                                         } else if (!knownPosts.contains(post.getId())) {
1152                                                                 sone.setKnown(false);
1153                                                                 coreListenerManager.fireNewPostFound(post);
1154                                                         }
1155                                                 }
1156                                                 posts.put(post.getId(), post);
1157                                         }
1158                                 }
1159                         }
1160                         synchronized (replies) {
1161                                 if (!soneRescueMode) {
1162                                         for (PostReply reply : storedSone.getReplies()) {
1163                                                 replies.remove(reply.getId());
1164                                                 if (!sone.getReplies().contains(reply)) {
1165                                                         coreListenerManager.fireReplyRemoved(reply);
1166                                                 }
1167                                         }
1168                                 }
1169                                 Set<PostReply> storedReplies = storedSone.getReplies();
1170                                 synchronized (knownReplies) {
1171                                         for (PostReply reply : sone.getReplies()) {
1172                                                 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1173                                                 if (!storedReplies.contains(reply)) {
1174                                                         if (reply.getTime() < getSoneFollowingTime(sone)) {
1175                                                                 knownReplies.add(reply.getId());
1176                                                         } else if (!knownReplies.contains(reply.getId())) {
1177                                                                 reply.setKnown(false);
1178                                                                 coreListenerManager.fireNewReplyFound(reply);
1179                                                         }
1180                                                 }
1181                                                 replies.put(reply.getId(), reply);
1182                                         }
1183                                 }
1184                         }
1185                         synchronized (albums) {
1186                                 synchronized (images) {
1187                                         for (Album album : storedSone.getAlbums()) {
1188                                                 albums.remove(album.getId());
1189                                                 for (Image image : album.getImages()) {
1190                                                         images.remove(image.getId());
1191                                                 }
1192                                         }
1193                                         for (Album album : sone.getAlbums()) {
1194                                                 albums.put(album.getId(), album);
1195                                                 for (Image image : album.getImages()) {
1196                                                         images.put(image.getId(), image);
1197                                                 }
1198                                         }
1199                                 }
1200                         }
1201                         synchronized (storedSone) {
1202                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1203                                         storedSone.setTime(sone.getTime());
1204                                 }
1205                                 storedSone.setClient(sone.getClient());
1206                                 storedSone.setProfile(sone.getProfile());
1207                                 if (soneRescueMode) {
1208                                         for (Post post : sone.getPosts()) {
1209                                                 storedSone.addPost(post);
1210                                         }
1211                                         for (PostReply reply : sone.getReplies()) {
1212                                                 storedSone.addReply(reply);
1213                                         }
1214                                         for (String likedPostId : sone.getLikedPostIds()) {
1215                                                 storedSone.addLikedPostId(likedPostId);
1216                                         }
1217                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1218                                                 storedSone.addLikedReplyId(likedReplyId);
1219                                         }
1220                                         for (Album album : sone.getAlbums()) {
1221                                                 storedSone.addAlbum(album);
1222                                         }
1223                                 } else {
1224                                         storedSone.setPosts(sone.getPosts());
1225                                         storedSone.setReplies(sone.getReplies());
1226                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1227                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1228                                         storedSone.setAlbums(sone.getAlbums());
1229                                 }
1230                                 storedSone.setLatestEdition(sone.getLatestEdition());
1231                         }
1232                 }
1233         }
1234
1235         /**
1236          * Deletes the given Sone. This will remove the Sone from the
1237          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1238          * and remove the context from its identity.
1239          *
1240          * @param sone
1241          *            The Sone to delete
1242          */
1243         public void deleteSone(Sone sone) {
1244                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1245                         logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1246                         return;
1247                 }
1248                 synchronized (localSones) {
1249                         if (!localSones.containsKey(sone.getId())) {
1250                                 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1251                                 return;
1252                         }
1253                         localSones.remove(sone.getId());
1254                         SoneInserter soneInserter = soneInserters.remove(sone);
1255                         soneInserter.removeSoneInsertListener(this);
1256                         soneInserter.stop();
1257                 }
1258                 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1259                 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1260                 try {
1261                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1262                 } catch (ConfigurationException ce1) {
1263                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1264                 }
1265         }
1266
1267         /**
1268          * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1269          * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1270          *
1271          * @param sone
1272          *            The Sone to mark as known
1273          */
1274         public void markSoneKnown(Sone sone) {
1275                 if (!sone.isKnown()) {
1276                         sone.setKnown(true);
1277                         synchronized (knownSones) {
1278                                 knownSones.add(sone.getId());
1279                         }
1280                         coreListenerManager.fireMarkSoneKnown(sone);
1281                         touchConfiguration();
1282                 }
1283         }
1284
1285         /**
1286          * Loads and updates the given Sone from the configuration. If any error is
1287          * encountered, loading is aborted and the given Sone is not changed.
1288          *
1289          * @param sone
1290          *            The Sone to load and update
1291          */
1292         public void loadSone(Sone sone) {
1293                 if (!isLocalSone(sone)) {
1294                         logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1295                         return;
1296                 }
1297
1298                 /* initialize options. */
1299                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1300                 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1301                 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1302                 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1303                 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1304                 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1305
1306                 /* load Sone. */
1307                 String sonePrefix = "Sone/" + sone.getId();
1308                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1309                 if (soneTime == null) {
1310                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1311                         return;
1312                 }
1313                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1314
1315                 /* load profile. */
1316                 Profile profile = new Profile(sone);
1317                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1318                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1319                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1320                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1321                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1322                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1323
1324                 /* load profile fields. */
1325                 while (true) {
1326                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1327                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1328                         if (fieldName == null) {
1329                                 break;
1330                         }
1331                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1332                         profile.addField(fieldName).setValue(fieldValue);
1333                 }
1334
1335                 /* load posts. */
1336                 Set<Post> posts = new HashSet<Post>();
1337                 while (true) {
1338                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1339                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1340                         if (postId == null) {
1341                                 break;
1342                         }
1343                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1344                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1345                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1346                         if ((postTime == 0) || (postText == null)) {
1347                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1348                                 return;
1349                         }
1350                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1351                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1352                                 post.setRecipient(getSone(postRecipientId));
1353                         }
1354                         posts.add(post);
1355                 }
1356
1357                 /* load replies. */
1358                 Set<PostReply> replies = new HashSet<PostReply>();
1359                 while (true) {
1360                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1361                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1362                         if (replyId == null) {
1363                                 break;
1364                         }
1365                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1366                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1367                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1368                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1369                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1370                                 return;
1371                         }
1372                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1373                 }
1374
1375                 /* load post likes. */
1376                 Set<String> likedPostIds = new HashSet<String>();
1377                 while (true) {
1378                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1379                         if (likedPostId == null) {
1380                                 break;
1381                         }
1382                         likedPostIds.add(likedPostId);
1383                 }
1384
1385                 /* load reply likes. */
1386                 Set<String> likedReplyIds = new HashSet<String>();
1387                 while (true) {
1388                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1389                         if (likedReplyId == null) {
1390                                 break;
1391                         }
1392                         likedReplyIds.add(likedReplyId);
1393                 }
1394
1395                 /* load friends. */
1396                 Set<String> friends = new HashSet<String>();
1397                 while (true) {
1398                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1399                         if (friendId == null) {
1400                                 break;
1401                         }
1402                         friends.add(friendId);
1403                 }
1404
1405                 /* load albums. */
1406                 List<Album> topLevelAlbums = new ArrayList<Album>();
1407                 int albumCounter = 0;
1408                 while (true) {
1409                         String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1410                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1411                         if (albumId == null) {
1412                                 break;
1413                         }
1414                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1415                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1416                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1417                         String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1418                         if ((albumTitle == null) || (albumDescription == null)) {
1419                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1420                                 return;
1421                         }
1422                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1423                         if (albumParentId != null) {
1424                                 Album parentAlbum = getAlbum(albumParentId, false);
1425                                 if (parentAlbum == null) {
1426                                         logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1427                                         return;
1428                                 }
1429                                 parentAlbum.addAlbum(album);
1430                         } else {
1431                                 if (!topLevelAlbums.contains(album)) {
1432                                         topLevelAlbums.add(album);
1433                                 }
1434                         }
1435                 }
1436
1437                 /* load images. */
1438                 int imageCounter = 0;
1439                 while (true) {
1440                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1441                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1442                         if (imageId == null) {
1443                                 break;
1444                         }
1445                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1446                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1447                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1448                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1449                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1450                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1451                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1452                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1453                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1454                                 return;
1455                         }
1456                         Album album = getAlbum(albumId, false);
1457                         if (album == null) {
1458                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1459                                 return;
1460                         }
1461                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1462                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1463                         album.addImage(image);
1464                 }
1465
1466                 /* load avatar. */
1467                 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1468                 if (avatarId != null) {
1469                         profile.setAvatar(getImage(avatarId, false));
1470                 }
1471
1472                 /* load options. */
1473                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1474                 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1475                 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1476                 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1477                 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1478                 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1479
1480                 /* if we’re still here, Sone was loaded successfully. */
1481                 synchronized (sone) {
1482                         sone.setTime(soneTime);
1483                         sone.setProfile(profile);
1484                         sone.setPosts(posts);
1485                         sone.setReplies(replies);
1486                         sone.setLikePostIds(likedPostIds);
1487                         sone.setLikeReplyIds(likedReplyIds);
1488                         for (String friendId : friends) {
1489                                 followSone(sone, friendId);
1490                         }
1491                         sone.setAlbums(topLevelAlbums);
1492                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1493                 }
1494                 synchronized (knownSones) {
1495                         for (String friend : friends) {
1496                                 knownSones.add(friend);
1497                         }
1498                 }
1499                 synchronized (knownPosts) {
1500                         for (Post post : posts) {
1501                                 knownPosts.add(post.getId());
1502                         }
1503                 }
1504                 synchronized (knownReplies) {
1505                         for (PostReply reply : replies) {
1506                                 knownReplies.add(reply.getId());
1507                         }
1508                 }
1509         }
1510
1511         /**
1512          * Creates a new post.
1513          *
1514          * @param sone
1515          *            The Sone that creates the post
1516          * @param text
1517          *            The text of the post
1518          * @return The created post
1519          */
1520         public Post createPost(Sone sone, String text) {
1521                 return createPost(sone, System.currentTimeMillis(), text);
1522         }
1523
1524         /**
1525          * Creates a new post.
1526          *
1527          * @param sone
1528          *            The Sone that creates the post
1529          * @param time
1530          *            The time of the post
1531          * @param text
1532          *            The text of the post
1533          * @return The created post
1534          */
1535         public Post createPost(Sone sone, long time, String text) {
1536                 return createPost(sone, null, time, text);
1537         }
1538
1539         /**
1540          * Creates a new post.
1541          *
1542          * @param sone
1543          *            The Sone that creates the post
1544          * @param recipient
1545          *            The recipient Sone, or {@code null} if this post does not have
1546          *            a recipient
1547          * @param text
1548          *            The text of the post
1549          * @return The created post
1550          */
1551         public Post createPost(Sone sone, Sone recipient, String text) {
1552                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1553         }
1554
1555         /**
1556          * Creates a new post.
1557          *
1558          * @param sone
1559          *            The Sone that creates the post
1560          * @param recipient
1561          *            The recipient Sone, or {@code null} if this post does not have
1562          *            a recipient
1563          * @param time
1564          *            The time of the post
1565          * @param text
1566          *            The text of the post
1567          * @return The created post
1568          */
1569         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1570                 if (!isLocalSone(sone)) {
1571                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1572                         return null;
1573                 }
1574                 final Post post = new PostImpl(sone, time, text);
1575                 if (recipient != null) {
1576                         post.setRecipient(recipient);
1577                 }
1578                 synchronized (posts) {
1579                         posts.put(post.getId(), post);
1580                 }
1581                 coreListenerManager.fireNewPostFound(post);
1582                 sone.addPost(post);
1583                 touchConfiguration();
1584                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1585
1586                         /**
1587                          * {@inheritDoc}
1588                          */
1589                         @Override
1590                         public void run() {
1591                                 markPostKnown(post);
1592                         }
1593                 }, "Mark " + post + " read.");
1594                 return post;
1595         }
1596
1597         /**
1598          * Deletes the given post.
1599          *
1600          * @param post
1601          *            The post to delete
1602          */
1603         public void deletePost(Post post) {
1604                 if (!isLocalSone(post.getSone())) {
1605                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1606                         return;
1607                 }
1608                 post.getSone().removePost(post);
1609                 synchronized (posts) {
1610                         posts.remove(post.getId());
1611                 }
1612                 coreListenerManager.firePostRemoved(post);
1613                 markPostKnown(post);
1614                 touchConfiguration();
1615         }
1616
1617         /**
1618          * Marks the given post as known, if it is currently not a known post
1619          * (according to {@link Post#isKnown()}).
1620          *
1621          * @param post
1622          *            The post to mark as known
1623          */
1624         public void markPostKnown(Post post) {
1625                 post.setKnown(true);
1626                 synchronized (knownPosts) {
1627                         coreListenerManager.fireMarkPostKnown(post);
1628                         if (knownPosts.add(post.getId())) {
1629                                 touchConfiguration();
1630                         }
1631                 }
1632                 for (PostReply reply : getReplies(post)) {
1633                         markReplyKnown(reply);
1634                 }
1635         }
1636
1637         /**
1638          * Bookmarks the given post.
1639          *
1640          * @param post
1641          *            The post to bookmark
1642          */
1643         public void bookmark(Post post) {
1644                 bookmarkPost(post.getId());
1645         }
1646
1647         /**
1648          * Bookmarks the post with the given ID.
1649          *
1650          * @param id
1651          *            The ID of the post to bookmark
1652          */
1653         public void bookmarkPost(String id) {
1654                 synchronized (bookmarkedPosts) {
1655                         bookmarkedPosts.add(id);
1656                 }
1657         }
1658
1659         /**
1660          * Removes the given post from the bookmarks.
1661          *
1662          * @param post
1663          *            The post to unbookmark
1664          */
1665         public void unbookmark(Post post) {
1666                 unbookmarkPost(post.getId());
1667         }
1668
1669         /**
1670          * Removes the post with the given ID from the bookmarks.
1671          *
1672          * @param id
1673          *            The ID of the post to unbookmark
1674          */
1675         public void unbookmarkPost(String id) {
1676                 synchronized (bookmarkedPosts) {
1677                         bookmarkedPosts.remove(id);
1678                 }
1679         }
1680
1681         /**
1682          * Creates a new reply.
1683          *
1684          * @param sone
1685          *            The Sone that creates the reply
1686          * @param post
1687          *            The post that this reply refers to
1688          * @param text
1689          *            The text of the reply
1690          * @return The created reply
1691          */
1692         public PostReply createReply(Sone sone, Post post, String text) {
1693                 return createReply(sone, post, System.currentTimeMillis(), text);
1694         }
1695
1696         /**
1697          * Creates a new reply.
1698          *
1699          * @param sone
1700          *            The Sone that creates the reply
1701          * @param post
1702          *            The post that this reply refers to
1703          * @param time
1704          *            The time of the reply
1705          * @param text
1706          *            The text of the reply
1707          * @return The created reply
1708          */
1709         public PostReply createReply(Sone sone, Post post, long time, String text) {
1710                 if (!isLocalSone(sone)) {
1711                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1712                         return null;
1713                 }
1714                 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1715                 synchronized (replies) {
1716                         replies.put(reply.getId(), reply);
1717                 }
1718                 synchronized (knownReplies) {
1719                         coreListenerManager.fireNewReplyFound(reply);
1720                 }
1721                 sone.addReply(reply);
1722                 touchConfiguration();
1723                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1724
1725                         /**
1726                          * {@inheritDoc}
1727                          */
1728                         @Override
1729                         public void run() {
1730                                 markReplyKnown(reply);
1731                         }
1732                 }, "Mark " + reply + " read.");
1733                 return reply;
1734         }
1735
1736         /**
1737          * Deletes the given reply.
1738          *
1739          * @param reply
1740          *            The reply to delete
1741          */
1742         public void deleteReply(PostReply reply) {
1743                 Sone sone = reply.getSone();
1744                 if (!isLocalSone(sone)) {
1745                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1746                         return;
1747                 }
1748                 synchronized (replies) {
1749                         replies.remove(reply.getId());
1750                 }
1751                 synchronized (knownReplies) {
1752                         markReplyKnown(reply);
1753                         knownReplies.remove(reply.getId());
1754                 }
1755                 sone.removeReply(reply);
1756                 touchConfiguration();
1757         }
1758
1759         /**
1760          * Marks the given reply as known, if it is currently not a known reply
1761          * (according to {@link Reply#isKnown()}).
1762          *
1763          * @param reply
1764          *            The reply to mark as known
1765          */
1766         public void markReplyKnown(PostReply reply) {
1767                 reply.setKnown(true);
1768                 synchronized (knownReplies) {
1769                         coreListenerManager.fireMarkReplyKnown(reply);
1770                         if (knownReplies.add(reply.getId())) {
1771                                 touchConfiguration();
1772                         }
1773                 }
1774         }
1775
1776         /**
1777          * Creates a new top-level album for the given Sone.
1778          *
1779          * @param sone
1780          *            The Sone to create the album for
1781          * @return The new album
1782          */
1783         public Album createAlbum(Sone sone) {
1784                 return createAlbum(sone, null);
1785         }
1786
1787         /**
1788          * Creates a new album for the given Sone.
1789          *
1790          * @param sone
1791          *            The Sone to create the album for
1792          * @param parent
1793          *            The parent of the album (may be {@code null} to create a
1794          *            top-level album)
1795          * @return The new album
1796          */
1797         public Album createAlbum(Sone sone, Album parent) {
1798                 Album album = new Album();
1799                 synchronized (albums) {
1800                         albums.put(album.getId(), album);
1801                 }
1802                 album.setSone(sone);
1803                 if (parent != null) {
1804                         parent.addAlbum(album);
1805                 } else {
1806                         sone.addAlbum(album);
1807                 }
1808                 return album;
1809         }
1810
1811         /**
1812          * Deletes the given album. The owner of the album has to be a local Sone,
1813          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1814          *
1815          * @param album
1816          *            The album to remove
1817          */
1818         public void deleteAlbum(Album album) {
1819                 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1820                 if (!album.isEmpty()) {
1821                         return;
1822                 }
1823                 if (album.getParent() == null) {
1824                         album.getSone().removeAlbum(album);
1825                 } else {
1826                         album.getParent().removeAlbum(album);
1827                 }
1828                 synchronized (albums) {
1829                         albums.remove(album.getId());
1830                 }
1831                 touchConfiguration();
1832         }
1833
1834         /**
1835          * Creates a new image.
1836          *
1837          * @param sone
1838          *            The Sone creating the image
1839          * @param album
1840          *            The album the image will be inserted into
1841          * @param temporaryImage
1842          *            The temporary image to create the image from
1843          * @return The newly created image
1844          */
1845         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1846                 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();
1847                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1848                 album.addImage(image);
1849                 synchronized (images) {
1850                         images.put(image.getId(), image);
1851                 }
1852                 imageInserter.insertImage(temporaryImage, image);
1853                 return image;
1854         }
1855
1856         /**
1857          * Deletes the given image. This method will also delete a matching
1858          * temporary image.
1859          *
1860          * @see #deleteTemporaryImage(TemporaryImage)
1861          * @param image
1862          *            The image to delete
1863          */
1864         public void deleteImage(Image image) {
1865                 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1866                 deleteTemporaryImage(image.getId());
1867                 image.getAlbum().removeImage(image);
1868                 synchronized (images) {
1869                         images.remove(image.getId());
1870                 }
1871                 touchConfiguration();
1872         }
1873
1874         /**
1875          * Creates a new temporary image.
1876          *
1877          * @param mimeType
1878          *            The MIME type of the temporary image
1879          * @param imageData
1880          *            The encoded data of the image
1881          * @return The temporary image
1882          */
1883         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1884                 TemporaryImage temporaryImage = new TemporaryImage();
1885                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1886                 synchronized (temporaryImages) {
1887                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1888                 }
1889                 return temporaryImage;
1890         }
1891
1892         /**
1893          * Deletes the given temporary image.
1894          *
1895          * @param temporaryImage
1896          *            The temporary image to delete
1897          */
1898         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1899                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1900                 deleteTemporaryImage(temporaryImage.getId());
1901         }
1902
1903         /**
1904          * Deletes the temporary image with the given ID.
1905          *
1906          * @param imageId
1907          *            The ID of the temporary image to delete
1908          */
1909         public void deleteTemporaryImage(String imageId) {
1910                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1911                 synchronized (temporaryImages) {
1912                         temporaryImages.remove(imageId);
1913                 }
1914                 Image image = getImage(imageId, false);
1915                 if (image != null) {
1916                         imageInserter.cancelImageInsert(image);
1917                 }
1918         }
1919
1920         /**
1921          * Notifies the core that the configuration, either of the core or of a
1922          * single local Sone, has changed, and that the configuration should be
1923          * saved.
1924          */
1925         public void touchConfiguration() {
1926                 lastConfigurationUpdate = System.currentTimeMillis();
1927         }
1928
1929         //
1930         // SERVICE METHODS
1931         //
1932
1933         /**
1934          * Starts the core.
1935          */
1936         @Override
1937         public void serviceStart() {
1938                 loadConfiguration();
1939                 updateChecker.addUpdateListener(this);
1940                 updateChecker.start();
1941                 webOfTrustUpdater.start();
1942         }
1943
1944         /**
1945          * {@inheritDoc}
1946          */
1947         @Override
1948         public void serviceRun() {
1949                 long lastSaved = System.currentTimeMillis();
1950                 while (!shouldStop()) {
1951                         sleep(1000);
1952                         long now = System.currentTimeMillis();
1953                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1954                                 for (Sone localSone : getLocalSones()) {
1955                                         saveSone(localSone);
1956                                 }
1957                                 saveConfiguration();
1958                                 lastSaved = now;
1959                         }
1960                 }
1961         }
1962
1963         /**
1964          * Stops the core.
1965          */
1966         @Override
1967         public void serviceStop() {
1968                 synchronized (localSones) {
1969                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1970                                 soneInserter.getValue().removeSoneInsertListener(this);
1971                                 soneInserter.getValue().stop();
1972                                 saveSone(soneInserter.getKey());
1973                         }
1974                 }
1975                 saveConfiguration();
1976                 webOfTrustUpdater.stop();
1977                 updateChecker.stop();
1978                 updateChecker.removeUpdateListener(this);
1979                 soneDownloader.stop();
1980         }
1981
1982         //
1983         // PRIVATE METHODS
1984         //
1985
1986         /**
1987          * Saves the given Sone. This will persist all local settings for the given
1988          * Sone, such as the friends list and similar, private options.
1989          *
1990          * @param sone
1991          *            The Sone to save
1992          */
1993         private synchronized void saveSone(Sone sone) {
1994                 if (!isLocalSone(sone)) {
1995                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1996                         return;
1997                 }
1998                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1999                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2000                         return;
2001                 }
2002
2003                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2004                 try {
2005                         /* save Sone into configuration. */
2006                         String sonePrefix = "Sone/" + sone.getId();
2007                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2008                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2009
2010                         /* save profile. */
2011                         Profile profile = sone.getProfile();
2012                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2013                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2014                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2015                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2016                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2017                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2018                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2019
2020                         /* save profile fields. */
2021                         int fieldCounter = 0;
2022                         for (Field profileField : profile.getFields()) {
2023                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2024                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2025                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2026                         }
2027                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2028
2029                         /* save posts. */
2030                         int postCounter = 0;
2031                         for (Post post : sone.getPosts()) {
2032                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2033                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2034                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2035                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2036                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2037                         }
2038                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2039
2040                         /* save replies. */
2041                         int replyCounter = 0;
2042                         for (PostReply reply : sone.getReplies()) {
2043                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2044                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2045                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2046                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2047                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2048                         }
2049                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2050
2051                         /* save post likes. */
2052                         int postLikeCounter = 0;
2053                         for (String postId : sone.getLikedPostIds()) {
2054                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2055                         }
2056                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2057
2058                         /* save reply likes. */
2059                         int replyLikeCounter = 0;
2060                         for (String replyId : sone.getLikedReplyIds()) {
2061                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2062                         }
2063                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2064
2065                         /* save friends. */
2066                         int friendCounter = 0;
2067                         for (String friendId : sone.getFriends()) {
2068                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2069                         }
2070                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2071
2072                         /* save albums. first, collect in a flat structure, top-level first. */
2073                         List<Album> albums = sone.getAllAlbums();
2074
2075                         int albumCounter = 0;
2076                         for (Album album : albums) {
2077                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2078                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2079                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2080                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2081                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2082                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2083                         }
2084                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2085
2086                         /* save images. */
2087                         int imageCounter = 0;
2088                         for (Album album : albums) {
2089                                 for (Image image : album.getImages()) {
2090                                         if (!image.isInserted()) {
2091                                                 continue;
2092                                         }
2093                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2094                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2095                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2096                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2097                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2098                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2099                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2100                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2101                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2102                                 }
2103                         }
2104                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2105
2106                         /* save options. */
2107                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2108                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2109                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2110                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2111                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2112                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2113
2114                         configuration.save();
2115
2116                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2117
2118                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2119                 } catch (ConfigurationException ce1) {
2120                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2121                 }
2122         }
2123
2124         /**
2125          * Saves the current options.
2126          */
2127         private void saveConfiguration() {
2128                 synchronized (configuration) {
2129                         if (storingConfiguration) {
2130                                 logger.log(Level.FINE, "Already storing configuration…");
2131                                 return;
2132                         }
2133                         storingConfiguration = true;
2134                 }
2135
2136                 /* store the options first. */
2137                 try {
2138                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2139                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2140                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2141                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2142                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2143                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2144                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2145                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2146                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2147                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2148                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2149                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2150
2151                         /* save known Sones. */
2152                         int soneCounter = 0;
2153                         synchronized (knownSones) {
2154                                 for (String knownSoneId : knownSones) {
2155                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2156                                 }
2157                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2158                         }
2159
2160                         /* save Sone following times. */
2161                         soneCounter = 0;
2162                         synchronized (soneFollowingTimes) {
2163                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2164                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2165                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2166                                         ++soneCounter;
2167                                 }
2168                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2169                         }
2170
2171                         /* save known posts. */
2172                         int postCounter = 0;
2173                         synchronized (knownPosts) {
2174                                 for (String knownPostId : knownPosts) {
2175                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2176                                 }
2177                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2178                         }
2179
2180                         /* save known replies. */
2181                         int replyCounter = 0;
2182                         synchronized (knownReplies) {
2183                                 for (String knownReplyId : knownReplies) {
2184                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2185                                 }
2186                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2187                         }
2188
2189                         /* save bookmarked posts. */
2190                         int bookmarkedPostCounter = 0;
2191                         synchronized (bookmarkedPosts) {
2192                                 for (String bookmarkedPostId : bookmarkedPosts) {
2193                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2194                                 }
2195                         }
2196                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2197
2198                         /* now save it. */
2199                         configuration.save();
2200
2201                 } catch (ConfigurationException ce1) {
2202                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2203                 } finally {
2204                         synchronized (configuration) {
2205                                 storingConfiguration = false;
2206                         }
2207                 }
2208         }
2209
2210         /**
2211          * Loads the configuration.
2212          */
2213         @SuppressWarnings("unchecked")
2214         private void loadConfiguration() {
2215                 /* create options. */
2216                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2217
2218                         @Override
2219                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2220                                 SoneInserter.setInsertionDelay(newValue);
2221                         }
2222
2223                 }));
2224                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2225                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2226                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2227                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2228                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2229                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2230                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2231                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2232                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2233
2234                         @Override
2235                         @SuppressWarnings("synthetic-access")
2236                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2237                                 fcpInterface.setActive(newValue);
2238                         }
2239                 }));
2240                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2241
2242                         @Override
2243                         @SuppressWarnings("synthetic-access")
2244                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2245                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2246                         }
2247
2248                 }));
2249
2250                 loadConfigurationValue("InsertionDelay");
2251                 loadConfigurationValue("PostsPerPage");
2252                 loadConfigurationValue("ImagesPerPage");
2253                 loadConfigurationValue("CharactersPerPost");
2254                 loadConfigurationValue("PostCutOffLength");
2255                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2256                 loadConfigurationValue("PositiveTrust");
2257                 loadConfigurationValue("NegativeTrust");
2258                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2259                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2260                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2261
2262                 /* load known Sones. */
2263                 int soneCounter = 0;
2264                 while (true) {
2265                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2266                         if (knownSoneId == null) {
2267                                 break;
2268                         }
2269                         synchronized (knownSones) {
2270                                 knownSones.add(knownSoneId);
2271                         }
2272                 }
2273
2274                 /* load Sone following times. */
2275                 soneCounter = 0;
2276                 while (true) {
2277                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2278                         if (soneId == null) {
2279                                 break;
2280                         }
2281                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2282                         Sone followedSone = getSone(soneId);
2283                         if (followedSone == null) {
2284                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2285                         } else {
2286                                 synchronized (soneFollowingTimes) {
2287                                         soneFollowingTimes.put(getSone(soneId), time);
2288                                 }
2289                         }
2290                         ++soneCounter;
2291                 }
2292
2293                 /* load known posts. */
2294                 int postCounter = 0;
2295                 while (true) {
2296                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2297                         if (knownPostId == null) {
2298                                 break;
2299                         }
2300                         synchronized (knownPosts) {
2301                                 knownPosts.add(knownPostId);
2302                         }
2303                 }
2304
2305                 /* load known replies. */
2306                 int replyCounter = 0;
2307                 while (true) {
2308                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2309                         if (knownReplyId == null) {
2310                                 break;
2311                         }
2312                         synchronized (knownReplies) {
2313                                 knownReplies.add(knownReplyId);
2314                         }
2315                 }
2316
2317                 /* load bookmarked posts. */
2318                 int bookmarkedPostCounter = 0;
2319                 while (true) {
2320                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2321                         if (bookmarkedPostId == null) {
2322                                 break;
2323                         }
2324                         synchronized (bookmarkedPosts) {
2325                                 bookmarkedPosts.add(bookmarkedPostId);
2326                         }
2327                 }
2328
2329         }
2330
2331         /**
2332          * Loads an {@link Integer} configuration value for the option with the
2333          * given name, logging validation failures.
2334          *
2335          * @param optionName
2336          *            The name of the option to load
2337          */
2338         private void loadConfigurationValue(String optionName) {
2339                 try {
2340                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2341                 } catch (IllegalArgumentException iae1) {
2342                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2343                 }
2344         }
2345
2346         /**
2347          * Generate a Sone URI from the given URI and latest edition.
2348          *
2349          * @param uriString
2350          *            The URI to derive the Sone URI from
2351          * @return The derived URI
2352          */
2353         private static FreenetURI getSoneUri(String uriString) {
2354                 try {
2355                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2356                         return uri;
2357                 } catch (MalformedURLException mue1) {
2358                         logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2359                         return null;
2360                 }
2361         }
2362
2363         //
2364         // INTERFACE IdentityListener
2365         //
2366
2367         /**
2368          * {@inheritDoc}
2369          */
2370         @Override
2371         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2372                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2373                 if (ownIdentity.hasContext("Sone")) {
2374                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2375                         addLocalSone(ownIdentity);
2376                 }
2377         }
2378
2379         /**
2380          * {@inheritDoc}
2381          */
2382         @Override
2383         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2384                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2385                 trustedIdentities.remove(ownIdentity);
2386         }
2387
2388         /**
2389          * {@inheritDoc}
2390          */
2391         @Override
2392         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2393                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2394                 trustedIdentities.get(ownIdentity).add(identity);
2395                 addRemoteSone(identity);
2396         }
2397
2398         /**
2399          * {@inheritDoc}
2400          */
2401         @Override
2402         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2403                 new Thread(new Runnable() {
2404
2405                         @Override
2406                         @SuppressWarnings("synthetic-access")
2407                         public void run() {
2408                                 Sone sone = getRemoteSone(identity.getId(), false);
2409                                 sone.setIdentity(identity);
2410                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2411                                 soneDownloader.addSone(sone);
2412                                 soneDownloader.fetchSone(sone);
2413                         }
2414                 }).start();
2415         }
2416
2417         /**
2418          * {@inheritDoc}
2419          */
2420         @Override
2421         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2422                 trustedIdentities.get(ownIdentity).remove(identity);
2423                 boolean foundIdentity = false;
2424                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2425                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2426                                 continue;
2427                         }
2428                         if (trustedIdentity.getValue().contains(identity)) {
2429                                 foundIdentity = true;
2430                         }
2431                 }
2432                 if (foundIdentity) {
2433                         /* some local identity still trusts this identity, don’t remove. */
2434                         return;
2435                 }
2436                 Sone sone = getSone(identity.getId(), false);
2437                 if (sone == null) {
2438                         /* TODO - we don’t have the Sone anymore. should this happen? */
2439                         return;
2440                 }
2441                 synchronized (posts) {
2442                         synchronized (knownPosts) {
2443                                 for (Post post : sone.getPosts()) {
2444                                         posts.remove(post.getId());
2445                                         coreListenerManager.firePostRemoved(post);
2446                                 }
2447                         }
2448                 }
2449                 synchronized (replies) {
2450                         synchronized (knownReplies) {
2451                                 for (PostReply reply : sone.getReplies()) {
2452                                         replies.remove(reply.getId());
2453                                         coreListenerManager.fireReplyRemoved(reply);
2454                                 }
2455                         }
2456                 }
2457                 synchronized (remoteSones) {
2458                         remoteSones.remove(identity.getId());
2459                 }
2460                 coreListenerManager.fireSoneRemoved(sone);
2461         }
2462
2463         //
2464         // INTERFACE UpdateListener
2465         //
2466
2467         /**
2468          * {@inheritDoc}
2469          */
2470         @Override
2471         public void updateFound(Version version, long releaseTime, long latestEdition) {
2472                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2473         }
2474
2475         //
2476         // INTERFACE ImageInsertListener
2477         //
2478
2479         /**
2480          * {@inheritDoc}
2481          */
2482         @Override
2483         public void insertStarted(Sone sone) {
2484                 coreListenerManager.fireSoneInserting(sone);
2485         }
2486
2487         /**
2488          * {@inheritDoc}
2489          */
2490         @Override
2491         public void insertFinished(Sone sone, long insertDuration) {
2492                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2493         }
2494
2495         /**
2496          * {@inheritDoc}
2497          */
2498         @Override
2499         public void insertAborted(Sone sone, Throwable cause) {
2500                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2501         }
2502
2503         //
2504         // SONEINSERTLISTENER METHODS
2505         //
2506
2507         /**
2508          * {@inheritDoc}
2509          */
2510         @Override
2511         public void imageInsertStarted(Image image) {
2512                 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2513                 coreListenerManager.fireImageInsertStarted(image);
2514         }
2515
2516         /**
2517          * {@inheritDoc}
2518          */
2519         @Override
2520         public void imageInsertAborted(Image image) {
2521                 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2522                 coreListenerManager.fireImageInsertAborted(image);
2523         }
2524
2525         /**
2526          * {@inheritDoc}
2527          */
2528         @Override
2529         public void imageInsertFinished(Image image, FreenetURI key) {
2530                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2531                 image.setKey(key.toString());
2532                 deleteTemporaryImage(image.getId());
2533                 touchConfiguration();
2534                 coreListenerManager.fireImageInsertFinished(image);
2535         }
2536
2537         /**
2538          * {@inheritDoc}
2539          */
2540         @Override
2541         public void imageInsertFailed(Image image, Throwable cause) {
2542                 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2543                 coreListenerManager.fireImageInsertFailed(image, cause);
2544         }
2545
2546         /**
2547          * Convenience interface for external classes that want to access the core’s
2548          * configuration.
2549          *
2550          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2551          */
2552         public static class Preferences {
2553
2554                 /** The wrapped options. */
2555                 private final Options options;
2556
2557                 /**
2558                  * Creates a new preferences object wrapped around the given options.
2559                  *
2560                  * @param options
2561                  *            The options to wrap
2562                  */
2563                 public Preferences(Options options) {
2564                         this.options = options;
2565                 }
2566
2567                 /**
2568                  * Returns the insertion delay.
2569                  *
2570                  * @return The insertion delay
2571                  */
2572                 public int getInsertionDelay() {
2573                         return options.getIntegerOption("InsertionDelay").get();
2574                 }
2575
2576                 /**
2577                  * Validates the given insertion delay.
2578                  *
2579                  * @param insertionDelay
2580                  *            The insertion delay to validate
2581                  * @return {@code true} if the given insertion delay was valid,
2582                  *         {@code false} otherwise
2583                  */
2584                 public boolean validateInsertionDelay(Integer insertionDelay) {
2585                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2586                 }
2587
2588                 /**
2589                  * Sets the insertion delay
2590                  *
2591                  * @param insertionDelay
2592                  *            The new insertion delay, or {@code null} to restore it to
2593                  *            the default value
2594                  * @return This preferences
2595                  */
2596                 public Preferences setInsertionDelay(Integer insertionDelay) {
2597                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2598                         return this;
2599                 }
2600
2601                 /**
2602                  * Returns the number of posts to show per page.
2603                  *
2604                  * @return The number of posts to show per page
2605                  */
2606                 public int getPostsPerPage() {
2607                         return options.getIntegerOption("PostsPerPage").get();
2608                 }
2609
2610                 /**
2611                  * Validates the number of posts per page.
2612                  *
2613                  * @param postsPerPage
2614                  *            The number of posts per page
2615                  * @return {@code true} if the number of posts per page was valid,
2616                  *         {@code false} otherwise
2617                  */
2618                 public boolean validatePostsPerPage(Integer postsPerPage) {
2619                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2620                 }
2621
2622                 /**
2623                  * Sets the number of posts to show per page.
2624                  *
2625                  * @param postsPerPage
2626                  *            The number of posts to show per page
2627                  * @return This preferences object
2628                  */
2629                 public Preferences setPostsPerPage(Integer postsPerPage) {
2630                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2631                         return this;
2632                 }
2633
2634                 /**
2635                  * Returns the number of images to show per page.
2636                  *
2637                  * @return The number of images to show per page
2638                  */
2639                 public int getImagesPerPage() {
2640                         return options.getIntegerOption("ImagesPerPage").get();
2641                 }
2642
2643                 /**
2644                  * Validates the number of images per page.
2645                  *
2646                  * @param imagesPerPage
2647                  *            The number of images per page
2648                  * @return {@code true} if the number of images per page was valid,
2649                  *         {@code false} otherwise
2650                  */
2651                 public boolean validateImagesPerPage(Integer imagesPerPage) {
2652                         return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2653                 }
2654
2655                 /**
2656                  * Sets the number of images per page.
2657                  *
2658                  * @param imagesPerPage
2659                  *            The number of images per page
2660                  * @return This preferences object
2661                  */
2662                 public Preferences setImagesPerPage(Integer imagesPerPage) {
2663                         options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2664                         return this;
2665                 }
2666
2667                 /**
2668                  * Returns the number of characters per post, or <code>-1</code> if the
2669                  * posts should not be cut off.
2670                  *
2671                  * @return The numbers of characters per post
2672                  */
2673                 public int getCharactersPerPost() {
2674                         return options.getIntegerOption("CharactersPerPost").get();
2675                 }
2676
2677                 /**
2678                  * Validates the number of characters per post.
2679                  *
2680                  * @param charactersPerPost
2681                  *            The number of characters per post
2682                  * @return {@code true} if the number of characters per post was valid,
2683                  *         {@code false} otherwise
2684                  */
2685                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2686                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2687                 }
2688
2689                 /**
2690                  * Sets the number of characters per post.
2691                  *
2692                  * @param charactersPerPost
2693                  *            The number of characters per post, or <code>-1</code> to
2694                  *            not cut off the posts
2695                  * @return This preferences objects
2696                  */
2697                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2698                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2699                         return this;
2700                 }
2701
2702                 /**
2703                  * Returns the number of characters the shortened post should have.
2704                  *
2705                  * @return The number of characters of the snippet
2706                  */
2707                 public int getPostCutOffLength() {
2708                         return options.getIntegerOption("PostCutOffLength").get();
2709                 }
2710
2711                 /**
2712                  * Validates the number of characters after which to cut off the post.
2713                  *
2714                  * @param postCutOffLength
2715                  *            The number of characters of the snippet
2716                  * @return {@code true} if the number of characters of the snippet is
2717                  *         valid, {@code false} otherwise
2718                  */
2719                 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2720                         return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2721                 }
2722
2723                 /**
2724                  * Sets the number of characters the shortened post should have.
2725                  *
2726                  * @param postCutOffLength
2727                  *            The number of characters of the snippet
2728                  * @return This preferences
2729                  */
2730                 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2731                         options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2732                         return this;
2733                 }
2734
2735                 /**
2736                  * Returns whether Sone requires full access to be even visible.
2737                  *
2738                  * @return {@code true} if Sone requires full access, {@code false}
2739                  *         otherwise
2740                  */
2741                 public boolean isRequireFullAccess() {
2742                         return options.getBooleanOption("RequireFullAccess").get();
2743                 }
2744
2745                 /**
2746                  * Sets whether Sone requires full access to be even visible.
2747                  *
2748                  * @param requireFullAccess
2749                  *            {@code true} if Sone requires full access, {@code false}
2750                  *            otherwise
2751                  */
2752                 public void setRequireFullAccess(Boolean requireFullAccess) {
2753                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2754                 }
2755
2756                 /**
2757                  * Returns the positive trust.
2758                  *
2759                  * @return The positive trust
2760                  */
2761                 public int getPositiveTrust() {
2762                         return options.getIntegerOption("PositiveTrust").get();
2763                 }
2764
2765                 /**
2766                  * Validates the positive trust.
2767                  *
2768                  * @param positiveTrust
2769                  *            The positive trust to validate
2770                  * @return {@code true} if the positive trust was valid, {@code false}
2771                  *         otherwise
2772                  */
2773                 public boolean validatePositiveTrust(Integer positiveTrust) {
2774                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2775                 }
2776
2777                 /**
2778                  * Sets the positive trust.
2779                  *
2780                  * @param positiveTrust
2781                  *            The new positive trust, or {@code null} to restore it to
2782                  *            the default vlaue
2783                  * @return This preferences
2784                  */
2785                 public Preferences setPositiveTrust(Integer positiveTrust) {
2786                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2787                         return this;
2788                 }
2789
2790                 /**
2791                  * Returns the negative trust.
2792                  *
2793                  * @return The negative trust
2794                  */
2795                 public int getNegativeTrust() {
2796                         return options.getIntegerOption("NegativeTrust").get();
2797                 }
2798
2799                 /**
2800                  * Validates the negative trust.
2801                  *
2802                  * @param negativeTrust
2803                  *            The negative trust to validate
2804                  * @return {@code true} if the negative trust was valid, {@code false}
2805                  *         otherwise
2806                  */
2807                 public boolean validateNegativeTrust(Integer negativeTrust) {
2808                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2809                 }
2810
2811                 /**
2812                  * Sets the negative trust.
2813                  *
2814                  * @param negativeTrust
2815                  *            The negative trust, or {@code null} to restore it to the
2816                  *            default value
2817                  * @return The preferences
2818                  */
2819                 public Preferences setNegativeTrust(Integer negativeTrust) {
2820                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2821                         return this;
2822                 }
2823
2824                 /**
2825                  * Returns the trust comment. This is the comment that is set in the web
2826                  * of trust when a trust value is assigned to an identity.
2827                  *
2828                  * @return The trust comment
2829                  */
2830                 public String getTrustComment() {
2831                         return options.getStringOption("TrustComment").get();
2832                 }
2833
2834                 /**
2835                  * Sets the trust comment.
2836                  *
2837                  * @param trustComment
2838                  *            The trust comment, or {@code null} to restore it to the
2839                  *            default value
2840                  * @return This preferences
2841                  */
2842                 public Preferences setTrustComment(String trustComment) {
2843                         options.getStringOption("TrustComment").set(trustComment);
2844                         return this;
2845                 }
2846
2847                 /**
2848                  * Returns whether the {@link FcpInterface FCP interface} is currently
2849                  * active.
2850                  *
2851                  * @see FcpInterface#setActive(boolean)
2852                  * @return {@code true} if the FCP interface is currently active,
2853                  *         {@code false} otherwise
2854                  */
2855                 public boolean isFcpInterfaceActive() {
2856                         return options.getBooleanOption("ActivateFcpInterface").get();
2857                 }
2858
2859                 /**
2860                  * Sets whether the {@link FcpInterface FCP interface} is currently
2861                  * active.
2862                  *
2863                  * @see FcpInterface#setActive(boolean)
2864                  * @param fcpInterfaceActive
2865                  *            {@code true} to activate the FCP interface, {@code false}
2866                  *            to deactivate the FCP interface
2867                  * @return This preferences object
2868                  */
2869                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2870                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2871                         return this;
2872                 }
2873
2874                 /**
2875                  * Returns the action level for which full access to the FCP interface
2876                  * is required.
2877                  *
2878                  * @return The action level for which full access to the FCP interface
2879                  *         is required
2880                  */
2881                 public FullAccessRequired getFcpFullAccessRequired() {
2882                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2883                 }
2884
2885                 /**
2886                  * Sets the action level for which full access to the FCP interface is
2887                  * required
2888                  *
2889                  * @param fcpFullAccessRequired
2890                  *            The action level
2891                  * @return This preferences
2892                  */
2893                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2894                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2895                         return this;
2896                 }
2897
2898         }
2899
2900 }