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