20ff26cdc3467729072bc69622c78ad8cc40b343
[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.getLikedReplyIds().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                         final Sone sone;
440                         try {
441                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
442                                 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
443                         } catch (MalformedURLException mue1) {
444                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
445                                 return null;
446                         }
447                         /* TODO - load posts ’n stuff */
448                         localSones.put(ownIdentity.getId(), sone);
449                         SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
450                         soneInserters.put(sone, soneInserter);
451                         soneInserter.start();
452                         setSoneStatus(sone, SoneStatus.idle);
453                         loadSone(sone);
454                         new Thread(new Runnable() {
455
456                                 @Override
457                                 @SuppressWarnings("synthetic-access")
458                                 public void run() {
459                                         soneDownloader.fetchSone(sone);
460                                 }
461
462                         }, "Sone Downloader").start();
463                         return sone;
464                 }
465         }
466
467         /**
468          * Creates a new Sone for the given own identity.
469          *
470          * @param ownIdentity
471          *            The own identity to create a Sone for
472          * @return The created Sone
473          */
474         public Sone createSone(OwnIdentity ownIdentity) {
475                 identityManager.addContext(ownIdentity, "Sone");
476                 Sone sone = addLocalSone(ownIdentity);
477                 synchronized (sone) {
478                         /* mark as modified so that it gets inserted immediately. */
479                         sone.setModificationCounter(sone.getModificationCounter() + 1);
480                 }
481                 return sone;
482         }
483
484         /**
485          * Adds the Sone of the given identity.
486          *
487          * @param identity
488          *            The identity whose Sone to add
489          * @return The added or already existing Sone
490          */
491         public Sone addRemoteSone(Identity identity) {
492                 if (identity == null) {
493                         logger.log(Level.WARNING, "Given Identity is null!");
494                         return null;
495                 }
496                 synchronized (remoteSones) {
497                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
498                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
499                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
500                         remoteSones.put(identity.getId(), sone);
501                         soneDownloader.addSone(sone);
502                         new Thread(new Runnable() {
503
504                                 @Override
505                                 @SuppressWarnings("synthetic-access")
506                                 public void run() {
507                                         soneDownloader.fetchSone(sone);
508                                 }
509
510                         }, "Sone Downloader").start();
511                         setSoneStatus(sone, SoneStatus.idle);
512                         return sone;
513                 }
514         }
515
516         /**
517          * Updates the stores Sone with the given Sone.
518          *
519          * @param sone
520          *            The updated Sone
521          */
522         public void updateSone(Sone sone) {
523                 if (isRemoteSone(sone)) {
524                         Sone storedSone = getRemoteSone(sone.getId());
525                         if (!(sone.getTime() > storedSone.getTime())) {
526                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
527                                 return;
528                         }
529                         synchronized (posts) {
530                                 for (Post post : storedSone.getPosts()) {
531                                         posts.remove(post.getId());
532                                 }
533                                 for (Post post : sone.getPosts()) {
534                                         posts.put(post.getId(), post);
535                                 }
536                         }
537                         synchronized (replies) {
538                                 for (Reply reply : storedSone.getReplies()) {
539                                         replies.remove(reply.getId());
540                                 }
541                                 for (Reply reply : sone.getReplies()) {
542                                         replies.put(reply.getId(), reply);
543                                 }
544                         }
545                         synchronized (storedSone) {
546                                 storedSone.setTime(sone.getTime());
547                                 storedSone.setProfile(sone.getProfile());
548                                 storedSone.setPosts(sone.getPosts());
549                                 storedSone.setReplies(sone.getReplies());
550                                 storedSone.setLikePostIds(sone.getLikedPostIds());
551                                 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
552                                 storedSone.setLatestEdition(sone.getRequestUri().getEdition());
553                                 storedSone.setModificationCounter(0);
554                         }
555                         saveSone(storedSone);
556                 }
557         }
558
559         /**
560          * Deletes the given Sone. This will remove the Sone from the
561          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
562          * and remove the context from its identity.
563          *
564          * @param sone
565          *            The Sone to delete
566          */
567         public void deleteSone(Sone sone) {
568                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
569                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
570                         return;
571                 }
572                 synchronized (localSones) {
573                         if (!localSones.containsKey(sone.getId())) {
574                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
575                                 return;
576                         }
577                         localSones.remove(sone.getId());
578                         soneInserters.remove(sone).stop();
579                 }
580                 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
581                 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
582                 try {
583                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
584                 } catch (ConfigurationException ce1) {
585                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
586                 }
587         }
588
589         /**
590          * Loads and updates the given Sone from the configuration. If any error is
591          * encountered, loading is aborted and the given Sone is not changed.
592          *
593          * @param sone
594          *            The Sone to load and update
595          */
596         public void loadSone(Sone sone) {
597                 if (!isLocalSone(sone)) {
598                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
599                         return;
600                 }
601
602                 /* load Sone. */
603                 String sonePrefix = "Sone/" + sone.getId();
604                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
605                 if (soneTime == null) {
606                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
607                         return;
608                 }
609                 long soneModificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
610
611                 /* load profile. */
612                 Profile profile = new Profile();
613                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
614                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
615                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
616                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
617                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
618                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
619
620                 /* load posts. */
621                 Set<Post> posts = new HashSet<Post>();
622                 while (true) {
623                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
624                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
625                         if (postId == null) {
626                                 break;
627                         }
628                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
629                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
630                         if ((postTime == 0) || (postText == null)) {
631                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
632                                 return;
633                         }
634                         posts.add(getPost(postId).setSone(sone).setTime(postTime).setText(postText));
635                 }
636
637                 /* load replies. */
638                 Set<Reply> replies = new HashSet<Reply>();
639                 while (true) {
640                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
641                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
642                         if (replyId == null) {
643                                 break;
644                         }
645                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
646                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
647                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
648                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
649                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
650                                 return;
651                         }
652                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
653                 }
654
655                 /* load post likes. */
656                 Set<String> likedPostIds = new HashSet<String>();
657                 while (true) {
658                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
659                         if (likedPostId == null) {
660                                 break;
661                         }
662                         likedPostIds.add(likedPostId);
663                 }
664
665                 /* load reply likes. */
666                 Set<String> likedReplyIds = new HashSet<String>();
667                 while (true) {
668                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
669                         if (likedReplyId == null) {
670                                 break;
671                         }
672                         likedReplyIds.add(likedReplyId);
673                 }
674
675                 /* load friends. */
676                 Set<Sone> friends = new HashSet<Sone>();
677                 while (true) {
678                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
679                         if (friendId == null) {
680                                 break;
681                         }
682                         Boolean friendLocal = configuration.getBooleanValue(sonePrefix + "/Friends/" + friends.size() + "/Local").getValue(null);
683                         if (friendLocal == null) {
684                                 logger.log(Level.WARNING, "Invalid friend found, aborting load!");
685                                 return;
686                         }
687                         friends.add(friendLocal ? getLocalSone(friendId) : getRemoteSone(friendId));
688                 }
689
690                 /* if we’re still here, Sone was loaded successfully. */
691                 synchronized (sone) {
692                         sone.setTime(soneTime);
693                         sone.setProfile(profile);
694                         sone.setPosts(posts);
695                         sone.setReplies(replies);
696                         sone.setLikePostIds(likedPostIds);
697                         sone.setLikeReplyIds(likedReplyIds);
698                         sone.setFriends(friends);
699                         sone.setModificationCounter(soneModificationCounter);
700                 }
701         }
702
703         /**
704          * Saves the given Sone. This will persist all local settings for the given
705          * Sone, such as the friends list and similar, private options.
706          *
707          * @param sone
708          *            The Sone to save
709          */
710         public void saveSone(Sone sone) {
711                 if (!isLocalSone(sone)) {
712                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
713                         return;
714                 }
715                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
716                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
717                         return;
718                 }
719
720                 logger.log(Level.INFO, "Saving Sone: %s", sone);
721                 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
722                 try {
723                         /* save Sone into configuration. */
724                         String sonePrefix = "Sone/" + sone.getId();
725                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
726                         configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
727
728                         /* save profile. */
729                         Profile profile = sone.getProfile();
730                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
731                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
732                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
733                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
734                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
735                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
736
737                         /* save posts. */
738                         int postCounter = 0;
739                         for (Post post : sone.getPosts()) {
740                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
741                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
742                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
743                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
744                         }
745                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
746
747                         /* save replies. */
748                         int replyCounter = 0;
749                         for (Reply reply : sone.getReplies()) {
750                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
751                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
752                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
753                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
754                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
755                         }
756                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
757
758                         /* save post likes. */
759                         int postLikeCounter = 0;
760                         for (String postId : sone.getLikedPostIds()) {
761                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
762                         }
763                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
764
765                         /* save reply likes. */
766                         int replyLikeCounter = 0;
767                         for (String replyId : sone.getLikedReplyIds()) {
768                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
769                         }
770                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
771
772                         /* save friends. */
773                         int friendCounter = 0;
774                         for (Sone friend : sone.getFriends()) {
775                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(friend.getId());
776                                 configuration.getBooleanValue(sonePrefix + "/Friends/" + friendCounter++ + "/Local").setValue(friend.getInsertUri() != null);
777                         }
778                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
779
780                         logger.log(Level.INFO, "Sone %s saved.", sone);
781                 } catch (ConfigurationException ce1) {
782                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
783                 }
784         }
785
786         /**
787          * Creates a new post.
788          *
789          * @param sone
790          *            The Sone that creates the post
791          * @param text
792          *            The text of the post
793          */
794         public void createPost(Sone sone, String text) {
795                 createPost(sone, System.currentTimeMillis(), text);
796         }
797
798         /**
799          * Creates a new post.
800          *
801          * @param sone
802          *            The Sone that creates the post
803          * @param time
804          *            The time of the post
805          * @param text
806          *            The text of the post
807          */
808         public void createPost(Sone sone, long time, String text) {
809                 if (!isLocalSone(sone)) {
810                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
811                         return;
812                 }
813                 Post post = new Post(sone, time, text);
814                 synchronized (posts) {
815                         posts.put(post.getId(), post);
816                 }
817                 sone.addPost(post);
818                 saveSone(sone);
819         }
820
821         /**
822          * Deletes the given post.
823          *
824          * @param post
825          *            The post to delete
826          */
827         public void deletePost(Post post) {
828                 if (!isLocalSone(post.getSone())) {
829                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
830                         return;
831                 }
832                 post.getSone().removePost(post);
833                 synchronized (posts) {
834                         posts.remove(post.getId());
835                 }
836                 saveSone(post.getSone());
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 text
847          *            The text of the reply
848          */
849         public void createReply(Sone sone, Post post, String text) {
850                 createReply(sone, post, System.currentTimeMillis(), text);
851         }
852
853         /**
854          * Creates a new reply.
855          *
856          * @param sone
857          *            The Sone that creates the reply
858          * @param post
859          *            The post that this reply refers to
860          * @param time
861          *            The time of the reply
862          * @param text
863          *            The text of the reply
864          */
865         public void createReply(Sone sone, Post post, long time, String text) {
866                 if (!isLocalSone(sone)) {
867                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
868                         return;
869                 }
870                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
871                 synchronized (replies) {
872                         replies.put(reply.getId(), reply);
873                 }
874                 sone.addReply(reply);
875                 saveSone(sone);
876         }
877
878         /**
879          * Deletes the given reply.
880          *
881          * @param reply
882          *            The reply to delete
883          */
884         public void deleteReply(Reply reply) {
885                 Sone sone = reply.getSone();
886                 if (!isLocalSone(sone)) {
887                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
888                         return;
889                 }
890                 synchronized (replies) {
891                         replies.remove(reply.getId());
892                 }
893                 sone.removeReply(reply);
894                 saveSone(sone);
895         }
896
897         /**
898          * Starts the core.
899          */
900         public void start() {
901                 loadConfiguration();
902         }
903
904         /**
905          * Stops the core.
906          */
907         public void stop() {
908                 synchronized (localSones) {
909                         for (SoneInserter soneInserter : soneInserters.values()) {
910                                 soneInserter.stop();
911                         }
912                 }
913                 saveConfiguration();
914         }
915
916         //
917         // PRIVATE METHODS
918         //
919
920         /**
921          * Loads the configuration.
922          */
923         @SuppressWarnings("unchecked")
924         private void loadConfiguration() {
925                 /* create options. */
926                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
927
928                         @Override
929                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
930                                 SoneInserter.setInsertionDelay(newValue);
931                         }
932
933                 }));
934                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
935                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
936
937                 /* read options from configuration. */
938                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
939                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
940                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
941                 options.getBooleanOption("ClearOnNextRestart").set(null);
942                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
943                 if (clearConfiguration) {
944                         /* stop loading the configuration. */
945                         return;
946                 }
947
948                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
949
950         }
951
952         /**
953          * Saves the current options.
954          */
955         private void saveConfiguration() {
956                 /* store the options first. */
957                 try {
958                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
959                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
960                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
961                 } catch (ConfigurationException ce1) {
962                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
963                 }
964         }
965
966         /**
967          * Generate a Sone URI from the given URI and latest edition.
968          *
969          * @param uriString
970          *            The URI to derive the Sone URI from
971          * @return The derived URI
972          */
973         private FreenetURI getSoneUri(String uriString) {
974                 try {
975                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
976                         return uri;
977                 } catch (MalformedURLException mue1) {
978                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
979                         return null;
980                 }
981         }
982
983         //
984         // INTERFACE IdentityListener
985         //
986
987         /**
988          * {@inheritDoc}
989          */
990         @Override
991         public void ownIdentityAdded(OwnIdentity ownIdentity) {
992                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
993                 if (ownIdentity.hasContext("Sone")) {
994                         addLocalSone(ownIdentity);
995                 }
996         }
997
998         /**
999          * {@inheritDoc}
1000          */
1001         @Override
1002         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1003                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1004         }
1005
1006         /**
1007          * {@inheritDoc}
1008          */
1009         @Override
1010         public void identityAdded(Identity identity) {
1011                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1012                 addRemoteSone(identity);
1013         }
1014
1015         /**
1016          * {@inheritDoc}
1017          */
1018         @Override
1019         public void identityUpdated(final Identity identity) {
1020                 new Thread(new Runnable() {
1021
1022                         @Override
1023                         @SuppressWarnings("synthetic-access")
1024                         public void run() {
1025                                 Sone sone = getRemoteSone(identity.getId());
1026                                 soneDownloader.fetchSone(sone);
1027                         }
1028                 }).start();
1029         }
1030
1031         /**
1032          * {@inheritDoc}
1033          */
1034         @Override
1035         public void identityRemoved(Identity identity) {
1036                 /* TODO */
1037         }
1038
1039 }