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