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