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