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