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