Show all top-level albums.
[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.Reply;
40 import net.pterodactylus.sone.data.Sone;
41 import net.pterodactylus.sone.freenet.wot.Identity;
42 import net.pterodactylus.sone.freenet.wot.IdentityListener;
43 import net.pterodactylus.sone.freenet.wot.IdentityManager;
44 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
45 import net.pterodactylus.sone.main.SonePlugin;
46 import net.pterodactylus.util.config.Configuration;
47 import net.pterodactylus.util.config.ConfigurationException;
48 import net.pterodactylus.util.logging.Logging;
49 import net.pterodactylus.util.number.Numbers;
50 import net.pterodactylus.util.version.Version;
51 import freenet.keys.FreenetURI;
52
53 /**
54  * The Sone core.
55  *
56  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57  */
58 public class Core implements IdentityListener, UpdateListener {
59
60         /**
61          * Enumeration for the possible states of a {@link Sone}.
62          *
63          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64          */
65         public enum SoneStatus {
66
67                 /** The Sone is unknown, i.e. not yet downloaded. */
68                 unknown,
69
70                 /** The Sone is idle, i.e. not being downloaded or inserted. */
71                 idle,
72
73                 /** The Sone is currently being inserted. */
74                 inserting,
75
76                 /** The Sone is currently being downloaded. */
77                 downloading,
78         }
79
80         /** The logger. */
81         private static final Logger logger = Logging.getLogger(Core.class);
82
83         /** The options. */
84         private final Options options = new Options();
85
86         /** The core listener manager. */
87         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
88
89         /** The configuration. */
90         private Configuration configuration;
91
92         /** Whether we’re currently saving the configuration. */
93         private boolean storingConfiguration = false;
94
95         /** The identity manager. */
96         private final IdentityManager identityManager;
97
98         /** Interface to freenet. */
99         private final FreenetInterface freenetInterface;
100
101         /** The Sone downloader. */
102         private final SoneDownloader soneDownloader;
103
104         /** The update checker. */
105         private final UpdateChecker updateChecker;
106
107         /** Whether the core has been stopped. */
108         private volatile boolean stopped;
109
110         /** The Sones’ statuses. */
111         /* synchronize access on itself. */
112         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
113
114         /** Locked local Sones. */
115         /* synchronize on itself. */
116         private final Set<Sone> lockedSones = new HashSet<Sone>();
117
118         /** Sone inserters. */
119         /* synchronize access on this on localSones. */
120         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
121
122         /** All local Sones. */
123         /* synchronize access on this on itself. */
124         private Map<String, Sone> localSones = new HashMap<String, Sone>();
125
126         /** All remote Sones. */
127         /* synchronize access on this on itself. */
128         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
129
130         /** All new Sones. */
131         private Set<String> newSones = new HashSet<String>();
132
133         /** All known Sones. */
134         /* synchronize access on {@link #newSones}. */
135         private Set<String> knownSones = new HashSet<String>();
136
137         /** All posts. */
138         private Map<String, Post> posts = new HashMap<String, Post>();
139
140         /** All new posts. */
141         private Set<String> newPosts = new HashSet<String>();
142
143         /** All known posts. */
144         /* synchronize access on {@link #newPosts}. */
145         private Set<String> knownPosts = new HashSet<String>();
146
147         /** All replies. */
148         private Map<String, Reply> replies = new HashMap<String, Reply>();
149
150         /** All new replies. */
151         private Set<String> newReplies = new HashSet<String>();
152
153         /** All known replies. */
154         private Set<String> knownReplies = new HashSet<String>();
155
156         /** All known albums. */
157         private Map<String, Album> albums = new HashMap<String, Album>();
158
159         /** All known images. */
160         private Map<String, Image> images = new HashMap<String, Image>();
161
162         /**
163          * Creates a new core.
164          *
165          * @param configuration
166          *            The configuration of the core
167          * @param freenetInterface
168          *            The freenet interface
169          * @param identityManager
170          *            The identity manager
171          */
172         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
173                 this.configuration = configuration;
174                 this.freenetInterface = freenetInterface;
175                 this.identityManager = identityManager;
176                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
177                 this.updateChecker = new UpdateChecker(freenetInterface);
178         }
179
180         //
181         // LISTENER MANAGEMENT
182         //
183
184         /**
185          * Adds a new core listener.
186          *
187          * @param coreListener
188          *            The listener to add
189          */
190         public void addCoreListener(CoreListener coreListener) {
191                 coreListenerManager.addListener(coreListener);
192         }
193
194         /**
195          * Removes a core listener.
196          *
197          * @param coreListener
198          *            The listener to remove
199          */
200         public void removeCoreListener(CoreListener coreListener) {
201                 coreListenerManager.removeListener(coreListener);
202         }
203
204         //
205         // ACCESSORS
206         //
207
208         /**
209          * Sets the configuration to use. This will automatically save the current
210          * configuration to the given configuration.
211          *
212          * @param configuration
213          *            The new configuration to use
214          */
215         public void setConfiguration(Configuration configuration) {
216                 this.configuration = configuration;
217                 saveConfiguration();
218         }
219
220         /**
221          * Returns the options used by the core.
222          *
223          * @return The options of the core
224          */
225         public Options getOptions() {
226                 return options;
227         }
228
229         /**
230          * Returns whether the “Sone rescue mode” is currently activated.
231          *
232          * @return {@code true} if the “Sone rescue mode” is currently activated,
233          *         {@code false} if it is not
234          */
235         public boolean isSoneRescueMode() {
236                 return options.getBooleanOption("SoneRescueMode").get();
237         }
238
239         /**
240          * Returns the identity manager used by the core.
241          *
242          * @return The identity manager
243          */
244         public IdentityManager getIdentityManager() {
245                 return identityManager;
246         }
247
248         /**
249          * Returns the update checker.
250          *
251          * @return The update checker
252          */
253         public UpdateChecker getUpdateChecker() {
254                 return updateChecker;
255         }
256
257         /**
258          * Returns the status of the given Sone.
259          *
260          * @param sone
261          *            The Sone to get the status for
262          * @return The status of the Sone
263          */
264         public SoneStatus getSoneStatus(Sone sone) {
265                 synchronized (soneStatuses) {
266                         return soneStatuses.get(sone);
267                 }
268         }
269
270         /**
271          * Sets the status of the given Sone.
272          *
273          * @param sone
274          *            The Sone to set the status of
275          * @param soneStatus
276          *            The status to set
277          */
278         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
279                 synchronized (soneStatuses) {
280                         soneStatuses.put(sone, soneStatus);
281                 }
282         }
283
284         /**
285          * Returns whether the given Sone is currently locked.
286          *
287          * @param sone
288          *            The sone to check
289          * @return {@code true} if the Sone is locked, {@code false} if it is not
290          */
291         public boolean isLocked(Sone sone) {
292                 synchronized (lockedSones) {
293                         return lockedSones.contains(sone);
294                 }
295         }
296
297         /**
298          * Returns all Sones, remote and local.
299          *
300          * @return All Sones
301          */
302         public Set<Sone> getSones() {
303                 Set<Sone> allSones = new HashSet<Sone>();
304                 allSones.addAll(getLocalSones());
305                 allSones.addAll(getRemoteSones());
306                 return allSones;
307         }
308
309         /**
310          * Returns the Sone with the given ID, regardless whether it’s local or
311          * remote.
312          *
313          * @param id
314          *            The ID of the Sone to get
315          * @return The Sone with the given ID, or {@code null} if there is no such
316          *         Sone
317          */
318         public Sone getSone(String id) {
319                 return getSone(id, true);
320         }
321
322         /**
323          * Returns the Sone with the given ID, regardless whether it’s local or
324          * remote.
325          *
326          * @param id
327          *            The ID of the Sone to get
328          * @param create
329          *            {@code true} to create a new Sone if none exists,
330          *            {@code false} to return {@code null} if a Sone with the given
331          *            ID does not exist
332          * @return The Sone with the given ID, or {@code null} if there is no such
333          *         Sone
334          */
335         public Sone getSone(String id, boolean create) {
336                 if (isLocalSone(id)) {
337                         return getLocalSone(id);
338                 }
339                 return getRemoteSone(id, create);
340         }
341
342         /**
343          * Checks whether the core knows a Sone with the given ID.
344          *
345          * @param id
346          *            The ID of the Sone
347          * @return {@code true} if there is a Sone with the given ID, {@code false}
348          *         otherwise
349          */
350         public boolean hasSone(String id) {
351                 return isLocalSone(id) || isRemoteSone(id);
352         }
353
354         /**
355          * Returns whether the given Sone is a local Sone.
356          *
357          * @param sone
358          *            The Sone to check for its locality
359          * @return {@code true} if the given Sone is local, {@code false} otherwise
360          */
361         public boolean isLocalSone(Sone sone) {
362                 synchronized (localSones) {
363                         return localSones.containsKey(sone.getId());
364                 }
365         }
366
367         /**
368          * Returns whether the given ID is the ID of a local Sone.
369          *
370          * @param id
371          *            The Sone ID to check for its locality
372          * @return {@code true} if the given ID is a local Sone, {@code false}
373          *         otherwise
374          */
375         public boolean isLocalSone(String id) {
376                 synchronized (localSones) {
377                         return localSones.containsKey(id);
378                 }
379         }
380
381         /**
382          * Returns all local Sones.
383          *
384          * @return All local Sones
385          */
386         public Set<Sone> getLocalSones() {
387                 synchronized (localSones) {
388                         return new HashSet<Sone>(localSones.values());
389                 }
390         }
391
392         /**
393          * Returns the local Sone with the given ID.
394          *
395          * @param id
396          *            The ID of the Sone to get
397          * @return The Sone with the given ID
398          */
399         public Sone getLocalSone(String id) {
400                 return getLocalSone(id, true);
401         }
402
403         /**
404          * Returns the local Sone with the given ID, optionally creating a new Sone.
405          *
406          * @param id
407          *            The ID of the Sone
408          * @param create
409          *            {@code true} to create a new Sone if none exists,
410          *            {@code false} to return null if none exists
411          * @return The Sone with the given ID, or {@code null}
412          */
413         public Sone getLocalSone(String id, boolean create) {
414                 synchronized (localSones) {
415                         Sone sone = localSones.get(id);
416                         if ((sone == null) && create) {
417                                 sone = new Sone(id);
418                                 localSones.put(id, sone);
419                         }
420                         return sone;
421                 }
422         }
423
424         /**
425          * Returns all remote Sones.
426          *
427          * @return All remote Sones
428          */
429         public Set<Sone> getRemoteSones() {
430                 synchronized (remoteSones) {
431                         return new HashSet<Sone>(remoteSones.values());
432                 }
433         }
434
435         /**
436          * Returns the remote Sone with the given ID.
437          *
438          * @param id
439          *            The ID of the remote Sone to get
440          * @return The Sone with the given ID
441          */
442         public Sone getRemoteSone(String id) {
443                 return getRemoteSone(id, true);
444         }
445
446         /**
447          * Returns the remote Sone with the given ID.
448          *
449          * @param id
450          *            The ID of the remote Sone to get
451          * @param create
452          *            {@code true} to always create a Sone, {@code false} to return
453          *            {@code null} if no Sone with the given ID exists
454          * @return The Sone with the given ID
455          */
456         public Sone getRemoteSone(String id, boolean create) {
457                 synchronized (remoteSones) {
458                         Sone sone = remoteSones.get(id);
459                         if ((sone == null) && create) {
460                                 sone = new Sone(id);
461                                 remoteSones.put(id, sone);
462                         }
463                         return sone;
464                 }
465         }
466
467         /**
468          * Returns whether the given Sone is a remote Sone.
469          *
470          * @param sone
471          *            The Sone to check
472          * @return {@code true} if the given Sone is a remote Sone, {@code false}
473          *         otherwise
474          */
475         public boolean isRemoteSone(Sone sone) {
476                 synchronized (remoteSones) {
477                         return remoteSones.containsKey(sone.getId());
478                 }
479         }
480
481         /**
482          * Returns whether the Sone with the given ID is a remote Sone.
483          *
484          * @param id
485          *            The ID of the Sone to check
486          * @return {@code true} if the Sone with the given ID is a remote Sone,
487          *         {@code false} otherwise
488          */
489         public boolean isRemoteSone(String id) {
490                 synchronized (remoteSones) {
491                         return remoteSones.containsKey(id);
492                 }
493         }
494
495         /**
496          * Returns whether the given Sone is a new Sone. After this check, the Sone
497          * is marked as known, i.e. a second call with the same parameters will
498          * always yield {@code false}.
499          *
500          * @param sone
501          *            The sone to check for
502          * @return {@code true} if the given Sone is new, false otherwise
503          */
504         public boolean isNewSone(Sone sone) {
505                 synchronized (newSones) {
506                         boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
507                         knownSones.add(sone.getId());
508                         if (isNew) {
509                                 coreListenerManager.fireMarkSoneKnown(sone);
510                         }
511                         return isNew;
512                 }
513         }
514
515         /**
516          * Returns whether the given Sone has been modified.
517          *
518          * @param sone
519          *            The Sone to check for modifications
520          * @return {@code true} if a modification has been detected in the Sone,
521          *         {@code false} otherwise
522          */
523         public boolean isModifiedSone(Sone sone) {
524                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
525         }
526
527         /**
528          * Returns the post with the given ID.
529          *
530          * @param postId
531          *            The ID of the post to get
532          * @return The post, or {@code null} if there is no such post
533          */
534         public Post getPost(String postId) {
535                 return getPost(postId, true);
536         }
537
538         /**
539          * Returns the post with the given ID, optionally creating a new post.
540          *
541          * @param postId
542          *            The ID of the post to get
543          * @param create
544          *            {@code true} it create a new post if no post with the given ID
545          *            exists, {@code false} to return {@code null}
546          * @return The post, or {@code null} if there is no such post
547          */
548         public Post getPost(String postId, boolean create) {
549                 synchronized (posts) {
550                         Post post = posts.get(postId);
551                         if ((post == null) && create) {
552                                 post = new Post(postId);
553                                 posts.put(postId, post);
554                         }
555                         return post;
556                 }
557         }
558
559         /**
560          * Returns whether the given post ID is new. After this method returns it is
561          * marked a known post ID.
562          *
563          * @param postId
564          *            The post ID
565          * @return {@code true} if the post is considered to be new, {@code false}
566          *         otherwise
567          */
568         public boolean isNewPost(String postId) {
569                 return isNewPost(postId, true);
570         }
571
572         /**
573          * Returns whether the given post ID is new. If {@code markAsKnown} is
574          * {@code true} then after this method returns the post ID is marked a known
575          * post ID.
576          *
577          * @param postId
578          *            The post ID
579          * @param markAsKnown
580          *            {@code true} to mark the post ID as known, {@code false} to
581          *            not to mark it as known
582          * @return {@code true} if the post is considered to be new, {@code false}
583          *         otherwise
584          */
585         public boolean isNewPost(String postId, boolean markAsKnown) {
586                 synchronized (newPosts) {
587                         boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
588                         if (markAsKnown) {
589                                 Post post = getPost(postId, false);
590                                 if (post != null) {
591                                         markPostKnown(post);
592                                 }
593                         }
594                         return isNew;
595                 }
596         }
597
598         /**
599          * Returns the reply with the given ID. If there is no reply with the given
600          * ID yet, a new one is created.
601          *
602          * @param replyId
603          *            The ID of the reply to get
604          * @return The reply
605          */
606         public Reply getReply(String replyId) {
607                 return getReply(replyId, true);
608         }
609
610         /**
611          * Returns the reply with the given ID. If there is no reply with the given
612          * ID yet, a new one is created, unless {@code create} is false in which
613          * case {@code null} is returned.
614          *
615          * @param replyId
616          *            The ID of the reply to get
617          * @param create
618          *            {@code true} to always return a {@link Reply}, {@code false}
619          *            to return {@code null} if no reply can be found
620          * @return The reply, or {@code null} if there is no such reply
621          */
622         public Reply getReply(String replyId, boolean create) {
623                 synchronized (replies) {
624                         Reply reply = replies.get(replyId);
625                         if (create && (reply == null)) {
626                                 reply = new Reply(replyId);
627                                 replies.put(replyId, reply);
628                         }
629                         return reply;
630                 }
631         }
632
633         /**
634          * Returns all replies for the given post, order ascending by time.
635          *
636          * @param post
637          *            The post to get all replies for
638          * @return All replies for the given post
639          */
640         public List<Reply> getReplies(Post post) {
641                 Set<Sone> sones = getSones();
642                 List<Reply> replies = new ArrayList<Reply>();
643                 for (Sone sone : sones) {
644                         for (Reply reply : sone.getReplies()) {
645                                 if (reply.getPost().equals(post)) {
646                                         replies.add(reply);
647                                 }
648                         }
649                 }
650                 Collections.sort(replies, Reply.TIME_COMPARATOR);
651                 return replies;
652         }
653
654         /**
655          * Returns whether the reply with the given ID is new.
656          *
657          * @param replyId
658          *            The ID of the reply to check
659          * @return {@code true} if the reply is considered to be new, {@code false}
660          *         otherwise
661          */
662         public boolean isNewReply(String replyId) {
663                 return isNewReply(replyId, true);
664         }
665
666         /**
667          * Returns whether the reply with the given ID is new.
668          *
669          * @param replyId
670          *            The ID of the reply to check
671          * @param markAsKnown
672          *            {@code true} to mark the reply as known, {@code false} to not
673          *            to mark it as known
674          * @return {@code true} if the reply is considered to be new, {@code false}
675          *         otherwise
676          */
677         public boolean isNewReply(String replyId, boolean markAsKnown) {
678                 synchronized (newReplies) {
679                         boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
680                         if (markAsKnown) {
681                                 Reply reply = getReply(replyId, false);
682                                 if (reply != null) {
683                                         markReplyKnown(reply);
684                                 }
685                         }
686                         return isNew;
687                 }
688         }
689
690         /**
691          * Returns all Sones that have liked the given post.
692          *
693          * @param post
694          *            The post to get the liking Sones for
695          * @return The Sones that like the given post
696          */
697         public Set<Sone> getLikes(Post post) {
698                 Set<Sone> sones = new HashSet<Sone>();
699                 for (Sone sone : getSones()) {
700                         if (sone.getLikedPostIds().contains(post.getId())) {
701                                 sones.add(sone);
702                         }
703                 }
704                 return sones;
705         }
706
707         /**
708          * Returns all Sones that have liked the given reply.
709          *
710          * @param reply
711          *            The reply to get the liking Sones for
712          * @return The Sones that like the given reply
713          */
714         public Set<Sone> getLikes(Reply reply) {
715                 Set<Sone> sones = new HashSet<Sone>();
716                 for (Sone sone : getSones()) {
717                         if (sone.getLikedReplyIds().contains(reply.getId())) {
718                                 sones.add(sone);
719                         }
720                 }
721                 return sones;
722         }
723
724         /**
725          * Returns the album with the given ID, creating a new album if no album
726          * with the given ID can be found.
727          *
728          * @param albumId
729          *            The ID of the album
730          * @return The album with the given ID
731          */
732         public Album getAlbum(String albumId) {
733                 return getAlbum(albumId, true);
734         }
735
736         /**
737          * Returns the album with the given ID, optionally creating a new album if
738          * an album with the given ID can not be found.
739          *
740          * @param albumId
741          *            The ID of the album
742          * @param create
743          *            {@code true} to create a new album if none exists for the
744          *            given ID
745          * @return The album with the given ID, or {@code null} if no album with the
746          *         given ID exists and {@code create} is {@code false}
747          */
748         public Album getAlbum(String albumId, boolean create) {
749                 synchronized (albums) {
750                         Album album = albums.get(albumId);
751                         if (create && (album == null)) {
752                                 album = new Album(albumId);
753                                 albums.put(albumId, album);
754                         }
755                         return album;
756                 }
757         }
758
759         /**
760          * Returns the image with the given ID, creating it if necessary.
761          *
762          * @param imageId
763          *            The ID of the image
764          * @return The image with the given ID
765          */
766         public Image getImage(String imageId) {
767                 return getImage(imageId, true);
768         }
769
770         /**
771          * Returns the image with the given ID, optionally creating it if it does
772          * not exist.
773          *
774          * @param imageId
775          *            The ID of the image
776          * @param create
777          *            {@code true} to create an image if none exists with the given
778          *            ID
779          * @return The image with the given ID, or {@code null} if none exists and
780          *         none was created
781          */
782         public Image getImage(String imageId, boolean create) {
783                 synchronized (images) {
784                         Image image = images.get(imageId);
785                         if (create && (image == null)) {
786                                 image = new Image(imageId);
787                                 images.put(imageId, image);
788                         }
789                         return image;
790                 }
791         }
792
793         //
794         // ACTIONS
795         //
796
797         /**
798          * Locks the given Sone. A locked Sone will not be inserted by
799          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
800          * again.
801          *
802          * @param sone
803          *            The sone to lock
804          */
805         public void lockSone(Sone sone) {
806                 synchronized (lockedSones) {
807                         if (lockedSones.add(sone)) {
808                                 coreListenerManager.fireSoneLocked(sone);
809                         }
810                 }
811         }
812
813         /**
814          * Unlocks the given Sone.
815          *
816          * @see #lockSone(Sone)
817          * @param sone
818          *            The sone to unlock
819          */
820         public void unlockSone(Sone sone) {
821                 synchronized (lockedSones) {
822                         if (lockedSones.remove(sone)) {
823                                 coreListenerManager.fireSoneUnlocked(sone);
824                         }
825                 }
826         }
827
828         /**
829          * Adds a local Sone from the given ID which has to be the ID of an own
830          * identity.
831          *
832          * @param id
833          *            The ID of an own identity to add a Sone for
834          * @return The added (or already existing) Sone
835          */
836         public Sone addLocalSone(String id) {
837                 synchronized (localSones) {
838                         if (localSones.containsKey(id)) {
839                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
840                                 return localSones.get(id);
841                         }
842                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
843                         if (ownIdentity == null) {
844                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
845                                 return null;
846                         }
847                         return addLocalSone(ownIdentity);
848                 }
849         }
850
851         /**
852          * Adds a local Sone from the given own identity.
853          *
854          * @param ownIdentity
855          *            The own identity to create a Sone from
856          * @return The added (or already existing) Sone
857          */
858         public Sone addLocalSone(OwnIdentity ownIdentity) {
859                 if (ownIdentity == null) {
860                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
861                         return null;
862                 }
863                 synchronized (localSones) {
864                         final Sone sone;
865                         try {
866                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
867                         } catch (MalformedURLException mue1) {
868                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
869                                 return null;
870                         }
871                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
872                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
873                         /* TODO - load posts ’n stuff */
874                         localSones.put(ownIdentity.getId(), sone);
875                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
876                         soneInserters.put(sone, soneInserter);
877                         setSoneStatus(sone, SoneStatus.idle);
878                         loadSone(sone);
879                         if (!isSoneRescueMode()) {
880                                 soneInserter.start();
881                         }
882                         new Thread(new Runnable() {
883
884                                 @Override
885                                 @SuppressWarnings("synthetic-access")
886                                 public void run() {
887                                         if (!isSoneRescueMode()) {
888                                                 soneDownloader.fetchSone(sone);
889                                                 return;
890                                         }
891                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
892                                         coreListenerManager.fireRescuingSone(sone);
893                                         lockSone(sone);
894                                         long edition = sone.getLatestEdition();
895                                         while (!stopped && (edition >= 0) && isSoneRescueMode()) {
896                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
897                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
898                                                 --edition;
899                                         }
900                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
901                                         saveSone(sone);
902                                         coreListenerManager.fireRescuedSone(sone);
903                                         soneInserter.start();
904                                 }
905
906                         }, "Sone Downloader").start();
907                         return sone;
908                 }
909         }
910
911         /**
912          * Creates a new Sone for the given own identity.
913          *
914          * @param ownIdentity
915          *            The own identity to create a Sone for
916          * @return The created Sone
917          */
918         public Sone createSone(OwnIdentity ownIdentity) {
919                 identityManager.addContext(ownIdentity, "Sone");
920                 Sone sone = addLocalSone(ownIdentity);
921                 return sone;
922         }
923
924         /**
925          * Adds the Sone of the given identity.
926          *
927          * @param identity
928          *            The identity whose Sone to add
929          * @return The added or already existing Sone
930          */
931         public Sone addRemoteSone(Identity identity) {
932                 if (identity == null) {
933                         logger.log(Level.WARNING, "Given Identity is null!");
934                         return null;
935                 }
936                 synchronized (remoteSones) {
937                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
938                         boolean newSone = sone.getRequestUri() == null;
939                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
940                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
941                         if (newSone) {
942                                 synchronized (newSones) {
943                                         newSone = !knownSones.contains(sone.getId());
944                                         if (newSone) {
945                                                 newSones.add(sone.getId());
946                                         }
947                                 }
948                                 if (newSone) {
949                                         coreListenerManager.fireNewSoneFound(sone);
950                                 }
951                         }
952                         remoteSones.put(identity.getId(), sone);
953                         soneDownloader.addSone(sone);
954                         setSoneStatus(sone, SoneStatus.unknown);
955                         new Thread(new Runnable() {
956
957                                 @Override
958                                 @SuppressWarnings("synthetic-access")
959                                 public void run() {
960                                         soneDownloader.fetchSone(sone);
961                                 }
962
963                         }, "Sone Downloader").start();
964                         return sone;
965                 }
966         }
967
968         /**
969          * Updates the stores Sone with the given Sone.
970          *
971          * @param sone
972          *            The updated Sone
973          */
974         public void updateSone(Sone sone) {
975                 if (hasSone(sone.getId())) {
976                         boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
977                         Sone storedSone = getSone(sone.getId());
978                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
979                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
980                                 return;
981                         }
982                         synchronized (posts) {
983                                 if (!soneRescueMode) {
984                                         for (Post post : storedSone.getPosts()) {
985                                                 posts.remove(post.getId());
986                                                 if (!sone.getPosts().contains(post)) {
987                                                         coreListenerManager.firePostRemoved(post);
988                                                 }
989                                         }
990                                 }
991                                 synchronized (newPosts) {
992                                         for (Post post : sone.getPosts()) {
993                                                 post.setSone(getSone(post.getSone().getId()));
994                                                 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
995                                                         newPosts.add(post.getId());
996                                                         coreListenerManager.fireNewPostFound(post);
997                                                 }
998                                                 posts.put(post.getId(), post);
999                                         }
1000                                 }
1001                         }
1002                         synchronized (replies) {
1003                                 if (!soneRescueMode) {
1004                                         for (Reply reply : storedSone.getReplies()) {
1005                                                 replies.remove(reply.getId());
1006                                                 if (!sone.getReplies().contains(reply)) {
1007                                                         coreListenerManager.fireReplyRemoved(reply);
1008                                                 }
1009                                         }
1010                                 }
1011                                 synchronized (newReplies) {
1012                                         for (Reply reply : sone.getReplies()) {
1013                                                 reply.setSone(getSone(reply.getSone().getId()));
1014                                                 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
1015                                                         newReplies.add(reply.getId());
1016                                                         coreListenerManager.fireNewReplyFound(reply);
1017                                                 }
1018                                                 replies.put(reply.getId(), reply);
1019                                         }
1020                                 }
1021                         }
1022                         synchronized (storedSone) {
1023                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1024                                         storedSone.setTime(sone.getTime());
1025                                 }
1026                                 storedSone.setClient(sone.getClient());
1027                                 storedSone.setProfile(sone.getProfile());
1028                                 if (soneRescueMode) {
1029                                         for (Post post : sone.getPosts()) {
1030                                                 storedSone.addPost(post);
1031                                         }
1032                                         for (Reply reply : sone.getReplies()) {
1033                                                 storedSone.addReply(reply);
1034                                         }
1035                                         for (String likedPostId : sone.getLikedPostIds()) {
1036                                                 storedSone.addLikedPostId(likedPostId);
1037                                         }
1038                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1039                                                 storedSone.addLikedReplyId(likedReplyId);
1040                                         }
1041                                 } else {
1042                                         storedSone.setPosts(sone.getPosts());
1043                                         storedSone.setReplies(sone.getReplies());
1044                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1045                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1046                                 }
1047                                 storedSone.setLatestEdition(sone.getLatestEdition());
1048                         }
1049                 }
1050         }
1051
1052         /**
1053          * Deletes the given Sone. This will remove the Sone from the
1054          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1055          * and remove the context from its identity.
1056          *
1057          * @param sone
1058          *            The Sone to delete
1059          */
1060         public void deleteSone(Sone sone) {
1061                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1062                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1063                         return;
1064                 }
1065                 synchronized (localSones) {
1066                         if (!localSones.containsKey(sone.getId())) {
1067                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1068                                 return;
1069                         }
1070                         localSones.remove(sone.getId());
1071                         soneInserters.remove(sone).stop();
1072                 }
1073                 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1074                 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1075                 try {
1076                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1077                 } catch (ConfigurationException ce1) {
1078                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1079                 }
1080         }
1081
1082         /**
1083          * Loads and updates the given Sone from the configuration. If any error is
1084          * encountered, loading is aborted and the given Sone is not changed.
1085          *
1086          * @param sone
1087          *            The Sone to load and update
1088          */
1089         public void loadSone(Sone sone) {
1090                 if (!isLocalSone(sone)) {
1091                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1092                         return;
1093                 }
1094
1095                 /* load Sone. */
1096                 String sonePrefix = "Sone/" + sone.getId();
1097                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1098                 if (soneTime == null) {
1099                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1100                         return;
1101                 }
1102                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1103
1104                 /* load profile. */
1105                 Profile profile = new Profile();
1106                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1107                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1108                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1109                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1110                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1111                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1112
1113                 /* load posts. */
1114                 Set<Post> posts = new HashSet<Post>();
1115                 while (true) {
1116                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1117                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1118                         if (postId == null) {
1119                                 break;
1120                         }
1121                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1122                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1123                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1124                         if ((postTime == 0) || (postText == null)) {
1125                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1126                                 return;
1127                         }
1128                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1129                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1130                                 post.setRecipient(getSone(postRecipientId));
1131                         }
1132                         posts.add(post);
1133                 }
1134
1135                 /* load replies. */
1136                 Set<Reply> replies = new HashSet<Reply>();
1137                 while (true) {
1138                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1139                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1140                         if (replyId == null) {
1141                                 break;
1142                         }
1143                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1144                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1145                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1146                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1147                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1148                                 return;
1149                         }
1150                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1151                 }
1152
1153                 /* load post likes. */
1154                 Set<String> likedPostIds = new HashSet<String>();
1155                 while (true) {
1156                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1157                         if (likedPostId == null) {
1158                                 break;
1159                         }
1160                         likedPostIds.add(likedPostId);
1161                 }
1162
1163                 /* load reply likes. */
1164                 Set<String> likedReplyIds = new HashSet<String>();
1165                 while (true) {
1166                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1167                         if (likedReplyId == null) {
1168                                 break;
1169                         }
1170                         likedReplyIds.add(likedReplyId);
1171                 }
1172
1173                 /* load friends. */
1174                 Set<String> friends = new HashSet<String>();
1175                 while (true) {
1176                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1177                         if (friendId == null) {
1178                                 break;
1179                         }
1180                         friends.add(friendId);
1181                 }
1182
1183                 /* if we’re still here, Sone was loaded successfully. */
1184                 synchronized (sone) {
1185                         sone.setTime(soneTime);
1186                         sone.setProfile(profile);
1187                         sone.setPosts(posts);
1188                         sone.setReplies(replies);
1189                         sone.setLikePostIds(likedPostIds);
1190                         sone.setLikeReplyIds(likedReplyIds);
1191                         sone.setFriends(friends);
1192                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1193                 }
1194                 synchronized (newSones) {
1195                         for (String friend : friends) {
1196                                 knownSones.add(friend);
1197                         }
1198                 }
1199                 synchronized (newPosts) {
1200                         for (Post post : posts) {
1201                                 knownPosts.add(post.getId());
1202                         }
1203                 }
1204                 synchronized (newReplies) {
1205                         for (Reply reply : replies) {
1206                                 knownReplies.add(reply.getId());
1207                         }
1208                 }
1209         }
1210
1211         /**
1212          * Saves the given Sone. This will persist all local settings for the given
1213          * Sone, such as the friends list and similar, private options.
1214          *
1215          * @param sone
1216          *            The Sone to save
1217          */
1218         public synchronized void saveSone(Sone sone) {
1219                 if (!isLocalSone(sone)) {
1220                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1221                         return;
1222                 }
1223                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1224                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1225                         return;
1226                 }
1227
1228                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1229                 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1230                 try {
1231                         /* save Sone into configuration. */
1232                         String sonePrefix = "Sone/" + sone.getId();
1233                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1234                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1235
1236                         /* save profile. */
1237                         Profile profile = sone.getProfile();
1238                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1239                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1240                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1241                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1242                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1243                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1244
1245                         /* save posts. */
1246                         int postCounter = 0;
1247                         for (Post post : sone.getPosts()) {
1248                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1249                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1250                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1251                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1252                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1253                         }
1254                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1255
1256                         /* save replies. */
1257                         int replyCounter = 0;
1258                         for (Reply reply : sone.getReplies()) {
1259                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1260                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1261                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1262                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1263                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1264                         }
1265                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1266
1267                         /* save post likes. */
1268                         int postLikeCounter = 0;
1269                         for (String postId : sone.getLikedPostIds()) {
1270                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1271                         }
1272                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1273
1274                         /* save reply likes. */
1275                         int replyLikeCounter = 0;
1276                         for (String replyId : sone.getLikedReplyIds()) {
1277                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1278                         }
1279                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1280
1281                         /* save friends. */
1282                         int friendCounter = 0;
1283                         for (String friendId : sone.getFriends()) {
1284                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1285                         }
1286                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1287
1288                         configuration.save();
1289                         logger.log(Level.INFO, "Sone %s saved.", sone);
1290                 } catch (ConfigurationException ce1) {
1291                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1292                 }
1293         }
1294
1295         /**
1296          * Creates a new post.
1297          *
1298          * @param sone
1299          *            The Sone that creates the post
1300          * @param text
1301          *            The text of the post
1302          * @return The created post
1303          */
1304         public Post createPost(Sone sone, String text) {
1305                 return createPost(sone, System.currentTimeMillis(), text);
1306         }
1307
1308         /**
1309          * Creates a new post.
1310          *
1311          * @param sone
1312          *            The Sone that creates the post
1313          * @param time
1314          *            The time of the post
1315          * @param text
1316          *            The text of the post
1317          * @return The created post
1318          */
1319         public Post createPost(Sone sone, long time, String text) {
1320                 return createPost(sone, null, time, text);
1321         }
1322
1323         /**
1324          * Creates a new post.
1325          *
1326          * @param sone
1327          *            The Sone that creates the post
1328          * @param recipient
1329          *            The recipient Sone, or {@code null} if this post does not have
1330          *            a recipient
1331          * @param text
1332          *            The text of the post
1333          * @return The created post
1334          */
1335         public Post createPost(Sone sone, Sone recipient, String text) {
1336                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1337         }
1338
1339         /**
1340          * Creates a new post.
1341          *
1342          * @param sone
1343          *            The Sone that creates the post
1344          * @param recipient
1345          *            The recipient Sone, or {@code null} if this post does not have
1346          *            a recipient
1347          * @param time
1348          *            The time of the post
1349          * @param text
1350          *            The text of the post
1351          * @return The created post
1352          */
1353         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1354                 if (!isLocalSone(sone)) {
1355                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1356                         return null;
1357                 }
1358                 Post post = new Post(sone, time, text);
1359                 if (recipient != null) {
1360                         post.setRecipient(recipient);
1361                 }
1362                 synchronized (posts) {
1363                         posts.put(post.getId(), post);
1364                 }
1365                 synchronized (newPosts) {
1366                         knownPosts.add(post.getId());
1367                 }
1368                 sone.addPost(post);
1369                 saveSone(sone);
1370                 return post;
1371         }
1372
1373         /**
1374          * Deletes the given post.
1375          *
1376          * @param post
1377          *            The post to delete
1378          */
1379         public void deletePost(Post post) {
1380                 if (!isLocalSone(post.getSone())) {
1381                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1382                         return;
1383                 }
1384                 post.getSone().removePost(post);
1385                 synchronized (posts) {
1386                         posts.remove(post.getId());
1387                 }
1388                 saveSone(post.getSone());
1389         }
1390
1391         /**
1392          * Marks the given post as known, if it is currently a new post (according
1393          * to {@link #isNewPost(String)}).
1394          *
1395          * @param post
1396          *            The post to mark as known
1397          */
1398         public void markPostKnown(Post post) {
1399                 synchronized (newPosts) {
1400                         if (newPosts.remove(post.getId())) {
1401                                 knownPosts.add(post.getId());
1402                                 coreListenerManager.fireMarkPostKnown(post);
1403                                 saveConfiguration();
1404                         }
1405                 }
1406         }
1407
1408         /**
1409          * Creates a new reply.
1410          *
1411          * @param sone
1412          *            The Sone that creates the reply
1413          * @param post
1414          *            The post that this reply refers to
1415          * @param text
1416          *            The text of the reply
1417          * @return The created reply
1418          */
1419         public Reply createReply(Sone sone, Post post, String text) {
1420                 return createReply(sone, post, System.currentTimeMillis(), text);
1421         }
1422
1423         /**
1424          * Creates a new reply.
1425          *
1426          * @param sone
1427          *            The Sone that creates the reply
1428          * @param post
1429          *            The post that this reply refers to
1430          * @param time
1431          *            The time of the reply
1432          * @param text
1433          *            The text of the reply
1434          * @return The created reply
1435          */
1436         public Reply createReply(Sone sone, Post post, long time, String text) {
1437                 if (!isLocalSone(sone)) {
1438                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1439                         return null;
1440                 }
1441                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1442                 synchronized (replies) {
1443                         replies.put(reply.getId(), reply);
1444                 }
1445                 synchronized (newReplies) {
1446                         knownReplies.add(reply.getId());
1447                 }
1448                 sone.addReply(reply);
1449                 saveSone(sone);
1450                 return reply;
1451         }
1452
1453         /**
1454          * Deletes the given reply.
1455          *
1456          * @param reply
1457          *            The reply to delete
1458          */
1459         public void deleteReply(Reply reply) {
1460                 Sone sone = reply.getSone();
1461                 if (!isLocalSone(sone)) {
1462                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1463                         return;
1464                 }
1465                 synchronized (replies) {
1466                         replies.remove(reply.getId());
1467                 }
1468                 sone.removeReply(reply);
1469                 saveSone(sone);
1470         }
1471
1472         /**
1473          * Marks the given reply as known, if it is currently a new reply (according
1474          * to {@link #isNewReply(String)}).
1475          *
1476          * @param reply
1477          *            The reply to mark as known
1478          */
1479         public void markReplyKnown(Reply reply) {
1480                 synchronized (newReplies) {
1481                         if (newReplies.remove(reply.getId())) {
1482                                 knownReplies.add(reply.getId());
1483                                 coreListenerManager.fireMarkReplyKnown(reply);
1484                                 saveConfiguration();
1485                         }
1486                 }
1487         }
1488
1489         /**
1490          * Creates a new top-level album for the given Sone.
1491          *
1492          * @param sone
1493          *            The Sone to create the album for
1494          * @return The new album
1495          */
1496         public Album createAlbum(Sone sone) {
1497                 return createAlbum(sone, null);
1498         }
1499
1500         /**
1501          * Creates a new album for the given Sone.
1502          *
1503          * @param sone
1504          *            The Sone to create the album for
1505          * @param parent
1506          *            The parent of the album (may be {@code null} to create a
1507          *            top-level album)
1508          * @return The new album
1509          */
1510         public Album createAlbum(Sone sone, Album parent) {
1511                 Album album = new Album();
1512                 synchronized (albums) {
1513                         albums.put(album.getId(), album);
1514                 }
1515                 album.setSone(sone);
1516                 if (parent != null) {
1517                         parent.addAlbum(album);
1518                 }
1519                 sone.addAlbum(album);
1520                 return album;
1521         }
1522
1523         /**
1524          * Starts the core.
1525          */
1526         public void start() {
1527                 loadConfiguration();
1528                 updateChecker.addUpdateListener(this);
1529                 updateChecker.start();
1530         }
1531
1532         /**
1533          * Stops the core.
1534          */
1535         public void stop() {
1536                 synchronized (localSones) {
1537                         for (SoneInserter soneInserter : soneInserters.values()) {
1538                                 soneInserter.stop();
1539                         }
1540                 }
1541                 updateChecker.stop();
1542                 updateChecker.removeUpdateListener(this);
1543                 soneDownloader.stop();
1544                 saveConfiguration();
1545                 stopped = true;
1546         }
1547
1548         /**
1549          * Saves the current options.
1550          */
1551         public void saveConfiguration() {
1552                 synchronized (configuration) {
1553                         if (storingConfiguration) {
1554                                 logger.log(Level.FINE, "Already storing configuration…");
1555                                 return;
1556                         }
1557                         storingConfiguration = true;
1558                 }
1559
1560                 /* store the options first. */
1561                 try {
1562                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1563                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1564                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1565                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1566                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1567
1568                         /* save known Sones. */
1569                         int soneCounter = 0;
1570                         synchronized (newSones) {
1571                                 for (String knownSoneId : knownSones) {
1572                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1573                                 }
1574                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1575                         }
1576
1577                         /* save known posts. */
1578                         int postCounter = 0;
1579                         synchronized (newPosts) {
1580                                 for (String knownPostId : knownPosts) {
1581                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1582                                 }
1583                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1584                         }
1585
1586                         /* save known replies. */
1587                         int replyCounter = 0;
1588                         synchronized (newReplies) {
1589                                 for (String knownReplyId : knownReplies) {
1590                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1591                                 }
1592                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1593                         }
1594
1595                         /* now save it. */
1596                         configuration.save();
1597
1598                 } catch (ConfigurationException ce1) {
1599                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1600                 } finally {
1601                         synchronized (configuration) {
1602                                 storingConfiguration = false;
1603                         }
1604                 }
1605         }
1606
1607         //
1608         // PRIVATE METHODS
1609         //
1610
1611         /**
1612          * Loads the configuration.
1613          */
1614         @SuppressWarnings("unchecked")
1615         private void loadConfiguration() {
1616                 /* create options. */
1617                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1618
1619                         @Override
1620                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1621                                 SoneInserter.setInsertionDelay(newValue);
1622                         }
1623
1624                 }));
1625                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1626                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1627                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1628
1629                 /* read options from configuration. */
1630                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1631                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1632                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1633                 options.getBooleanOption("ClearOnNextRestart").set(null);
1634                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1635                 if (clearConfiguration) {
1636                         /* stop loading the configuration. */
1637                         return;
1638                 }
1639
1640                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1641                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1642
1643                 /* load known Sones. */
1644                 int soneCounter = 0;
1645                 while (true) {
1646                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1647                         if (knownSoneId == null) {
1648                                 break;
1649                         }
1650                         synchronized (newSones) {
1651                                 knownSones.add(knownSoneId);
1652                         }
1653                 }
1654
1655                 /* load known posts. */
1656                 int postCounter = 0;
1657                 while (true) {
1658                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1659                         if (knownPostId == null) {
1660                                 break;
1661                         }
1662                         synchronized (newPosts) {
1663                                 knownPosts.add(knownPostId);
1664                         }
1665                 }
1666
1667                 /* load known replies. */
1668                 int replyCounter = 0;
1669                 while (true) {
1670                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1671                         if (knownReplyId == null) {
1672                                 break;
1673                         }
1674                         synchronized (newReplies) {
1675                                 knownReplies.add(knownReplyId);
1676                         }
1677                 }
1678
1679         }
1680
1681         /**
1682          * Generate a Sone URI from the given URI and latest edition.
1683          *
1684          * @param uriString
1685          *            The URI to derive the Sone URI from
1686          * @return The derived URI
1687          */
1688         private FreenetURI getSoneUri(String uriString) {
1689                 try {
1690                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1691                         return uri;
1692                 } catch (MalformedURLException mue1) {
1693                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1694                         return null;
1695                 }
1696         }
1697
1698         //
1699         // INTERFACE IdentityListener
1700         //
1701
1702         /**
1703          * {@inheritDoc}
1704          */
1705         @Override
1706         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1707                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1708                 if (ownIdentity.hasContext("Sone")) {
1709                         addLocalSone(ownIdentity);
1710                 }
1711         }
1712
1713         /**
1714          * {@inheritDoc}
1715          */
1716         @Override
1717         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1718                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1719         }
1720
1721         /**
1722          * {@inheritDoc}
1723          */
1724         @Override
1725         public void identityAdded(Identity identity) {
1726                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1727                 addRemoteSone(identity);
1728         }
1729
1730         /**
1731          * {@inheritDoc}
1732          */
1733         @Override
1734         public void identityUpdated(final Identity identity) {
1735                 new Thread(new Runnable() {
1736
1737                         @Override
1738                         @SuppressWarnings("synthetic-access")
1739                         public void run() {
1740                                 Sone sone = getRemoteSone(identity.getId());
1741                                 soneDownloader.fetchSone(sone);
1742                         }
1743                 }).start();
1744         }
1745
1746         /**
1747          * {@inheritDoc}
1748          */
1749         @Override
1750         public void identityRemoved(Identity identity) {
1751                 /* TODO */
1752         }
1753
1754         //
1755         // INTERFACE UpdateListener
1756         //
1757
1758         /**
1759          * {@inheritDoc}
1760          */
1761         @Override
1762         public void updateFound(Version version, long releaseTime) {
1763                 coreListenerManager.fireUpdateFound(version, releaseTime);
1764         }
1765
1766 }