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