Always store all own identities.
[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                                                         } else if (!knownPosts.contains(post.getId())) {
1164                                                                 sone.setKnown(false);
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                                                         } else if (!knownReplies.contains(reply.getId())) {
1189                                                                 reply.setKnown(false);
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                 if (!isLocalSone(sone)) {
1583                         logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1584                         return null;
1585                 }
1586                 final Post post = new PostImpl(sone, time, text);
1587                 if (recipient != null) {
1588                         post.setRecipient(recipient);
1589                 }
1590                 synchronized (posts) {
1591                         posts.put(post.getId(), post);
1592                 }
1593                 coreListenerManager.fireNewPostFound(post);
1594                 sone.addPost(post);
1595                 touchConfiguration();
1596                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1597
1598                         /**
1599                          * {@inheritDoc}
1600                          */
1601                         @Override
1602                         public void run() {
1603                                 markPostKnown(post);
1604                         }
1605                 }, "Mark " + post + " read.");
1606                 return post;
1607         }
1608
1609         /**
1610          * Deletes the given post.
1611          *
1612          * @param post
1613          *            The post to delete
1614          */
1615         public void deletePost(Post post) {
1616                 if (!isLocalSone(post.getSone())) {
1617                         logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1618                         return;
1619                 }
1620                 post.getSone().removePost(post);
1621                 synchronized (posts) {
1622                         posts.remove(post.getId());
1623                 }
1624                 coreListenerManager.firePostRemoved(post);
1625                 markPostKnown(post);
1626                 touchConfiguration();
1627         }
1628
1629         /**
1630          * Marks the given post as known, if it is currently not a known post
1631          * (according to {@link Post#isKnown()}).
1632          *
1633          * @param post
1634          *            The post to mark as known
1635          */
1636         public void markPostKnown(Post post) {
1637                 post.setKnown(true);
1638                 synchronized (knownPosts) {
1639                         coreListenerManager.fireMarkPostKnown(post);
1640                         if (knownPosts.add(post.getId())) {
1641                                 touchConfiguration();
1642                         }
1643                 }
1644                 for (PostReply reply : getReplies(post)) {
1645                         markReplyKnown(reply);
1646                 }
1647         }
1648
1649         /**
1650          * Bookmarks the given post.
1651          *
1652          * @param post
1653          *            The post to bookmark
1654          */
1655         public void bookmark(Post post) {
1656                 bookmarkPost(post.getId());
1657         }
1658
1659         /**
1660          * Bookmarks the post with the given ID.
1661          *
1662          * @param id
1663          *            The ID of the post to bookmark
1664          */
1665         public void bookmarkPost(String id) {
1666                 synchronized (bookmarkedPosts) {
1667                         bookmarkedPosts.add(id);
1668                 }
1669         }
1670
1671         /**
1672          * Removes the given post from the bookmarks.
1673          *
1674          * @param post
1675          *            The post to unbookmark
1676          */
1677         public void unbookmark(Post post) {
1678                 unbookmarkPost(post.getId());
1679         }
1680
1681         /**
1682          * Removes the post with the given ID from the bookmarks.
1683          *
1684          * @param id
1685          *            The ID of the post to unbookmark
1686          */
1687         public void unbookmarkPost(String id) {
1688                 synchronized (bookmarkedPosts) {
1689                         bookmarkedPosts.remove(id);
1690                 }
1691         }
1692
1693         /**
1694          * Creates a new reply.
1695          *
1696          * @param sone
1697          *            The Sone that creates the reply
1698          * @param post
1699          *            The post that this reply refers to
1700          * @param text
1701          *            The text of the reply
1702          * @return The created reply
1703          */
1704         public PostReply createReply(Sone sone, Post post, String text) {
1705                 return createReply(sone, post, System.currentTimeMillis(), text);
1706         }
1707
1708         /**
1709          * Creates a new reply.
1710          *
1711          * @param sone
1712          *            The Sone that creates the reply
1713          * @param post
1714          *            The post that this reply refers to
1715          * @param time
1716          *            The time of the reply
1717          * @param text
1718          *            The text of the reply
1719          * @return The created reply
1720          */
1721         public PostReply createReply(Sone sone, Post post, long time, String text) {
1722                 if (!isLocalSone(sone)) {
1723                         logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1724                         return null;
1725                 }
1726                 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1727                 synchronized (replies) {
1728                         replies.put(reply.getId(), reply);
1729                 }
1730                 synchronized (knownReplies) {
1731                         coreListenerManager.fireNewReplyFound(reply);
1732                 }
1733                 sone.addReply(reply);
1734                 touchConfiguration();
1735                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1736
1737                         /**
1738                          * {@inheritDoc}
1739                          */
1740                         @Override
1741                         public void run() {
1742                                 markReplyKnown(reply);
1743                         }
1744                 }, "Mark " + reply + " read.");
1745                 return reply;
1746         }
1747
1748         /**
1749          * Deletes the given reply.
1750          *
1751          * @param reply
1752          *            The reply to delete
1753          */
1754         public void deleteReply(PostReply reply) {
1755                 Sone sone = reply.getSone();
1756                 if (!isLocalSone(sone)) {
1757                         logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1758                         return;
1759                 }
1760                 synchronized (replies) {
1761                         replies.remove(reply.getId());
1762                 }
1763                 synchronized (knownReplies) {
1764                         markReplyKnown(reply);
1765                         knownReplies.remove(reply.getId());
1766                 }
1767                 sone.removeReply(reply);
1768                 touchConfiguration();
1769         }
1770
1771         /**
1772          * Marks the given reply as known, if it is currently not a known reply
1773          * (according to {@link Reply#isKnown()}).
1774          *
1775          * @param reply
1776          *            The reply to mark as known
1777          */
1778         public void markReplyKnown(PostReply reply) {
1779                 reply.setKnown(true);
1780                 synchronized (knownReplies) {
1781                         coreListenerManager.fireMarkReplyKnown(reply);
1782                         if (knownReplies.add(reply.getId())) {
1783                                 touchConfiguration();
1784                         }
1785                 }
1786         }
1787
1788         /**
1789          * Creates a new top-level album for the given Sone.
1790          *
1791          * @param sone
1792          *            The Sone to create the album for
1793          * @return The new album
1794          */
1795         public Album createAlbum(Sone sone) {
1796                 return createAlbum(sone, null);
1797         }
1798
1799         /**
1800          * Creates a new album for the given Sone.
1801          *
1802          * @param sone
1803          *            The Sone to create the album for
1804          * @param parent
1805          *            The parent of the album (may be {@code null} to create a
1806          *            top-level album)
1807          * @return The new album
1808          */
1809         public Album createAlbum(Sone sone, Album parent) {
1810                 Album album = new Album();
1811                 synchronized (albums) {
1812                         albums.put(album.getId(), album);
1813                 }
1814                 album.setSone(sone);
1815                 if (parent != null) {
1816                         parent.addAlbum(album);
1817                 } else {
1818                         sone.addAlbum(album);
1819                 }
1820                 return album;
1821         }
1822
1823         /**
1824          * Deletes the given album. The owner of the album has to be a local Sone,
1825          * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1826          *
1827          * @param album
1828          *            The album to remove
1829          */
1830         public void deleteAlbum(Album album) {
1831                 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1832                 if (!album.isEmpty()) {
1833                         return;
1834                 }
1835                 if (album.getParent() == null) {
1836                         album.getSone().removeAlbum(album);
1837                 } else {
1838                         album.getParent().removeAlbum(album);
1839                 }
1840                 synchronized (albums) {
1841                         albums.remove(album.getId());
1842                 }
1843                 touchConfiguration();
1844         }
1845
1846         /**
1847          * Creates a new image.
1848          *
1849          * @param sone
1850          *            The Sone creating the image
1851          * @param album
1852          *            The album the image will be inserted into
1853          * @param temporaryImage
1854          *            The temporary image to create the image from
1855          * @return The newly created image
1856          */
1857         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1858                 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();
1859                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1860                 album.addImage(image);
1861                 synchronized (images) {
1862                         images.put(image.getId(), image);
1863                 }
1864                 imageInserter.insertImage(temporaryImage, image);
1865                 return image;
1866         }
1867
1868         /**
1869          * Deletes the given image. This method will also delete a matching
1870          * temporary image.
1871          *
1872          * @see #deleteTemporaryImage(TemporaryImage)
1873          * @param image
1874          *            The image to delete
1875          */
1876         public void deleteImage(Image image) {
1877                 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1878                 deleteTemporaryImage(image.getId());
1879                 image.getAlbum().removeImage(image);
1880                 synchronized (images) {
1881                         images.remove(image.getId());
1882                 }
1883                 touchConfiguration();
1884         }
1885
1886         /**
1887          * Creates a new temporary image.
1888          *
1889          * @param mimeType
1890          *            The MIME type of the temporary image
1891          * @param imageData
1892          *            The encoded data of the image
1893          * @return The temporary image
1894          */
1895         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1896                 TemporaryImage temporaryImage = new TemporaryImage();
1897                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1898                 synchronized (temporaryImages) {
1899                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1900                 }
1901                 return temporaryImage;
1902         }
1903
1904         /**
1905          * Deletes the given temporary image.
1906          *
1907          * @param temporaryImage
1908          *            The temporary image to delete
1909          */
1910         public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1911                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1912                 deleteTemporaryImage(temporaryImage.getId());
1913         }
1914
1915         /**
1916          * Deletes the temporary image with the given ID.
1917          *
1918          * @param imageId
1919          *            The ID of the temporary image to delete
1920          */
1921         public void deleteTemporaryImage(String imageId) {
1922                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1923                 synchronized (temporaryImages) {
1924                         temporaryImages.remove(imageId);
1925                 }
1926                 Image image = getImage(imageId, false);
1927                 if (image != null) {
1928                         imageInserter.cancelImageInsert(image);
1929                 }
1930         }
1931
1932         /**
1933          * Notifies the core that the configuration, either of the core or of a
1934          * single local Sone, has changed, and that the configuration should be
1935          * saved.
1936          */
1937         public void touchConfiguration() {
1938                 lastConfigurationUpdate = System.currentTimeMillis();
1939         }
1940
1941         //
1942         // SERVICE METHODS
1943         //
1944
1945         /**
1946          * Starts the core.
1947          */
1948         @Override
1949         public void serviceStart() {
1950                 loadConfiguration();
1951                 updateChecker.addUpdateListener(this);
1952                 updateChecker.start();
1953                 webOfTrustUpdater.start();
1954         }
1955
1956         /**
1957          * {@inheritDoc}
1958          */
1959         @Override
1960         public void serviceRun() {
1961                 long lastSaved = System.currentTimeMillis();
1962                 while (!shouldStop()) {
1963                         sleep(1000);
1964                         long now = System.currentTimeMillis();
1965                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1966                                 for (Sone localSone : getLocalSones()) {
1967                                         saveSone(localSone);
1968                                 }
1969                                 saveConfiguration();
1970                                 lastSaved = now;
1971                         }
1972                 }
1973         }
1974
1975         /**
1976          * Stops the core.
1977          */
1978         @Override
1979         public void serviceStop() {
1980                 synchronized (localSones) {
1981                         for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1982                                 soneInserter.getValue().removeSoneInsertListener(this);
1983                                 soneInserter.getValue().stop();
1984                                 saveSone(soneInserter.getKey());
1985                         }
1986                 }
1987                 saveConfiguration();
1988                 webOfTrustUpdater.stop();
1989                 updateChecker.stop();
1990                 updateChecker.removeUpdateListener(this);
1991                 soneDownloader.stop();
1992         }
1993
1994         //
1995         // PRIVATE METHODS
1996         //
1997
1998         /**
1999          * Saves the given Sone. This will persist all local settings for the given
2000          * Sone, such as the friends list and similar, private options.
2001          *
2002          * @param sone
2003          *            The Sone to save
2004          */
2005         private synchronized void saveSone(Sone sone) {
2006                 if (!isLocalSone(sone)) {
2007                         logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2008                         return;
2009                 }
2010                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2011                         logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2012                         return;
2013                 }
2014
2015                 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2016                 try {
2017                         /* save Sone into configuration. */
2018                         String sonePrefix = "Sone/" + sone.getId();
2019                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2020                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2021
2022                         /* save profile. */
2023                         Profile profile = sone.getProfile();
2024                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2025                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2026                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2027                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2028                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2029                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2030                         configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2031
2032                         /* save profile fields. */
2033                         int fieldCounter = 0;
2034                         for (Field profileField : profile.getFields()) {
2035                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2036                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2037                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2038                         }
2039                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2040
2041                         /* save posts. */
2042                         int postCounter = 0;
2043                         for (Post post : sone.getPosts()) {
2044                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2045                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2046                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2047                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2048                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2049                         }
2050                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2051
2052                         /* save replies. */
2053                         int replyCounter = 0;
2054                         for (PostReply reply : sone.getReplies()) {
2055                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2056                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2057                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2058                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2059                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2060                         }
2061                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2062
2063                         /* save post likes. */
2064                         int postLikeCounter = 0;
2065                         for (String postId : sone.getLikedPostIds()) {
2066                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2067                         }
2068                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2069
2070                         /* save reply likes. */
2071                         int replyLikeCounter = 0;
2072                         for (String replyId : sone.getLikedReplyIds()) {
2073                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2074                         }
2075                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2076
2077                         /* save friends. */
2078                         int friendCounter = 0;
2079                         for (String friendId : sone.getFriends()) {
2080                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2081                         }
2082                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2083
2084                         /* save albums. first, collect in a flat structure, top-level first. */
2085                         List<Album> albums = sone.getAllAlbums();
2086
2087                         int albumCounter = 0;
2088                         for (Album album : albums) {
2089                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2090                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2091                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2092                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2093                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2094                                 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2095                         }
2096                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2097
2098                         /* save images. */
2099                         int imageCounter = 0;
2100                         for (Album album : albums) {
2101                                 for (Image image : album.getImages()) {
2102                                         if (!image.isInserted()) {
2103                                                 continue;
2104                                         }
2105                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2106                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2107                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2108                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2109                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2110                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2111                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2112                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2113                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2114                                 }
2115                         }
2116                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2117
2118                         /* save options. */
2119                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2120                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2121                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2122                         configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2123                         configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2124                         configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2125
2126                         configuration.save();
2127
2128                         webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2129
2130                         logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2131                 } catch (ConfigurationException ce1) {
2132                         logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2133                 }
2134         }
2135
2136         /**
2137          * Saves the current options.
2138          */
2139         private void saveConfiguration() {
2140                 synchronized (configuration) {
2141                         if (storingConfiguration) {
2142                                 logger.log(Level.FINE, "Already storing configuration…");
2143                                 return;
2144                         }
2145                         storingConfiguration = true;
2146                 }
2147
2148                 /* store the options first. */
2149                 try {
2150                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2151                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2152                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2153                         configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2154                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2155                         configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2156                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2157                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2158                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2159                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2160                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2161                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2162
2163                         /* save known Sones. */
2164                         int soneCounter = 0;
2165                         synchronized (knownSones) {
2166                                 for (String knownSoneId : knownSones) {
2167                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2168                                 }
2169                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2170                         }
2171
2172                         /* save Sone following times. */
2173                         soneCounter = 0;
2174                         synchronized (soneFollowingTimes) {
2175                                 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2176                                         configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2177                                         configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2178                                         ++soneCounter;
2179                                 }
2180                                 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2181                         }
2182
2183                         /* save known posts. */
2184                         int postCounter = 0;
2185                         synchronized (knownPosts) {
2186                                 for (String knownPostId : knownPosts) {
2187                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2188                                 }
2189                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2190                         }
2191
2192                         /* save known replies. */
2193                         int replyCounter = 0;
2194                         synchronized (knownReplies) {
2195                                 for (String knownReplyId : knownReplies) {
2196                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2197                                 }
2198                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2199                         }
2200
2201                         /* save bookmarked posts. */
2202                         int bookmarkedPostCounter = 0;
2203                         synchronized (bookmarkedPosts) {
2204                                 for (String bookmarkedPostId : bookmarkedPosts) {
2205                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2206                                 }
2207                         }
2208                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2209
2210                         /* now save it. */
2211                         configuration.save();
2212
2213                 } catch (ConfigurationException ce1) {
2214                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2215                 } finally {
2216                         synchronized (configuration) {
2217                                 storingConfiguration = false;
2218                         }
2219                 }
2220         }
2221
2222         /**
2223          * Loads the configuration.
2224          */
2225         @SuppressWarnings("unchecked")
2226         private void loadConfiguration() {
2227                 /* create options. */
2228                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2229
2230                         @Override
2231                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2232                                 SoneInserter.setInsertionDelay(newValue);
2233                         }
2234
2235                 }));
2236                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2237                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2238                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2239                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2240                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2241                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2242                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2243                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2244                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2245
2246                         @Override
2247                         @SuppressWarnings("synthetic-access")
2248                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2249                                 fcpInterface.setActive(newValue);
2250                         }
2251                 }));
2252                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2253
2254                         @Override
2255                         @SuppressWarnings("synthetic-access")
2256                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2257                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2258                         }
2259
2260                 }));
2261
2262                 loadConfigurationValue("InsertionDelay");
2263                 loadConfigurationValue("PostsPerPage");
2264                 loadConfigurationValue("ImagesPerPage");
2265                 loadConfigurationValue("CharactersPerPost");
2266                 loadConfigurationValue("PostCutOffLength");
2267                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2268                 loadConfigurationValue("PositiveTrust");
2269                 loadConfigurationValue("NegativeTrust");
2270                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2271                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2272                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2273
2274                 /* load known Sones. */
2275                 int soneCounter = 0;
2276                 while (true) {
2277                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2278                         if (knownSoneId == null) {
2279                                 break;
2280                         }
2281                         synchronized (knownSones) {
2282                                 knownSones.add(knownSoneId);
2283                         }
2284                 }
2285
2286                 /* load Sone following times. */
2287                 soneCounter = 0;
2288                 while (true) {
2289                         String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2290                         if (soneId == null) {
2291                                 break;
2292                         }
2293                         long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2294                         Sone followedSone = getSone(soneId);
2295                         if (followedSone == null) {
2296                                 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2297                         } else {
2298                                 synchronized (soneFollowingTimes) {
2299                                         soneFollowingTimes.put(getSone(soneId), time);
2300                                 }
2301                         }
2302                         ++soneCounter;
2303                 }
2304
2305                 /* load known posts. */
2306                 int postCounter = 0;
2307                 while (true) {
2308                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2309                         if (knownPostId == null) {
2310                                 break;
2311                         }
2312                         synchronized (knownPosts) {
2313                                 knownPosts.add(knownPostId);
2314                         }
2315                 }
2316
2317                 /* load known replies. */
2318                 int replyCounter = 0;
2319                 while (true) {
2320                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2321                         if (knownReplyId == null) {
2322                                 break;
2323                         }
2324                         synchronized (knownReplies) {
2325                                 knownReplies.add(knownReplyId);
2326                         }
2327                 }
2328
2329                 /* load bookmarked posts. */
2330                 int bookmarkedPostCounter = 0;
2331                 while (true) {
2332                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2333                         if (bookmarkedPostId == null) {
2334                                 break;
2335                         }
2336                         synchronized (bookmarkedPosts) {
2337                                 bookmarkedPosts.add(bookmarkedPostId);
2338                         }
2339                 }
2340
2341         }
2342
2343         /**
2344          * Loads an {@link Integer} configuration value for the option with the
2345          * given name, logging validation failures.
2346          *
2347          * @param optionName
2348          *            The name of the option to load
2349          */
2350         private void loadConfigurationValue(String optionName) {
2351                 try {
2352                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2353                 } catch (IllegalArgumentException iae1) {
2354                         logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2355                 }
2356         }
2357
2358         /**
2359          * Generate a Sone URI from the given URI and latest edition.
2360          *
2361          * @param uriString
2362          *            The URI to derive the Sone URI from
2363          * @return The derived URI
2364          */
2365         private static FreenetURI getSoneUri(String uriString) {
2366                 try {
2367                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2368                         return uri;
2369                 } catch (MalformedURLException mue1) {
2370                         logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2371                         return null;
2372                 }
2373         }
2374
2375         //
2376         // INTERFACE IdentityListener
2377         //
2378
2379         /**
2380          * {@inheritDoc}
2381          */
2382         @Override
2383         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2384                 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2385                 if (ownIdentity.hasContext("Sone")) {
2386                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2387                         addLocalSone(ownIdentity);
2388                 }
2389         }
2390
2391         /**
2392          * {@inheritDoc}
2393          */
2394         @Override
2395         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2396                 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2397                 trustedIdentities.remove(ownIdentity);
2398         }
2399
2400         /**
2401          * {@inheritDoc}
2402          */
2403         @Override
2404         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2405                 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2406                 trustedIdentities.get(ownIdentity).add(identity);
2407                 addRemoteSone(identity);
2408         }
2409
2410         /**
2411          * {@inheritDoc}
2412          */
2413         @Override
2414         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2415                 new Thread(new Runnable() {
2416
2417                         @Override
2418                         @SuppressWarnings("synthetic-access")
2419                         public void run() {
2420                                 Sone sone = getRemoteSone(identity.getId(), false);
2421                                 sone.setIdentity(identity);
2422                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2423                                 soneDownloader.addSone(sone);
2424                                 soneDownloader.fetchSone(sone);
2425                         }
2426                 }).start();
2427         }
2428
2429         /**
2430          * {@inheritDoc}
2431          */
2432         @Override
2433         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2434                 trustedIdentities.get(ownIdentity).remove(identity);
2435                 boolean foundIdentity = false;
2436                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2437                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2438                                 continue;
2439                         }
2440                         if (trustedIdentity.getValue().contains(identity)) {
2441                                 foundIdentity = true;
2442                         }
2443                 }
2444                 if (foundIdentity) {
2445                         /* some local identity still trusts this identity, don’t remove. */
2446                         return;
2447                 }
2448                 Sone sone = getSone(identity.getId(), false);
2449                 if (sone == null) {
2450                         /* TODO - we don’t have the Sone anymore. should this happen? */
2451                         return;
2452                 }
2453                 synchronized (posts) {
2454                         synchronized (knownPosts) {
2455                                 for (Post post : sone.getPosts()) {
2456                                         posts.remove(post.getId());
2457                                         coreListenerManager.firePostRemoved(post);
2458                                 }
2459                         }
2460                 }
2461                 synchronized (replies) {
2462                         synchronized (knownReplies) {
2463                                 for (PostReply reply : sone.getReplies()) {
2464                                         replies.remove(reply.getId());
2465                                         coreListenerManager.fireReplyRemoved(reply);
2466                                 }
2467                         }
2468                 }
2469                 synchronized (remoteSones) {
2470                         remoteSones.remove(identity.getId());
2471                 }
2472                 coreListenerManager.fireSoneRemoved(sone);
2473         }
2474
2475         //
2476         // INTERFACE UpdateListener
2477         //
2478
2479         /**
2480          * {@inheritDoc}
2481          */
2482         @Override
2483         public void updateFound(Version version, long releaseTime, long latestEdition) {
2484                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2485         }
2486
2487         //
2488         // INTERFACE ImageInsertListener
2489         //
2490
2491         /**
2492          * {@inheritDoc}
2493          */
2494         @Override
2495         public void insertStarted(Sone sone) {
2496                 coreListenerManager.fireSoneInserting(sone);
2497         }
2498
2499         /**
2500          * {@inheritDoc}
2501          */
2502         @Override
2503         public void insertFinished(Sone sone, long insertDuration) {
2504                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2505         }
2506
2507         /**
2508          * {@inheritDoc}
2509          */
2510         @Override
2511         public void insertAborted(Sone sone, Throwable cause) {
2512                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2513         }
2514
2515         //
2516         // SONEINSERTLISTENER METHODS
2517         //
2518
2519         /**
2520          * {@inheritDoc}
2521          */
2522         @Override
2523         public void imageInsertStarted(Image image) {
2524                 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2525                 coreListenerManager.fireImageInsertStarted(image);
2526         }
2527
2528         /**
2529          * {@inheritDoc}
2530          */
2531         @Override
2532         public void imageInsertAborted(Image image) {
2533                 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2534                 coreListenerManager.fireImageInsertAborted(image);
2535         }
2536
2537         /**
2538          * {@inheritDoc}
2539          */
2540         @Override
2541         public void imageInsertFinished(Image image, FreenetURI key) {
2542                 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2543                 image.setKey(key.toString());
2544                 deleteTemporaryImage(image.getId());
2545                 touchConfiguration();
2546                 coreListenerManager.fireImageInsertFinished(image);
2547         }
2548
2549         /**
2550          * {@inheritDoc}
2551          */
2552         @Override
2553         public void imageInsertFailed(Image image, Throwable cause) {
2554                 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2555                 coreListenerManager.fireImageInsertFailed(image, cause);
2556         }
2557
2558         /**
2559          * Convenience interface for external classes that want to access the core’s
2560          * configuration.
2561          *
2562          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2563          */
2564         public static class Preferences {
2565
2566                 /** The wrapped options. */
2567                 private final Options options;
2568
2569                 /**
2570                  * Creates a new preferences object wrapped around the given options.
2571                  *
2572                  * @param options
2573                  *            The options to wrap
2574                  */
2575                 public Preferences(Options options) {
2576                         this.options = options;
2577                 }
2578
2579                 /**
2580                  * Returns the insertion delay.
2581                  *
2582                  * @return The insertion delay
2583                  */
2584                 public int getInsertionDelay() {
2585                         return options.getIntegerOption("InsertionDelay").get();
2586                 }
2587
2588                 /**
2589                  * Validates the given insertion delay.
2590                  *
2591                  * @param insertionDelay
2592                  *            The insertion delay to validate
2593                  * @return {@code true} if the given insertion delay was valid,
2594                  *         {@code false} otherwise
2595                  */
2596                 public boolean validateInsertionDelay(Integer insertionDelay) {
2597                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2598                 }
2599
2600                 /**
2601                  * Sets the insertion delay
2602                  *
2603                  * @param insertionDelay
2604                  *            The new insertion delay, or {@code null} to restore it to
2605                  *            the default value
2606                  * @return This preferences
2607                  */
2608                 public Preferences setInsertionDelay(Integer insertionDelay) {
2609                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2610                         return this;
2611                 }
2612
2613                 /**
2614                  * Returns the number of posts to show per page.
2615                  *
2616                  * @return The number of posts to show per page
2617                  */
2618                 public int getPostsPerPage() {
2619                         return options.getIntegerOption("PostsPerPage").get();
2620                 }
2621
2622                 /**
2623                  * Validates the number of posts per page.
2624                  *
2625                  * @param postsPerPage
2626                  *            The number of posts per page
2627                  * @return {@code true} if the number of posts per page was valid,
2628                  *         {@code false} otherwise
2629                  */
2630                 public boolean validatePostsPerPage(Integer postsPerPage) {
2631                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2632                 }
2633
2634                 /**
2635                  * Sets the number of posts to show per page.
2636                  *
2637                  * @param postsPerPage
2638                  *            The number of posts to show per page
2639                  * @return This preferences object
2640                  */
2641                 public Preferences setPostsPerPage(Integer postsPerPage) {
2642                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2643                         return this;
2644                 }
2645
2646                 /**
2647                  * Returns the number of images to show per page.
2648                  *
2649                  * @return The number of images to show per page
2650                  */
2651                 public int getImagesPerPage() {
2652                         return options.getIntegerOption("ImagesPerPage").get();
2653                 }
2654
2655                 /**
2656                  * Validates the number of images per page.
2657                  *
2658                  * @param imagesPerPage
2659                  *            The number of images per page
2660                  * @return {@code true} if the number of images per page was valid,
2661                  *         {@code false} otherwise
2662                  */
2663                 public boolean validateImagesPerPage(Integer imagesPerPage) {
2664                         return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2665                 }
2666
2667                 /**
2668                  * Sets the number of images per page.
2669                  *
2670                  * @param imagesPerPage
2671                  *            The number of images per page
2672                  * @return This preferences object
2673                  */
2674                 public Preferences setImagesPerPage(Integer imagesPerPage) {
2675                         options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2676                         return this;
2677                 }
2678
2679                 /**
2680                  * Returns the number of characters per post, or <code>-1</code> if the
2681                  * posts should not be cut off.
2682                  *
2683                  * @return The numbers of characters per post
2684                  */
2685                 public int getCharactersPerPost() {
2686                         return options.getIntegerOption("CharactersPerPost").get();
2687                 }
2688
2689                 /**
2690                  * Validates the number of characters per post.
2691                  *
2692                  * @param charactersPerPost
2693                  *            The number of characters per post
2694                  * @return {@code true} if the number of characters per post was valid,
2695                  *         {@code false} otherwise
2696                  */
2697                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2698                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2699                 }
2700
2701                 /**
2702                  * Sets the number of characters per post.
2703                  *
2704                  * @param charactersPerPost
2705                  *            The number of characters per post, or <code>-1</code> to
2706                  *            not cut off the posts
2707                  * @return This preferences objects
2708                  */
2709                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2710                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2711                         return this;
2712                 }
2713
2714                 /**
2715                  * Returns the number of characters the shortened post should have.
2716                  *
2717                  * @return The number of characters of the snippet
2718                  */
2719                 public int getPostCutOffLength() {
2720                         return options.getIntegerOption("PostCutOffLength").get();
2721                 }
2722
2723                 /**
2724                  * Validates the number of characters after which to cut off the post.
2725                  *
2726                  * @param postCutOffLength
2727                  *            The number of characters of the snippet
2728                  * @return {@code true} if the number of characters of the snippet is
2729                  *         valid, {@code false} otherwise
2730                  */
2731                 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2732                         return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2733                 }
2734
2735                 /**
2736                  * Sets the number of characters the shortened post should have.
2737                  *
2738                  * @param postCutOffLength
2739                  *            The number of characters of the snippet
2740                  * @return This preferences
2741                  */
2742                 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2743                         options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2744                         return this;
2745                 }
2746
2747                 /**
2748                  * Returns whether Sone requires full access to be even visible.
2749                  *
2750                  * @return {@code true} if Sone requires full access, {@code false}
2751                  *         otherwise
2752                  */
2753                 public boolean isRequireFullAccess() {
2754                         return options.getBooleanOption("RequireFullAccess").get();
2755                 }
2756
2757                 /**
2758                  * Sets whether Sone requires full access to be even visible.
2759                  *
2760                  * @param requireFullAccess
2761                  *            {@code true} if Sone requires full access, {@code false}
2762                  *            otherwise
2763                  */
2764                 public void setRequireFullAccess(Boolean requireFullAccess) {
2765                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2766                 }
2767
2768                 /**
2769                  * Returns the positive trust.
2770                  *
2771                  * @return The positive trust
2772                  */
2773                 public int getPositiveTrust() {
2774                         return options.getIntegerOption("PositiveTrust").get();
2775                 }
2776
2777                 /**
2778                  * Validates the positive trust.
2779                  *
2780                  * @param positiveTrust
2781                  *            The positive trust to validate
2782                  * @return {@code true} if the positive trust was valid, {@code false}
2783                  *         otherwise
2784                  */
2785                 public boolean validatePositiveTrust(Integer positiveTrust) {
2786                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2787                 }
2788
2789                 /**
2790                  * Sets the positive trust.
2791                  *
2792                  * @param positiveTrust
2793                  *            The new positive trust, or {@code null} to restore it to
2794                  *            the default vlaue
2795                  * @return This preferences
2796                  */
2797                 public Preferences setPositiveTrust(Integer positiveTrust) {
2798                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2799                         return this;
2800                 }
2801
2802                 /**
2803                  * Returns the negative trust.
2804                  *
2805                  * @return The negative trust
2806                  */
2807                 public int getNegativeTrust() {
2808                         return options.getIntegerOption("NegativeTrust").get();
2809                 }
2810
2811                 /**
2812                  * Validates the negative trust.
2813                  *
2814                  * @param negativeTrust
2815                  *            The negative trust to validate
2816                  * @return {@code true} if the negative trust was valid, {@code false}
2817                  *         otherwise
2818                  */
2819                 public boolean validateNegativeTrust(Integer negativeTrust) {
2820                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2821                 }
2822
2823                 /**
2824                  * Sets the negative trust.
2825                  *
2826                  * @param negativeTrust
2827                  *            The negative trust, or {@code null} to restore it to the
2828                  *            default value
2829                  * @return The preferences
2830                  */
2831                 public Preferences setNegativeTrust(Integer negativeTrust) {
2832                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2833                         return this;
2834                 }
2835
2836                 /**
2837                  * Returns the trust comment. This is the comment that is set in the web
2838                  * of trust when a trust value is assigned to an identity.
2839                  *
2840                  * @return The trust comment
2841                  */
2842                 public String getTrustComment() {
2843                         return options.getStringOption("TrustComment").get();
2844                 }
2845
2846                 /**
2847                  * Sets the trust comment.
2848                  *
2849                  * @param trustComment
2850                  *            The trust comment, or {@code null} to restore it to the
2851                  *            default value
2852                  * @return This preferences
2853                  */
2854                 public Preferences setTrustComment(String trustComment) {
2855                         options.getStringOption("TrustComment").set(trustComment);
2856                         return this;
2857                 }
2858
2859                 /**
2860                  * Returns whether the {@link FcpInterface FCP interface} is currently
2861                  * active.
2862                  *
2863                  * @see FcpInterface#setActive(boolean)
2864                  * @return {@code true} if the FCP interface is currently active,
2865                  *         {@code false} otherwise
2866                  */
2867                 public boolean isFcpInterfaceActive() {
2868                         return options.getBooleanOption("ActivateFcpInterface").get();
2869                 }
2870
2871                 /**
2872                  * Sets whether the {@link FcpInterface FCP interface} is currently
2873                  * active.
2874                  *
2875                  * @see FcpInterface#setActive(boolean)
2876                  * @param fcpInterfaceActive
2877                  *            {@code true} to activate the FCP interface, {@code false}
2878                  *            to deactivate the FCP interface
2879                  * @return This preferences object
2880                  */
2881                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2882                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2883                         return this;
2884                 }
2885
2886                 /**
2887                  * Returns the action level for which full access to the FCP interface
2888                  * is required.
2889                  *
2890                  * @return The action level for which full access to the FCP interface
2891                  *         is required
2892                  */
2893                 public FullAccessRequired getFcpFullAccessRequired() {
2894                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2895                 }
2896
2897                 /**
2898                  * Sets the action level for which full access to the FCP interface is
2899                  * required
2900                  *
2901                  * @param fcpFullAccessRequired
2902                  *            The action level
2903                  * @return This preferences
2904                  */
2905                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2906                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2907                         return this;
2908                 }
2909
2910         }
2911
2912 }