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