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