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