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