59116751188b5064633cab1ebce3d45e8ce8b693
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * Sone - Core.java - Copyright © 2010 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.core.Options.DefaultOption;
32 import net.pterodactylus.sone.core.Options.Option;
33 import net.pterodactylus.sone.core.Options.OptionWatcher;
34 import net.pterodactylus.sone.data.Album;
35 import net.pterodactylus.sone.data.Client;
36 import net.pterodactylus.sone.data.Image;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.Profile;
39 import net.pterodactylus.sone.data.Profile.Field;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.TemporaryImage;
43 import net.pterodactylus.sone.freenet.wot.Identity;
44 import net.pterodactylus.sone.freenet.wot.IdentityListener;
45 import net.pterodactylus.sone.freenet.wot.IdentityManager;
46 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
47 import net.pterodactylus.sone.freenet.wot.Trust;
48 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
49 import net.pterodactylus.sone.main.SonePlugin;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
52 import net.pterodactylus.util.logging.Logging;
53 import net.pterodactylus.util.number.Numbers;
54 import net.pterodactylus.util.validation.Validation;
55 import net.pterodactylus.util.version.Version;
56 import freenet.keys.FreenetURI;
57
58 /**
59  * The Sone core.
60  *
61  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
62  */
63 public class Core implements IdentityListener, UpdateListener, ImageInsertListener {
64
65         /**
66          * Enumeration for the possible states of a {@link Sone}.
67          *
68          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69          */
70         public enum SoneStatus {
71
72                 /** The Sone is unknown, i.e. not yet downloaded. */
73                 unknown,
74
75                 /** The Sone is idle, i.e. not being downloaded or inserted. */
76                 idle,
77
78                 /** The Sone is currently being inserted. */
79                 inserting,
80
81                 /** The Sone is currently being downloaded. */
82                 downloading,
83         }
84
85         /** The logger. */
86         private static final Logger logger = Logging.getLogger(Core.class);
87
88         /** The options. */
89         private final Options options = new Options();
90
91         /** The preferences. */
92         private final Preferences preferences = new Preferences(options);
93
94         /** The core listener manager. */
95         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
96
97         /** The configuration. */
98         private Configuration configuration;
99
100         /** Whether we’re currently saving the configuration. */
101         private boolean storingConfiguration = false;
102
103         /** The identity manager. */
104         private final IdentityManager identityManager;
105
106         /** Interface to freenet. */
107         private final FreenetInterface freenetInterface;
108
109         /** The Sone downloader. */
110         private final SoneDownloader soneDownloader;
111
112         /** The image inserter. */
113         private final ImageInserter imageInserter;
114
115         /** The update checker. */
116         private final UpdateChecker updateChecker;
117
118         /** Whether the core has been stopped. */
119         private volatile boolean stopped;
120
121         /** The Sones’ statuses. */
122         /* synchronize access on itself. */
123         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
124
125         /** Locked local Sones. */
126         /* synchronize on itself. */
127         private final Set<Sone> lockedSones = new HashSet<Sone>();
128
129         /** Sone inserters. */
130         /* synchronize access on this on localSones. */
131         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
132
133         /** All local Sones. */
134         /* synchronize access on this on itself. */
135         private Map<String, Sone> localSones = new HashMap<String, Sone>();
136
137         /** All remote Sones. */
138         /* synchronize access on this on itself. */
139         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
140
141         /** All new Sones. */
142         private Set<String> newSones = new HashSet<String>();
143
144         /** All known Sones. */
145         /* synchronize access on {@link #newSones}. */
146         private Set<String> knownSones = new HashSet<String>();
147
148         /** All posts. */
149         private Map<String, Post> posts = new HashMap<String, Post>();
150
151         /** All new posts. */
152         private Set<String> newPosts = new HashSet<String>();
153
154         /** All known posts. */
155         /* synchronize access on {@link #newPosts}. */
156         private Set<String> knownPosts = new HashSet<String>();
157
158         /** All replies. */
159         private Map<String, Reply> replies = new HashMap<String, Reply>();
160
161         /** All new replies. */
162         private Set<String> newReplies = new HashSet<String>();
163
164         /** All known replies. */
165         private Set<String> knownReplies = new HashSet<String>();
166
167         /** All bookmarked posts. */
168         /* synchronize access on itself. */
169         private Set<String> bookmarkedPosts = new HashSet<String>();
170
171         /** Trusted identities, sorted by own identities. */
172         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
173
174         /** All known albums. */
175         private Map<String, Album> albums = new HashMap<String, Album>();
176
177         /** All known images. */
178         private Map<String, Image> images = new HashMap<String, Image>();
179
180         /** All temporary images. */
181         private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
182
183         /**
184          * Creates a new core.
185          *
186          * @param configuration
187          *            The configuration of the core
188          * @param freenetInterface
189          *            The freenet interface
190          * @param identityManager
191          *            The identity manager
192          */
193         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
194                 this.configuration = configuration;
195                 this.freenetInterface = freenetInterface;
196                 this.identityManager = identityManager;
197                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
198                 this.imageInserter = new ImageInserter(this, freenetInterface);
199                 this.updateChecker = new UpdateChecker(freenetInterface);
200         }
201
202         //
203         // LISTENER MANAGEMENT
204         //
205
206         /**
207          * Adds a new core listener.
208          *
209          * @param coreListener
210          *            The listener to add
211          */
212         public void addCoreListener(CoreListener coreListener) {
213                 coreListenerManager.addListener(coreListener);
214         }
215
216         /**
217          * Removes a core listener.
218          *
219          * @param coreListener
220          *            The listener to remove
221          */
222         public void removeCoreListener(CoreListener coreListener) {
223                 coreListenerManager.removeListener(coreListener);
224         }
225
226         //
227         // ACCESSORS
228         //
229
230         /**
231          * Sets the configuration to use. This will automatically save the current
232          * configuration to the given configuration.
233          *
234          * @param configuration
235          *            The new configuration to use
236          */
237         public void setConfiguration(Configuration configuration) {
238                 this.configuration = configuration;
239                 saveConfiguration();
240         }
241
242         /**
243          * Returns the options used by the core.
244          *
245          * @return The options of the core
246          */
247         public Preferences getPreferences() {
248                 return preferences;
249         }
250
251         /**
252          * Returns the identity manager used by the core.
253          *
254          * @return The identity manager
255          */
256         public IdentityManager getIdentityManager() {
257                 return identityManager;
258         }
259
260         /**
261          * Returns the update checker.
262          *
263          * @return The update checker
264          */
265         public UpdateChecker getUpdateChecker() {
266                 return updateChecker;
267         }
268
269         /**
270          * Returns the status of the given Sone.
271          *
272          * @param sone
273          *            The Sone to get the status for
274          * @return The status of the Sone
275          */
276         public SoneStatus getSoneStatus(Sone sone) {
277                 synchronized (soneStatuses) {
278                         return soneStatuses.get(sone);
279                 }
280         }
281
282         /**
283          * Sets the status of the given Sone.
284          *
285          * @param sone
286          *            The Sone to set the status of
287          * @param soneStatus
288          *            The status to set
289          */
290         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
291                 synchronized (soneStatuses) {
292                         soneStatuses.put(sone, soneStatus);
293                 }
294         }
295
296         /**
297          * Returns whether the given Sone is currently locked.
298          *
299          * @param sone
300          *            The sone to check
301          * @return {@code true} if the Sone is locked, {@code false} if it is not
302          */
303         public boolean isLocked(Sone sone) {
304                 synchronized (lockedSones) {
305                         return lockedSones.contains(sone);
306                 }
307         }
308
309         /**
310          * Returns all Sones, remote and local.
311          *
312          * @return All Sones
313          */
314         public Set<Sone> getSones() {
315                 Set<Sone> allSones = new HashSet<Sone>();
316                 allSones.addAll(getLocalSones());
317                 allSones.addAll(getRemoteSones());
318                 return allSones;
319         }
320
321         /**
322          * Returns the Sone with the given ID, regardless whether it’s local or
323          * remote.
324          *
325          * @param id
326          *            The ID of the Sone to get
327          * @return The Sone with the given ID, or {@code null} if there is no such
328          *         Sone
329          */
330         public Sone getSone(String id) {
331                 return getSone(id, true);
332         }
333
334         /**
335          * Returns the Sone with the given ID, regardless whether it’s local or
336          * remote.
337          *
338          * @param id
339          *            The ID of the Sone to get
340          * @param create
341          *            {@code true} to create a new Sone if none exists,
342          *            {@code false} to return {@code null} if a Sone with the given
343          *            ID does not exist
344          * @return The Sone with the given ID, or {@code null} if there is no such
345          *         Sone
346          */
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                                 setSoneStatus(sone, SoneStatus.unknown);
432                         }
433                         return sone;
434                 }
435         }
436
437         /**
438          * Returns all remote Sones.
439          *
440          * @return All remote Sones
441          */
442         public Set<Sone> getRemoteSones() {
443                 synchronized (remoteSones) {
444                         return new HashSet<Sone>(remoteSones.values());
445                 }
446         }
447
448         /**
449          * Returns the remote Sone with the given ID.
450          *
451          * @param id
452          *            The ID of the remote Sone to get
453          * @return The Sone with the given ID
454          */
455         public Sone getRemoteSone(String id) {
456                 return getRemoteSone(id, true);
457         }
458
459         /**
460          * Returns the remote Sone with the given ID.
461          *
462          * @param id
463          *            The ID of the remote Sone to get
464          * @param create
465          *            {@code true} to always create a Sone, {@code false} to return
466          *            {@code null} if no Sone with the given ID exists
467          * @return The Sone with the given ID
468          */
469         public Sone getRemoteSone(String id, boolean create) {
470                 synchronized (remoteSones) {
471                         Sone sone = remoteSones.get(id);
472                         if ((sone == null) && create) {
473                                 sone = new Sone(id);
474                                 remoteSones.put(id, sone);
475                                 setSoneStatus(sone, SoneStatus.unknown);
476                         }
477                         return sone;
478                 }
479         }
480
481         /**
482          * Returns whether the given Sone is a remote Sone.
483          *
484          * @param sone
485          *            The Sone to check
486          * @return {@code true} if the given Sone is a remote Sone, {@code false}
487          *         otherwise
488          */
489         public boolean isRemoteSone(Sone sone) {
490                 synchronized (remoteSones) {
491                         return remoteSones.containsKey(sone.getId());
492                 }
493         }
494
495         /**
496          * Returns whether the Sone with the given ID is a remote Sone.
497          *
498          * @param id
499          *            The ID of the Sone to check
500          * @return {@code true} if the Sone with the given ID is a remote Sone,
501          *         {@code false} otherwise
502          */
503         public boolean isRemoteSone(String id) {
504                 synchronized (remoteSones) {
505                         return remoteSones.containsKey(id);
506                 }
507         }
508
509         /**
510          * Returns whether the Sone with the given ID is a new Sone.
511          *
512          * @param soneId
513          *            The ID of the sone to check for
514          * @return {@code true} if the given Sone is new, false otherwise
515          */
516         public boolean isNewSone(String soneId) {
517                 synchronized (newSones) {
518                         return !knownSones.contains(soneId) && newSones.contains(soneId);
519                 }
520         }
521
522         /**
523          * Returns whether the given Sone has been modified.
524          *
525          * @param sone
526          *            The Sone to check for modifications
527          * @return {@code true} if a modification has been detected in the Sone,
528          *         {@code false} otherwise
529          */
530         public boolean isModifiedSone(Sone sone) {
531                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
532         }
533
534         /**
535          * Returns whether the target Sone is trusted by the origin Sone.
536          *
537          * @param origin
538          *            The origin Sone
539          * @param target
540          *            The target Sone
541          * @return {@code true} if the target Sone is trusted by the origin Sone
542          */
543         public boolean isSoneTrusted(Sone origin, Sone target) {
544                 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
545         }
546
547         /**
548          * Returns the post with the given ID.
549          *
550          * @param postId
551          *            The ID of the post to get
552          * @return The post, or {@code null} if there is no such post
553          */
554         public Post getPost(String postId) {
555                 return getPost(postId, true);
556         }
557
558         /**
559          * Returns the post with the given ID, optionally creating a new post.
560          *
561          * @param postId
562          *            The ID of the post to get
563          * @param create
564          *            {@code true} it create a new post if no post with the given ID
565          *            exists, {@code false} to return {@code null}
566          * @return The post, or {@code null} if there is no such post
567          */
568         public Post getPost(String postId, boolean create) {
569                 synchronized (posts) {
570                         Post post = posts.get(postId);
571                         if ((post == null) && create) {
572                                 post = new Post(postId);
573                                 posts.put(postId, post);
574                         }
575                         return post;
576                 }
577         }
578
579         /**
580          * Returns whether the given post ID is new.
581          *
582          * @param postId
583          *            The post ID
584          * @return {@code true} if the post is considered to be new, {@code false}
585          *         otherwise
586          */
587         public boolean isNewPost(String postId) {
588                 synchronized (newPosts) {
589                         return !knownPosts.contains(postId) && newPosts.contains(postId);
590                 }
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 Reply 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 Reply getReply(String replyId, boolean create) {
618                 synchronized (replies) {
619                         Reply reply = replies.get(replyId);
620                         if (create && (reply == null)) {
621                                 reply = new Reply(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<Reply> getReplies(Post post) {
636                 Set<Sone> sones = getSones();
637                 List<Reply> replies = new ArrayList<Reply>();
638                 for (Sone sone : sones) {
639                         for (Reply 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 whether the reply with the given ID is new.
651          *
652          * @param replyId
653          *            The ID of the reply to check
654          * @return {@code true} if the reply is considered to be new, {@code false}
655          *         otherwise
656          */
657         public boolean isNewReply(String replyId) {
658                 synchronized (newReplies) {
659                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
660                 }
661         }
662
663         /**
664          * Returns all Sones that have liked the given post.
665          *
666          * @param post
667          *            The post to get the liking Sones for
668          * @return The Sones that like the given post
669          */
670         public Set<Sone> getLikes(Post post) {
671                 Set<Sone> sones = new HashSet<Sone>();
672                 for (Sone sone : getSones()) {
673                         if (sone.getLikedPostIds().contains(post.getId())) {
674                                 sones.add(sone);
675                         }
676                 }
677                 return sones;
678         }
679
680         /**
681          * Returns all Sones that have liked the given reply.
682          *
683          * @param reply
684          *            The reply to get the liking Sones for
685          * @return The Sones that like the given reply
686          */
687         public Set<Sone> getLikes(Reply reply) {
688                 Set<Sone> sones = new HashSet<Sone>();
689                 for (Sone sone : getSones()) {
690                         if (sone.getLikedReplyIds().contains(reply.getId())) {
691                                 sones.add(sone);
692                         }
693                 }
694                 return sones;
695         }
696
697         /**
698          * Returns whether the given post is bookmarked.
699          *
700          * @param post
701          *            The post to check
702          * @return {@code true} if the given post is bookmarked, {@code false}
703          *         otherwise
704          */
705         public boolean isBookmarked(Post post) {
706                 return isPostBookmarked(post.getId());
707         }
708
709         /**
710          * Returns whether the post with the given ID is bookmarked.
711          *
712          * @param id
713          *            The ID of the post to check
714          * @return {@code true} if the post with the given ID is bookmarked,
715          *         {@code false} otherwise
716          */
717         public boolean isPostBookmarked(String id) {
718                 synchronized (bookmarkedPosts) {
719                         return bookmarkedPosts.contains(id);
720                 }
721         }
722
723         /**
724          * Returns all currently known bookmarked posts.
725          *
726          * @return All bookmarked posts
727          */
728         public Set<Post> getBookmarkedPosts() {
729                 Set<Post> posts = new HashSet<Post>();
730                 synchronized (bookmarkedPosts) {
731                         for (String bookmarkedPostId : bookmarkedPosts) {
732                                 Post post = getPost(bookmarkedPostId, false);
733                                 if (post != null) {
734                                         posts.add(post);
735                                 }
736                         }
737                 }
738                 return posts;
739         }
740
741         /**
742          * Returns the album with the given ID, creating a new album if no album
743          * with the given ID can be found.
744          *
745          * @param albumId
746          *            The ID of the album
747          * @return The album with the given ID
748          */
749         public Album getAlbum(String albumId) {
750                 return getAlbum(albumId, true);
751         }
752
753         /**
754          * Returns the album with the given ID, optionally creating a new album if
755          * an album with the given ID can not be found.
756          *
757          * @param albumId
758          *            The ID of the album
759          * @param create
760          *            {@code true} to create a new album if none exists for the
761          *            given ID
762          * @return The album with the given ID, or {@code null} if no album with the
763          *         given ID exists and {@code create} is {@code false}
764          */
765         public Album getAlbum(String albumId, boolean create) {
766                 synchronized (albums) {
767                         Album album = albums.get(albumId);
768                         if (create && (album == null)) {
769                                 album = new Album(albumId);
770                                 albums.put(albumId, album);
771                         }
772                         return album;
773                 }
774         }
775
776         /**
777          * Returns the image with the given ID, creating it if necessary.
778          *
779          * @param imageId
780          *            The ID of the image
781          * @return The image with the given ID
782          */
783         public Image getImage(String imageId) {
784                 return getImage(imageId, true);
785         }
786
787         /**
788          * Returns the image with the given ID, optionally creating it if it does
789          * not exist.
790          *
791          * @param imageId
792          *            The ID of the image
793          * @param create
794          *            {@code true} to create an image if none exists with the given
795          *            ID
796          * @return The image with the given ID, or {@code null} if none exists and
797          *         none was created
798          */
799         public Image getImage(String imageId, boolean create) {
800                 synchronized (images) {
801                         Image image = images.get(imageId);
802                         if (create && (image == null)) {
803                                 image = new Image(imageId);
804                                 images.put(imageId, image);
805                         }
806                         return image;
807                 }
808         }
809
810         /**
811          * Returns the temporary image with the given ID.
812          *
813          * @param imageId
814          *            The ID of the temporary image
815          * @return The temporary image, or {@code null} if there is no temporary
816          *         image with the given ID
817          */
818         public TemporaryImage getTemporaryImage(String imageId) {
819                 synchronized (temporaryImages) {
820                         return temporaryImages.get(imageId);
821                 }
822         }
823
824         //
825         // ACTIONS
826         //
827
828         /**
829          * Locks the given Sone. A locked Sone will not be inserted by
830          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
831          * again.
832          *
833          * @param sone
834          *            The sone to lock
835          */
836         public void lockSone(Sone sone) {
837                 synchronized (lockedSones) {
838                         if (lockedSones.add(sone)) {
839                                 coreListenerManager.fireSoneLocked(sone);
840                         }
841                 }
842         }
843
844         /**
845          * Unlocks the given Sone.
846          *
847          * @see #lockSone(Sone)
848          * @param sone
849          *            The sone to unlock
850          */
851         public void unlockSone(Sone sone) {
852                 synchronized (lockedSones) {
853                         if (lockedSones.remove(sone)) {
854                                 coreListenerManager.fireSoneUnlocked(sone);
855                         }
856                 }
857         }
858
859         /**
860          * Adds a local Sone from the given ID which has to be the ID of an own
861          * identity.
862          *
863          * @param id
864          *            The ID of an own identity to add a Sone for
865          * @return The added (or already existing) Sone
866          */
867         public Sone addLocalSone(String id) {
868                 synchronized (localSones) {
869                         if (localSones.containsKey(id)) {
870                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
871                                 return localSones.get(id);
872                         }
873                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
874                         if (ownIdentity == null) {
875                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
876                                 return null;
877                         }
878                         return addLocalSone(ownIdentity);
879                 }
880         }
881
882         /**
883          * Adds a local Sone from the given own identity.
884          *
885          * @param ownIdentity
886          *            The own identity to create a Sone from
887          * @return The added (or already existing) Sone
888          */
889         public Sone addLocalSone(OwnIdentity ownIdentity) {
890                 if (ownIdentity == null) {
891                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
892                         return null;
893                 }
894                 synchronized (localSones) {
895                         final Sone sone;
896                         try {
897                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
898                         } catch (MalformedURLException mue1) {
899                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
900                                 return null;
901                         }
902                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
903                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
904                         /* TODO - load posts ’n stuff */
905                         localSones.put(ownIdentity.getId(), sone);
906                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
907                         soneInserters.put(sone, soneInserter);
908                         setSoneStatus(sone, SoneStatus.idle);
909                         loadSone(sone);
910                         if (!preferences.isSoneRescueMode()) {
911                                 soneInserter.start();
912                         }
913                         new Thread(new Runnable() {
914
915                                 @Override
916                                 @SuppressWarnings("synthetic-access")
917                                 public void run() {
918                                         if (!preferences.isSoneRescueMode()) {
919                                                 soneDownloader.fetchSone(sone);
920                                                 return;
921                                         }
922                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
923                                         coreListenerManager.fireRescuingSone(sone);
924                                         lockSone(sone);
925                                         long edition = sone.getLatestEdition();
926                                         while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
927                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
928                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
929                                                 --edition;
930                                         }
931                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
932                                         saveSone(sone);
933                                         coreListenerManager.fireRescuedSone(sone);
934                                         soneInserter.start();
935                                 }
936
937                         }, "Sone Downloader").start();
938                         return sone;
939                 }
940         }
941
942         /**
943          * Creates a new Sone for the given own identity.
944          *
945          * @param ownIdentity
946          *            The own identity to create a Sone for
947          * @return The created Sone
948          */
949         public Sone createSone(OwnIdentity ownIdentity) {
950                 try {
951                         ownIdentity.addContext("Sone");
952                 } catch (WebOfTrustException wote1) {
953                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
954                         return null;
955                 }
956                 Sone sone = addLocalSone(ownIdentity);
957                 return sone;
958         }
959
960         /**
961          * Adds the Sone of the given identity.
962          *
963          * @param identity
964          *            The identity whose Sone to add
965          * @return The added or already existing Sone
966          */
967         public Sone addRemoteSone(Identity identity) {
968                 if (identity == null) {
969                         logger.log(Level.WARNING, "Given Identity is null!");
970                         return null;
971                 }
972                 synchronized (remoteSones) {
973                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
974                         boolean newSone = sone.getRequestUri() == null;
975                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
976                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
977                         if (newSone) {
978                                 synchronized (newSones) {
979                                         newSone = !knownSones.contains(sone.getId());
980                                         if (newSone) {
981                                                 newSones.add(sone.getId());
982                                         }
983                                 }
984                                 if (newSone) {
985                                         coreListenerManager.fireNewSoneFound(sone);
986                                 }
987                         }
988                         remoteSones.put(identity.getId(), sone);
989                         soneDownloader.addSone(sone);
990                         setSoneStatus(sone, SoneStatus.unknown);
991                         new Thread(new Runnable() {
992
993                                 @Override
994                                 @SuppressWarnings("synthetic-access")
995                                 public void run() {
996                                         soneDownloader.fetchSone(sone);
997                                 }
998
999                         }, "Sone Downloader").start();
1000                         return sone;
1001                 }
1002         }
1003
1004         /**
1005          * Retrieves the trust relationship from the origin to the target. If the
1006          * trust relationship can not be retrieved, {@code null} is returned.
1007          *
1008          * @see Identity#getTrust(OwnIdentity)
1009          * @param origin
1010          *            The origin of the trust tree
1011          * @param target
1012          *            The target of the trust
1013          * @return The trust relationship
1014          */
1015         public Trust getTrust(Sone origin, Sone target) {
1016                 if (!isLocalSone(origin)) {
1017                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1018                         return null;
1019                 }
1020                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1021         }
1022
1023         /**
1024          * Sets the trust value of the given origin Sone for the target Sone.
1025          *
1026          * @param origin
1027          *            The origin Sone
1028          * @param target
1029          *            The target Sone
1030          * @param trustValue
1031          *            The trust value (from {@code -100} to {@code 100})
1032          */
1033         public void setTrust(Sone origin, Sone target, int trustValue) {
1034                 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();
1035                 try {
1036                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1037                 } catch (WebOfTrustException wote1) {
1038                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1039                 }
1040         }
1041
1042         /**
1043          * Removes any trust assignment for the given target Sone.
1044          *
1045          * @param origin
1046          *            The trust origin
1047          * @param target
1048          *            The trust target
1049          */
1050         public void removeTrust(Sone origin, Sone target) {
1051                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1052                 try {
1053                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1054                 } catch (WebOfTrustException wote1) {
1055                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1056                 }
1057         }
1058
1059         /**
1060          * Assigns the configured positive trust value for the given target.
1061          *
1062          * @param origin
1063          *            The trust origin
1064          * @param target
1065          *            The trust target
1066          */
1067         public void trustSone(Sone origin, Sone target) {
1068                 setTrust(origin, target, preferences.getPositiveTrust());
1069         }
1070
1071         /**
1072          * Assigns the configured negative trust value for the given target.
1073          *
1074          * @param origin
1075          *            The trust origin
1076          * @param target
1077          *            The trust target
1078          */
1079         public void distrustSone(Sone origin, Sone target) {
1080                 setTrust(origin, target, preferences.getNegativeTrust());
1081         }
1082
1083         /**
1084          * Removes the trust assignment for the given target.
1085          *
1086          * @param origin
1087          *            The trust origin
1088          * @param target
1089          *            The trust target
1090          */
1091         public void untrustSone(Sone origin, Sone target) {
1092                 removeTrust(origin, target);
1093         }
1094
1095         /**
1096          * Updates the stores Sone with the given Sone.
1097          *
1098          * @param sone
1099          *            The updated Sone
1100          */
1101         public void updateSone(Sone sone) {
1102                 if (hasSone(sone.getId())) {
1103                         boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1104                         Sone storedSone = getSone(sone.getId());
1105                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1106                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1107                                 return;
1108                         }
1109                         synchronized (posts) {
1110                                 if (!soneRescueMode) {
1111                                         for (Post post : storedSone.getPosts()) {
1112                                                 posts.remove(post.getId());
1113                                                 if (!sone.getPosts().contains(post)) {
1114                                                         coreListenerManager.firePostRemoved(post);
1115                                                 }
1116                                         }
1117                                 }
1118                                 List<Post> storedPosts = storedSone.getPosts();
1119                                 synchronized (newPosts) {
1120                                         for (Post post : sone.getPosts()) {
1121                                                 post.setSone(storedSone);
1122                                                 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1123                                                         newPosts.add(post.getId());
1124                                                         coreListenerManager.fireNewPostFound(post);
1125                                                 }
1126                                                 posts.put(post.getId(), post);
1127                                         }
1128                                 }
1129                         }
1130                         synchronized (replies) {
1131                                 if (!soneRescueMode) {
1132                                         for (Reply reply : storedSone.getReplies()) {
1133                                                 replies.remove(reply.getId());
1134                                                 if (!sone.getReplies().contains(reply)) {
1135                                                         coreListenerManager.fireReplyRemoved(reply);
1136                                                 }
1137                                         }
1138                                 }
1139                                 Set<Reply> storedReplies = storedSone.getReplies();
1140                                 synchronized (newReplies) {
1141                                         for (Reply reply : sone.getReplies()) {
1142                                                 reply.setSone(storedSone);
1143                                                 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1144                                                         newReplies.add(reply.getId());
1145                                                         coreListenerManager.fireNewReplyFound(reply);
1146                                                 }
1147                                                 replies.put(reply.getId(), reply);
1148                                         }
1149                                 }
1150                         }
1151                         synchronized (storedSone) {
1152                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1153                                         storedSone.setTime(sone.getTime());
1154                                 }
1155                                 storedSone.setClient(sone.getClient());
1156                                 storedSone.setProfile(sone.getProfile());
1157                                 if (soneRescueMode) {
1158                                         for (Post post : sone.getPosts()) {
1159                                                 storedSone.addPost(post);
1160                                         }
1161                                         for (Reply reply : sone.getReplies()) {
1162                                                 storedSone.addReply(reply);
1163                                         }
1164                                         for (String likedPostId : sone.getLikedPostIds()) {
1165                                                 storedSone.addLikedPostId(likedPostId);
1166                                         }
1167                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1168                                                 storedSone.addLikedReplyId(likedReplyId);
1169                                         }
1170                                 } else {
1171                                         storedSone.setPosts(sone.getPosts());
1172                                         storedSone.setReplies(sone.getReplies());
1173                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1174                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1175                                 }
1176                                 storedSone.setLatestEdition(sone.getLatestEdition());
1177                         }
1178                 }
1179         }
1180
1181         /**
1182          * Deletes the given Sone. This will remove the Sone from the
1183          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1184          * and remove the context from its identity.
1185          *
1186          * @param sone
1187          *            The Sone to delete
1188          */
1189         public void deleteSone(Sone sone) {
1190                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1191                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1192                         return;
1193                 }
1194                 synchronized (localSones) {
1195                         if (!localSones.containsKey(sone.getId())) {
1196                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1197                                 return;
1198                         }
1199                         localSones.remove(sone.getId());
1200                         soneInserters.remove(sone).stop();
1201                 }
1202                 try {
1203                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1204                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1205                 } catch (WebOfTrustException wote1) {
1206                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1207                 }
1208                 try {
1209                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1210                 } catch (ConfigurationException ce1) {
1211                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1212                 }
1213         }
1214
1215         /**
1216          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1217          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1218          *
1219          * @param sone
1220          *            The Sone to mark as known
1221          */
1222         public void markSoneKnown(Sone sone) {
1223                 synchronized (newSones) {
1224                         if (newSones.remove(sone.getId())) {
1225                                 knownSones.add(sone.getId());
1226                                 coreListenerManager.fireMarkSoneKnown(sone);
1227                                 saveConfiguration();
1228                         }
1229                 }
1230         }
1231
1232         /**
1233          * Loads and updates the given Sone from the configuration. If any error is
1234          * encountered, loading is aborted and the given Sone is not changed.
1235          *
1236          * @param sone
1237          *            The Sone to load and update
1238          */
1239         public void loadSone(Sone sone) {
1240                 if (!isLocalSone(sone)) {
1241                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1242                         return;
1243                 }
1244
1245                 /* load Sone. */
1246                 String sonePrefix = "Sone/" + sone.getId();
1247                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1248                 if (soneTime == null) {
1249                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1250                         return;
1251                 }
1252                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1253
1254                 /* load profile. */
1255                 Profile profile = new Profile();
1256                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1257                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1258                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1259                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1260                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1261                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1262
1263                 /* load profile fields. */
1264                 while (true) {
1265                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1266                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1267                         if (fieldName == null) {
1268                                 break;
1269                         }
1270                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1271                         profile.addField(fieldName).setValue(fieldValue);
1272                 }
1273
1274                 /* load posts. */
1275                 Set<Post> posts = new HashSet<Post>();
1276                 while (true) {
1277                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1278                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1279                         if (postId == null) {
1280                                 break;
1281                         }
1282                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1283                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1284                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1285                         if ((postTime == 0) || (postText == null)) {
1286                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1287                                 return;
1288                         }
1289                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1290                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1291                                 post.setRecipient(getSone(postRecipientId));
1292                         }
1293                         posts.add(post);
1294                 }
1295
1296                 /* load replies. */
1297                 Set<Reply> replies = new HashSet<Reply>();
1298                 while (true) {
1299                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1300                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1301                         if (replyId == null) {
1302                                 break;
1303                         }
1304                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1305                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1306                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1307                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1308                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1309                                 return;
1310                         }
1311                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1312                 }
1313
1314                 /* load post likes. */
1315                 Set<String> likedPostIds = new HashSet<String>();
1316                 while (true) {
1317                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1318                         if (likedPostId == null) {
1319                                 break;
1320                         }
1321                         likedPostIds.add(likedPostId);
1322                 }
1323
1324                 /* load reply likes. */
1325                 Set<String> likedReplyIds = new HashSet<String>();
1326                 while (true) {
1327                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1328                         if (likedReplyId == null) {
1329                                 break;
1330                         }
1331                         likedReplyIds.add(likedReplyId);
1332                 }
1333
1334                 /* load friends. */
1335                 Set<String> friends = new HashSet<String>();
1336                 while (true) {
1337                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1338                         if (friendId == null) {
1339                                 break;
1340                         }
1341                         friends.add(friendId);
1342                 }
1343
1344                 /* load albums. */
1345                 List<Album> topLevelAlbums = new ArrayList<Album>();
1346                 while (true) {
1347                         String albumPrefix = sonePrefix + "/Albums/" + albums.size();
1348                         String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1349                         if (albumId == null) {
1350                                 break;
1351                         }
1352                         String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1353                         String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1354                         String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1355                         if ((albumTitle == null) || (albumDescription == null)) {
1356                                 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1357                                 return;
1358                         }
1359                         Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription);
1360                         if (albumParentId != null) {
1361                                 Album parentAlbum = getAlbum(albumParentId, false);
1362                                 if (parentAlbum == null) {
1363                                         logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1364                                         return;
1365                                 }
1366                                 parentAlbum.addAlbum(album);
1367                         } else {
1368                                 topLevelAlbums.add(album);
1369                         }
1370                 }
1371
1372                 /* load images. */
1373                 int imageCounter = 0;
1374                 while (true) {
1375                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1376                         String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1377                         if (imageId == null) {
1378                                 break;
1379                         }
1380                         String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1381                         String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1382                         String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1383                         String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1384                         Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1385                         Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1386                         Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1387                         if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1388                                 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1389                                 return;
1390                         }
1391                         Album album = getAlbum(albumId, false);
1392                         if (album == null) {
1393                                 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1394                                 return;
1395                         }
1396                         Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1397                         image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1398                         album.addImage(image);
1399                 }
1400
1401                 /* load options. */
1402                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1403                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1404
1405                 /* if we’re still here, Sone was loaded successfully. */
1406                 synchronized (sone) {
1407                         sone.setTime(soneTime);
1408                         sone.setProfile(profile);
1409                         sone.setPosts(posts);
1410                         sone.setReplies(replies);
1411                         sone.setLikePostIds(likedPostIds);
1412                         sone.setLikeReplyIds(likedReplyIds);
1413                         sone.setFriends(friends);
1414                         sone.setAlbums(topLevelAlbums);
1415                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1416                 }
1417                 synchronized (newSones) {
1418                         for (String friend : friends) {
1419                                 knownSones.add(friend);
1420                         }
1421                 }
1422                 synchronized (newPosts) {
1423                         for (Post post : posts) {
1424                                 knownPosts.add(post.getId());
1425                         }
1426                 }
1427                 synchronized (newReplies) {
1428                         for (Reply reply : replies) {
1429                                 knownReplies.add(reply.getId());
1430                         }
1431                 }
1432         }
1433
1434         /**
1435          * Saves the given Sone. This will persist all local settings for the given
1436          * Sone, such as the friends list and similar, private options.
1437          *
1438          * @param sone
1439          *            The Sone to save
1440          */
1441         public synchronized void saveSone(Sone sone) {
1442                 if (!isLocalSone(sone)) {
1443                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1444                         return;
1445                 }
1446                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1447                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1448                         return;
1449                 }
1450
1451                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1452                 try {
1453                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1454
1455                         /* save Sone into configuration. */
1456                         String sonePrefix = "Sone/" + sone.getId();
1457                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1458                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1459
1460                         /* save profile. */
1461                         Profile profile = sone.getProfile();
1462                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1463                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1464                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1465                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1466                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1467                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1468
1469                         /* save profile fields. */
1470                         int fieldCounter = 0;
1471                         for (Field profileField : profile.getFields()) {
1472                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1473                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1474                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1475                         }
1476                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1477
1478                         /* save posts. */
1479                         int postCounter = 0;
1480                         for (Post post : sone.getPosts()) {
1481                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1482                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1483                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1484                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1485                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1486                         }
1487                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1488
1489                         /* save replies. */
1490                         int replyCounter = 0;
1491                         for (Reply reply : sone.getReplies()) {
1492                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1493                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1494                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1495                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1496                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1497                         }
1498                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1499
1500                         /* save post likes. */
1501                         int postLikeCounter = 0;
1502                         for (String postId : sone.getLikedPostIds()) {
1503                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1504                         }
1505                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1506
1507                         /* save reply likes. */
1508                         int replyLikeCounter = 0;
1509                         for (String replyId : sone.getLikedReplyIds()) {
1510                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1511                         }
1512                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1513
1514                         /* save friends. */
1515                         int friendCounter = 0;
1516                         for (String friendId : sone.getFriends()) {
1517                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1518                         }
1519                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1520
1521                         /* save albums. first, collect in a flat structure, top-level first. */
1522                         List<Album> albums = new ArrayList<Album>();
1523                         albums.addAll(sone.getAlbums());
1524                         int lastAlbumIndex = 0;
1525                         while (lastAlbumIndex < albums.size()) {
1526                                 int previousAlbumCount = albums.size();
1527                                 for (Album album : new ArrayList<Album>(albums.subList(lastAlbumIndex, albums.size()))) {
1528                                         albums.addAll(album.getAlbums());
1529                                 }
1530                                 lastAlbumIndex = previousAlbumCount;
1531                         }
1532
1533                         int albumCounter = 0;
1534                         for (Album album : albums) {
1535                                 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1536                                 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1537                                 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1538                                 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1539                                 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1540                         }
1541                         configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1542
1543                         /* save images. */
1544                         int imageCounter = 0;
1545                         for (Album album : albums) {
1546                                 for (Image image : album.getImages()) {
1547                                         if (!image.isInserted()) {
1548                                                 continue;
1549                                         }
1550                                         String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1551                                         configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1552                                         configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1553                                         configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1554                                         configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1555                                         configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1556                                         configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1557                                         configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1558                                         configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1559                                 }
1560                         }
1561                         configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1562
1563                         /* save options. */
1564                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1565
1566                         configuration.save();
1567                         logger.log(Level.INFO, "Sone %s saved.", sone);
1568                 } catch (ConfigurationException ce1) {
1569                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1570                 } catch (WebOfTrustException wote1) {
1571                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1572                 }
1573         }
1574
1575         /**
1576          * Creates a new post.
1577          *
1578          * @param sone
1579          *            The Sone that creates the post
1580          * @param text
1581          *            The text of the post
1582          * @return The created post
1583          */
1584         public Post createPost(Sone sone, String text) {
1585                 return createPost(sone, System.currentTimeMillis(), text);
1586         }
1587
1588         /**
1589          * Creates a new post.
1590          *
1591          * @param sone
1592          *            The Sone that creates the post
1593          * @param time
1594          *            The time of the post
1595          * @param text
1596          *            The text of the post
1597          * @return The created post
1598          */
1599         public Post createPost(Sone sone, long time, String text) {
1600                 return createPost(sone, null, time, text);
1601         }
1602
1603         /**
1604          * Creates a new post.
1605          *
1606          * @param sone
1607          *            The Sone that creates the post
1608          * @param recipient
1609          *            The recipient Sone, or {@code null} if this post does not have
1610          *            a recipient
1611          * @param text
1612          *            The text of the post
1613          * @return The created post
1614          */
1615         public Post createPost(Sone sone, Sone recipient, String text) {
1616                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1617         }
1618
1619         /**
1620          * Creates a new post.
1621          *
1622          * @param sone
1623          *            The Sone that creates the post
1624          * @param recipient
1625          *            The recipient Sone, or {@code null} if this post does not have
1626          *            a recipient
1627          * @param time
1628          *            The time of the post
1629          * @param text
1630          *            The text of the post
1631          * @return The created post
1632          */
1633         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1634                 if (!isLocalSone(sone)) {
1635                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1636                         return null;
1637                 }
1638                 Post post = new Post(sone, time, text);
1639                 if (recipient != null) {
1640                         post.setRecipient(recipient);
1641                 }
1642                 synchronized (posts) {
1643                         posts.put(post.getId(), post);
1644                 }
1645                 synchronized (newPosts) {
1646                         knownPosts.add(post.getId());
1647                 }
1648                 sone.addPost(post);
1649                 saveSone(sone);
1650                 return post;
1651         }
1652
1653         /**
1654          * Deletes the given post.
1655          *
1656          * @param post
1657          *            The post to delete
1658          */
1659         public void deletePost(Post post) {
1660                 if (!isLocalSone(post.getSone())) {
1661                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1662                         return;
1663                 }
1664                 post.getSone().removePost(post);
1665                 synchronized (posts) {
1666                         posts.remove(post.getId());
1667                 }
1668                 saveSone(post.getSone());
1669         }
1670
1671         /**
1672          * Marks the given post as known, if it is currently a new post (according
1673          * to {@link #isNewPost(String)}).
1674          *
1675          * @param post
1676          *            The post to mark as known
1677          */
1678         public void markPostKnown(Post post) {
1679                 synchronized (newPosts) {
1680                         if (newPosts.remove(post.getId())) {
1681                                 knownPosts.add(post.getId());
1682                                 coreListenerManager.fireMarkPostKnown(post);
1683                                 saveConfiguration();
1684                         }
1685                 }
1686         }
1687
1688         /**
1689          * Bookmarks the given post.
1690          *
1691          * @param post
1692          *            The post to bookmark
1693          */
1694         public void bookmark(Post post) {
1695                 bookmarkPost(post.getId());
1696         }
1697
1698         /**
1699          * Bookmarks the post with the given ID.
1700          *
1701          * @param id
1702          *            The ID of the post to bookmark
1703          */
1704         public void bookmarkPost(String id) {
1705                 synchronized (bookmarkedPosts) {
1706                         bookmarkedPosts.add(id);
1707                 }
1708         }
1709
1710         /**
1711          * Removes the given post from the bookmarks.
1712          *
1713          * @param post
1714          *            The post to unbookmark
1715          */
1716         public void unbookmark(Post post) {
1717                 unbookmarkPost(post.getId());
1718         }
1719
1720         /**
1721          * Removes the post with the given ID from the bookmarks.
1722          *
1723          * @param id
1724          *            The ID of the post to unbookmark
1725          */
1726         public void unbookmarkPost(String id) {
1727                 synchronized (bookmarkedPosts) {
1728                         bookmarkedPosts.remove(id);
1729                 }
1730         }
1731
1732         /**
1733          * Creates a new reply.
1734          *
1735          * @param sone
1736          *            The Sone that creates the reply
1737          * @param post
1738          *            The post that this reply refers to
1739          * @param text
1740          *            The text of the reply
1741          * @return The created reply
1742          */
1743         public Reply createReply(Sone sone, Post post, String text) {
1744                 return createReply(sone, post, System.currentTimeMillis(), text);
1745         }
1746
1747         /**
1748          * Creates a new reply.
1749          *
1750          * @param sone
1751          *            The Sone that creates the reply
1752          * @param post
1753          *            The post that this reply refers to
1754          * @param time
1755          *            The time of the reply
1756          * @param text
1757          *            The text of the reply
1758          * @return The created reply
1759          */
1760         public Reply createReply(Sone sone, Post post, long time, String text) {
1761                 if (!isLocalSone(sone)) {
1762                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1763                         return null;
1764                 }
1765                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1766                 synchronized (replies) {
1767                         replies.put(reply.getId(), reply);
1768                 }
1769                 synchronized (newReplies) {
1770                         knownReplies.add(reply.getId());
1771                 }
1772                 sone.addReply(reply);
1773                 saveSone(sone);
1774                 return reply;
1775         }
1776
1777         /**
1778          * Deletes the given reply.
1779          *
1780          * @param reply
1781          *            The reply to delete
1782          */
1783         public void deleteReply(Reply reply) {
1784                 Sone sone = reply.getSone();
1785                 if (!isLocalSone(sone)) {
1786                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1787                         return;
1788                 }
1789                 synchronized (replies) {
1790                         replies.remove(reply.getId());
1791                 }
1792                 sone.removeReply(reply);
1793                 saveSone(sone);
1794         }
1795
1796         /**
1797          * Marks the given reply as known, if it is currently a new reply (according
1798          * to {@link #isNewReply(String)}).
1799          *
1800          * @param reply
1801          *            The reply to mark as known
1802          */
1803         public void markReplyKnown(Reply reply) {
1804                 synchronized (newReplies) {
1805                         if (newReplies.remove(reply.getId())) {
1806                                 knownReplies.add(reply.getId());
1807                                 coreListenerManager.fireMarkReplyKnown(reply);
1808                                 saveConfiguration();
1809                         }
1810                 }
1811         }
1812
1813         /**
1814          * Creates a new top-level album for the given Sone.
1815          *
1816          * @param sone
1817          *            The Sone to create the album for
1818          * @return The new album
1819          */
1820         public Album createAlbum(Sone sone) {
1821                 return createAlbum(sone, null);
1822         }
1823
1824         /**
1825          * Creates a new album for the given Sone.
1826          *
1827          * @param sone
1828          *            The Sone to create the album for
1829          * @param parent
1830          *            The parent of the album (may be {@code null} to create a
1831          *            top-level album)
1832          * @return The new album
1833          */
1834         public Album createAlbum(Sone sone, Album parent) {
1835                 Album album = new Album();
1836                 synchronized (albums) {
1837                         albums.put(album.getId(), album);
1838                 }
1839                 album.setSone(sone);
1840                 if (parent != null) {
1841                         parent.addAlbum(album);
1842                 } else {
1843                         sone.addAlbum(album);
1844                 }
1845                 return album;
1846         }
1847
1848         /**
1849          * Creates a new image.
1850          *
1851          * @param sone
1852          *            The Sone creating the image
1853          * @param album
1854          *            The album the image will be inserted into
1855          * @param temporaryImage
1856          *            The temporary image to create the image from
1857          * @return The newly created image
1858          */
1859         public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1860                 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();
1861                 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1862                 album.addImage(image);
1863                 synchronized (images) {
1864                         images.put(image.getId(), image);
1865                 }
1866                 return image;
1867         }
1868
1869         /**
1870          * Creates a new temporary image.
1871          *
1872          * @param mimeType
1873          *            The MIME type of the temporary image
1874          * @param imageData
1875          *            The encoded data of the image
1876          * @return The temporary image
1877          */
1878         public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1879                 TemporaryImage temporaryImage = new TemporaryImage();
1880                 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1881                 synchronized (temporaryImages) {
1882                         temporaryImages.put(temporaryImage.getId(), temporaryImage);
1883                 }
1884                 return temporaryImage;
1885         }
1886
1887         /**
1888          * Deletes the given temporary image.
1889          *
1890          * @param temporaryImage
1891          *            The temporary image to delete
1892          */
1893         public void deteleTemporaryImage(TemporaryImage temporaryImage) {
1894                 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1895                 deleteTemporaryImage(temporaryImage.getId());
1896         }
1897
1898         /**
1899          * Deletes the temporary image with the given ID.
1900          *
1901          * @param imageId
1902          *            The ID of the temporary image to delete
1903          */
1904         public void deleteTemporaryImage(String imageId) {
1905                 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1906                 synchronized (temporaryImages) {
1907                         temporaryImages.remove(imageId);
1908                 }
1909         }
1910
1911         /**
1912          * Starts the core.
1913          */
1914         public void start() {
1915                 loadConfiguration();
1916                 updateChecker.addUpdateListener(this);
1917                 updateChecker.start();
1918         }
1919
1920         /**
1921          * Stops the core.
1922          */
1923         public void stop() {
1924                 synchronized (localSones) {
1925                         for (SoneInserter soneInserter : soneInserters.values()) {
1926                                 soneInserter.stop();
1927                         }
1928                 }
1929                 updateChecker.stop();
1930                 updateChecker.removeUpdateListener(this);
1931                 soneDownloader.stop();
1932                 saveConfiguration();
1933                 stopped = true;
1934         }
1935
1936         /**
1937          * Saves the current options.
1938          */
1939         public void saveConfiguration() {
1940                 synchronized (configuration) {
1941                         if (storingConfiguration) {
1942                                 logger.log(Level.FINE, "Already storing configuration…");
1943                                 return;
1944                         }
1945                         storingConfiguration = true;
1946                 }
1947
1948                 /* store the options first. */
1949                 try {
1950                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1951                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1952                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1953                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1954                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1955                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1956                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1957                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1958
1959                         /* save known Sones. */
1960                         int soneCounter = 0;
1961                         synchronized (newSones) {
1962                                 for (String knownSoneId : knownSones) {
1963                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1964                                 }
1965                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1966                         }
1967
1968                         /* save known posts. */
1969                         int postCounter = 0;
1970                         synchronized (newPosts) {
1971                                 for (String knownPostId : knownPosts) {
1972                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1973                                 }
1974                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1975                         }
1976
1977                         /* save known replies. */
1978                         int replyCounter = 0;
1979                         synchronized (newReplies) {
1980                                 for (String knownReplyId : knownReplies) {
1981                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1982                                 }
1983                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1984                         }
1985
1986                         /* save bookmarked posts. */
1987                         int bookmarkedPostCounter = 0;
1988                         synchronized (bookmarkedPosts) {
1989                                 for (String bookmarkedPostId : bookmarkedPosts) {
1990                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1991                                 }
1992                         }
1993                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1994
1995                         /* now save it. */
1996                         configuration.save();
1997
1998                 } catch (ConfigurationException ce1) {
1999                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2000                 } finally {
2001                         synchronized (configuration) {
2002                                 storingConfiguration = false;
2003                         }
2004                 }
2005         }
2006
2007         //
2008         // PRIVATE METHODS
2009         //
2010
2011         /**
2012          * Loads the configuration.
2013          */
2014         @SuppressWarnings("unchecked")
2015         private void loadConfiguration() {
2016                 /* create options. */
2017                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
2018
2019                         @Override
2020                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2021                                 SoneInserter.setInsertionDelay(newValue);
2022                         }
2023
2024                 }));
2025                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
2026                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
2027                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2028                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2029                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2030                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2031
2032                 /* read options from configuration. */
2033                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2034                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2035                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2036                 options.getBooleanOption("ClearOnNextRestart").set(null);
2037                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2038                 if (clearConfiguration) {
2039                         /* stop loading the configuration. */
2040                         return;
2041                 }
2042
2043                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
2044                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
2045                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
2046                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2047                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2048
2049                 /* load known Sones. */
2050                 int soneCounter = 0;
2051                 while (true) {
2052                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2053                         if (knownSoneId == null) {
2054                                 break;
2055                         }
2056                         synchronized (newSones) {
2057                                 knownSones.add(knownSoneId);
2058                         }
2059                 }
2060
2061                 /* load known posts. */
2062                 int postCounter = 0;
2063                 while (true) {
2064                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2065                         if (knownPostId == null) {
2066                                 break;
2067                         }
2068                         synchronized (newPosts) {
2069                                 knownPosts.add(knownPostId);
2070                         }
2071                 }
2072
2073                 /* load known replies. */
2074                 int replyCounter = 0;
2075                 while (true) {
2076                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2077                         if (knownReplyId == null) {
2078                                 break;
2079                         }
2080                         synchronized (newReplies) {
2081                                 knownReplies.add(knownReplyId);
2082                         }
2083                 }
2084
2085                 /* load bookmarked posts. */
2086                 int bookmarkedPostCounter = 0;
2087                 while (true) {
2088                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2089                         if (bookmarkedPostId == null) {
2090                                 break;
2091                         }
2092                         synchronized (bookmarkedPosts) {
2093                                 bookmarkedPosts.add(bookmarkedPostId);
2094                         }
2095                 }
2096
2097         }
2098
2099         /**
2100          * Generate a Sone URI from the given URI and latest edition.
2101          *
2102          * @param uriString
2103          *            The URI to derive the Sone URI from
2104          * @return The derived URI
2105          */
2106         private FreenetURI getSoneUri(String uriString) {
2107                 try {
2108                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2109                         return uri;
2110                 } catch (MalformedURLException mue1) {
2111                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2112                         return null;
2113                 }
2114         }
2115
2116         //
2117         // INTERFACE IdentityListener
2118         //
2119
2120         /**
2121          * {@inheritDoc}
2122          */
2123         @Override
2124         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2125                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2126                 if (ownIdentity.hasContext("Sone")) {
2127                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2128                         addLocalSone(ownIdentity);
2129                 }
2130         }
2131
2132         /**
2133          * {@inheritDoc}
2134          */
2135         @Override
2136         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2137                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2138                 trustedIdentities.remove(ownIdentity);
2139         }
2140
2141         /**
2142          * {@inheritDoc}
2143          */
2144         @Override
2145         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2146                 logger.log(Level.FINEST, "Adding Identity: " + identity);
2147                 trustedIdentities.get(ownIdentity).add(identity);
2148                 addRemoteSone(identity);
2149         }
2150
2151         /**
2152          * {@inheritDoc}
2153          */
2154         @Override
2155         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2156                 new Thread(new Runnable() {
2157
2158                         @Override
2159                         @SuppressWarnings("synthetic-access")
2160                         public void run() {
2161                                 Sone sone = getRemoteSone(identity.getId());
2162                                 sone.setIdentity(identity);
2163                                 soneDownloader.addSone(sone);
2164                                 soneDownloader.fetchSone(sone);
2165                         }
2166                 }).start();
2167         }
2168
2169         /**
2170          * {@inheritDoc}
2171          */
2172         @Override
2173         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2174                 trustedIdentities.get(ownIdentity).remove(identity);
2175         }
2176
2177         //
2178         // INTERFACE UpdateListener
2179         //
2180
2181         /**
2182          * {@inheritDoc}
2183          */
2184         @Override
2185         public void updateFound(Version version, long releaseTime, long latestEdition) {
2186                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2187         }
2188
2189         //
2190         // INTERFACE ImageInsertListener
2191         //
2192
2193         /**
2194          * {@inheritDoc}
2195          */
2196         @Override
2197         public void imageInsertStarted(Image image) {
2198                 logger.log(Level.WARNING, "Image insert started for " + image);
2199                 coreListenerManager.fireImageInsertStarted(image);
2200         }
2201
2202         /**
2203          * {@inheritDoc}
2204          */
2205         @Override
2206         public void imageInsertAborted(Image image) {
2207                 logger.log(Level.WARNING, "Image insert aborted for " + image);
2208                 coreListenerManager.fireImageInsertAborted(image);
2209         }
2210
2211         /**
2212          * {@inheritDoc}
2213          */
2214         @Override
2215         public void imageInsertFinished(Image image, FreenetURI key) {
2216                 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2217                 image.setKey(key.toString());
2218                 deleteTemporaryImage(image.getId());
2219                 saveSone(image.getSone());
2220                 coreListenerManager.fireImageInsertFinished(image);
2221         }
2222
2223         /**
2224          * {@inheritDoc}
2225          */
2226         @Override
2227         public void imageInsertFailed(Image image, Throwable cause) {
2228                 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2229                 coreListenerManager.fireImageInsertFailed(image, cause);
2230         }
2231
2232         /**
2233          * Convenience interface for external classes that want to access the core’s
2234          * configuration.
2235          *
2236          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2237          */
2238         public static class Preferences {
2239
2240                 /** The wrapped options. */
2241                 private final Options options;
2242
2243                 /**
2244                  * Creates a new preferences object wrapped around the given options.
2245                  *
2246                  * @param options
2247                  *            The options to wrap
2248                  */
2249                 public Preferences(Options options) {
2250                         this.options = options;
2251                 }
2252
2253                 /**
2254                  * Returns the insertion delay.
2255                  *
2256                  * @return The insertion delay
2257                  */
2258                 public int getInsertionDelay() {
2259                         return options.getIntegerOption("InsertionDelay").get();
2260                 }
2261
2262                 /**
2263                  * Sets the insertion delay
2264                  *
2265                  * @param insertionDelay
2266                  *            The new insertion delay, or {@code null} to restore it to
2267                  *            the default value
2268                  * @return This preferences
2269                  */
2270                 public Preferences setInsertionDelay(Integer insertionDelay) {
2271                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2272                         return this;
2273                 }
2274
2275                 /**
2276                  * Returns the positive trust.
2277                  *
2278                  * @return The positive trust
2279                  */
2280                 public int getPositiveTrust() {
2281                         return options.getIntegerOption("PositiveTrust").get();
2282                 }
2283
2284                 /**
2285                  * Sets the positive trust.
2286                  *
2287                  * @param positiveTrust
2288                  *            The new positive trust, or {@code null} to restore it to
2289                  *            the default vlaue
2290                  * @return This preferences
2291                  */
2292                 public Preferences setPositiveTrust(Integer positiveTrust) {
2293                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2294                         return this;
2295                 }
2296
2297                 /**
2298                  * Returns the negative trust.
2299                  *
2300                  * @return The negative trust
2301                  */
2302                 public int getNegativeTrust() {
2303                         return options.getIntegerOption("NegativeTrust").get();
2304                 }
2305
2306                 /**
2307                  * Sets the negative trust.
2308                  *
2309                  * @param negativeTrust
2310                  *            The negative trust, or {@code null} to restore it to the
2311                  *            default value
2312                  * @return The preferences
2313                  */
2314                 public Preferences setNegativeTrust(Integer negativeTrust) {
2315                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2316                         return this;
2317                 }
2318
2319                 /**
2320                  * Returns the trust comment. This is the comment that is set in the web
2321                  * of trust when a trust value is assigned to an identity.
2322                  *
2323                  * @return The trust comment
2324                  */
2325                 public String getTrustComment() {
2326                         return options.getStringOption("TrustComment").get();
2327                 }
2328
2329                 /**
2330                  * Sets the trust comment.
2331                  *
2332                  * @param trustComment
2333                  *            The trust comment, or {@code null} to restore it to the
2334                  *            default value
2335                  * @return This preferences
2336                  */
2337                 public Preferences setTrustComment(String trustComment) {
2338                         options.getStringOption("TrustComment").set(trustComment);
2339                         return this;
2340                 }
2341
2342                 /**
2343                  * Returns whether the rescue mode is active.
2344                  *
2345                  * @return {@code true} if the rescue mode is active, {@code false}
2346                  *         otherwise
2347                  */
2348                 public boolean isSoneRescueMode() {
2349                         return options.getBooleanOption("SoneRescueMode").get();
2350                 }
2351
2352                 /**
2353                  * Sets whether the rescue mode is active.
2354                  *
2355                  * @param soneRescueMode
2356                  *            {@code true} if the rescue mode is active, {@code false}
2357                  *            otherwise
2358                  * @return This preferences
2359                  */
2360                 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2361                         options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2362                         return this;
2363                 }
2364
2365                 /**
2366                  * Returns whether Sone should clear its settings on the next restart.
2367                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2368                  * to return {@code true} as well!
2369                  *
2370                  * @return {@code true} if Sone should clear its settings on the next
2371                  *         restart, {@code false} otherwise
2372                  */
2373                 public boolean isClearOnNextRestart() {
2374                         return options.getBooleanOption("ClearOnNextRestart").get();
2375                 }
2376
2377                 /**
2378                  * Sets whether Sone will clear its settings on the next restart.
2379                  *
2380                  * @param clearOnNextRestart
2381                  *            {@code true} if Sone should clear its settings on the next
2382                  *            restart, {@code false} otherwise
2383                  * @return This preferences
2384                  */
2385                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2386                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2387                         return this;
2388                 }
2389
2390                 /**
2391                  * Returns whether Sone should really clear its settings on next
2392                  * restart. This is a confirmation option that needs to be set in
2393                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2394                  * settings on the next restart.
2395                  *
2396                  * @return {@code true} if Sone should really clear its settings on the
2397                  *         next restart, {@code false} otherwise
2398                  */
2399                 public boolean isReallyClearOnNextRestart() {
2400                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2401                 }
2402
2403                 /**
2404                  * Sets whether Sone should really clear its settings on the next
2405                  * restart.
2406                  *
2407                  * @param reallyClearOnNextRestart
2408                  *            {@code true} if Sone should really clear its settings on
2409                  *            the next restart, {@code false} otherwise
2410                  * @return This preferences
2411                  */
2412                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2413                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2414                         return this;
2415                 }
2416
2417         }
2418
2419 }