99a119bf77dd36f82f131d652920f0bace80cd4d
[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.
498          *
499          * @param soneId
500          *            The ID of the sone to check for
501          * @return {@code true} if the given Sone is new, false otherwise
502          */
503         public boolean isNewSone(String soneId) {
504                 synchronized (newSones) {
505                         return !knownSones.contains(soneId) && newSones.contains(soneId);
506                 }
507         }
508
509         /**
510          * Returns whether the given Sone has been modified.
511          *
512          * @param sone
513          *            The Sone to check for modifications
514          * @return {@code true} if a modification has been detected in the Sone,
515          *         {@code false} otherwise
516          */
517         public boolean isModifiedSone(Sone sone) {
518                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
519         }
520
521         /**
522          * Returns whether the target Sone is trusted by the origin Sone.
523          *
524          * @param origin
525          *            The origin Sone
526          * @param target
527          *            The target Sone
528          * @return {@code true} if the target Sone is trusted by the origin Sone
529          */
530         public boolean isSoneTrusted(Sone origin, Sone target) {
531                 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
532         }
533
534         /**
535          * Returns the post with the given ID.
536          *
537          * @param postId
538          *            The ID of the post to get
539          * @return The post, or {@code null} if there is no such post
540          */
541         public Post getPost(String postId) {
542                 return getPost(postId, true);
543         }
544
545         /**
546          * Returns the post with the given ID, optionally creating a new post.
547          *
548          * @param postId
549          *            The ID of the post to get
550          * @param create
551          *            {@code true} it create a new post if no post with the given ID
552          *            exists, {@code false} to return {@code null}
553          * @return The post, or {@code null} if there is no such post
554          */
555         public Post getPost(String postId, boolean create) {
556                 synchronized (posts) {
557                         Post post = posts.get(postId);
558                         if ((post == null) && create) {
559                                 post = new Post(postId);
560                                 posts.put(postId, post);
561                         }
562                         return post;
563                 }
564         }
565
566         /**
567          * Returns whether the given post ID is new.
568          *
569          * @param postId
570          *            The post ID
571          * @return {@code true} if the post is considered to be new, {@code false}
572          *         otherwise
573          */
574         public boolean isNewPost(String postId) {
575                 synchronized (newPosts) {
576                         return !knownPosts.contains(postId) && newPosts.contains(postId);
577                 }
578         }
579
580         /**
581          * Returns the reply with the given ID. If there is no reply with the given
582          * ID yet, a new one is created.
583          *
584          * @param replyId
585          *            The ID of the reply to get
586          * @return The reply
587          */
588         public Reply getReply(String replyId) {
589                 return getReply(replyId, true);
590         }
591
592         /**
593          * Returns the reply with the given ID. If there is no reply with the given
594          * ID yet, a new one is created, unless {@code create} is false in which
595          * case {@code null} is returned.
596          *
597          * @param replyId
598          *            The ID of the reply to get
599          * @param create
600          *            {@code true} to always return a {@link Reply}, {@code false}
601          *            to return {@code null} if no reply can be found
602          * @return The reply, or {@code null} if there is no such reply
603          */
604         public Reply getReply(String replyId, boolean create) {
605                 synchronized (replies) {
606                         Reply reply = replies.get(replyId);
607                         if (create && (reply == null)) {
608                                 reply = new Reply(replyId);
609                                 replies.put(replyId, reply);
610                         }
611                         return reply;
612                 }
613         }
614
615         /**
616          * Returns all replies for the given post, order ascending by time.
617          *
618          * @param post
619          *            The post to get all replies for
620          * @return All replies for the given post
621          */
622         public List<Reply> getReplies(Post post) {
623                 Set<Sone> sones = getSones();
624                 List<Reply> replies = new ArrayList<Reply>();
625                 for (Sone sone : sones) {
626                         for (Reply reply : sone.getReplies()) {
627                                 if (reply.getPost().equals(post)) {
628                                         replies.add(reply);
629                                 }
630                         }
631                 }
632                 Collections.sort(replies, Reply.TIME_COMPARATOR);
633                 return replies;
634         }
635
636         /**
637          * Returns whether the reply with the given ID is new.
638          *
639          * @param replyId
640          *            The ID of the reply to check
641          * @return {@code true} if the reply is considered to be new, {@code false}
642          *         otherwise
643          */
644         public boolean isNewReply(String replyId) {
645                 synchronized (newReplies) {
646                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
647                 }
648         }
649
650         /**
651          * Returns all Sones that have liked the given post.
652          *
653          * @param post
654          *            The post to get the liking Sones for
655          * @return The Sones that like the given post
656          */
657         public Set<Sone> getLikes(Post post) {
658                 Set<Sone> sones = new HashSet<Sone>();
659                 for (Sone sone : getSones()) {
660                         if (sone.getLikedPostIds().contains(post.getId())) {
661                                 sones.add(sone);
662                         }
663                 }
664                 return sones;
665         }
666
667         /**
668          * Returns all Sones that have liked the given reply.
669          *
670          * @param reply
671          *            The reply to get the liking Sones for
672          * @return The Sones that like the given reply
673          */
674         public Set<Sone> getLikes(Reply reply) {
675                 Set<Sone> sones = new HashSet<Sone>();
676                 for (Sone sone : getSones()) {
677                         if (sone.getLikedReplyIds().contains(reply.getId())) {
678                                 sones.add(sone);
679                         }
680                 }
681                 return sones;
682         }
683
684         //
685         // ACTIONS
686         //
687
688         /**
689          * Locks the given Sone. A locked Sone will not be inserted by
690          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
691          * again.
692          *
693          * @param sone
694          *            The sone to lock
695          */
696         public void lockSone(Sone sone) {
697                 synchronized (lockedSones) {
698                         if (lockedSones.add(sone)) {
699                                 coreListenerManager.fireSoneLocked(sone);
700                         }
701                 }
702         }
703
704         /**
705          * Unlocks the given Sone.
706          *
707          * @see #lockSone(Sone)
708          * @param sone
709          *            The sone to unlock
710          */
711         public void unlockSone(Sone sone) {
712                 synchronized (lockedSones) {
713                         if (lockedSones.remove(sone)) {
714                                 coreListenerManager.fireSoneUnlocked(sone);
715                         }
716                 }
717         }
718
719         /**
720          * Adds a local Sone from the given ID which has to be the ID of an own
721          * identity.
722          *
723          * @param id
724          *            The ID of an own identity to add a Sone for
725          * @return The added (or already existing) Sone
726          */
727         public Sone addLocalSone(String id) {
728                 synchronized (localSones) {
729                         if (localSones.containsKey(id)) {
730                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
731                                 return localSones.get(id);
732                         }
733                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
734                         if (ownIdentity == null) {
735                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
736                                 return null;
737                         }
738                         return addLocalSone(ownIdentity);
739                 }
740         }
741
742         /**
743          * Adds a local Sone from the given own identity.
744          *
745          * @param ownIdentity
746          *            The own identity to create a Sone from
747          * @return The added (or already existing) Sone
748          */
749         public Sone addLocalSone(OwnIdentity ownIdentity) {
750                 if (ownIdentity == null) {
751                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
752                         return null;
753                 }
754                 synchronized (localSones) {
755                         final Sone sone;
756                         try {
757                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
758                         } catch (MalformedURLException mue1) {
759                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
760                                 return null;
761                         }
762                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
763                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
764                         /* TODO - load posts ’n stuff */
765                         localSones.put(ownIdentity.getId(), sone);
766                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
767                         soneInserters.put(sone, soneInserter);
768                         setSoneStatus(sone, SoneStatus.idle);
769                         loadSone(sone);
770                         if (!isSoneRescueMode()) {
771                                 soneInserter.start();
772                         }
773                         new Thread(new Runnable() {
774
775                                 @Override
776                                 @SuppressWarnings("synthetic-access")
777                                 public void run() {
778                                         if (!isSoneRescueMode()) {
779                                                 soneDownloader.fetchSone(sone);
780                                                 return;
781                                         }
782                                         logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
783                                         coreListenerManager.fireRescuingSone(sone);
784                                         lockSone(sone);
785                                         long edition = sone.getLatestEdition();
786                                         while (!stopped && (edition >= 0) && isSoneRescueMode()) {
787                                                 logger.log(Level.FINE, "Downloading edition " + edition + "…");
788                                                 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
789                                                 --edition;
790                                         }
791                                         logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
792                                         saveSone(sone);
793                                         coreListenerManager.fireRescuedSone(sone);
794                                         soneInserter.start();
795                                 }
796
797                         }, "Sone Downloader").start();
798                         return sone;
799                 }
800         }
801
802         /**
803          * Creates a new Sone for the given own identity.
804          *
805          * @param ownIdentity
806          *            The own identity to create a Sone for
807          * @return The created Sone
808          */
809         public Sone createSone(OwnIdentity ownIdentity) {
810                 try {
811                         ownIdentity.addContext("Sone");
812                 } catch (WebOfTrustException wote1) {
813                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
814                         return null;
815                 }
816                 Sone sone = addLocalSone(ownIdentity);
817                 return sone;
818         }
819
820         /**
821          * Adds the Sone of the given identity.
822          *
823          * @param identity
824          *            The identity whose Sone to add
825          * @return The added or already existing Sone
826          */
827         public Sone addRemoteSone(Identity identity) {
828                 if (identity == null) {
829                         logger.log(Level.WARNING, "Given Identity is null!");
830                         return null;
831                 }
832                 synchronized (remoteSones) {
833                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
834                         boolean newSone = sone.getRequestUri() == null;
835                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
836                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
837                         if (newSone) {
838                                 synchronized (newSones) {
839                                         newSone = !knownSones.contains(sone.getId());
840                                         if (newSone) {
841                                                 newSones.add(sone.getId());
842                                         }
843                                 }
844                                 if (newSone) {
845                                         coreListenerManager.fireNewSoneFound(sone);
846                                 }
847                         }
848                         remoteSones.put(identity.getId(), sone);
849                         soneDownloader.addSone(sone);
850                         setSoneStatus(sone, SoneStatus.unknown);
851                         new Thread(new Runnable() {
852
853                                 @Override
854                                 @SuppressWarnings("synthetic-access")
855                                 public void run() {
856                                         soneDownloader.fetchSone(sone);
857                                 }
858
859                         }, "Sone Downloader").start();
860                         return sone;
861                 }
862         }
863
864         /**
865          * Retrieves the trust relationship from the origin to the target. If the
866          * trust relationship can not be retrieved, {@code null} is returned.
867          *
868          * @see Identity#getTrust(OwnIdentity)
869          * @param origin
870          *            The origin of the trust tree
871          * @param target
872          *            The target of the trust
873          * @return The trust relationship
874          */
875         public Trust getTrust(Sone origin, Sone target) {
876                 if (!isLocalSone(origin)) {
877                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
878                         return null;
879                 }
880                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
881         }
882
883         /**
884          * Sets the trust value of the given origin Sone for the target Sone.
885          *
886          * @param origin
887          *            The origin Sone
888          * @param target
889          *            The target Sone
890          * @param trustValue
891          *            The trust value (from {@code -100} to {@code 100})
892          */
893         public void setTrust(Sone origin, Sone target, int trustValue) {
894                 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();
895                 try {
896                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, options.getStringOption("TrustComment").get());
897                 } catch (WebOfTrustException wote1) {
898                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
899                 }
900         }
901
902         /**
903          * Removes any trust assignment for the given target Sone.
904          *
905          * @param origin
906          *            The trust origin
907          * @param target
908          *            The trust target
909          */
910         public void removeTrust(Sone origin, Sone target) {
911                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
912                 try {
913                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
914                 } catch (WebOfTrustException wote1) {
915                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
916                 }
917         }
918
919         /**
920          * Assigns the configured positive trust value for the given target.
921          *
922          * @param origin
923          *            The trust origin
924          * @param target
925          *            The trust target
926          */
927         public void trustSone(Sone origin, Sone target) {
928                 setTrust(origin, target, options.getIntegerOption("PositiveTrust").get());
929         }
930
931         /**
932          * Assigns the configured negative trust value for the given target.
933          *
934          * @param origin
935          *            The trust origin
936          * @param target
937          *            The trust target
938          */
939         public void distrustSone(Sone origin, Sone target) {
940                 setTrust(origin, target, options.getIntegerOption("NegativeTrust").get());
941         }
942
943         /**
944          * Removes the trust assignment for the given target.
945          *
946          * @param origin
947          *            The trust origin
948          * @param target
949          *            The trust target
950          */
951         public void untrustSone(Sone origin, Sone target) {
952                 removeTrust(origin, target);
953         }
954
955         /**
956          * Updates the stores Sone with the given Sone.
957          *
958          * @param sone
959          *            The updated Sone
960          */
961         public void updateSone(Sone sone) {
962                 if (hasSone(sone.getId())) {
963                         boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
964                         Sone storedSone = getSone(sone.getId());
965                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
966                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
967                                 return;
968                         }
969                         synchronized (posts) {
970                                 if (!soneRescueMode) {
971                                         for (Post post : storedSone.getPosts()) {
972                                                 posts.remove(post.getId());
973                                                 if (!sone.getPosts().contains(post)) {
974                                                         coreListenerManager.firePostRemoved(post);
975                                                 }
976                                         }
977                                 }
978                                 List<Post> storedPosts = storedSone.getPosts();
979                                 synchronized (newPosts) {
980                                         for (Post post : sone.getPosts()) {
981                                                 post.setSone(storedSone);
982                                                 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
983                                                         newPosts.add(post.getId());
984                                                         coreListenerManager.fireNewPostFound(post);
985                                                 }
986                                                 posts.put(post.getId(), post);
987                                         }
988                                 }
989                         }
990                         synchronized (replies) {
991                                 if (!soneRescueMode) {
992                                         for (Reply reply : storedSone.getReplies()) {
993                                                 replies.remove(reply.getId());
994                                                 if (!sone.getReplies().contains(reply)) {
995                                                         coreListenerManager.fireReplyRemoved(reply);
996                                                 }
997                                         }
998                                 }
999                                 Set<Reply> storedReplies = storedSone.getReplies();
1000                                 synchronized (newReplies) {
1001                                         for (Reply reply : sone.getReplies()) {
1002                                                 reply.setSone(storedSone);
1003                                                 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1004                                                         newReplies.add(reply.getId());
1005                                                         coreListenerManager.fireNewReplyFound(reply);
1006                                                 }
1007                                                 replies.put(reply.getId(), reply);
1008                                         }
1009                                 }
1010                         }
1011                         synchronized (storedSone) {
1012                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1013                                         storedSone.setTime(sone.getTime());
1014                                 }
1015                                 storedSone.setClient(sone.getClient());
1016                                 storedSone.setProfile(sone.getProfile());
1017                                 if (soneRescueMode) {
1018                                         for (Post post : sone.getPosts()) {
1019                                                 storedSone.addPost(post);
1020                                         }
1021                                         for (Reply reply : sone.getReplies()) {
1022                                                 storedSone.addReply(reply);
1023                                         }
1024                                         for (String likedPostId : sone.getLikedPostIds()) {
1025                                                 storedSone.addLikedPostId(likedPostId);
1026                                         }
1027                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1028                                                 storedSone.addLikedReplyId(likedReplyId);
1029                                         }
1030                                 } else {
1031                                         storedSone.setPosts(sone.getPosts());
1032                                         storedSone.setReplies(sone.getReplies());
1033                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1034                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1035                                 }
1036                                 storedSone.setLatestEdition(sone.getLatestEdition());
1037                         }
1038                 }
1039         }
1040
1041         /**
1042          * Deletes the given Sone. This will remove the Sone from the
1043          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1044          * and remove the context from its identity.
1045          *
1046          * @param sone
1047          *            The Sone to delete
1048          */
1049         public void deleteSone(Sone sone) {
1050                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1051                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1052                         return;
1053                 }
1054                 synchronized (localSones) {
1055                         if (!localSones.containsKey(sone.getId())) {
1056                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1057                                 return;
1058                         }
1059                         localSones.remove(sone.getId());
1060                         soneInserters.remove(sone).stop();
1061                 }
1062                 try {
1063                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1064                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1065                 } catch (WebOfTrustException wote1) {
1066                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1067                 }
1068                 try {
1069                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1070                 } catch (ConfigurationException ce1) {
1071                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1072                 }
1073         }
1074
1075         /**
1076          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1077          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1078          *
1079          * @param sone
1080          *            The Sone to mark as known
1081          */
1082         public void markSoneKnown(Sone sone) {
1083                 synchronized (newSones) {
1084                         if (newSones.remove(sone.getId())) {
1085                                 knownSones.add(sone.getId());
1086                                 coreListenerManager.fireMarkSoneKnown(sone);
1087                                 saveConfiguration();
1088                         }
1089                 }
1090         }
1091
1092         /**
1093          * Loads and updates the given Sone from the configuration. If any error is
1094          * encountered, loading is aborted and the given Sone is not changed.
1095          *
1096          * @param sone
1097          *            The Sone to load and update
1098          */
1099         public void loadSone(Sone sone) {
1100                 if (!isLocalSone(sone)) {
1101                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1102                         return;
1103                 }
1104
1105                 /* load Sone. */
1106                 String sonePrefix = "Sone/" + sone.getId();
1107                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1108                 if (soneTime == null) {
1109                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1110                         return;
1111                 }
1112                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1113
1114                 /* load profile. */
1115                 Profile profile = new Profile();
1116                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1117                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1118                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1119                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1120                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1121                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1122
1123                 /* load profile fields. */
1124                 while (true) {
1125                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1126                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1127                         if (fieldName == null) {
1128                                 break;
1129                         }
1130                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1131                         profile.addField(fieldName).setValue(fieldValue);
1132                 }
1133
1134                 /* load posts. */
1135                 Set<Post> posts = new HashSet<Post>();
1136                 while (true) {
1137                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1138                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1139                         if (postId == null) {
1140                                 break;
1141                         }
1142                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1143                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1144                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1145                         if ((postTime == 0) || (postText == null)) {
1146                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1147                                 return;
1148                         }
1149                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1150                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1151                                 post.setRecipient(getSone(postRecipientId));
1152                         }
1153                         posts.add(post);
1154                 }
1155
1156                 /* load replies. */
1157                 Set<Reply> replies = new HashSet<Reply>();
1158                 while (true) {
1159                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1160                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1161                         if (replyId == null) {
1162                                 break;
1163                         }
1164                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1165                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1166                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1167                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1168                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1169                                 return;
1170                         }
1171                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1172                 }
1173
1174                 /* load post likes. */
1175                 Set<String> likedPostIds = new HashSet<String>();
1176                 while (true) {
1177                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1178                         if (likedPostId == null) {
1179                                 break;
1180                         }
1181                         likedPostIds.add(likedPostId);
1182                 }
1183
1184                 /* load reply likes. */
1185                 Set<String> likedReplyIds = new HashSet<String>();
1186                 while (true) {
1187                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1188                         if (likedReplyId == null) {
1189                                 break;
1190                         }
1191                         likedReplyIds.add(likedReplyId);
1192                 }
1193
1194                 /* load friends. */
1195                 Set<String> friends = new HashSet<String>();
1196                 while (true) {
1197                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1198                         if (friendId == null) {
1199                                 break;
1200                         }
1201                         friends.add(friendId);
1202                 }
1203
1204                 /* if we’re still here, Sone was loaded successfully. */
1205                 synchronized (sone) {
1206                         sone.setTime(soneTime);
1207                         sone.setProfile(profile);
1208                         sone.setPosts(posts);
1209                         sone.setReplies(replies);
1210                         sone.setLikePostIds(likedPostIds);
1211                         sone.setLikeReplyIds(likedReplyIds);
1212                         sone.setFriends(friends);
1213                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1214                 }
1215                 synchronized (newSones) {
1216                         for (String friend : friends) {
1217                                 knownSones.add(friend);
1218                         }
1219                 }
1220                 synchronized (newPosts) {
1221                         for (Post post : posts) {
1222                                 knownPosts.add(post.getId());
1223                         }
1224                 }
1225                 synchronized (newReplies) {
1226                         for (Reply reply : replies) {
1227                                 knownReplies.add(reply.getId());
1228                         }
1229                 }
1230         }
1231
1232         /**
1233          * Saves the given Sone. This will persist all local settings for the given
1234          * Sone, such as the friends list and similar, private options.
1235          *
1236          * @param sone
1237          *            The Sone to save
1238          */
1239         public synchronized void saveSone(Sone sone) {
1240                 if (!isLocalSone(sone)) {
1241                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1242                         return;
1243                 }
1244                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1245                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1246                         return;
1247                 }
1248
1249                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1250                 try {
1251                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1252
1253                         /* save Sone into configuration. */
1254                         String sonePrefix = "Sone/" + sone.getId();
1255                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1256                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1257
1258                         /* save profile. */
1259                         Profile profile = sone.getProfile();
1260                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1261                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1262                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1263                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1264                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1265                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1266
1267                         /* save profile fields. */
1268                         int fieldCounter = 0;
1269                         for (Field profileField : profile.getFields()) {
1270                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1271                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1272                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1273                         }
1274                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1275
1276                         /* save posts. */
1277                         int postCounter = 0;
1278                         for (Post post : sone.getPosts()) {
1279                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1280                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1281                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1282                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1283                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1284                         }
1285                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1286
1287                         /* save replies. */
1288                         int replyCounter = 0;
1289                         for (Reply reply : sone.getReplies()) {
1290                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1291                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1292                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1293                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1294                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1295                         }
1296                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1297
1298                         /* save post likes. */
1299                         int postLikeCounter = 0;
1300                         for (String postId : sone.getLikedPostIds()) {
1301                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1302                         }
1303                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1304
1305                         /* save reply likes. */
1306                         int replyLikeCounter = 0;
1307                         for (String replyId : sone.getLikedReplyIds()) {
1308                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1309                         }
1310                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1311
1312                         /* save friends. */
1313                         int friendCounter = 0;
1314                         for (String friendId : sone.getFriends()) {
1315                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1316                         }
1317                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1318
1319                         configuration.save();
1320                         logger.log(Level.INFO, "Sone %s saved.", sone);
1321                 } catch (ConfigurationException ce1) {
1322                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1323                 } catch (WebOfTrustException wote1) {
1324                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1325                 }
1326         }
1327
1328         /**
1329          * Creates a new post.
1330          *
1331          * @param sone
1332          *            The Sone that creates the post
1333          * @param text
1334          *            The text of the post
1335          * @return The created post
1336          */
1337         public Post createPost(Sone sone, String text) {
1338                 return createPost(sone, System.currentTimeMillis(), text);
1339         }
1340
1341         /**
1342          * Creates a new post.
1343          *
1344          * @param sone
1345          *            The Sone that creates the post
1346          * @param time
1347          *            The time of the post
1348          * @param text
1349          *            The text of the post
1350          * @return The created post
1351          */
1352         public Post createPost(Sone sone, long time, String text) {
1353                 return createPost(sone, null, time, text);
1354         }
1355
1356         /**
1357          * Creates a new post.
1358          *
1359          * @param sone
1360          *            The Sone that creates the post
1361          * @param recipient
1362          *            The recipient Sone, or {@code null} if this post does not have
1363          *            a recipient
1364          * @param text
1365          *            The text of the post
1366          * @return The created post
1367          */
1368         public Post createPost(Sone sone, Sone recipient, String text) {
1369                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1370         }
1371
1372         /**
1373          * Creates a new post.
1374          *
1375          * @param sone
1376          *            The Sone that creates the post
1377          * @param recipient
1378          *            The recipient Sone, or {@code null} if this post does not have
1379          *            a recipient
1380          * @param time
1381          *            The time of the post
1382          * @param text
1383          *            The text of the post
1384          * @return The created post
1385          */
1386         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1387                 if (!isLocalSone(sone)) {
1388                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1389                         return null;
1390                 }
1391                 Post post = new Post(sone, time, text);
1392                 if (recipient != null) {
1393                         post.setRecipient(recipient);
1394                 }
1395                 synchronized (posts) {
1396                         posts.put(post.getId(), post);
1397                 }
1398                 synchronized (newPosts) {
1399                         knownPosts.add(post.getId());
1400                 }
1401                 sone.addPost(post);
1402                 saveSone(sone);
1403                 return post;
1404         }
1405
1406         /**
1407          * Deletes the given post.
1408          *
1409          * @param post
1410          *            The post to delete
1411          */
1412         public void deletePost(Post post) {
1413                 if (!isLocalSone(post.getSone())) {
1414                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1415                         return;
1416                 }
1417                 post.getSone().removePost(post);
1418                 synchronized (posts) {
1419                         posts.remove(post.getId());
1420                 }
1421                 saveSone(post.getSone());
1422         }
1423
1424         /**
1425          * Marks the given post as known, if it is currently a new post (according
1426          * to {@link #isNewPost(String)}).
1427          *
1428          * @param post
1429          *            The post to mark as known
1430          */
1431         public void markPostKnown(Post post) {
1432                 synchronized (newPosts) {
1433                         if (newPosts.remove(post.getId())) {
1434                                 knownPosts.add(post.getId());
1435                                 coreListenerManager.fireMarkPostKnown(post);
1436                                 saveConfiguration();
1437                         }
1438                 }
1439         }
1440
1441         /**
1442          * Creates a new reply.
1443          *
1444          * @param sone
1445          *            The Sone that creates the reply
1446          * @param post
1447          *            The post that this reply refers to
1448          * @param text
1449          *            The text of the reply
1450          * @return The created reply
1451          */
1452         public Reply createReply(Sone sone, Post post, String text) {
1453                 return createReply(sone, post, System.currentTimeMillis(), text);
1454         }
1455
1456         /**
1457          * Creates a new reply.
1458          *
1459          * @param sone
1460          *            The Sone that creates the reply
1461          * @param post
1462          *            The post that this reply refers to
1463          * @param time
1464          *            The time of the reply
1465          * @param text
1466          *            The text of the reply
1467          * @return The created reply
1468          */
1469         public Reply createReply(Sone sone, Post post, long time, String text) {
1470                 if (!isLocalSone(sone)) {
1471                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1472                         return null;
1473                 }
1474                 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1475                 synchronized (replies) {
1476                         replies.put(reply.getId(), reply);
1477                 }
1478                 synchronized (newReplies) {
1479                         knownReplies.add(reply.getId());
1480                 }
1481                 sone.addReply(reply);
1482                 saveSone(sone);
1483                 return reply;
1484         }
1485
1486         /**
1487          * Deletes the given reply.
1488          *
1489          * @param reply
1490          *            The reply to delete
1491          */
1492         public void deleteReply(Reply reply) {
1493                 Sone sone = reply.getSone();
1494                 if (!isLocalSone(sone)) {
1495                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1496                         return;
1497                 }
1498                 synchronized (replies) {
1499                         replies.remove(reply.getId());
1500                 }
1501                 sone.removeReply(reply);
1502                 saveSone(sone);
1503         }
1504
1505         /**
1506          * Marks the given reply as known, if it is currently a new reply (according
1507          * to {@link #isNewReply(String)}).
1508          *
1509          * @param reply
1510          *            The reply to mark as known
1511          */
1512         public void markReplyKnown(Reply reply) {
1513                 synchronized (newReplies) {
1514                         if (newReplies.remove(reply.getId())) {
1515                                 knownReplies.add(reply.getId());
1516                                 coreListenerManager.fireMarkReplyKnown(reply);
1517                                 saveConfiguration();
1518                         }
1519                 }
1520         }
1521
1522         /**
1523          * Starts the core.
1524          */
1525         public void start() {
1526                 loadConfiguration();
1527                 updateChecker.addUpdateListener(this);
1528                 updateChecker.start();
1529         }
1530
1531         /**
1532          * Stops the core.
1533          */
1534         public void stop() {
1535                 synchronized (localSones) {
1536                         for (SoneInserter soneInserter : soneInserters.values()) {
1537                                 soneInserter.stop();
1538                         }
1539                 }
1540                 updateChecker.stop();
1541                 updateChecker.removeUpdateListener(this);
1542                 soneDownloader.stop();
1543                 saveConfiguration();
1544                 stopped = true;
1545         }
1546
1547         /**
1548          * Saves the current options.
1549          */
1550         public void saveConfiguration() {
1551                 synchronized (configuration) {
1552                         if (storingConfiguration) {
1553                                 logger.log(Level.FINE, "Already storing configuration…");
1554                                 return;
1555                         }
1556                         storingConfiguration = true;
1557                 }
1558
1559                 /* store the options first. */
1560                 try {
1561                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1562                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1563                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1564                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1565                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1566                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1567                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1568                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1569
1570                         /* save known Sones. */
1571                         int soneCounter = 0;
1572                         synchronized (newSones) {
1573                                 for (String knownSoneId : knownSones) {
1574                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1575                                 }
1576                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1577                         }
1578
1579                         /* save known posts. */
1580                         int postCounter = 0;
1581                         synchronized (newPosts) {
1582                                 for (String knownPostId : knownPosts) {
1583                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1584                                 }
1585                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1586                         }
1587
1588                         /* save known replies. */
1589                         int replyCounter = 0;
1590                         synchronized (newReplies) {
1591                                 for (String knownReplyId : knownReplies) {
1592                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1593                                 }
1594                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1595                         }
1596
1597                         /* now save it. */
1598                         configuration.save();
1599
1600                 } catch (ConfigurationException ce1) {
1601                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1602                 } finally {
1603                         synchronized (configuration) {
1604                                 storingConfiguration = false;
1605                         }
1606                 }
1607         }
1608
1609         //
1610         // PRIVATE METHODS
1611         //
1612
1613         /**
1614          * Loads the configuration.
1615          */
1616         @SuppressWarnings("unchecked")
1617         private void loadConfiguration() {
1618                 /* create options. */
1619                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1620
1621                         @Override
1622                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1623                                 SoneInserter.setInsertionDelay(newValue);
1624                         }
1625
1626                 }));
1627                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
1628                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
1629                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1630                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1631                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1632                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1633
1634                 /* read options from configuration. */
1635                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1636                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1637                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1638                 options.getBooleanOption("ClearOnNextRestart").set(null);
1639                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1640                 if (clearConfiguration) {
1641                         /* stop loading the configuration. */
1642                         return;
1643                 }
1644
1645                 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1646                 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
1647                 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
1648                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1649                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1650
1651                 /* load known Sones. */
1652                 int soneCounter = 0;
1653                 while (true) {
1654                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1655                         if (knownSoneId == null) {
1656                                 break;
1657                         }
1658                         synchronized (newSones) {
1659                                 knownSones.add(knownSoneId);
1660                         }
1661                 }
1662
1663                 /* load known posts. */
1664                 int postCounter = 0;
1665                 while (true) {
1666                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1667                         if (knownPostId == null) {
1668                                 break;
1669                         }
1670                         synchronized (newPosts) {
1671                                 knownPosts.add(knownPostId);
1672                         }
1673                 }
1674
1675                 /* load known replies. */
1676                 int replyCounter = 0;
1677                 while (true) {
1678                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1679                         if (knownReplyId == null) {
1680                                 break;
1681                         }
1682                         synchronized (newReplies) {
1683                                 knownReplies.add(knownReplyId);
1684                         }
1685                 }
1686
1687         }
1688
1689         /**
1690          * Generate a Sone URI from the given URI and latest edition.
1691          *
1692          * @param uriString
1693          *            The URI to derive the Sone URI from
1694          * @return The derived URI
1695          */
1696         private FreenetURI getSoneUri(String uriString) {
1697                 try {
1698                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1699                         return uri;
1700                 } catch (MalformedURLException mue1) {
1701                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1702                         return null;
1703                 }
1704         }
1705
1706         //
1707         // INTERFACE IdentityListener
1708         //
1709
1710         /**
1711          * {@inheritDoc}
1712          */
1713         @Override
1714         public void ownIdentityAdded(OwnIdentity ownIdentity) {
1715                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1716                 if (ownIdentity.hasContext("Sone")) {
1717                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
1718                         addLocalSone(ownIdentity);
1719                 }
1720         }
1721
1722         /**
1723          * {@inheritDoc}
1724          */
1725         @Override
1726         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1727                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1728                 trustedIdentities.remove(ownIdentity);
1729         }
1730
1731         /**
1732          * {@inheritDoc}
1733          */
1734         @Override
1735         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
1736                 logger.log(Level.FINEST, "Adding Identity: " + identity);
1737                 trustedIdentities.get(ownIdentity).add(identity);
1738                 addRemoteSone(identity);
1739         }
1740
1741         /**
1742          * {@inheritDoc}
1743          */
1744         @Override
1745         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
1746                 new Thread(new Runnable() {
1747
1748                         @Override
1749                         @SuppressWarnings("synthetic-access")
1750                         public void run() {
1751                                 Sone sone = getRemoteSone(identity.getId());
1752                                 sone.setIdentity(identity);
1753                                 soneDownloader.fetchSone(sone);
1754                         }
1755                 }).start();
1756         }
1757
1758         /**
1759          * {@inheritDoc}
1760          */
1761         @Override
1762         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
1763                 trustedIdentities.get(ownIdentity).remove(identity);
1764         }
1765
1766         //
1767         // INTERFACE UpdateListener
1768         //
1769
1770         /**
1771          * {@inheritDoc}
1772          */
1773         @Override
1774         public void updateFound(Version version, long releaseTime, long latestEdition) {
1775                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
1776         }
1777
1778 }