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