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