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