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