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