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