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