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