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