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