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