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