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