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