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