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