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