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