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