2 * Sone - Core.java - Copyright © 2010 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.core;
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;
27 import java.util.Map.Entry;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sone.core.Options.DefaultOption;
33 import net.pterodactylus.sone.core.Options.Option;
34 import net.pterodactylus.sone.core.Options.OptionWatcher;
35 import net.pterodactylus.sone.data.Client;
36 import net.pterodactylus.sone.data.Post;
37 import net.pterodactylus.sone.data.Profile;
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.main.SonePlugin;
45 import net.pterodactylus.util.config.Configuration;
46 import net.pterodactylus.util.config.ConfigurationException;
47 import net.pterodactylus.util.logging.Logging;
48 import net.pterodactylus.util.number.Numbers;
49 import net.pterodactylus.util.version.Version;
50 import freenet.keys.FreenetURI;
55 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57 public class Core implements IdentityListener, UpdateListener {
60 * Enumeration for the possible states of a {@link Sone}.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public enum SoneStatus {
66 /** The Sone is unknown, i.e. not yet downloaded. */
69 /** The Sone is idle, i.e. not being downloaded or inserted. */
72 /** The Sone is currently being inserted. */
75 /** The Sone is currently being downloaded. */
80 private static final Logger logger = Logging.getLogger(Core.class);
83 private final Options options = new Options();
85 /** The core listener manager. */
86 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
88 /** The configuration. */
89 private Configuration configuration;
91 /** Whether we’re currently saving the configuration. */
92 private boolean storingConfiguration = false;
94 /** The identity manager. */
95 private final IdentityManager identityManager;
97 /** Interface to freenet. */
98 private final FreenetInterface freenetInterface;
100 /** The Sone downloader. */
101 private final SoneDownloader soneDownloader;
103 /** The update checker. */
104 private final UpdateChecker updateChecker;
106 /** Whether the core has been stopped. */
107 private volatile boolean stopped;
109 /** The Sones’ statuses. */
110 /* synchronize access on itself. */
111 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
113 /** Locked local Sones. */
114 /* synchronize on itself. */
115 private final Set<Sone> lockedSones = new HashSet<Sone>();
117 /** Sone inserters. */
118 /* synchronize access on this on localSones. */
119 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
121 /** All local Sones. */
122 /* synchronize access on this on itself. */
123 private Map<String, Sone> localSones = new HashMap<String, Sone>();
125 /** All remote Sones. */
126 /* synchronize access on this on itself. */
127 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
129 /** All new Sones. */
130 private Set<String> newSones = new HashSet<String>();
132 /** All known Sones. */
133 /* synchronize access on {@link #newSones}. */
134 private Set<String> knownSones = new HashSet<String>();
137 private Map<String, Post> posts = new HashMap<String, Post>();
139 /** All new posts. */
140 private Set<String> newPosts = new HashSet<String>();
142 /** All known posts. */
143 /* synchronize access on {@link #newPosts}. */
144 private Set<String> knownPosts = new HashSet<String>();
147 private Map<String, Reply> replies = new HashMap<String, Reply>();
149 /** All new replies. */
150 private Set<String> newReplies = new HashSet<String>();
152 /** All known replies. */
153 private Set<String> knownReplies = new HashSet<String>();
156 * Creates a new core.
158 * @param configuration
159 * The configuration of the core
160 * @param freenetInterface
161 * The freenet interface
162 * @param identityManager
163 * The identity manager
165 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
166 this.configuration = configuration;
167 this.freenetInterface = freenetInterface;
168 this.identityManager = identityManager;
169 this.soneDownloader = new SoneDownloader(this, freenetInterface);
170 this.updateChecker = new UpdateChecker(freenetInterface);
174 // LISTENER MANAGEMENT
178 * Adds a new core listener.
180 * @param coreListener
181 * The listener to add
183 public void addCoreListener(CoreListener coreListener) {
184 coreListenerManager.addListener(coreListener);
188 * Removes a core listener.
190 * @param coreListener
191 * The listener to remove
193 public void removeCoreListener(CoreListener coreListener) {
194 coreListenerManager.removeListener(coreListener);
202 * Sets the configuration to use. This will automatically save the current
203 * configuration to the given configuration.
205 * @param configuration
206 * The new configuration to use
208 public void setConfiguration(Configuration configuration) {
209 this.configuration = configuration;
214 * Returns the options used by the core.
216 * @return The options of the core
218 public Options getOptions() {
223 * Returns whether the “Sone rescue mode” is currently activated.
225 * @return {@code true} if the “Sone rescue mode” is currently activated,
226 * {@code false} if it is not
228 public boolean isSoneRescueMode() {
229 return options.getBooleanOption("SoneRescueMode").get();
233 * Returns the identity manager used by the core.
235 * @return The identity manager
237 public IdentityManager getIdentityManager() {
238 return identityManager;
242 * Returns the update checker.
244 * @return The update checker
246 public UpdateChecker getUpdateChecker() {
247 return updateChecker;
251 * Returns the status of the given Sone.
254 * The Sone to get the status for
255 * @return The status of the Sone
257 public SoneStatus getSoneStatus(Sone sone) {
258 synchronized (soneStatuses) {
259 return soneStatuses.get(sone);
264 * Sets the status of the given Sone.
267 * The Sone to set the status of
271 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
272 synchronized (soneStatuses) {
273 soneStatuses.put(sone, soneStatus);
278 * Returns whether the given Sone is currently locked.
282 * @return {@code true} if the Sone is locked, {@code false} if it is not
284 public boolean isLocked(Sone sone) {
285 synchronized (lockedSones) {
286 return lockedSones.contains(sone);
291 * Returns all Sones, remote and local.
295 public Set<Sone> getSones() {
296 Set<Sone> allSones = new HashSet<Sone>();
297 allSones.addAll(getLocalSones());
298 allSones.addAll(getRemoteSones());
303 * Returns the Sone with the given ID, regardless whether it’s local or
307 * The ID of the Sone to get
308 * @return The Sone with the given ID, or {@code null} if there is no such
311 public Sone getSone(String id) {
312 return getSone(id, true);
316 * Returns the Sone with the given ID, regardless whether it’s local or
320 * The ID of the Sone to get
322 * {@code true} to create a new Sone if none exists,
323 * {@code false} to return {@code null} if a Sone with the given
325 * @return The Sone with the given ID, or {@code null} if there is no such
328 public Sone getSone(String id, boolean create) {
329 if (isLocalSone(id)) {
330 return getLocalSone(id);
332 return getRemoteSone(id, create);
336 * Checks whether the core knows a Sone with the given ID.
340 * @return {@code true} if there is a Sone with the given ID, {@code false}
343 public boolean hasSone(String id) {
344 return isLocalSone(id) || isRemoteSone(id);
348 * Returns whether the given Sone is a local Sone.
351 * The Sone to check for its locality
352 * @return {@code true} if the given Sone is local, {@code false} otherwise
354 public boolean isLocalSone(Sone sone) {
355 synchronized (localSones) {
356 return localSones.containsKey(sone.getId());
361 * Returns whether the given ID is the ID of a local Sone.
364 * The Sone ID to check for its locality
365 * @return {@code true} if the given ID is a local Sone, {@code false}
368 public boolean isLocalSone(String id) {
369 synchronized (localSones) {
370 return localSones.containsKey(id);
375 * Returns all local Sones.
377 * @return All local Sones
379 public Set<Sone> getLocalSones() {
380 synchronized (localSones) {
381 return new HashSet<Sone>(localSones.values());
386 * Returns the local Sone with the given ID.
389 * The ID of the Sone to get
390 * @return The Sone with the given ID
392 public Sone getLocalSone(String id) {
393 return getLocalSone(id, true);
397 * Returns the local Sone with the given ID, optionally creating a new Sone.
402 * {@code true} to create a new Sone if none exists,
403 * {@code false} to return null if none exists
404 * @return The Sone with the given ID, or {@code null}
406 public Sone getLocalSone(String id, boolean create) {
407 synchronized (localSones) {
408 Sone sone = localSones.get(id);
409 if ((sone == null) && create) {
411 localSones.put(id, sone);
418 * Returns all remote Sones.
420 * @return All remote Sones
422 public Set<Sone> getRemoteSones() {
423 synchronized (remoteSones) {
424 return new HashSet<Sone>(remoteSones.values());
429 * Returns the remote Sone with the given ID.
432 * The ID of the remote Sone to get
433 * @return The Sone with the given ID
435 public Sone getRemoteSone(String id) {
436 return getRemoteSone(id, true);
440 * Returns the remote Sone with the given ID.
443 * The ID of the remote Sone to get
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
449 public Sone getRemoteSone(String id, boolean create) {
450 synchronized (remoteSones) {
451 Sone sone = remoteSones.get(id);
452 if ((sone == null) && create) {
454 remoteSones.put(id, sone);
461 * Returns whether the given Sone is a remote Sone.
465 * @return {@code true} if the given Sone is a remote Sone, {@code false}
468 public boolean isRemoteSone(Sone sone) {
469 synchronized (remoteSones) {
470 return remoteSones.containsKey(sone.getId());
475 * Returns whether the Sone with the given ID is a remote Sone.
478 * The ID of the Sone to check
479 * @return {@code true} if the Sone with the given ID is a remote Sone,
480 * {@code false} otherwise
482 public boolean isRemoteSone(String id) {
483 synchronized (remoteSones) {
484 return remoteSones.containsKey(id);
489 * Returns whether the given Sone is a new Sone. After this check, the Sone
490 * is marked as known, i.e. a second call with the same parameters will
491 * always yield {@code false}.
494 * The sone to check for
495 * @return {@code true} if the given Sone is new, false otherwise
497 public boolean isNewSone(Sone sone) {
498 synchronized (newSones) {
499 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
500 knownSones.add(sone.getId());
502 coreListenerManager.fireMarkSoneKnown(sone);
509 * Returns whether the given Sone has been modified.
512 * The Sone to check for modifications
513 * @return {@code true} if a modification has been detected in the Sone,
514 * {@code false} otherwise
516 public boolean isModifiedSone(Sone sone) {
517 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
521 * Returns the post with the given ID.
524 * The ID of the post to get
525 * @return The post, or {@code null} if there is no such post
527 public Post getPost(String postId) {
528 return getPost(postId, true);
532 * Returns the post with the given ID, optionally creating a new post.
535 * The ID of the post to get
537 * {@code true} it create a new post if no post with the given ID
538 * exists, {@code false} to return {@code null}
539 * @return The post, or {@code null} if there is no such post
541 public Post getPost(String postId, boolean create) {
542 synchronized (posts) {
543 Post post = posts.get(postId);
544 if ((post == null) && create) {
545 post = new Post(postId);
546 posts.put(postId, post);
553 * Returns whether the given post ID is new. After this method returns it is
554 * marked a known post ID.
558 * @return {@code true} if the post is considered to be new, {@code false}
561 public boolean isNewPost(String postId) {
562 return isNewPost(postId, true);
566 * Returns whether the given post ID is new. If {@code markAsKnown} is
567 * {@code true} then after this method returns the post ID is marked a known
573 * {@code true} to mark the post ID as known, {@code false} to
574 * not to mark it as known
575 * @return {@code true} if the post is considered to be new, {@code false}
578 public boolean isNewPost(String postId, boolean markAsKnown) {
579 synchronized (newPosts) {
580 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
582 Post post = getPost(postId, false);
592 * Returns the reply with the given ID. If there is no reply with the given
593 * ID yet, a new one is created.
596 * The ID of the reply to get
599 public Reply getReply(String replyId) {
600 return getReply(replyId, true);
604 * Returns the reply with the given ID. If there is no reply with the given
605 * ID yet, a new one is created, unless {@code create} is false in which
606 * case {@code null} is returned.
609 * The ID of the reply to get
611 * {@code true} to always return a {@link Reply}, {@code false}
612 * to return {@code null} if no reply can be found
613 * @return The reply, or {@code null} if there is no such reply
615 public Reply getReply(String replyId, boolean create) {
616 synchronized (replies) {
617 Reply reply = replies.get(replyId);
618 if (create && (reply == null)) {
619 reply = new Reply(replyId);
620 replies.put(replyId, reply);
627 * Returns all replies for the given post, order ascending by time.
630 * The post to get all replies for
631 * @return All replies for the given post
633 public List<Reply> getReplies(Post post) {
634 Set<Sone> sones = getSones();
635 List<Reply> replies = new ArrayList<Reply>();
636 for (Sone sone : sones) {
637 for (Reply reply : sone.getReplies()) {
638 if (reply.getPost().equals(post)) {
643 Collections.sort(replies, Reply.TIME_COMPARATOR);
648 * Returns whether the reply with the given ID is new.
651 * The ID of the reply to check
652 * @return {@code true} if the reply is considered to be new, {@code false}
655 public boolean isNewReply(String replyId) {
656 return isNewReply(replyId, true);
660 * Returns whether the reply with the given ID is new.
663 * The ID of the reply to check
665 * {@code true} to mark the reply as known, {@code false} to not
666 * to mark it as known
667 * @return {@code true} if the reply is considered to be new, {@code false}
670 public boolean isNewReply(String replyId, boolean markAsKnown) {
671 synchronized (newReplies) {
672 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
674 Reply reply = getReply(replyId, false);
676 markReplyKnown(reply);
684 * Returns all Sones that have liked the given post.
687 * The post to get the liking Sones for
688 * @return The Sones that like the given post
690 public Set<Sone> getLikes(Post post) {
691 Set<Sone> sones = new HashSet<Sone>();
692 for (Sone sone : getSones()) {
693 if (sone.getLikedPostIds().contains(post.getId())) {
701 * Returns all Sones that have liked the given reply.
704 * The reply to get the liking Sones for
705 * @return The Sones that like the given reply
707 public Set<Sone> getLikes(Reply reply) {
708 Set<Sone> sones = new HashSet<Sone>();
709 for (Sone sone : getSones()) {
710 if (sone.getLikedReplyIds().contains(reply.getId())) {
722 * Locks the given Sone. A locked Sone will not be inserted by
723 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
729 public void lockSone(Sone sone) {
730 synchronized (lockedSones) {
731 if (lockedSones.add(sone)) {
732 coreListenerManager.fireSoneLocked(sone);
738 * Unlocks the given Sone.
740 * @see #lockSone(Sone)
744 public void unlockSone(Sone sone) {
745 synchronized (lockedSones) {
746 if (lockedSones.remove(sone)) {
747 coreListenerManager.fireSoneUnlocked(sone);
753 * Adds a local Sone from the given ID which has to be the ID of an own
757 * The ID of an own identity to add a Sone for
758 * @return The added (or already existing) Sone
760 public Sone addLocalSone(String id) {
761 synchronized (localSones) {
762 if (localSones.containsKey(id)) {
763 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
764 return localSones.get(id);
766 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
767 if (ownIdentity == null) {
768 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
771 return addLocalSone(ownIdentity);
776 * Adds a local Sone from the given own identity.
779 * The own identity to create a Sone from
780 * @return The added (or already existing) Sone
782 public Sone addLocalSone(OwnIdentity ownIdentity) {
783 if (ownIdentity == null) {
784 logger.log(Level.WARNING, "Given OwnIdentity is null!");
787 synchronized (localSones) {
790 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
791 } catch (MalformedURLException mue1) {
792 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
795 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
796 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
797 /* TODO - load posts ’n stuff */
798 localSones.put(ownIdentity.getId(), sone);
799 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
800 soneInserters.put(sone, soneInserter);
801 setSoneStatus(sone, SoneStatus.idle);
803 if (!isSoneRescueMode()) {
804 soneInserter.start();
806 new Thread(new Runnable() {
809 @SuppressWarnings("synthetic-access")
811 if (!isSoneRescueMode()) {
812 soneDownloader.fetchSone(sone);
815 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
816 coreListenerManager.fireRescuingSone(sone);
818 long edition = sone.getLatestEdition();
819 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
820 logger.log(Level.FINE, "Downloading edition " + edition + "…");
821 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
824 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
826 coreListenerManager.fireRescuedSone(sone);
827 soneInserter.start();
830 }, "Sone Downloader").start();
836 * Creates a new Sone for the given own identity.
839 * The own identity to create a Sone for
840 * @return The created Sone
842 public Sone createSone(OwnIdentity ownIdentity) {
843 identityManager.addContext(ownIdentity, "Sone");
844 Sone sone = addLocalSone(ownIdentity);
849 * Adds the Sone of the given identity.
852 * The identity whose Sone to add
853 * @return The added or already existing Sone
855 public Sone addRemoteSone(Identity identity) {
856 if (identity == null) {
857 logger.log(Level.WARNING, "Given Identity is null!");
860 synchronized (remoteSones) {
861 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
862 boolean newSone = sone.getRequestUri() == null;
863 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
864 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
866 synchronized (newSones) {
867 newSone = !knownSones.contains(sone.getId());
869 newSones.add(sone.getId());
873 coreListenerManager.fireNewSoneFound(sone);
876 remoteSones.put(identity.getId(), sone);
877 soneDownloader.addSone(sone);
878 setSoneStatus(sone, SoneStatus.unknown);
879 new Thread(new Runnable() {
882 @SuppressWarnings("synthetic-access")
884 soneDownloader.fetchSone(sone);
887 }, "Sone Downloader").start();
893 * Updates the stores Sone with the given Sone.
898 public void updateSone(Sone sone) {
899 if (hasSone(sone.getId())) {
900 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
901 Sone storedSone = getSone(sone.getId());
902 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
903 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
906 synchronized (posts) {
907 if (!soneRescueMode) {
908 for (Post post : storedSone.getPosts()) {
909 posts.remove(post.getId());
910 if (!sone.getPosts().contains(post)) {
911 coreListenerManager.firePostRemoved(post);
915 synchronized (newPosts) {
916 for (Post post : sone.getPosts()) {
917 post.setSone(getSone(post.getSone().getId()));
918 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
919 newPosts.add(post.getId());
920 coreListenerManager.fireNewPostFound(post);
922 posts.put(post.getId(), post);
926 synchronized (replies) {
927 if (!soneRescueMode) {
928 for (Reply reply : storedSone.getReplies()) {
929 replies.remove(reply.getId());
930 if (!sone.getReplies().contains(reply)) {
931 coreListenerManager.fireReplyRemoved(reply);
935 synchronized (newReplies) {
936 for (Reply reply : sone.getReplies()) {
937 reply.setSone(getSone(reply.getSone().getId()));
938 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
939 newReplies.add(reply.getId());
940 coreListenerManager.fireNewReplyFound(reply);
942 replies.put(reply.getId(), reply);
946 synchronized (storedSone) {
947 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
948 storedSone.setTime(sone.getTime());
950 storedSone.setClient(sone.getClient());
951 storedSone.setProfile(sone.getProfile());
952 if (soneRescueMode) {
953 for (Post post : sone.getPosts()) {
954 storedSone.addPost(post);
956 for (Reply reply : sone.getReplies()) {
957 storedSone.addReply(reply);
959 for (String likedPostId : sone.getLikedPostIds()) {
960 storedSone.addLikedPostId(likedPostId);
962 for (String likedReplyId : sone.getLikedReplyIds()) {
963 storedSone.addLikedReplyId(likedReplyId);
966 storedSone.setPosts(sone.getPosts());
967 storedSone.setReplies(sone.getReplies());
968 storedSone.setLikePostIds(sone.getLikedPostIds());
969 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
971 storedSone.setLatestEdition(sone.getLatestEdition());
977 * Deletes the given Sone. This will remove the Sone from the
978 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
979 * and remove the context from its identity.
984 public void deleteSone(Sone sone) {
985 if (!(sone.getIdentity() instanceof OwnIdentity)) {
986 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
989 synchronized (localSones) {
990 if (!localSones.containsKey(sone.getId())) {
991 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
994 localSones.remove(sone.getId());
995 soneInserters.remove(sone).stop();
997 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
998 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1000 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1001 } catch (ConfigurationException ce1) {
1002 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1007 * Loads and updates the given Sone from the configuration. If any error is
1008 * encountered, loading is aborted and the given Sone is not changed.
1011 * The Sone to load and update
1013 public void loadSone(Sone sone) {
1014 if (!isLocalSone(sone)) {
1015 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1020 String sonePrefix = "Sone/" + sone.getId();
1021 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1022 if (soneTime == null) {
1023 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1026 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1029 Profile profile = new Profile();
1030 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1031 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1032 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1033 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1034 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1035 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1037 /* load profile fields. */
1039 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFieldNames().size();
1040 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1041 if (fieldName == null) {
1044 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue(null);
1045 if (fieldValue == null) {
1046 logger.log(Level.WARNING, "Invalid profile field found, aborting load!");
1049 profile.addField(fieldName);
1050 profile.setField(fieldName, fieldValue);
1054 Set<Post> posts = new HashSet<Post>();
1056 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1057 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1058 if (postId == null) {
1061 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1062 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1063 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1064 if ((postTime == 0) || (postText == null)) {
1065 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1068 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1069 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1070 post.setRecipient(getSone(postRecipientId));
1076 Set<Reply> replies = new HashSet<Reply>();
1078 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1079 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1080 if (replyId == null) {
1083 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1084 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1085 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1086 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1087 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1090 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1093 /* load post likes. */
1094 Set<String> likedPostIds = new HashSet<String>();
1096 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1097 if (likedPostId == null) {
1100 likedPostIds.add(likedPostId);
1103 /* load reply likes. */
1104 Set<String> likedReplyIds = new HashSet<String>();
1106 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1107 if (likedReplyId == null) {
1110 likedReplyIds.add(likedReplyId);
1114 Set<String> friends = new HashSet<String>();
1116 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1117 if (friendId == null) {
1120 friends.add(friendId);
1123 /* if we’re still here, Sone was loaded successfully. */
1124 synchronized (sone) {
1125 sone.setTime(soneTime);
1126 sone.setProfile(profile);
1127 sone.setPosts(posts);
1128 sone.setReplies(replies);
1129 sone.setLikePostIds(likedPostIds);
1130 sone.setLikeReplyIds(likedReplyIds);
1131 sone.setFriends(friends);
1132 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1134 synchronized (newSones) {
1135 for (String friend : friends) {
1136 knownSones.add(friend);
1139 synchronized (newPosts) {
1140 for (Post post : posts) {
1141 knownPosts.add(post.getId());
1144 synchronized (newReplies) {
1145 for (Reply reply : replies) {
1146 knownReplies.add(reply.getId());
1152 * Saves the given Sone. This will persist all local settings for the given
1153 * Sone, such as the friends list and similar, private options.
1158 public synchronized void saveSone(Sone sone) {
1159 if (!isLocalSone(sone)) {
1160 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1163 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1164 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1168 logger.log(Level.INFO, "Saving Sone: %s", sone);
1169 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1171 /* save Sone into configuration. */
1172 String sonePrefix = "Sone/" + sone.getId();
1173 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1174 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1177 Profile profile = sone.getProfile();
1178 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1179 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1180 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1181 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1182 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1183 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1185 /* save profile fields. */
1186 int fieldCounter = 0;
1187 for (Entry<String, String> profileField : profile.getFields().entrySet()) {
1188 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1189 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getKey());
1190 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1192 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1195 int postCounter = 0;
1196 for (Post post : sone.getPosts()) {
1197 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1198 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1199 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1200 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1201 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1203 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1206 int replyCounter = 0;
1207 for (Reply reply : sone.getReplies()) {
1208 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1209 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1210 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1211 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1212 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1214 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1216 /* save post likes. */
1217 int postLikeCounter = 0;
1218 for (String postId : sone.getLikedPostIds()) {
1219 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1221 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1223 /* save reply likes. */
1224 int replyLikeCounter = 0;
1225 for (String replyId : sone.getLikedReplyIds()) {
1226 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1228 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1231 int friendCounter = 0;
1232 for (String friendId : sone.getFriends()) {
1233 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1235 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1237 configuration.save();
1238 logger.log(Level.INFO, "Sone %s saved.", sone);
1239 } catch (ConfigurationException ce1) {
1240 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1245 * Creates a new post.
1248 * The Sone that creates the post
1250 * The text of the post
1251 * @return The created post
1253 public Post createPost(Sone sone, String text) {
1254 return createPost(sone, System.currentTimeMillis(), text);
1258 * Creates a new post.
1261 * The Sone that creates the post
1263 * The time of the post
1265 * The text of the post
1266 * @return The created post
1268 public Post createPost(Sone sone, long time, String text) {
1269 return createPost(sone, null, time, text);
1273 * Creates a new post.
1276 * The Sone that creates the post
1278 * The recipient Sone, or {@code null} if this post does not have
1281 * The text of the post
1282 * @return The created post
1284 public Post createPost(Sone sone, Sone recipient, String text) {
1285 return createPost(sone, recipient, System.currentTimeMillis(), text);
1289 * Creates a new post.
1292 * The Sone that creates the post
1294 * The recipient Sone, or {@code null} if this post does not have
1297 * The time of the post
1299 * The text of the post
1300 * @return The created post
1302 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1303 if (!isLocalSone(sone)) {
1304 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1307 Post post = new Post(sone, time, text);
1308 if (recipient != null) {
1309 post.setRecipient(recipient);
1311 synchronized (posts) {
1312 posts.put(post.getId(), post);
1314 synchronized (newPosts) {
1315 knownPosts.add(post.getId());
1323 * Deletes the given post.
1326 * The post to delete
1328 public void deletePost(Post post) {
1329 if (!isLocalSone(post.getSone())) {
1330 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1333 post.getSone().removePost(post);
1334 synchronized (posts) {
1335 posts.remove(post.getId());
1337 saveSone(post.getSone());
1341 * Marks the given post as known, if it is currently a new post (according
1342 * to {@link #isNewPost(String)}).
1345 * The post to mark as known
1347 public void markPostKnown(Post post) {
1348 synchronized (newPosts) {
1349 if (newPosts.remove(post.getId())) {
1350 knownPosts.add(post.getId());
1351 coreListenerManager.fireMarkPostKnown(post);
1352 saveConfiguration();
1358 * Creates a new reply.
1361 * The Sone that creates the reply
1363 * The post that this reply refers to
1365 * The text of the reply
1366 * @return The created reply
1368 public Reply createReply(Sone sone, Post post, String text) {
1369 return createReply(sone, post, System.currentTimeMillis(), text);
1373 * Creates a new reply.
1376 * The Sone that creates the reply
1378 * The post that this reply refers to
1380 * The time of the reply
1382 * The text of the reply
1383 * @return The created reply
1385 public Reply createReply(Sone sone, Post post, long time, String text) {
1386 if (!isLocalSone(sone)) {
1387 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1390 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1391 synchronized (replies) {
1392 replies.put(reply.getId(), reply);
1394 synchronized (newReplies) {
1395 knownReplies.add(reply.getId());
1397 sone.addReply(reply);
1403 * Deletes the given reply.
1406 * The reply to delete
1408 public void deleteReply(Reply reply) {
1409 Sone sone = reply.getSone();
1410 if (!isLocalSone(sone)) {
1411 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1414 synchronized (replies) {
1415 replies.remove(reply.getId());
1417 sone.removeReply(reply);
1422 * Marks the given reply as known, if it is currently a new reply (according
1423 * to {@link #isNewReply(String)}).
1426 * The reply to mark as known
1428 public void markReplyKnown(Reply reply) {
1429 synchronized (newReplies) {
1430 if (newReplies.remove(reply.getId())) {
1431 knownReplies.add(reply.getId());
1432 coreListenerManager.fireMarkReplyKnown(reply);
1433 saveConfiguration();
1441 public void start() {
1442 loadConfiguration();
1443 updateChecker.addUpdateListener(this);
1444 updateChecker.start();
1450 public void stop() {
1451 synchronized (localSones) {
1452 for (SoneInserter soneInserter : soneInserters.values()) {
1453 soneInserter.stop();
1456 updateChecker.stop();
1457 updateChecker.removeUpdateListener(this);
1458 soneDownloader.stop();
1459 saveConfiguration();
1464 * Saves the current options.
1466 public void saveConfiguration() {
1467 synchronized (configuration) {
1468 if (storingConfiguration) {
1469 logger.log(Level.FINE, "Already storing configuration…");
1472 storingConfiguration = true;
1475 /* store the options first. */
1477 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1478 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1479 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1480 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1481 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1483 /* save known Sones. */
1484 int soneCounter = 0;
1485 synchronized (newSones) {
1486 for (String knownSoneId : knownSones) {
1487 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1489 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1492 /* save known posts. */
1493 int postCounter = 0;
1494 synchronized (newPosts) {
1495 for (String knownPostId : knownPosts) {
1496 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1498 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1501 /* save known replies. */
1502 int replyCounter = 0;
1503 synchronized (newReplies) {
1504 for (String knownReplyId : knownReplies) {
1505 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1507 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1511 configuration.save();
1513 } catch (ConfigurationException ce1) {
1514 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1516 synchronized (configuration) {
1517 storingConfiguration = false;
1527 * Loads the configuration.
1529 @SuppressWarnings("unchecked")
1530 private void loadConfiguration() {
1531 /* create options. */
1532 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1535 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1536 SoneInserter.setInsertionDelay(newValue);
1540 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1541 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1542 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1544 /* read options from configuration. */
1545 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1546 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1547 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1548 options.getBooleanOption("ClearOnNextRestart").set(null);
1549 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1550 if (clearConfiguration) {
1551 /* stop loading the configuration. */
1555 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1556 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1558 /* load known Sones. */
1559 int soneCounter = 0;
1561 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1562 if (knownSoneId == null) {
1565 synchronized (newSones) {
1566 knownSones.add(knownSoneId);
1570 /* load known posts. */
1571 int postCounter = 0;
1573 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1574 if (knownPostId == null) {
1577 synchronized (newPosts) {
1578 knownPosts.add(knownPostId);
1582 /* load known replies. */
1583 int replyCounter = 0;
1585 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1586 if (knownReplyId == null) {
1589 synchronized (newReplies) {
1590 knownReplies.add(knownReplyId);
1597 * Generate a Sone URI from the given URI and latest edition.
1600 * The URI to derive the Sone URI from
1601 * @return The derived URI
1603 private FreenetURI getSoneUri(String uriString) {
1605 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1607 } catch (MalformedURLException mue1) {
1608 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1614 // INTERFACE IdentityListener
1621 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1622 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1623 if (ownIdentity.hasContext("Sone")) {
1624 addLocalSone(ownIdentity);
1632 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1633 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1640 public void identityAdded(Identity identity) {
1641 logger.log(Level.FINEST, "Adding Identity: " + identity);
1642 addRemoteSone(identity);
1649 public void identityUpdated(final Identity identity) {
1650 new Thread(new Runnable() {
1653 @SuppressWarnings("synthetic-access")
1655 Sone sone = getRemoteSone(identity.getId());
1656 soneDownloader.fetchSone(sone);
1665 public void identityRemoved(Identity identity) {
1670 // INTERFACE UpdateListener
1677 public void updateFound(Version version, long releaseTime) {
1678 coreListenerManager.fireUpdateFound(version, releaseTime);