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