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