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