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