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