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