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