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