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