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