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