Add a core thread that periodically saves the configuration.
[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.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Client;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.Profile;
40 import net.pterodactylus.sone.data.Profile.Field;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.fcp.FcpInterface;
44 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
45 import net.pterodactylus.sone.freenet.wot.Identity;
46 import net.pterodactylus.sone.freenet.wot.IdentityListener;
47 import net.pterodactylus.sone.freenet.wot.IdentityManager;
48 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
49 import net.pterodactylus.sone.freenet.wot.Trust;
50 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
51 import net.pterodactylus.sone.main.SonePlugin;
52 import net.pterodactylus.util.config.Configuration;
53 import net.pterodactylus.util.config.ConfigurationException;
54 import net.pterodactylus.util.logging.Logging;
55 import net.pterodactylus.util.number.Numbers;
56 import net.pterodactylus.util.service.AbstractService;
57 import net.pterodactylus.util.thread.Ticker;
58 import net.pterodactylus.util.validation.EqualityValidator;
59 import net.pterodactylus.util.validation.IntegerRangeValidator;
60 import net.pterodactylus.util.validation.OrValidator;
61 import net.pterodactylus.util.validation.Validation;
62 import net.pterodactylus.util.version.Version;
63 import freenet.keys.FreenetURI;
64
65 /**
66  * The Sone core.
67  *
68  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69  */
70 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener {
71
72         /**
73          * Enumeration for the possible states of a {@link Sone}.
74          *
75          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76          */
77         public enum SoneStatus {
78
79                 /** The Sone is unknown, i.e. not yet downloaded. */
80                 unknown,
81
82                 /** The Sone is idle, i.e. not being downloaded or inserted. */
83                 idle,
84
85                 /** The Sone is currently being inserted. */
86                 inserting,
87
88                 /** The Sone is currently being downloaded. */
89                 downloading,
90         }
91
92         /** The logger. */
93         private static final Logger logger = Logging.getLogger(Core.class);
94
95         /** The options. */
96         private final Options options = new Options();
97
98         /** The preferences. */
99         private final Preferences preferences = new Preferences(options);
100
101         /** The core listener manager. */
102         private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
103
104         /** The configuration. */
105         private Configuration configuration;
106
107         /** Whether we’re currently saving the configuration. */
108         private boolean storingConfiguration = false;
109
110         /** The identity manager. */
111         private final IdentityManager identityManager;
112
113         /** Interface to freenet. */
114         private final FreenetInterface freenetInterface;
115
116         /** The Sone downloader. */
117         private final SoneDownloader soneDownloader;
118
119         /** Sone downloader thread-pool. */
120         private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
121
122         /** The update checker. */
123         private final UpdateChecker updateChecker;
124
125         /** The FCP interface. */
126         private volatile FcpInterface fcpInterface;
127
128         /** The Sones’ statuses. */
129         /* synchronize access on itself. */
130         private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
131
132         /** Locked local Sones. */
133         /* synchronize on itself. */
134         private final Set<Sone> lockedSones = new HashSet<Sone>();
135
136         /** Sone inserters. */
137         /* synchronize access on this on localSones. */
138         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
139
140         /** Sone rescuers. */
141         /* synchronize access on this on localSones. */
142         private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
143
144         /** All local Sones. */
145         /* synchronize access on this on itself. */
146         private Map<String, Sone> localSones = new HashMap<String, Sone>();
147
148         /** All remote Sones. */
149         /* synchronize access on this on itself. */
150         private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
151
152         /** All new Sones. */
153         private Set<String> newSones = new HashSet<String>();
154
155         /** All known Sones. */
156         /* synchronize access on {@link #newSones}. */
157         private Set<String> knownSones = new HashSet<String>();
158
159         /** All posts. */
160         private Map<String, Post> posts = new HashMap<String, Post>();
161
162         /** All new posts. */
163         private Set<String> newPosts = new HashSet<String>();
164
165         /** All known posts. */
166         /* synchronize access on {@link #newPosts}. */
167         private Set<String> knownPosts = new HashSet<String>();
168
169         /** All replies. */
170         private Map<String, Reply> replies = new HashMap<String, Reply>();
171
172         /** All new replies. */
173         private Set<String> newReplies = new HashSet<String>();
174
175         /** All known replies. */
176         private Set<String> knownReplies = new HashSet<String>();
177
178         /** All bookmarked posts. */
179         /* synchronize access on itself. */
180         private Set<String> bookmarkedPosts = new HashSet<String>();
181
182         /** Trusted identities, sorted by own identities. */
183         private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
184
185         /** Ticker for threads that mark own elements as known. */
186         private Ticker localElementTicker = new Ticker();
187
188         /** The time the configuration was last touched. */
189         private volatile long lastConfigurationUpdate;
190
191         /**
192          * Creates a new core.
193          *
194          * @param configuration
195          *            The configuration of the core
196          * @param freenetInterface
197          *            The freenet interface
198          * @param identityManager
199          *            The identity manager
200          */
201         public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
202                 super("Sone Core");
203                 this.configuration = configuration;
204                 this.freenetInterface = freenetInterface;
205                 this.identityManager = identityManager;
206                 this.soneDownloader = new SoneDownloader(this, freenetInterface);
207                 this.updateChecker = new UpdateChecker(freenetInterface);
208         }
209
210         //
211         // LISTENER MANAGEMENT
212         //
213
214         /**
215          * Adds a new core listener.
216          *
217          * @param coreListener
218          *            The listener to add
219          */
220         public void addCoreListener(CoreListener coreListener) {
221                 coreListenerManager.addListener(coreListener);
222         }
223
224         /**
225          * Removes a core listener.
226          *
227          * @param coreListener
228          *            The listener to remove
229          */
230         public void removeCoreListener(CoreListener coreListener) {
231                 coreListenerManager.removeListener(coreListener);
232         }
233
234         //
235         // ACCESSORS
236         //
237
238         /**
239          * Sets the configuration to use. This will automatically save the current
240          * configuration to the given configuration.
241          *
242          * @param configuration
243          *            The new configuration to use
244          */
245         public void setConfiguration(Configuration configuration) {
246                 this.configuration = configuration;
247                 touchConfiguration();
248         }
249
250         /**
251          * Returns the options used by the core.
252          *
253          * @return The options of the core
254          */
255         public Preferences getPreferences() {
256                 return preferences;
257         }
258
259         /**
260          * Returns the identity manager used by the core.
261          *
262          * @return The identity manager
263          */
264         public IdentityManager getIdentityManager() {
265                 return identityManager;
266         }
267
268         /**
269          * Returns the update checker.
270          *
271          * @return The update checker
272          */
273         public UpdateChecker getUpdateChecker() {
274                 return updateChecker;
275         }
276
277         /**
278          * Sets the FCP interface to use.
279          *
280          * @param fcpInterface
281          *            The FCP interface to use
282          */
283         public void setFcpInterface(FcpInterface fcpInterface) {
284                 this.fcpInterface = fcpInterface;
285         }
286
287         /**
288          * Returns the status of the given Sone.
289          *
290          * @param sone
291          *            The Sone to get the status for
292          * @return The status of the Sone
293          */
294         public SoneStatus getSoneStatus(Sone sone) {
295                 synchronized (soneStatuses) {
296                         return soneStatuses.get(sone);
297                 }
298         }
299
300         /**
301          * Sets the status of the given Sone.
302          *
303          * @param sone
304          *            The Sone to set the status of
305          * @param soneStatus
306          *            The status to set
307          */
308         public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
309                 synchronized (soneStatuses) {
310                         soneStatuses.put(sone, soneStatus);
311                 }
312         }
313
314         /**
315          * Returns the Sone rescuer for the given local Sone.
316          *
317          * @param sone
318          *            The local Sone to get the rescuer for
319          * @return The Sone rescuer for the given Sone
320          */
321         public SoneRescuer getSoneRescuer(Sone sone) {
322                 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
323                 synchronized (localSones) {
324                         SoneRescuer soneRescuer = soneRescuers.get(sone);
325                         if (soneRescuer == null) {
326                                 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
327                                 soneRescuers.put(sone, soneRescuer);
328                                 soneRescuer.start();
329                         }
330                         return soneRescuer;
331                 }
332         }
333
334         /**
335          * Returns whether the given Sone is currently locked.
336          *
337          * @param sone
338          *            The sone to check
339          * @return {@code true} if the Sone is locked, {@code false} if it is not
340          */
341         public boolean isLocked(Sone sone) {
342                 synchronized (lockedSones) {
343                         return lockedSones.contains(sone);
344                 }
345         }
346
347         /**
348          * Returns all Sones, remote and local.
349          *
350          * @return All Sones
351          */
352         public Set<Sone> getSones() {
353                 Set<Sone> allSones = new HashSet<Sone>();
354                 allSones.addAll(getLocalSones());
355                 allSones.addAll(getRemoteSones());
356                 return allSones;
357         }
358
359         /**
360          * Returns the Sone with the given ID, regardless whether it’s local or
361          * remote.
362          *
363          * @param id
364          *            The ID of the Sone to get
365          * @return The Sone with the given ID, or {@code null} if there is no such
366          *         Sone
367          */
368         public Sone getSone(String id) {
369                 return getSone(id, true);
370         }
371
372         /**
373          * Returns the Sone with the given ID, regardless whether it’s local or
374          * remote.
375          *
376          * @param id
377          *            The ID of the Sone to get
378          * @param create
379          *            {@code true} to create a new Sone if none exists,
380          *            {@code false} to return {@code null} if a Sone with the given
381          *            ID does not exist
382          * @return The Sone with the given ID, or {@code null} if there is no such
383          *         Sone
384          */
385         @Override
386         public Sone getSone(String id, boolean create) {
387                 if (isLocalSone(id)) {
388                         return getLocalSone(id);
389                 }
390                 return getRemoteSone(id, create);
391         }
392
393         /**
394          * Checks whether the core knows a Sone with the given ID.
395          *
396          * @param id
397          *            The ID of the Sone
398          * @return {@code true} if there is a Sone with the given ID, {@code false}
399          *         otherwise
400          */
401         public boolean hasSone(String id) {
402                 return isLocalSone(id) || isRemoteSone(id);
403         }
404
405         /**
406          * Returns whether the given Sone is a local Sone.
407          *
408          * @param sone
409          *            The Sone to check for its locality
410          * @return {@code true} if the given Sone is local, {@code false} otherwise
411          */
412         public boolean isLocalSone(Sone sone) {
413                 synchronized (localSones) {
414                         return localSones.containsKey(sone.getId());
415                 }
416         }
417
418         /**
419          * Returns whether the given ID is the ID of a local Sone.
420          *
421          * @param id
422          *            The Sone ID to check for its locality
423          * @return {@code true} if the given ID is a local Sone, {@code false}
424          *         otherwise
425          */
426         public boolean isLocalSone(String id) {
427                 synchronized (localSones) {
428                         return localSones.containsKey(id);
429                 }
430         }
431
432         /**
433          * Returns all local Sones.
434          *
435          * @return All local Sones
436          */
437         public Set<Sone> getLocalSones() {
438                 synchronized (localSones) {
439                         return new HashSet<Sone>(localSones.values());
440                 }
441         }
442
443         /**
444          * Returns the local Sone with the given ID.
445          *
446          * @param id
447          *            The ID of the Sone to get
448          * @return The Sone with the given ID
449          */
450         public Sone getLocalSone(String id) {
451                 return getLocalSone(id, true);
452         }
453
454         /**
455          * Returns the local Sone with the given ID, optionally creating a new Sone.
456          *
457          * @param id
458          *            The ID of the Sone
459          * @param create
460          *            {@code true} to create a new Sone if none exists,
461          *            {@code false} to return null if none exists
462          * @return The Sone with the given ID, or {@code null}
463          */
464         public Sone getLocalSone(String id, boolean create) {
465                 synchronized (localSones) {
466                         Sone sone = localSones.get(id);
467                         if ((sone == null) && create) {
468                                 sone = new Sone(id);
469                                 localSones.put(id, sone);
470                                 setSoneStatus(sone, SoneStatus.unknown);
471                         }
472                         return sone;
473                 }
474         }
475
476         /**
477          * Returns all remote Sones.
478          *
479          * @return All remote Sones
480          */
481         public Set<Sone> getRemoteSones() {
482                 synchronized (remoteSones) {
483                         return new HashSet<Sone>(remoteSones.values());
484                 }
485         }
486
487         /**
488          * Returns the remote Sone with the given ID.
489          *
490          * @param id
491          *            The ID of the remote Sone to get
492          * @return The Sone with the given ID
493          */
494         public Sone getRemoteSone(String id) {
495                 return getRemoteSone(id, true);
496         }
497
498         /**
499          * Returns the remote Sone with the given ID.
500          *
501          * @param id
502          *            The ID of the remote Sone to get
503          * @param create
504          *            {@code true} to always create a Sone, {@code false} to return
505          *            {@code null} if no Sone with the given ID exists
506          * @return The Sone with the given ID
507          */
508         public Sone getRemoteSone(String id, boolean create) {
509                 synchronized (remoteSones) {
510                         Sone sone = remoteSones.get(id);
511                         if ((sone == null) && create) {
512                                 sone = new Sone(id);
513                                 remoteSones.put(id, sone);
514                                 setSoneStatus(sone, SoneStatus.unknown);
515                         }
516                         return sone;
517                 }
518         }
519
520         /**
521          * Returns whether the given Sone is a remote Sone.
522          *
523          * @param sone
524          *            The Sone to check
525          * @return {@code true} if the given Sone is a remote Sone, {@code false}
526          *         otherwise
527          */
528         public boolean isRemoteSone(Sone sone) {
529                 synchronized (remoteSones) {
530                         return remoteSones.containsKey(sone.getId());
531                 }
532         }
533
534         /**
535          * Returns whether the Sone with the given ID is a remote Sone.
536          *
537          * @param id
538          *            The ID of the Sone to check
539          * @return {@code true} if the Sone with the given ID is a remote Sone,
540          *         {@code false} otherwise
541          */
542         public boolean isRemoteSone(String id) {
543                 synchronized (remoteSones) {
544                         return remoteSones.containsKey(id);
545                 }
546         }
547
548         /**
549          * Returns whether the Sone with the given ID is a new Sone.
550          *
551          * @param soneId
552          *            The ID of the sone to check for
553          * @return {@code true} if the given Sone is new, false otherwise
554          */
555         public boolean isNewSone(String soneId) {
556                 synchronized (newSones) {
557                         return !knownSones.contains(soneId) && newSones.contains(soneId);
558                 }
559         }
560
561         /**
562          * Returns whether the given Sone has been modified.
563          *
564          * @param sone
565          *            The Sone to check for modifications
566          * @return {@code true} if a modification has been detected in the Sone,
567          *         {@code false} otherwise
568          */
569         public boolean isModifiedSone(Sone sone) {
570                 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
571         }
572
573         /**
574          * Returns whether the target Sone is trusted by the origin Sone.
575          *
576          * @param origin
577          *            The origin Sone
578          * @param target
579          *            The target Sone
580          * @return {@code true} if the target Sone is trusted by the origin Sone
581          */
582         public boolean isSoneTrusted(Sone origin, Sone target) {
583                 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
584                 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
585         }
586
587         /**
588          * Returns the post with the given ID.
589          *
590          * @param postId
591          *            The ID of the post to get
592          * @return The post with the given ID, or a new post with the given ID
593          */
594         public Post getPost(String postId) {
595                 return getPost(postId, true);
596         }
597
598         /**
599          * Returns the post with the given ID, optionally creating a new post.
600          *
601          * @param postId
602          *            The ID of the post to get
603          * @param create
604          *            {@code true} it create a new post if no post with the given ID
605          *            exists, {@code false} to return {@code null}
606          * @return The post, or {@code null} if there is no such post
607          */
608         @Override
609         public Post getPost(String postId, boolean create) {
610                 synchronized (posts) {
611                         Post post = posts.get(postId);
612                         if ((post == null) && create) {
613                                 post = new Post(postId);
614                                 posts.put(postId, post);
615                         }
616                         return post;
617                 }
618         }
619
620         /**
621          * Returns whether the given post ID is new.
622          *
623          * @param postId
624          *            The post ID
625          * @return {@code true} if the post is considered to be new, {@code false}
626          *         otherwise
627          */
628         public boolean isNewPost(String postId) {
629                 synchronized (newPosts) {
630                         return !knownPosts.contains(postId) && newPosts.contains(postId);
631                 }
632         }
633
634         /**
635          * Returns all posts that have the given Sone as recipient.
636          *
637          * @see Post#getRecipient()
638          * @param recipient
639          *            The recipient of the posts
640          * @return All posts that have the given Sone as recipient
641          */
642         public Set<Post> getDirectedPosts(Sone recipient) {
643                 Validation.begin().isNotNull("Recipient", recipient).check();
644                 Set<Post> directedPosts = new HashSet<Post>();
645                 synchronized (posts) {
646                         for (Post post : posts.values()) {
647                                 if (recipient.equals(post.getRecipient())) {
648                                         directedPosts.add(post);
649                                 }
650                         }
651                 }
652                 return directedPosts;
653         }
654
655         /**
656          * Returns the reply with the given ID. If there is no reply with the given
657          * ID yet, a new one is created.
658          *
659          * @param replyId
660          *            The ID of the reply to get
661          * @return The reply
662          */
663         public Reply getReply(String replyId) {
664                 return getReply(replyId, true);
665         }
666
667         /**
668          * Returns the reply with the given ID. If there is no reply with the given
669          * ID yet, a new one is created, unless {@code create} is false in which
670          * case {@code null} is returned.
671          *
672          * @param replyId
673          *            The ID of the reply to get
674          * @param create
675          *            {@code true} to always return a {@link Reply}, {@code false}
676          *            to return {@code null} if no reply can be found
677          * @return The reply, or {@code null} if there is no such reply
678          */
679         public Reply getReply(String replyId, boolean create) {
680                 synchronized (replies) {
681                         Reply reply = replies.get(replyId);
682                         if (create && (reply == null)) {
683                                 reply = new Reply(replyId);
684                                 replies.put(replyId, reply);
685                         }
686                         return reply;
687                 }
688         }
689
690         /**
691          * Returns all replies for the given post, order ascending by time.
692          *
693          * @param post
694          *            The post to get all replies for
695          * @return All replies for the given post
696          */
697         public List<Reply> getReplies(Post post) {
698                 Set<Sone> sones = getSones();
699                 List<Reply> replies = new ArrayList<Reply>();
700                 for (Sone sone : sones) {
701                         for (Reply reply : sone.getReplies()) {
702                                 if (reply.getPost().equals(post)) {
703                                         replies.add(reply);
704                                 }
705                         }
706                 }
707                 Collections.sort(replies, Reply.TIME_COMPARATOR);
708                 return replies;
709         }
710
711         /**
712          * Returns whether the reply with the given ID is new.
713          *
714          * @param replyId
715          *            The ID of the reply to check
716          * @return {@code true} if the reply is considered to be new, {@code false}
717          *         otherwise
718          */
719         public boolean isNewReply(String replyId) {
720                 synchronized (newReplies) {
721                         return !knownReplies.contains(replyId) && newReplies.contains(replyId);
722                 }
723         }
724
725         /**
726          * Returns all Sones that have liked the given post.
727          *
728          * @param post
729          *            The post to get the liking Sones for
730          * @return The Sones that like the given post
731          */
732         public Set<Sone> getLikes(Post post) {
733                 Set<Sone> sones = new HashSet<Sone>();
734                 for (Sone sone : getSones()) {
735                         if (sone.getLikedPostIds().contains(post.getId())) {
736                                 sones.add(sone);
737                         }
738                 }
739                 return sones;
740         }
741
742         /**
743          * Returns all Sones that have liked the given reply.
744          *
745          * @param reply
746          *            The reply to get the liking Sones for
747          * @return The Sones that like the given reply
748          */
749         public Set<Sone> getLikes(Reply reply) {
750                 Set<Sone> sones = new HashSet<Sone>();
751                 for (Sone sone : getSones()) {
752                         if (sone.getLikedReplyIds().contains(reply.getId())) {
753                                 sones.add(sone);
754                         }
755                 }
756                 return sones;
757         }
758
759         /**
760          * Returns whether the given post is bookmarked.
761          *
762          * @param post
763          *            The post to check
764          * @return {@code true} if the given post is bookmarked, {@code false}
765          *         otherwise
766          */
767         public boolean isBookmarked(Post post) {
768                 return isPostBookmarked(post.getId());
769         }
770
771         /**
772          * Returns whether the post with the given ID is bookmarked.
773          *
774          * @param id
775          *            The ID of the post to check
776          * @return {@code true} if the post with the given ID is bookmarked,
777          *         {@code false} otherwise
778          */
779         public boolean isPostBookmarked(String id) {
780                 synchronized (bookmarkedPosts) {
781                         return bookmarkedPosts.contains(id);
782                 }
783         }
784
785         /**
786          * Returns all currently known bookmarked posts.
787          *
788          * @return All bookmarked posts
789          */
790         public Set<Post> getBookmarkedPosts() {
791                 Set<Post> posts = new HashSet<Post>();
792                 synchronized (bookmarkedPosts) {
793                         for (String bookmarkedPostId : bookmarkedPosts) {
794                                 Post post = getPost(bookmarkedPostId, false);
795                                 if (post != null) {
796                                         posts.add(post);
797                                 }
798                         }
799                 }
800                 return posts;
801         }
802
803         //
804         // ACTIONS
805         //
806
807         /**
808          * Locks the given Sone. A locked Sone will not be inserted by
809          * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
810          * again.
811          *
812          * @param sone
813          *            The sone to lock
814          */
815         public void lockSone(Sone sone) {
816                 synchronized (lockedSones) {
817                         if (lockedSones.add(sone)) {
818                                 coreListenerManager.fireSoneLocked(sone);
819                         }
820                 }
821         }
822
823         /**
824          * Unlocks the given Sone.
825          *
826          * @see #lockSone(Sone)
827          * @param sone
828          *            The sone to unlock
829          */
830         public void unlockSone(Sone sone) {
831                 synchronized (lockedSones) {
832                         if (lockedSones.remove(sone)) {
833                                 coreListenerManager.fireSoneUnlocked(sone);
834                         }
835                 }
836         }
837
838         /**
839          * Adds a local Sone from the given ID which has to be the ID of an own
840          * identity.
841          *
842          * @param id
843          *            The ID of an own identity to add a Sone for
844          * @return The added (or already existing) Sone
845          */
846         public Sone addLocalSone(String id) {
847                 synchronized (localSones) {
848                         if (localSones.containsKey(id)) {
849                                 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
850                                 return localSones.get(id);
851                         }
852                         OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
853                         if (ownIdentity == null) {
854                                 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
855                                 return null;
856                         }
857                         return addLocalSone(ownIdentity);
858                 }
859         }
860
861         /**
862          * Adds a local Sone from the given own identity.
863          *
864          * @param ownIdentity
865          *            The own identity to create a Sone from
866          * @return The added (or already existing) Sone
867          */
868         public Sone addLocalSone(OwnIdentity ownIdentity) {
869                 if (ownIdentity == null) {
870                         logger.log(Level.WARNING, "Given OwnIdentity is null!");
871                         return null;
872                 }
873                 synchronized (localSones) {
874                         final Sone sone;
875                         try {
876                                 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
877                         } catch (MalformedURLException mue1) {
878                                 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
879                                 return null;
880                         }
881                         sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
882                         sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
883                         /* TODO - load posts ’n stuff */
884                         localSones.put(ownIdentity.getId(), sone);
885                         final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
886                         soneInserter.addSoneInsertListener(this);
887                         soneInserters.put(sone, soneInserter);
888                         setSoneStatus(sone, SoneStatus.idle);
889                         loadSone(sone);
890                         soneInserter.start();
891                         return sone;
892                 }
893         }
894
895         /**
896          * Creates a new Sone for the given own identity.
897          *
898          * @param ownIdentity
899          *            The own identity to create a Sone for
900          * @return The created Sone
901          */
902         public Sone createSone(OwnIdentity ownIdentity) {
903                 try {
904                         ownIdentity.addContext("Sone");
905                 } catch (WebOfTrustException wote1) {
906                         logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
907                         return null;
908                 }
909                 Sone sone = addLocalSone(ownIdentity);
910                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
911                 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
912                 touchConfiguration();
913                 return sone;
914         }
915
916         /**
917          * Adds the Sone of the given identity.
918          *
919          * @param identity
920          *            The identity whose Sone to add
921          * @return The added or already existing Sone
922          */
923         public Sone addRemoteSone(Identity identity) {
924                 if (identity == null) {
925                         logger.log(Level.WARNING, "Given Identity is null!");
926                         return null;
927                 }
928                 synchronized (remoteSones) {
929                         final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
930                         boolean newSone = sone.getRequestUri() == null;
931                         sone.setRequestUri(getSoneUri(identity.getRequestUri()));
932                         sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
933                         if (newSone) {
934                                 synchronized (newSones) {
935                                         newSone = !knownSones.contains(sone.getId());
936                                         if (newSone) {
937                                                 newSones.add(sone.getId());
938                                         }
939                                 }
940                                 if (newSone) {
941                                         coreListenerManager.fireNewSoneFound(sone);
942                                         for (Sone localSone : getLocalSones()) {
943                                                 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
944                                                         localSone.addFriend(sone.getId());
945                                                         touchConfiguration();
946                                                 }
947                                         }
948                                 }
949                         }
950                         remoteSones.put(identity.getId(), sone);
951                         soneDownloader.addSone(sone);
952                         setSoneStatus(sone, SoneStatus.unknown);
953                         soneDownloaders.execute(new Runnable() {
954
955                                 @Override
956                                 @SuppressWarnings("synthetic-access")
957                                 public void run() {
958                                         soneDownloader.fetchSone(sone, sone.getRequestUri());
959                                 }
960
961                         });
962                         return sone;
963                 }
964         }
965
966         /**
967          * Retrieves the trust relationship from the origin to the target. If the
968          * trust relationship can not be retrieved, {@code null} is returned.
969          *
970          * @see Identity#getTrust(OwnIdentity)
971          * @param origin
972          *            The origin of the trust tree
973          * @param target
974          *            The target of the trust
975          * @return The trust relationship
976          */
977         public Trust getTrust(Sone origin, Sone target) {
978                 if (!isLocalSone(origin)) {
979                         logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
980                         return null;
981                 }
982                 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
983         }
984
985         /**
986          * Sets the trust value of the given origin Sone for the target Sone.
987          *
988          * @param origin
989          *            The origin Sone
990          * @param target
991          *            The target Sone
992          * @param trustValue
993          *            The trust value (from {@code -100} to {@code 100})
994          */
995         public void setTrust(Sone origin, Sone target, int trustValue) {
996                 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();
997                 try {
998                         ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
999                 } catch (WebOfTrustException wote1) {
1000                         logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1001                 }
1002         }
1003
1004         /**
1005          * Removes any trust assignment for the given target Sone.
1006          *
1007          * @param origin
1008          *            The trust origin
1009          * @param target
1010          *            The trust target
1011          */
1012         public void removeTrust(Sone origin, Sone target) {
1013                 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1014                 try {
1015                         ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1016                 } catch (WebOfTrustException wote1) {
1017                         logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1018                 }
1019         }
1020
1021         /**
1022          * Assigns the configured positive trust value for the given target.
1023          *
1024          * @param origin
1025          *            The trust origin
1026          * @param target
1027          *            The trust target
1028          */
1029         public void trustSone(Sone origin, Sone target) {
1030                 setTrust(origin, target, preferences.getPositiveTrust());
1031         }
1032
1033         /**
1034          * Assigns the configured negative trust value for the given target.
1035          *
1036          * @param origin
1037          *            The trust origin
1038          * @param target
1039          *            The trust target
1040          */
1041         public void distrustSone(Sone origin, Sone target) {
1042                 setTrust(origin, target, preferences.getNegativeTrust());
1043         }
1044
1045         /**
1046          * Removes the trust assignment for the given target.
1047          *
1048          * @param origin
1049          *            The trust origin
1050          * @param target
1051          *            The trust target
1052          */
1053         public void untrustSone(Sone origin, Sone target) {
1054                 removeTrust(origin, target);
1055         }
1056
1057         /**
1058          * Updates the stored Sone with the given Sone.
1059          *
1060          * @param sone
1061          *            The updated Sone
1062          */
1063         public void updateSone(Sone sone) {
1064                 updateSone(sone, false);
1065         }
1066
1067         /**
1068          * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1069          * {@code true}, an older Sone than the current Sone can be given to restore
1070          * an old state.
1071          *
1072          * @param sone
1073          *            The Sone to update
1074          * @param soneRescueMode
1075          *            {@code true} if the stored Sone should be updated regardless
1076          *            of the age of the given Sone
1077          */
1078         public void updateSone(Sone sone, boolean soneRescueMode) {
1079                 if (hasSone(sone.getId())) {
1080                         Sone storedSone = getSone(sone.getId());
1081                         if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1082                                 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1083                                 return;
1084                         }
1085                         synchronized (posts) {
1086                                 if (!soneRescueMode) {
1087                                         for (Post post : storedSone.getPosts()) {
1088                                                 posts.remove(post.getId());
1089                                                 if (!sone.getPosts().contains(post)) {
1090                                                         coreListenerManager.firePostRemoved(post);
1091                                                 }
1092                                         }
1093                                 }
1094                                 List<Post> storedPosts = storedSone.getPosts();
1095                                 synchronized (newPosts) {
1096                                         for (Post post : sone.getPosts()) {
1097                                                 post.setSone(storedSone);
1098                                                 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1099                                                         newPosts.add(post.getId());
1100                                                         coreListenerManager.fireNewPostFound(post);
1101                                                 }
1102                                                 posts.put(post.getId(), post);
1103                                         }
1104                                 }
1105                         }
1106                         synchronized (replies) {
1107                                 if (!soneRescueMode) {
1108                                         for (Reply reply : storedSone.getReplies()) {
1109                                                 replies.remove(reply.getId());
1110                                                 if (!sone.getReplies().contains(reply)) {
1111                                                         coreListenerManager.fireReplyRemoved(reply);
1112                                                 }
1113                                         }
1114                                 }
1115                                 Set<Reply> storedReplies = storedSone.getReplies();
1116                                 synchronized (newReplies) {
1117                                         for (Reply reply : sone.getReplies()) {
1118                                                 reply.setSone(storedSone);
1119                                                 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1120                                                         newReplies.add(reply.getId());
1121                                                         coreListenerManager.fireNewReplyFound(reply);
1122                                                 }
1123                                                 replies.put(reply.getId(), reply);
1124                                         }
1125                                 }
1126                         }
1127                         synchronized (storedSone) {
1128                                 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1129                                         storedSone.setTime(sone.getTime());
1130                                 }
1131                                 storedSone.setClient(sone.getClient());
1132                                 storedSone.setProfile(sone.getProfile());
1133                                 if (soneRescueMode) {
1134                                         for (Post post : sone.getPosts()) {
1135                                                 storedSone.addPost(post);
1136                                         }
1137                                         for (Reply reply : sone.getReplies()) {
1138                                                 storedSone.addReply(reply);
1139                                         }
1140                                         for (String likedPostId : sone.getLikedPostIds()) {
1141                                                 storedSone.addLikedPostId(likedPostId);
1142                                         }
1143                                         for (String likedReplyId : sone.getLikedReplyIds()) {
1144                                                 storedSone.addLikedReplyId(likedReplyId);
1145                                         }
1146                                 } else {
1147                                         storedSone.setPosts(sone.getPosts());
1148                                         storedSone.setReplies(sone.getReplies());
1149                                         storedSone.setLikePostIds(sone.getLikedPostIds());
1150                                         storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1151                                 }
1152                                 storedSone.setLatestEdition(sone.getLatestEdition());
1153                         }
1154                 }
1155         }
1156
1157         /**
1158          * Deletes the given Sone. This will remove the Sone from the
1159          * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1160          * and remove the context from its identity.
1161          *
1162          * @param sone
1163          *            The Sone to delete
1164          */
1165         public void deleteSone(Sone sone) {
1166                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1167                         logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1168                         return;
1169                 }
1170                 synchronized (localSones) {
1171                         if (!localSones.containsKey(sone.getId())) {
1172                                 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1173                                 return;
1174                         }
1175                         localSones.remove(sone.getId());
1176                         SoneInserter soneInserter = soneInserters.remove(sone);
1177                         soneInserter.removeSoneInsertListener(this);
1178                         soneInserter.stop();
1179                 }
1180                 try {
1181                         ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1182                         ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1183                 } catch (WebOfTrustException wote1) {
1184                         logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1185                 }
1186                 try {
1187                         configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1188                 } catch (ConfigurationException ce1) {
1189                         logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1190                 }
1191         }
1192
1193         /**
1194          * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1195          * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1196          *
1197          * @param sone
1198          *            The Sone to mark as known
1199          */
1200         public void markSoneKnown(Sone sone) {
1201                 synchronized (newSones) {
1202                         if (newSones.remove(sone.getId())) {
1203                                 knownSones.add(sone.getId());
1204                                 coreListenerManager.fireMarkSoneKnown(sone);
1205                                 touchConfiguration();
1206                         }
1207                 }
1208         }
1209
1210         /**
1211          * Loads and updates the given Sone from the configuration. If any error is
1212          * encountered, loading is aborted and the given Sone is not changed.
1213          *
1214          * @param sone
1215          *            The Sone to load and update
1216          */
1217         public void loadSone(Sone sone) {
1218                 if (!isLocalSone(sone)) {
1219                         logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1220                         return;
1221                 }
1222
1223                 /* initialize options. */
1224                 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1225
1226                 /* load Sone. */
1227                 String sonePrefix = "Sone/" + sone.getId();
1228                 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1229                 if (soneTime == null) {
1230                         logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1231                         return;
1232                 }
1233                 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1234
1235                 /* load profile. */
1236                 Profile profile = new Profile();
1237                 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1238                 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1239                 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1240                 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1241                 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1242                 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1243
1244                 /* load profile fields. */
1245                 while (true) {
1246                         String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1247                         String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1248                         if (fieldName == null) {
1249                                 break;
1250                         }
1251                         String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1252                         profile.addField(fieldName).setValue(fieldValue);
1253                 }
1254
1255                 /* load posts. */
1256                 Set<Post> posts = new HashSet<Post>();
1257                 while (true) {
1258                         String postPrefix = sonePrefix + "/Posts/" + posts.size();
1259                         String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1260                         if (postId == null) {
1261                                 break;
1262                         }
1263                         String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1264                         long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1265                         String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1266                         if ((postTime == 0) || (postText == null)) {
1267                                 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1268                                 return;
1269                         }
1270                         Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1271                         if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1272                                 post.setRecipient(getSone(postRecipientId));
1273                         }
1274                         posts.add(post);
1275                 }
1276
1277                 /* load replies. */
1278                 Set<Reply> replies = new HashSet<Reply>();
1279                 while (true) {
1280                         String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1281                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1282                         if (replyId == null) {
1283                                 break;
1284                         }
1285                         String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1286                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1287                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1288                         if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1289                                 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1290                                 return;
1291                         }
1292                         replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1293                 }
1294
1295                 /* load post likes. */
1296                 Set<String> likedPostIds = new HashSet<String>();
1297                 while (true) {
1298                         String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1299                         if (likedPostId == null) {
1300                                 break;
1301                         }
1302                         likedPostIds.add(likedPostId);
1303                 }
1304
1305                 /* load reply likes. */
1306                 Set<String> likedReplyIds = new HashSet<String>();
1307                 while (true) {
1308                         String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1309                         if (likedReplyId == null) {
1310                                 break;
1311                         }
1312                         likedReplyIds.add(likedReplyId);
1313                 }
1314
1315                 /* load friends. */
1316                 Set<String> friends = new HashSet<String>();
1317                 while (true) {
1318                         String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1319                         if (friendId == null) {
1320                                 break;
1321                         }
1322                         friends.add(friendId);
1323                 }
1324
1325                 /* load options. */
1326                 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1327
1328                 /* if we’re still here, Sone was loaded successfully. */
1329                 synchronized (sone) {
1330                         sone.setTime(soneTime);
1331                         sone.setProfile(profile);
1332                         sone.setPosts(posts);
1333                         sone.setReplies(replies);
1334                         sone.setLikePostIds(likedPostIds);
1335                         sone.setLikeReplyIds(likedReplyIds);
1336                         sone.setFriends(friends);
1337                         soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1338                 }
1339                 synchronized (newSones) {
1340                         for (String friend : friends) {
1341                                 knownSones.add(friend);
1342                         }
1343                 }
1344                 synchronized (newPosts) {
1345                         for (Post post : posts) {
1346                                 knownPosts.add(post.getId());
1347                         }
1348                 }
1349                 synchronized (newReplies) {
1350                         for (Reply reply : replies) {
1351                                 knownReplies.add(reply.getId());
1352                         }
1353                 }
1354         }
1355
1356         /**
1357          * Creates a new post.
1358          *
1359          * @param sone
1360          *            The Sone that creates the post
1361          * @param text
1362          *            The text of the post
1363          * @return The created post
1364          */
1365         public Post createPost(Sone sone, String text) {
1366                 return createPost(sone, System.currentTimeMillis(), text);
1367         }
1368
1369         /**
1370          * Creates a new post.
1371          *
1372          * @param sone
1373          *            The Sone that creates the post
1374          * @param time
1375          *            The time of the post
1376          * @param text
1377          *            The text of the post
1378          * @return The created post
1379          */
1380         public Post createPost(Sone sone, long time, String text) {
1381                 return createPost(sone, null, time, text);
1382         }
1383
1384         /**
1385          * Creates a new post.
1386          *
1387          * @param sone
1388          *            The Sone that creates the post
1389          * @param recipient
1390          *            The recipient Sone, or {@code null} if this post does not have
1391          *            a recipient
1392          * @param text
1393          *            The text of the post
1394          * @return The created post
1395          */
1396         public Post createPost(Sone sone, Sone recipient, String text) {
1397                 return createPost(sone, recipient, System.currentTimeMillis(), text);
1398         }
1399
1400         /**
1401          * Creates a new post.
1402          *
1403          * @param sone
1404          *            The Sone that creates the post
1405          * @param recipient
1406          *            The recipient Sone, or {@code null} if this post does not have
1407          *            a recipient
1408          * @param time
1409          *            The time of the post
1410          * @param text
1411          *            The text of the post
1412          * @return The created post
1413          */
1414         public Post createPost(Sone sone, Sone recipient, long time, String text) {
1415                 if (!isLocalSone(sone)) {
1416                         logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1417                         return null;
1418                 }
1419                 final Post post = new Post(sone, time, text);
1420                 if (recipient != null) {
1421                         post.setRecipient(recipient);
1422                 }
1423                 synchronized (posts) {
1424                         posts.put(post.getId(), post);
1425                 }
1426                 synchronized (newPosts) {
1427                         newPosts.add(post.getId());
1428                         coreListenerManager.fireNewPostFound(post);
1429                 }
1430                 sone.addPost(post);
1431                 touchConfiguration();
1432                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1433
1434                         /**
1435                          * {@inheritDoc}
1436                          */
1437                         @Override
1438                         public void run() {
1439                                 markPostKnown(post);
1440                         }
1441                 }, "Mark " + post + " read.");
1442                 return post;
1443         }
1444
1445         /**
1446          * Deletes the given post.
1447          *
1448          * @param post
1449          *            The post to delete
1450          */
1451         public void deletePost(Post post) {
1452                 if (!isLocalSone(post.getSone())) {
1453                         logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1454                         return;
1455                 }
1456                 post.getSone().removePost(post);
1457                 synchronized (posts) {
1458                         posts.remove(post.getId());
1459                 }
1460                 coreListenerManager.firePostRemoved(post);
1461                 synchronized (newPosts) {
1462                         markPostKnown(post);
1463                         knownPosts.remove(post.getId());
1464                 }
1465                 touchConfiguration();
1466         }
1467
1468         /**
1469          * Marks the given post as known, if it is currently a new post (according
1470          * to {@link #isNewPost(String)}).
1471          *
1472          * @param post
1473          *            The post to mark as known
1474          */
1475         public void markPostKnown(Post post) {
1476                 synchronized (newPosts) {
1477                         if (newPosts.remove(post.getId())) {
1478                                 knownPosts.add(post.getId());
1479                                 coreListenerManager.fireMarkPostKnown(post);
1480                                 touchConfiguration();
1481                         }
1482                 }
1483         }
1484
1485         /**
1486          * Bookmarks the given post.
1487          *
1488          * @param post
1489          *            The post to bookmark
1490          */
1491         public void bookmark(Post post) {
1492                 bookmarkPost(post.getId());
1493         }
1494
1495         /**
1496          * Bookmarks the post with the given ID.
1497          *
1498          * @param id
1499          *            The ID of the post to bookmark
1500          */
1501         public void bookmarkPost(String id) {
1502                 synchronized (bookmarkedPosts) {
1503                         bookmarkedPosts.add(id);
1504                 }
1505         }
1506
1507         /**
1508          * Removes the given post from the bookmarks.
1509          *
1510          * @param post
1511          *            The post to unbookmark
1512          */
1513         public void unbookmark(Post post) {
1514                 unbookmarkPost(post.getId());
1515         }
1516
1517         /**
1518          * Removes the post with the given ID from the bookmarks.
1519          *
1520          * @param id
1521          *            The ID of the post to unbookmark
1522          */
1523         public void unbookmarkPost(String id) {
1524                 synchronized (bookmarkedPosts) {
1525                         bookmarkedPosts.remove(id);
1526                 }
1527         }
1528
1529         /**
1530          * Creates a new reply.
1531          *
1532          * @param sone
1533          *            The Sone that creates the reply
1534          * @param post
1535          *            The post that this reply refers to
1536          * @param text
1537          *            The text of the reply
1538          * @return The created reply
1539          */
1540         public Reply createReply(Sone sone, Post post, String text) {
1541                 return createReply(sone, post, System.currentTimeMillis(), text);
1542         }
1543
1544         /**
1545          * Creates a new reply.
1546          *
1547          * @param sone
1548          *            The Sone that creates the reply
1549          * @param post
1550          *            The post that this reply refers to
1551          * @param time
1552          *            The time of the reply
1553          * @param text
1554          *            The text of the reply
1555          * @return The created reply
1556          */
1557         public Reply createReply(Sone sone, Post post, long time, String text) {
1558                 if (!isLocalSone(sone)) {
1559                         logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1560                         return null;
1561                 }
1562                 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1563                 synchronized (replies) {
1564                         replies.put(reply.getId(), reply);
1565                 }
1566                 synchronized (newReplies) {
1567                         newReplies.add(reply.getId());
1568                         coreListenerManager.fireNewReplyFound(reply);
1569                 }
1570                 sone.addReply(reply);
1571                 touchConfiguration();
1572                 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1573
1574                         /**
1575                          * {@inheritDoc}
1576                          */
1577                         @Override
1578                         public void run() {
1579                                 markReplyKnown(reply);
1580                         }
1581                 }, "Mark " + reply + " read.");
1582                 return reply;
1583         }
1584
1585         /**
1586          * Deletes the given reply.
1587          *
1588          * @param reply
1589          *            The reply to delete
1590          */
1591         public void deleteReply(Reply reply) {
1592                 Sone sone = reply.getSone();
1593                 if (!isLocalSone(sone)) {
1594                         logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1595                         return;
1596                 }
1597                 synchronized (replies) {
1598                         replies.remove(reply.getId());
1599                 }
1600                 synchronized (newReplies) {
1601                         markReplyKnown(reply);
1602                         knownReplies.remove(reply.getId());
1603                 }
1604                 sone.removeReply(reply);
1605                 touchConfiguration();
1606         }
1607
1608         /**
1609          * Marks the given reply as known, if it is currently a new reply (according
1610          * to {@link #isNewReply(String)}).
1611          *
1612          * @param reply
1613          *            The reply to mark as known
1614          */
1615         public void markReplyKnown(Reply reply) {
1616                 synchronized (newReplies) {
1617                         if (newReplies.remove(reply.getId())) {
1618                                 knownReplies.add(reply.getId());
1619                                 coreListenerManager.fireMarkReplyKnown(reply);
1620                                 touchConfiguration();
1621                         }
1622                 }
1623         }
1624
1625         /**
1626          * Notifies the core that the configuration, either of the core or of a
1627          * single local Sone, has changed, and that the configuration should be
1628          * saved.
1629          */
1630         public void touchConfiguration() {
1631                 lastConfigurationUpdate = System.currentTimeMillis();
1632         }
1633
1634         //
1635         // SERVICE METHODS
1636         //
1637
1638         /**
1639          * Starts the core.
1640          */
1641         @Override
1642         public void serviceStart() {
1643                 loadConfiguration();
1644                 updateChecker.addUpdateListener(this);
1645                 updateChecker.start();
1646         }
1647
1648         /**
1649          * {@inheritDoc}
1650          */
1651         @Override
1652         public void serviceRun() {
1653                 long lastSaved = System.currentTimeMillis();
1654                 while (!shouldStop()) {
1655                         sleep(1000);
1656                         long now = System.currentTimeMillis();
1657                         if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1658                                 for (Sone localSone : getLocalSones()) {
1659                                         saveSone(localSone);
1660                                 }
1661                                 saveConfiguration();
1662                                 lastSaved = now;
1663                         }
1664                 }
1665         }
1666
1667         /**
1668          * Stops the core.
1669          */
1670         @Override
1671         public void serviceStop() {
1672                 synchronized (localSones) {
1673                         for (SoneInserter soneInserter : soneInserters.values()) {
1674                                 soneInserter.removeSoneInsertListener(this);
1675                                 soneInserter.stop();
1676                         }
1677                 }
1678                 updateChecker.stop();
1679                 updateChecker.removeUpdateListener(this);
1680                 soneDownloader.stop();
1681         }
1682
1683         //
1684         // PRIVATE METHODS
1685         //
1686
1687         /**
1688          * Saves the given Sone. This will persist all local settings for the given
1689          * Sone, such as the friends list and similar, private options.
1690          *
1691          * @param sone
1692          *            The Sone to save
1693          */
1694         private synchronized void saveSone(Sone sone) {
1695                 if (!isLocalSone(sone)) {
1696                         logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1697                         return;
1698                 }
1699                 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1700                         logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1701                         return;
1702                 }
1703
1704                 logger.log(Level.INFO, "Saving Sone: %s", sone);
1705                 try {
1706                         ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1707
1708                         /* save Sone into configuration. */
1709                         String sonePrefix = "Sone/" + sone.getId();
1710                         configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1711                         configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1712
1713                         /* save profile. */
1714                         Profile profile = sone.getProfile();
1715                         configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1716                         configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1717                         configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1718                         configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1719                         configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1720                         configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1721
1722                         /* save profile fields. */
1723                         int fieldCounter = 0;
1724                         for (Field profileField : profile.getFields()) {
1725                                 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1726                                 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1727                                 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1728                         }
1729                         configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1730
1731                         /* save posts. */
1732                         int postCounter = 0;
1733                         for (Post post : sone.getPosts()) {
1734                                 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1735                                 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1736                                 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1737                                 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1738                                 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1739                         }
1740                         configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1741
1742                         /* save replies. */
1743                         int replyCounter = 0;
1744                         for (Reply reply : sone.getReplies()) {
1745                                 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1746                                 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1747                                 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1748                                 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1749                                 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1750                         }
1751                         configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1752
1753                         /* save post likes. */
1754                         int postLikeCounter = 0;
1755                         for (String postId : sone.getLikedPostIds()) {
1756                                 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1757                         }
1758                         configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1759
1760                         /* save reply likes. */
1761                         int replyLikeCounter = 0;
1762                         for (String replyId : sone.getLikedReplyIds()) {
1763                                 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1764                         }
1765                         configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1766
1767                         /* save friends. */
1768                         int friendCounter = 0;
1769                         for (String friendId : sone.getFriends()) {
1770                                 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1771                         }
1772                         configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1773
1774                         /* save options. */
1775                         configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1776
1777                         configuration.save();
1778                         logger.log(Level.INFO, "Sone %s saved.", sone);
1779                 } catch (ConfigurationException ce1) {
1780                         logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1781                 } catch (WebOfTrustException wote1) {
1782                         logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1783                 }
1784         }
1785
1786         /**
1787          * Saves the current options.
1788          */
1789         private void saveConfiguration() {
1790                 synchronized (configuration) {
1791                         if (storingConfiguration) {
1792                                 logger.log(Level.FINE, "Already storing configuration…");
1793                                 return;
1794                         }
1795                         storingConfiguration = true;
1796                 }
1797
1798                 /* store the options first. */
1799                 try {
1800                         configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1801                         configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1802                         configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1803                         configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1804                         configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1805                         configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1806                         configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1807                         configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1808                         configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1809                         configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1810                         configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1811                         configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1812                         configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1813
1814                         /* save known Sones. */
1815                         int soneCounter = 0;
1816                         synchronized (newSones) {
1817                                 for (String knownSoneId : knownSones) {
1818                                         configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1819                                 }
1820                                 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1821                         }
1822
1823                         /* save known posts. */
1824                         int postCounter = 0;
1825                         synchronized (newPosts) {
1826                                 for (String knownPostId : knownPosts) {
1827                                         configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1828                                 }
1829                                 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1830                         }
1831
1832                         /* save known replies. */
1833                         int replyCounter = 0;
1834                         synchronized (newReplies) {
1835                                 for (String knownReplyId : knownReplies) {
1836                                         configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1837                                 }
1838                                 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1839                         }
1840
1841                         /* save bookmarked posts. */
1842                         int bookmarkedPostCounter = 0;
1843                         synchronized (bookmarkedPosts) {
1844                                 for (String bookmarkedPostId : bookmarkedPosts) {
1845                                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1846                                 }
1847                         }
1848                         configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1849
1850                         /* now save it. */
1851                         configuration.save();
1852
1853                 } catch (ConfigurationException ce1) {
1854                         logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1855                 } finally {
1856                         synchronized (configuration) {
1857                                 storingConfiguration = false;
1858                         }
1859                 }
1860         }
1861
1862         /**
1863          * Loads the configuration.
1864          */
1865         @SuppressWarnings("unchecked")
1866         private void loadConfiguration() {
1867                 /* create options. */
1868                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1869
1870                         @Override
1871                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1872                                 SoneInserter.setInsertionDelay(newValue);
1873                         }
1874
1875                 }));
1876                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
1877                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
1878                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1879                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
1880                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
1881                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1882                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1883
1884                         @Override
1885                         @SuppressWarnings("synthetic-access")
1886                         public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1887                                 fcpInterface.setActive(newValue);
1888                         }
1889                 }));
1890                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1891
1892                         @Override
1893                         @SuppressWarnings("synthetic-access")
1894                         public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1895                                 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1896                         }
1897
1898                 }));
1899                 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1900                 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1901                 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1902
1903                 /* read options from configuration. */
1904                 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1905                 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1906                 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1907                 options.getBooleanOption("ClearOnNextRestart").set(null);
1908                 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1909                 if (clearConfiguration) {
1910                         /* stop loading the configuration. */
1911                         return;
1912                 }
1913
1914                 loadConfigurationValue("InsertionDelay");
1915                 loadConfigurationValue("PostsPerPage");
1916                 loadConfigurationValue("CharactersPerPost");
1917                 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1918                 loadConfigurationValue("PositiveTrust");
1919                 loadConfigurationValue("NegativeTrust");
1920                 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1921                 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1922                 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1923                 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1924
1925                 /* load known Sones. */
1926                 int soneCounter = 0;
1927                 while (true) {
1928                         String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1929                         if (knownSoneId == null) {
1930                                 break;
1931                         }
1932                         synchronized (newSones) {
1933                                 knownSones.add(knownSoneId);
1934                         }
1935                 }
1936
1937                 /* load known posts. */
1938                 int postCounter = 0;
1939                 while (true) {
1940                         String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1941                         if (knownPostId == null) {
1942                                 break;
1943                         }
1944                         synchronized (newPosts) {
1945                                 knownPosts.add(knownPostId);
1946                         }
1947                 }
1948
1949                 /* load known replies. */
1950                 int replyCounter = 0;
1951                 while (true) {
1952                         String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1953                         if (knownReplyId == null) {
1954                                 break;
1955                         }
1956                         synchronized (newReplies) {
1957                                 knownReplies.add(knownReplyId);
1958                         }
1959                 }
1960
1961                 /* load bookmarked posts. */
1962                 int bookmarkedPostCounter = 0;
1963                 while (true) {
1964                         String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1965                         if (bookmarkedPostId == null) {
1966                                 break;
1967                         }
1968                         synchronized (bookmarkedPosts) {
1969                                 bookmarkedPosts.add(bookmarkedPostId);
1970                         }
1971                 }
1972
1973         }
1974
1975         /**
1976          * Loads an {@link Integer} configuration value for the option with the
1977          * given name, logging validation failures.
1978          *
1979          * @param optionName
1980          *            The name of the option to load
1981          */
1982         private void loadConfigurationValue(String optionName) {
1983                 try {
1984                         options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1985                 } catch (IllegalArgumentException iae1) {
1986                         logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
1987                 }
1988         }
1989
1990         /**
1991          * Generate a Sone URI from the given URI and latest edition.
1992          *
1993          * @param uriString
1994          *            The URI to derive the Sone URI from
1995          * @return The derived URI
1996          */
1997         private FreenetURI getSoneUri(String uriString) {
1998                 try {
1999                         FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2000                         return uri;
2001                 } catch (MalformedURLException mue1) {
2002                         logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2003                         return null;
2004                 }
2005         }
2006
2007         //
2008         // INTERFACE IdentityListener
2009         //
2010
2011         /**
2012          * {@inheritDoc}
2013          */
2014         @Override
2015         public void ownIdentityAdded(OwnIdentity ownIdentity) {
2016                 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2017                 if (ownIdentity.hasContext("Sone")) {
2018                         trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2019                         addLocalSone(ownIdentity);
2020                 }
2021         }
2022
2023         /**
2024          * {@inheritDoc}
2025          */
2026         @Override
2027         public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2028                 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2029                 trustedIdentities.remove(ownIdentity);
2030         }
2031
2032         /**
2033          * {@inheritDoc}
2034          */
2035         @Override
2036         public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2037                 logger.log(Level.FINEST, "Adding Identity: " + identity);
2038                 trustedIdentities.get(ownIdentity).add(identity);
2039                 addRemoteSone(identity);
2040         }
2041
2042         /**
2043          * {@inheritDoc}
2044          */
2045         @Override
2046         public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2047                 new Thread(new Runnable() {
2048
2049                         @Override
2050                         @SuppressWarnings("synthetic-access")
2051                         public void run() {
2052                                 Sone sone = getRemoteSone(identity.getId());
2053                                 sone.setIdentity(identity);
2054                                 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2055                                 soneDownloader.addSone(sone);
2056                                 soneDownloader.fetchSone(sone);
2057                         }
2058                 }).start();
2059         }
2060
2061         /**
2062          * {@inheritDoc}
2063          */
2064         @Override
2065         public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2066                 trustedIdentities.get(ownIdentity).remove(identity);
2067                 boolean foundIdentity = false;
2068                 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2069                         if (trustedIdentity.getKey().equals(ownIdentity)) {
2070                                 continue;
2071                         }
2072                         if (trustedIdentity.getValue().contains(identity)) {
2073                                 foundIdentity = true;
2074                         }
2075                 }
2076                 if (foundIdentity) {
2077                         /* some local identity still trusts this identity, don’t remove. */
2078                         return;
2079                 }
2080                 Sone sone = getSone(identity.getId(), false);
2081                 if (sone == null) {
2082                         /* TODO - we don’t have the Sone anymore. should this happen? */
2083                         return;
2084                 }
2085                 synchronized (posts) {
2086                         synchronized (newPosts) {
2087                                 for (Post post : sone.getPosts()) {
2088                                         posts.remove(post.getId());
2089                                         newPosts.remove(post.getId());
2090                                         coreListenerManager.firePostRemoved(post);
2091                                 }
2092                         }
2093                 }
2094                 synchronized (replies) {
2095                         synchronized (newReplies) {
2096                                 for (Reply reply : sone.getReplies()) {
2097                                         replies.remove(reply.getId());
2098                                         newReplies.remove(reply.getId());
2099                                         coreListenerManager.fireReplyRemoved(reply);
2100                                 }
2101                         }
2102                 }
2103                 synchronized (remoteSones) {
2104                         remoteSones.remove(identity.getId());
2105                 }
2106                 synchronized (newSones) {
2107                         newSones.remove(identity.getId());
2108                         coreListenerManager.fireSoneRemoved(sone);
2109                 }
2110         }
2111
2112         //
2113         // INTERFACE UpdateListener
2114         //
2115
2116         /**
2117          * {@inheritDoc}
2118          */
2119         @Override
2120         public void updateFound(Version version, long releaseTime, long latestEdition) {
2121                 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2122         }
2123
2124         //
2125         // SONEINSERTLISTENER METHODS
2126         //
2127
2128         /**
2129          * {@inheritDoc}
2130          */
2131         public void insertStarted(Sone sone) {
2132                 coreListenerManager.fireSoneInserting(sone);
2133         }
2134
2135         /**
2136          * {@inheritDoc}
2137          */
2138         @Override
2139         public void insertFinished(Sone sone, long insertDuration) {
2140                 coreListenerManager.fireSoneInserted(sone, insertDuration);
2141         }
2142
2143         /**
2144          * {@inheritDoc}
2145          */
2146         @Override
2147         public void insertAborted(Sone sone, Throwable cause) {
2148                 coreListenerManager.fireSoneInsertAborted(sone, cause);
2149         }
2150
2151         /**
2152          * Convenience interface for external classes that want to access the core’s
2153          * configuration.
2154          *
2155          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2156          */
2157         public static class Preferences {
2158
2159                 /** The wrapped options. */
2160                 private final Options options;
2161
2162                 /**
2163                  * Creates a new preferences object wrapped around the given options.
2164                  *
2165                  * @param options
2166                  *            The options to wrap
2167                  */
2168                 public Preferences(Options options) {
2169                         this.options = options;
2170                 }
2171
2172                 /**
2173                  * Returns the insertion delay.
2174                  *
2175                  * @return The insertion delay
2176                  */
2177                 public int getInsertionDelay() {
2178                         return options.getIntegerOption("InsertionDelay").get();
2179                 }
2180
2181                 /**
2182                  * Validates the given insertion delay.
2183                  *
2184                  * @param insertionDelay
2185                  *            The insertion delay to validate
2186                  * @return {@code true} if the given insertion delay was valid, {@code
2187                  *         false} otherwise
2188                  */
2189                 public boolean validateInsertionDelay(Integer insertionDelay) {
2190                         return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2191                 }
2192
2193                 /**
2194                  * Sets the insertion delay
2195                  *
2196                  * @param insertionDelay
2197                  *            The new insertion delay, or {@code null} to restore it to
2198                  *            the default value
2199                  * @return This preferences
2200                  */
2201                 public Preferences setInsertionDelay(Integer insertionDelay) {
2202                         options.getIntegerOption("InsertionDelay").set(insertionDelay);
2203                         return this;
2204                 }
2205
2206                 /**
2207                  * Returns the number of posts to show per page.
2208                  *
2209                  * @return The number of posts to show per page
2210                  */
2211                 public int getPostsPerPage() {
2212                         return options.getIntegerOption("PostsPerPage").get();
2213                 }
2214
2215                 /**
2216                  * Validates the number of posts per page.
2217                  *
2218                  * @param postsPerPage
2219                  *            The number of posts per page
2220                  * @return {@code true} if the number of posts per page was valid,
2221                  *         {@code false} otherwise
2222                  */
2223                 public boolean validatePostsPerPage(Integer postsPerPage) {
2224                         return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2225                 }
2226
2227                 /**
2228                  * Sets the number of posts to show per page.
2229                  *
2230                  * @param postsPerPage
2231                  *            The number of posts to show per page
2232                  * @return This preferences object
2233                  */
2234                 public Preferences setPostsPerPage(Integer postsPerPage) {
2235                         options.getIntegerOption("PostsPerPage").set(postsPerPage);
2236                         return this;
2237                 }
2238
2239                 /**
2240                  * Returns the number of characters per post, or <code>-1</code> if the
2241                  * posts should not be cut off.
2242                  *
2243                  * @return The numbers of characters per post
2244                  */
2245                 public int getCharactersPerPost() {
2246                         return options.getIntegerOption("CharactersPerPost").get();
2247                 }
2248
2249                 /**
2250                  * Validates the number of characters per post.
2251                  *
2252                  * @param charactersPerPost
2253                  *            The number of characters per post
2254                  * @return {@code true} if the number of characters per post was valid,
2255                  *         {@code false} otherwise
2256                  */
2257                 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2258                         return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2259                 }
2260
2261                 /**
2262                  * Sets the number of characters per post.
2263                  *
2264                  * @param charactersPerPost
2265                  *            The number of characters per post, or <code>-1</code> to
2266                  *            not cut off the posts
2267                  * @return This preferences objects
2268                  */
2269                 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2270                         options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2271                         return this;
2272                 }
2273
2274                 /**
2275                  * Returns whether Sone requires full access to be even visible.
2276                  *
2277                  * @return {@code true} if Sone requires full access, {@code false}
2278                  *         otherwise
2279                  */
2280                 public boolean isRequireFullAccess() {
2281                         return options.getBooleanOption("RequireFullAccess").get();
2282                 }
2283
2284                 /**
2285                  * Sets whether Sone requires full access to be even visible.
2286                  *
2287                  * @param requireFullAccess
2288                  *            {@code true} if Sone requires full access, {@code false}
2289                  *            otherwise
2290                  */
2291                 public void setRequireFullAccess(Boolean requireFullAccess) {
2292                         options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2293                 }
2294
2295                 /**
2296                  * Returns the positive trust.
2297                  *
2298                  * @return The positive trust
2299                  */
2300                 public int getPositiveTrust() {
2301                         return options.getIntegerOption("PositiveTrust").get();
2302                 }
2303
2304                 /**
2305                  * Validates the positive trust.
2306                  *
2307                  * @param positiveTrust
2308                  *            The positive trust to validate
2309                  * @return {@code true} if the positive trust was valid, {@code false}
2310                  *         otherwise
2311                  */
2312                 public boolean validatePositiveTrust(Integer positiveTrust) {
2313                         return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2314                 }
2315
2316                 /**
2317                  * Sets the positive trust.
2318                  *
2319                  * @param positiveTrust
2320                  *            The new positive trust, or {@code null} to restore it to
2321                  *            the default vlaue
2322                  * @return This preferences
2323                  */
2324                 public Preferences setPositiveTrust(Integer positiveTrust) {
2325                         options.getIntegerOption("PositiveTrust").set(positiveTrust);
2326                         return this;
2327                 }
2328
2329                 /**
2330                  * Returns the negative trust.
2331                  *
2332                  * @return The negative trust
2333                  */
2334                 public int getNegativeTrust() {
2335                         return options.getIntegerOption("NegativeTrust").get();
2336                 }
2337
2338                 /**
2339                  * Validates the negative trust.
2340                  *
2341                  * @param negativeTrust
2342                  *            The negative trust to validate
2343                  * @return {@code true} if the negative trust was valid, {@code false}
2344                  *         otherwise
2345                  */
2346                 public boolean validateNegativeTrust(Integer negativeTrust) {
2347                         return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2348                 }
2349
2350                 /**
2351                  * Sets the negative trust.
2352                  *
2353                  * @param negativeTrust
2354                  *            The negative trust, or {@code null} to restore it to the
2355                  *            default value
2356                  * @return The preferences
2357                  */
2358                 public Preferences setNegativeTrust(Integer negativeTrust) {
2359                         options.getIntegerOption("NegativeTrust").set(negativeTrust);
2360                         return this;
2361                 }
2362
2363                 /**
2364                  * Returns the trust comment. This is the comment that is set in the web
2365                  * of trust when a trust value is assigned to an identity.
2366                  *
2367                  * @return The trust comment
2368                  */
2369                 public String getTrustComment() {
2370                         return options.getStringOption("TrustComment").get();
2371                 }
2372
2373                 /**
2374                  * Sets the trust comment.
2375                  *
2376                  * @param trustComment
2377                  *            The trust comment, or {@code null} to restore it to the
2378                  *            default value
2379                  * @return This preferences
2380                  */
2381                 public Preferences setTrustComment(String trustComment) {
2382                         options.getStringOption("TrustComment").set(trustComment);
2383                         return this;
2384                 }
2385
2386                 /**
2387                  * Returns whether the {@link FcpInterface FCP interface} is currently
2388                  * active.
2389                  *
2390                  * @see FcpInterface#setActive(boolean)
2391                  * @return {@code true} if the FCP interface is currently active,
2392                  *         {@code false} otherwise
2393                  */
2394                 public boolean isFcpInterfaceActive() {
2395                         return options.getBooleanOption("ActivateFcpInterface").get();
2396                 }
2397
2398                 /**
2399                  * Sets whether the {@link FcpInterface FCP interface} is currently
2400                  * active.
2401                  *
2402                  * @see FcpInterface#setActive(boolean)
2403                  * @param fcpInterfaceActive
2404                  *            {@code true} to activate the FCP interface, {@code false}
2405                  *            to deactivate the FCP interface
2406                  * @return This preferences object
2407                  */
2408                 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2409                         options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2410                         return this;
2411                 }
2412
2413                 /**
2414                  * Returns the action level for which full access to the FCP interface
2415                  * is required.
2416                  *
2417                  * @return The action level for which full access to the FCP interface
2418                  *         is required
2419                  */
2420                 public FullAccessRequired getFcpFullAccessRequired() {
2421                         return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2422                 }
2423
2424                 /**
2425                  * Sets the action level for which full access to the FCP interface is
2426                  * required
2427                  *
2428                  * @param fcpFullAccessRequired
2429                  *            The action level
2430                  * @return This preferences
2431                  */
2432                 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2433                         options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2434                         return this;
2435                 }
2436
2437                 /**
2438                  * Returns whether Sone should clear its settings on the next restart.
2439                  * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2440                  * to return {@code true} as well!
2441                  *
2442                  * @return {@code true} if Sone should clear its settings on the next
2443                  *         restart, {@code false} otherwise
2444                  */
2445                 public boolean isClearOnNextRestart() {
2446                         return options.getBooleanOption("ClearOnNextRestart").get();
2447                 }
2448
2449                 /**
2450                  * Sets whether Sone will clear its settings on the next restart.
2451                  *
2452                  * @param clearOnNextRestart
2453                  *            {@code true} if Sone should clear its settings on the next
2454                  *            restart, {@code false} otherwise
2455                  * @return This preferences
2456                  */
2457                 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2458                         options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2459                         return this;
2460                 }
2461
2462                 /**
2463                  * Returns whether Sone should really clear its settings on next
2464                  * restart. This is a confirmation option that needs to be set in
2465                  * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2466                  * settings on the next restart.
2467                  *
2468                  * @return {@code true} if Sone should really clear its settings on the
2469                  *         next restart, {@code false} otherwise
2470                  */
2471                 public boolean isReallyClearOnNextRestart() {
2472                         return options.getBooleanOption("ReallyClearOnNextRestart").get();
2473                 }
2474
2475                 /**
2476                  * Sets whether Sone should really clear its settings on the next
2477                  * restart.
2478                  *
2479                  * @param reallyClearOnNextRestart
2480                  *            {@code true} if Sone should really clear its settings on
2481                  *            the next restart, {@code false} otherwise
2482                  * @return This preferences
2483                  */
2484                 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2485                         options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);
2486                         return this;
2487                 }
2488
2489         }
2490
2491 }