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