Store client information in local Sones.
[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.Client;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.freenet.wot.Identity;
40 import net.pterodactylus.sone.freenet.wot.IdentityListener;
41 import net.pterodactylus.sone.freenet.wot.IdentityManager;
42 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
43 import net.pterodactylus.sone.main.SonePlugin;
44 import net.pterodactylus.util.config.Configuration;
45 import net.pterodactylus.util.config.ConfigurationException;
46 import net.pterodactylus.util.logging.Logging;
47 import net.pterodactylus.util.number.Numbers;
48 import freenet.keys.FreenetURI;
49
50 /**
51  * The Sone core.
52  *
53  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54  */
55 public class Core implements IdentityListener {
56
57         /**
58          * Enumeration for the possible states of a {@link Sone}.
59          *
60          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61          */
62         public enum SoneStatus {
63
64                 /** The Sone is unknown, i.e. not yet downloaded. */
65                 unknown,
66
67                 /** The Sone is idle, i.e. not being downloaded or inserted. */
68                 idle,
69
70                 /** The Sone is currently being inserted. */
71                 inserting,
72
73                 /** The Sone is currently being downloaded. */
74                 downloading,
75         }
76
77         /** The logger. */
78         private static final Logger logger = Logging.getLogger(Core.class);
79
80         /** The options. */
81         private final Options options = new Options();
82
83         /** The configuration. */
84         private final Configuration configuration;
85
86         /** The identity manager. */
87         private final IdentityManager identityManager;
88
89         /** Interface to freenet. */
90         private final FreenetInterface freenetInterface;
91
92         /** The Sone downloader. */
93         private final SoneDownloader soneDownloader;
94
95         /** The Sones’ statuses. */
96         /* synchronize access on itself. */
97         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
98
99         /** Sone inserters. */
100         /* synchronize access on this on localSones. */
101         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
102
103         /** All local Sones. */
104         /* synchronize access on this on itself. */
105         private Map<String, Sone> localSones = new HashMap<String, Sone>();
106
107         /** All remote Sones. */
108         /* synchronize access on this on itself. */
109         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
110
111         /** All new Sones. */
112         private Set<String> newSones = new HashSet<String>();
113
114         /** All known Sones. */
115         /* synchronize access on {@link #newSones}. */
116         private Set<String> knownSones = new HashSet<String>();
117
118         /** All posts. */
119         private Map<String, Post> posts = new HashMap<String, Post>();
120
121         /** All new posts. */
122         private Set<String> newPosts = new HashSet<String>();
123
124         /** All known posts. */
125         /* synchronize access on {@link #newPosts}. */
126         private Set<String> knownPosts = new HashSet<String>();
127
128         /** All replies. */
129         private Map<String, Reply> replies = new HashMap<String, Reply>();
130
131         /** All new replies. */
132         private Set<String> newReplies = new HashSet<String>();
133
134         /** All known replies. */
135         private Set<String> knownReplies = new HashSet<String>();
136
137         /**
138          * Creates a new core.
139          *
140          * @param configuration
141          *            The configuration of the core
142          * @param freenetInterface
143          *            The freenet interface
144          * @param identityManager
145          *            The identity manager
146          */
147         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
148                 this.configuration = configuration;
149                 this.freenetInterface = freenetInterface;
150                 this.identityManager = identityManager;
151                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
152         }
153
154         //
155         // ACCESSORS
156         //
157
158         /**
159          * Returns the options used by the core.
160          *
161          * @return The options of the core
162          */
163         public Options getOptions() {
164                 return options;
165         }
166
167         /**
168          * Returns the identity manager used by the core.
169          *
170          * @return The identity manager
171          */
172         public IdentityManager getIdentityManager() {
173                 return identityManager;
174         }
175
176         /**
177          * Returns the status of the given Sone.
178          *
179          * @param sone
180          *            The Sone to get the status for
181          * @return The status of the Sone
182          */
183         public SoneStatus getSoneStatus(Sone sone) {
184                 synchronized (soneStatuses) {
185                         return soneStatuses.get(sone);
186                 }
187         }
188
189         /**
190          * Sets the status of the given Sone.
191          *
192          * @param sone
193          *            The Sone to set the status of
194          * @param soneStatus
195          *            The status to set
196          */
197         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
198                 synchronized (soneStatuses) {
199                         soneStatuses.put(sone, soneStatus);
200                 }
201         }
202
203         /**
204          * Returns all Sones, remote and local.
205          *
206          * @return All Sones
207          */
208         public Set<Sone> getSones() {
209                 Set<Sone> allSones = new HashSet<Sone>();
210                 allSones.addAll(getLocalSones());
211                 allSones.addAll(getRemoteSones());
212                 return allSones;
213         }
214
215         /**
216          * Returns the Sone with the given ID, regardless whether it’s local or
217          * remote.
218          *
219          * @param id
220          *            The ID of the Sone to get
221          * @return The Sone with the given ID, or {@code null} if there is no such
222          *         Sone
223          */
224         public Sone getSone(String id) {
225                 return getSone(id, true);
226         }
227
228         /**
229          * Returns the Sone with the given ID, regardless whether it’s local or
230          * remote.
231          *
232          * @param id
233          *            The ID of the Sone to get
234          * @param create
235          *            {@code true} to create a new Sone if none exists,
236          *            {@code false} to return {@code null} if a Sone with the given
237          *            ID does not exist
238          * @return The Sone with the given ID, or {@code null} if there is no such
239          *         Sone
240          */
241         public Sone getSone(String id, boolean create) {
242                 if (isLocalSone(id)) {
243                         return getLocalSone(id);
244                 }
245                 return getRemoteSone(id, create);
246         }
247
248         /**
249          * Checks whether the core knows a Sone with the given ID.
250          *
251          * @param id
252          *            The ID of the Sone
253          * @return {@code true} if there is a Sone with the given ID, {@code false}
254          *         otherwise
255          */
256         public boolean hasSone(String id) {
257                 return isLocalSone(id) || isRemoteSone(id);
258         }
259
260         /**
261          * Returns whether the given Sone is a local Sone.
262          *
263          * @param sone
264          *            The Sone to check for its locality
265          * @return {@code true} if the given Sone is local, {@code false} otherwise
266          */
267         public boolean isLocalSone(Sone sone) {
268                 synchronized (localSones) {
269                         return localSones.containsKey(sone.getId());
270                 }
271         }
272
273         /**
274          * Returns whether the given ID is the ID of a local Sone.
275          *
276          * @param id
277          *            The Sone ID to check for its locality
278          * @return {@code true} if the given ID is a local Sone, {@code false}
279          *         otherwise
280          */
281         public boolean isLocalSone(String id) {
282                 synchronized (localSones) {
283                         return localSones.containsKey(id);
284                 }
285         }
286
287         /**
288          * Returns all local Sones.
289          *
290          * @return All local Sones
291          */
292         public Set<Sone> getLocalSones() {
293                 synchronized (localSones) {
294                         return new HashSet<Sone>(localSones.values());
295                 }
296         }
297
298         /**
299          * Returns the local Sone with the given ID.
300          *
301          * @param id
302          *            The ID of the Sone to get
303          * @return The Sone with the given ID
304          */
305         public Sone getLocalSone(String id) {
306                 return getLocalSone(id, true);
307         }
308
309         /**
310          * Returns the local Sone with the given ID, optionally creating a new Sone.
311          *
312          * @param id
313          *            The ID of the Sone
314          * @param create
315          *            {@code true} to create a new Sone if none exists,
316          *            {@code false} to return null if none exists
317          * @return The Sone with the given ID, or {@code null}
318          */
319         public Sone getLocalSone(String id, boolean create) {
320                 synchronized (localSones) {
321                         Sone sone = localSones.get(id);
322                         if ((sone == null) && create) {
323                                 sone = new Sone(id);
324                                 localSones.put(id, sone);
325                         }
326                         return sone;
327                 }
328         }
329
330         /**
331          * Returns all remote Sones.
332          *
333          * @return All remote Sones
334          */
335         public Set<Sone> getRemoteSones() {
336                 synchronized (remoteSones) {
337                         return new HashSet<Sone>(remoteSones.values());
338                 }
339         }
340
341         /**
342          * Returns the remote Sone with the given ID.
343          *
344          * @param id
345          *            The ID of the remote Sone to get
346          * @return The Sone with the given ID
347          */
348         public Sone getRemoteSone(String id) {
349                 return getRemoteSone(id, true);
350         }
351
352         /**
353          * Returns the remote Sone with the given ID.
354          *
355          * @param id
356          *            The ID of the remote Sone to get
357          * @param create
358          *            {@code true} to always create a Sone, {@code false} to return
359          *            {@code null} if no Sone with the given ID exists
360          * @return The Sone with the given ID
361          */
362         public Sone getRemoteSone(String id, boolean create) {
363                 synchronized (remoteSones) {
364                         Sone sone = remoteSones.get(id);
365                         if ((sone == null) && create) {
366                                 sone = new Sone(id);
367                                 remoteSones.put(id, sone);
368                         }
369                         return sone;
370                 }
371         }
372
373         /**
374          * Returns whether the given Sone is a remote Sone.
375          *
376          * @param sone
377          *            The Sone to check
378          * @return {@code true} if the given Sone is a remote Sone, {@code false}
379          *         otherwise
380          */
381         public boolean isRemoteSone(Sone sone) {
382                 synchronized (remoteSones) {
383                         return remoteSones.containsKey(sone.getId());
384                 }
385         }
386
387         /**
388          * Returns whether the Sone with the given ID is a remote Sone.
389          *
390          * @param id
391          *            The ID of the Sone to check
392          * @return {@code true} if the Sone with the given ID is a remote Sone,
393          *         {@code false} otherwise
394          */
395         public boolean isRemoteSone(String id) {
396                 synchronized (remoteSones) {
397                         return remoteSones.containsKey(id);
398                 }
399         }
400
401         /**
402          * Returns whether the given Sone is a new Sone. After this check, the Sone
403          * is marked as known, i.e. a second call with the same parameters will
404          * always yield {@code false}.
405          *
406          * @param sone
407          *            The sone to check for
408          * @return {@code true} if the given Sone is new, false otherwise
409          */
410         public boolean isNewSone(Sone sone) {
411                 synchronized (newSones) {
412                         boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
413                         knownSones.add(sone.getId());
414                         return isNew;
415                 }
416         }
417
418         /**
419          * Returns whether the given Sone has been modified.
420          *
421          * @param sone
422          *            The Sone to check for modifications
423          * @return {@code true} if a modification has been detected in the Sone,
424          *         {@code false} otherwise
425          */
426         public boolean isModifiedSone(Sone sone) {
427                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
428         }
429
430         /**
431          * Returns the post with the given ID.
432          *
433          * @param postId
434          *            The ID of the post to get
435          * @return The post, or {@code null} if there is no such post
436          */
437         public Post getPost(String postId) {
438                 synchronized (posts) {
439                         Post post = posts.get(postId);
440                         if (post == null) {
441                                 post = new Post(postId);
442                                 posts.put(postId, post);
443                         }
444                         return post;
445                 }
446         }
447
448         /**
449          * Returns whether the given post ID is new. After this method returns it is
450          * marked a known post ID.
451          *
452          * @param postId
453          *            The post ID
454          * @return {@code true} if the post is considered to be new, {@code false}
455          *         otherwise
456          */
457         public boolean isNewPost(String postId) {
458                 synchronized (newPosts) {
459                         boolean isNew = !knownPosts.contains(postId) && newPosts.remove(postId);
460                         knownPosts.add(postId);
461                         return isNew;
462                 }
463         }
464
465         /**
466          * Returns the reply with the given ID.
467          *
468          * @param replyId
469          *            The ID of the reply to get
470          * @return The reply, or {@code null} if there is no such reply
471          */
472         public Reply getReply(String replyId) {
473                 synchronized (replies) {
474                         Reply reply = replies.get(replyId);
475                         if (reply == null) {
476                                 reply = new Reply(replyId);
477                                 replies.put(replyId, reply);
478                         }
479                         return reply;
480                 }
481         }
482
483         /**
484          * Returns all replies for the given post, order ascending by time.
485          *
486          * @param post
487          *            The post to get all replies for
488          * @return All replies for the given post
489          */
490         public List<Reply> getReplies(Post post) {
491                 Set<Sone> sones = getSones();
492                 List<Reply> replies = new ArrayList<Reply>();
493                 for (Sone sone : sones) {
494                         for (Reply reply : sone.getReplies()) {
495                                 if (reply.getPost().equals(post)) {
496                                         replies.add(reply);
497                                 }
498                         }
499                 }
500                 Collections.sort(replies, Reply.TIME_COMPARATOR);
501                 return replies;
502         }
503
504         /**
505          * Returns whether the reply with the given ID is new.
506          *
507          * @param replyId
508          *            The ID of the reply to check
509          * @return {@code true} if the reply is considered to be new, {@code false}
510          *         otherwise
511          */
512         public boolean isNewReply(String replyId) {
513                 synchronized (newReplies) {
514                         boolean isNew = !knownReplies.contains(replyId) && newReplies.remove(replyId);
515                         knownReplies.add(replyId);
516                         return isNew;
517                 }
518         }
519
520         /**
521          * Returns all Sones that have liked the given post.
522          *
523          * @param post
524          *            The post to get the liking Sones for
525          * @return The Sones that like the given post
526          */
527         public Set<Sone> getLikes(Post post) {
528                 Set<Sone> sones = new HashSet<Sone>();
529                 for (Sone sone : getSones()) {
530                         if (sone.getLikedPostIds().contains(post.getId())) {
531                                 sones.add(sone);
532                         }
533                 }
534                 return sones;
535         }
536
537         /**
538          * Returns all Sones that have liked the given reply.
539          *
540          * @param reply
541          *            The reply to get the liking Sones for
542          * @return The Sones that like the given reply
543          */
544         public Set<Sone> getLikes(Reply reply) {
545                 Set<Sone> sones = new HashSet<Sone>();
546                 for (Sone sone : getSones()) {
547                         if (sone.getLikedReplyIds().contains(reply.getId())) {
548                                 sones.add(sone);
549                         }
550                 }
551                 return sones;
552         }
553
554         //
555         // ACTIONS
556         //
557
558         /**
559          * Adds a local Sone from the given ID which has to be the ID of an own
560          * identity.
561          *
562          * @param id
563          *            The ID of an own identity to add a Sone for
564          * @return The added (or already existing) Sone
565          */
566         public Sone addLocalSone(String id) {
567                 synchronized (localSones) {
568                         if (localSones.containsKey(id)) {
569                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
570                                 return localSones.get(id);
571                         }
572                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
573                         if (ownIdentity == null) {
574                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
575                                 return null;
576                         }
577                         return addLocalSone(ownIdentity);
578                 }
579         }
580
581         /**
582          * Adds a local Sone from the given own identity.
583          *
584          * @param ownIdentity
585          *            The own identity to create a Sone from
586          * @return The added (or already existing) Sone
587          */
588         public Sone addLocalSone(OwnIdentity ownIdentity) {
589                 if (ownIdentity == null) {
590                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
591                         return null;
592                 }
593                 synchronized (localSones) {
594                         final Sone sone;
595                         try {
596                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
597                         } catch (MalformedURLException mue1) {
598                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
599                                 return null;
600                         }
601                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
602                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
603                         /* TODO - load posts ’n stuff */
604                         localSones.put(ownIdentity.getId(), sone);
605                         SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
606                         soneInserters.put(sone, soneInserter);
607                         setSoneStatus(sone, SoneStatus.idle);
608                         loadSone(sone);
609                         soneInserter.start();
610                         new Thread(new Runnable() {
611
612                                 @Override
613                                 @SuppressWarnings("synthetic-access")
614                                 public void run() {
615                                         soneDownloader.fetchSone(sone);
616                                 }
617
618                         }, "Sone Downloader").start();
619                         return sone;
620                 }
621         }
622
623         /**
624          * Creates a new Sone for the given own identity.
625          *
626          * @param ownIdentity
627          *            The own identity to create a Sone for
628          * @return The created Sone
629          */
630         public Sone createSone(OwnIdentity ownIdentity) {
631                 identityManager.addContext(ownIdentity, "Sone");
632                 Sone sone = addLocalSone(ownIdentity);
633                 return sone;
634         }
635
636         /**
637          * Adds the Sone of the given identity.
638          *
639          * @param identity
640          *            The identity whose Sone to add
641          * @return The added or already existing Sone
642          */
643         public Sone addRemoteSone(Identity identity) {
644                 if (identity == null) {
645                         logger.log(Level.WARNING, "Given Identity is null!");
646                         return null;
647                 }
648                 synchronized (remoteSones) {
649                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
650                         boolean newSone = sone.getRequestUri() == null;
651                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
652                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
653                         if (newSone) {
654                                 synchronized (newSones) {
655                                         newSones.add(sone.getId());
656                                 }
657                         }
658                         remoteSones.put(identity.getId(), sone);
659                         soneDownloader.addSone(sone);
660                         setSoneStatus(sone, SoneStatus.unknown);
661                         new Thread(new Runnable() {
662
663                                 @Override
664                                 @SuppressWarnings("synthetic-access")
665                                 public void run() {
666                                         soneDownloader.fetchSone(sone);
667                                 }
668
669                         }, "Sone Downloader").start();
670                         return sone;
671                 }
672         }
673
674         /**
675          * Updates the stores Sone with the given Sone.
676          *
677          * @param sone
678          *            The updated Sone
679          */
680         public void updateSone(Sone sone) {
681                 if (hasSone(sone.getId())) {
682                         Sone storedSone = getSone(sone.getId());
683                         if (!(sone.getTime() > storedSone.getTime())) {
684                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
685                                 return;
686                         }
687                         synchronized (posts) {
688                                 for (Post post : storedSone.getPosts()) {
689                                         posts.remove(post.getId());
690                                 }
691                                 synchronized (newPosts) {
692                                         for (Post post : sone.getPosts()) {
693                                                 if (!storedSone.getPosts().contains(post) && !knownSones.contains(post.getId())) {
694                                                         newPosts.add(post.getId());
695                                                 }
696                                                 posts.put(post.getId(), post);
697                                         }
698                                 }
699                         }
700                         synchronized (replies) {
701                                 for (Reply reply : storedSone.getReplies()) {
702                                         replies.remove(reply.getId());
703                                 }
704                                 synchronized (newReplies) {
705                                         for (Reply reply : sone.getReplies()) {
706                                                 if (!storedSone.getReplies().contains(reply) && !knownSones.contains(reply.getId())) {
707                                                         newReplies.add(reply.getId());
708                                                 }
709                                                 replies.put(reply.getId(), reply);
710                                         }
711                                 }
712                         }
713                         synchronized (storedSone) {
714                                 storedSone.setTime(sone.getTime());
715                                 storedSone.setProfile(sone.getProfile());
716                                 storedSone.setPosts(sone.getPosts());
717                                 storedSone.setReplies(sone.getReplies());
718                                 storedSone.setLikePostIds(sone.getLikedPostIds());
719                                 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
720                                 storedSone.setLatestEdition(sone.getRequestUri().getEdition());
721                         }
722                 }
723         }
724
725         /**
726          * Deletes the given Sone. This will remove the Sone from the
727          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
728          * and remove the context from its identity.
729          *
730          * @param sone
731          *            The Sone to delete
732          */
733         public void deleteSone(Sone sone) {
734                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
735                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
736                         return;
737                 }
738                 synchronized (localSones) {
739                         if (!localSones.containsKey(sone.getId())) {
740                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
741                                 return;
742                         }
743                         localSones.remove(sone.getId());
744                         soneInserters.remove(sone).stop();
745                 }
746                 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
747                 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
748                 try {
749                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
750                 } catch (ConfigurationException ce1) {
751                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
752                 }
753         }
754
755         /**
756          * Loads and updates the given Sone from the configuration. If any error is
757          * encountered, loading is aborted and the given Sone is not changed.
758          *
759          * @param sone
760          *            The Sone to load and update
761          */
762         public void loadSone(Sone sone) {
763                 if (!isLocalSone(sone)) {
764                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
765                         return;
766                 }
767
768                 /* load Sone. */
769                 String sonePrefix = "Sone/" + sone.getId();
770                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
771                 if (soneTime == null) {
772                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
773                         return;
774                 }
775                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
776
777                 /* load profile. */
778                 Profile profile = new Profile();
779                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
780                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
781                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
782                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
783                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
784                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
785
786                 /* load posts. */
787                 Set<Post> posts = new HashSet<Post>();
788                 while (true) {
789                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
790                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
791                         if (postId == null) {
792                                 break;
793                         }
794                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
795                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
796                         if ((postTime == 0) || (postText == null)) {
797                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
798                                 return;
799                         }
800                         posts.add(getPost(postId).setSone(sone).setTime(postTime).setText(postText));
801                 }
802
803                 /* load replies. */
804                 Set<Reply> replies = new HashSet<Reply>();
805                 while (true) {
806                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
807                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
808                         if (replyId == null) {
809                                 break;
810                         }
811                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
812                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
813                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
814                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
815                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
816                                 return;
817                         }
818                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
819                 }
820
821                 /* load post likes. */
822                 Set<String> likedPostIds = new HashSet<String>();
823                 while (true) {
824                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
825                         if (likedPostId == null) {
826                                 break;
827                         }
828                         likedPostIds.add(likedPostId);
829                 }
830
831                 /* load reply likes. */
832                 Set<String> likedReplyIds = new HashSet<String>();
833                 while (true) {
834                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
835                         if (likedReplyId == null) {
836                                 break;
837                         }
838                         likedReplyIds.add(likedReplyId);
839                 }
840
841                 /* load friends. */
842                 Set<String> friends = new HashSet<String>();
843                 while (true) {
844                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
845                         if (friendId == null) {
846                                 break;
847                         }
848                         friends.add(friendId);
849                 }
850
851                 /* if we’re still here, Sone was loaded successfully. */
852                 synchronized (sone) {
853                         sone.setTime(soneTime);
854                         sone.setProfile(profile);
855                         sone.setPosts(posts);
856                         sone.setReplies(replies);
857                         sone.setLikePostIds(likedPostIds);
858                         sone.setLikeReplyIds(likedReplyIds);
859                         sone.setFriends(friends);
860                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
861                 }
862                 synchronized (newSones) {
863                         for (String friend : friends) {
864                                 knownSones.add(friend);
865                         }
866                 }
867                 synchronized (newPosts) {
868                         for (Post post : posts) {
869                                 knownPosts.add(post.getId());
870                         }
871                 }
872                 synchronized (newReplies) {
873                         for (Reply reply : replies) {
874                                 knownReplies.add(reply.getId());
875                         }
876                 }
877         }
878
879         /**
880          * Saves the given Sone. This will persist all local settings for the given
881          * Sone, such as the friends list and similar, private options.
882          *
883          * @param sone
884          *            The Sone to save
885          */
886         public void saveSone(Sone sone) {
887                 if (!isLocalSone(sone)) {
888                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
889                         return;
890                 }
891                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
892                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
893                         return;
894                 }
895
896                 logger.log(Level.INFO, "Saving Sone: %s", sone);
897                 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
898                 try {
899                         /* save Sone into configuration. */
900                         String sonePrefix = "Sone/" + sone.getId();
901                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
902                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
903
904                         /* save profile. */
905                         Profile profile = sone.getProfile();
906                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
907                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
908                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
909                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
910                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
911                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
912
913                         /* save posts. */
914                         int postCounter = 0;
915                         for (Post post : sone.getPosts()) {
916                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
917                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
918                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
919                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
920                         }
921                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
922
923                         /* save replies. */
924                         int replyCounter = 0;
925                         for (Reply reply : sone.getReplies()) {
926                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
927                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
928                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
929                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
930                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
931                         }
932                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
933
934                         /* save post likes. */
935                         int postLikeCounter = 0;
936                         for (String postId : sone.getLikedPostIds()) {
937                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
938                         }
939                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
940
941                         /* save reply likes. */
942                         int replyLikeCounter = 0;
943                         for (String replyId : sone.getLikedReplyIds()) {
944                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
945                         }
946                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
947
948                         /* save friends. */
949                         int friendCounter = 0;
950                         for (String friendId : sone.getFriends()) {
951                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
952                         }
953                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
954
955                         logger.log(Level.INFO, "Sone %s saved.", sone);
956                 } catch (ConfigurationException ce1) {
957                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
958                 }
959         }
960
961         /**
962          * Creates a new post.
963          *
964          * @param sone
965          *            The Sone that creates the post
966          * @param text
967          *            The text of the post
968          */
969         public void createPost(Sone sone, String text) {
970                 createPost(sone, System.currentTimeMillis(), text);
971         }
972
973         /**
974          * Creates a new post.
975          *
976          * @param sone
977          *            The Sone that creates the post
978          * @param time
979          *            The time of the post
980          * @param text
981          *            The text of the post
982          */
983         public void createPost(Sone sone, long time, String text) {
984                 if (!isLocalSone(sone)) {
985                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
986                         return;
987                 }
988                 Post post = new Post(sone, time, text);
989                 synchronized (posts) {
990                         posts.put(post.getId(), post);
991                 }
992                 synchronized (newPosts) {
993                         knownPosts.add(post.getId());
994                 }
995                 sone.addPost(post);
996                 saveSone(sone);
997         }
998
999         /**
1000          * Deletes the given post.
1001          *
1002          * @param post
1003          *            The post to delete
1004          */
1005         public void deletePost(Post post) {
1006                 if (!isLocalSone(post.getSone())) {
1007                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1008                         return;
1009                 }
1010                 post.getSone().removePost(post);
1011                 synchronized (posts) {
1012                         posts.remove(post.getId());
1013                 }
1014                 saveSone(post.getSone());
1015         }
1016
1017         /**
1018          * Creates a new reply.
1019          *
1020          * @param sone
1021          *            The Sone that creates the reply
1022          * @param post
1023          *            The post that this reply refers to
1024          * @param text
1025          *            The text of the reply
1026          * @return The created reply
1027          */
1028         public Reply createReply(Sone sone, Post post, String text) {
1029                 return createReply(sone, post, System.currentTimeMillis(), text);
1030         }
1031
1032         /**
1033          * Creates a new reply.
1034          *
1035          * @param sone
1036          *            The Sone that creates the reply
1037          * @param post
1038          *            The post that this reply refers to
1039          * @param time
1040          *            The time of the reply
1041          * @param text
1042          *            The text of the reply
1043          * @return The created reply
1044          */
1045         public Reply createReply(Sone sone, Post post, long time, String text) {
1046                 if (!isLocalSone(sone)) {
1047                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1048                         return null;
1049                 }
1050                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1051                 synchronized (replies) {
1052                         replies.put(reply.getId(), reply);
1053                 }
1054                 synchronized (newReplies) {
1055                         knownReplies.add(reply.getId());
1056                 }
1057                 sone.addReply(reply);
1058                 saveSone(sone);
1059                 return reply;
1060         }
1061
1062         /**
1063          * Deletes the given reply.
1064          *
1065          * @param reply
1066          *            The reply to delete
1067          */
1068         public void deleteReply(Reply reply) {
1069                 Sone sone = reply.getSone();
1070                 if (!isLocalSone(sone)) {
1071                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1072                         return;
1073                 }
1074                 synchronized (replies) {
1075                         replies.remove(reply.getId());
1076                 }
1077                 sone.removeReply(reply);
1078                 saveSone(sone);
1079         }
1080
1081         /**
1082          * Starts the core.
1083          */
1084         public void start() {
1085                 loadConfiguration();
1086         }
1087
1088         /**
1089          * Stops the core.
1090          */
1091         public void stop() {
1092                 synchronized (localSones) {
1093                         for (SoneInserter soneInserter : soneInserters.values()) {
1094                                 soneInserter.stop();
1095                         }
1096                 }
1097                 saveConfiguration();
1098         }
1099
1100         //
1101         // PRIVATE METHODS
1102         //
1103
1104         /**
1105          * Loads the configuration.
1106          */
1107         @SuppressWarnings("unchecked")
1108         private void loadConfiguration() {
1109                 /* create options. */
1110                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1111
1112                         @Override
1113                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1114                                 SoneInserter.setInsertionDelay(newValue);
1115                         }
1116
1117                 }));
1118                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1119                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1120
1121                 /* read options from configuration. */
1122                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1123                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1124                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1125                 options.getBooleanOption("ClearOnNextRestart").set(null);
1126                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1127                 if (clearConfiguration) {
1128                         /* stop loading the configuration. */
1129                         return;
1130                 }
1131
1132                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1133
1134                 /* load known Sones. */
1135                 int soneCounter = 0;
1136                 while (true) {
1137                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1138                         if (knownSoneId == null) {
1139                                 break;
1140                         }
1141                         synchronized (newSones) {
1142                                 knownSones.add(knownSoneId);
1143                         }
1144                 }
1145
1146                 /* load known posts. */
1147                 int postCounter = 0;
1148                 while (true) {
1149                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1150                         if (knownPostId == null) {
1151                                 break;
1152                         }
1153                         synchronized (newPosts) {
1154                                 knownPosts.add(knownPostId);
1155                         }
1156                 }
1157
1158                 /* load known replies. */
1159                 int replyCounter = 0;
1160                 while (true) {
1161                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1162                         if (knownReplyId == null) {
1163                                 break;
1164                         }
1165                         synchronized (newReplies) {
1166                                 knownReplies.add(knownReplyId);
1167                         }
1168                 }
1169
1170         }
1171
1172         /**
1173          * Saves the current options.
1174          */
1175         private void saveConfiguration() {
1176                 /* store the options first. */
1177                 try {
1178                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1179                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1180                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1181
1182                         /* save known Sones. */
1183                         int soneCounter = 0;
1184                         synchronized (newSones) {
1185                                 for (String knownSoneId : knownSones) {
1186                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1187                                 }
1188                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1189                         }
1190
1191                         /* save known posts. */
1192                         int postCounter = 0;
1193                         synchronized (newPosts) {
1194                                 for (String knownPostId : knownPosts) {
1195                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1196                                 }
1197                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1198                         }
1199
1200                         /* save known replies. */
1201                         int replyCounter = 0;
1202                         synchronized (newReplies) {
1203                                 for (String knownReplyId : knownReplies) {
1204                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1205                                 }
1206                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1207                         }
1208
1209                 } catch (ConfigurationException ce1) {
1210                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1211                 }
1212         }
1213
1214         /**
1215          * Generate a Sone URI from the given URI and latest edition.
1216          *
1217          * @param uriString
1218          *            The URI to derive the Sone URI from
1219          * @return The derived URI
1220          */
1221         private FreenetURI getSoneUri(String uriString) {
1222                 try {
1223                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1224                         return uri;
1225                 } catch (MalformedURLException mue1) {
1226                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1227                         return null;
1228                 }
1229         }
1230
1231         //
1232         // INTERFACE IdentityListener
1233         //
1234
1235         /**
1236          * {@inheritDoc}
1237          */
1238         @Override
1239         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1240                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1241                 if (ownIdentity.hasContext("Sone")) {
1242                         addLocalSone(ownIdentity);
1243                 }
1244         }
1245
1246         /**
1247          * {@inheritDoc}
1248          */
1249         @Override
1250         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1251                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1252         }
1253
1254         /**
1255          * {@inheritDoc}
1256          */
1257         @Override
1258         public void identityAdded(Identity identity) {
1259                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1260                 addRemoteSone(identity);
1261         }
1262
1263         /**
1264          * {@inheritDoc}
1265          */
1266         @Override
1267         public void identityUpdated(final Identity identity) {
1268                 new Thread(new Runnable() {
1269
1270                         @Override
1271                         @SuppressWarnings("synthetic-access")
1272                         public void run() {
1273                                 Sone sone = getRemoteSone(identity.getId());
1274                                 soneDownloader.fetchSone(sone);
1275                         }
1276                 }).start();
1277         }
1278
1279         /**
1280          * {@inheritDoc}
1281          */
1282         @Override
1283         public void identityRemoved(Identity identity) {
1284                 /* TODO */
1285         }
1286
1287 }