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