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;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
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.Album;
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>();
155 /** All known albums. */
156 private Map<String, Album> albums = new HashMap<String, Album>();
159 * Creates a new core.
161 * @param configuration
162 * The configuration of the core
163 * @param freenetInterface
164 * The freenet interface
165 * @param identityManager
166 * The identity manager
168 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
169 this.configuration = configuration;
170 this.freenetInterface = freenetInterface;
171 this.identityManager = identityManager;
172 this.soneDownloader = new SoneDownloader(this, freenetInterface);
173 this.updateChecker = new UpdateChecker(freenetInterface);
177 // LISTENER MANAGEMENT
181 * Adds a new core listener.
183 * @param coreListener
184 * The listener to add
186 public void addCoreListener(CoreListener coreListener) {
187 coreListenerManager.addListener(coreListener);
191 * Removes a core listener.
193 * @param coreListener
194 * The listener to remove
196 public void removeCoreListener(CoreListener coreListener) {
197 coreListenerManager.removeListener(coreListener);
205 * Sets the configuration to use. This will automatically save the current
206 * configuration to the given configuration.
208 * @param configuration
209 * The new configuration to use
211 public void setConfiguration(Configuration configuration) {
212 this.configuration = configuration;
217 * Returns the options used by the core.
219 * @return The options of the core
221 public Options getOptions() {
226 * Returns whether the “Sone rescue mode” is currently activated.
228 * @return {@code true} if the “Sone rescue mode” is currently activated,
229 * {@code false} if it is not
231 public boolean isSoneRescueMode() {
232 return options.getBooleanOption("SoneRescueMode").get();
236 * Returns the identity manager used by the core.
238 * @return The identity manager
240 public IdentityManager getIdentityManager() {
241 return identityManager;
245 * Returns the update checker.
247 * @return The update checker
249 public UpdateChecker getUpdateChecker() {
250 return updateChecker;
254 * Returns the status of the given Sone.
257 * The Sone to get the status for
258 * @return The status of the Sone
260 public SoneStatus getSoneStatus(Sone sone) {
261 synchronized (soneStatuses) {
262 return soneStatuses.get(sone);
267 * Sets the status of the given Sone.
270 * The Sone to set the status of
274 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
275 synchronized (soneStatuses) {
276 soneStatuses.put(sone, soneStatus);
281 * Returns whether the given Sone is currently locked.
285 * @return {@code true} if the Sone is locked, {@code false} if it is not
287 public boolean isLocked(Sone sone) {
288 synchronized (lockedSones) {
289 return lockedSones.contains(sone);
294 * Returns all Sones, remote and local.
298 public Set<Sone> getSones() {
299 Set<Sone> allSones = new HashSet<Sone>();
300 allSones.addAll(getLocalSones());
301 allSones.addAll(getRemoteSones());
306 * Returns the Sone with the given ID, regardless whether it’s local or
310 * The ID of the Sone to get
311 * @return The Sone with the given ID, or {@code null} if there is no such
314 public Sone getSone(String id) {
315 return getSone(id, true);
319 * Returns the Sone with the given ID, regardless whether it’s local or
323 * The ID of the Sone to get
325 * {@code true} to create a new Sone if none exists,
326 * {@code false} to return {@code null} if a Sone with the given
328 * @return The Sone with the given ID, or {@code null} if there is no such
331 public Sone getSone(String id, boolean create) {
332 if (isLocalSone(id)) {
333 return getLocalSone(id);
335 return getRemoteSone(id, create);
339 * Checks whether the core knows a Sone with the given ID.
343 * @return {@code true} if there is a Sone with the given ID, {@code false}
346 public boolean hasSone(String id) {
347 return isLocalSone(id) || isRemoteSone(id);
351 * Returns whether the given Sone is a local Sone.
354 * The Sone to check for its locality
355 * @return {@code true} if the given Sone is local, {@code false} otherwise
357 public boolean isLocalSone(Sone sone) {
358 synchronized (localSones) {
359 return localSones.containsKey(sone.getId());
364 * Returns whether the given ID is the ID of a local Sone.
367 * The Sone ID to check for its locality
368 * @return {@code true} if the given ID is a local Sone, {@code false}
371 public boolean isLocalSone(String id) {
372 synchronized (localSones) {
373 return localSones.containsKey(id);
378 * Returns all local Sones.
380 * @return All local Sones
382 public Set<Sone> getLocalSones() {
383 synchronized (localSones) {
384 return new HashSet<Sone>(localSones.values());
389 * Returns the local Sone with the given ID.
392 * The ID of the Sone to get
393 * @return The Sone with the given ID
395 public Sone getLocalSone(String id) {
396 return getLocalSone(id, true);
400 * Returns the local Sone with the given ID, optionally creating a new Sone.
405 * {@code true} to create a new Sone if none exists,
406 * {@code false} to return null if none exists
407 * @return The Sone with the given ID, or {@code null}
409 public Sone getLocalSone(String id, boolean create) {
410 synchronized (localSones) {
411 Sone sone = localSones.get(id);
412 if ((sone == null) && create) {
414 localSones.put(id, sone);
421 * Returns all remote Sones.
423 * @return All remote Sones
425 public Set<Sone> getRemoteSones() {
426 synchronized (remoteSones) {
427 return new HashSet<Sone>(remoteSones.values());
432 * Returns the remote Sone with the given ID.
435 * The ID of the remote Sone to get
436 * @return The Sone with the given ID
438 public Sone getRemoteSone(String id) {
439 return getRemoteSone(id, true);
443 * Returns the remote Sone with the given ID.
446 * The ID of the remote Sone to get
448 * {@code true} to always create a Sone, {@code false} to return
449 * {@code null} if no Sone with the given ID exists
450 * @return The Sone with the given ID
452 public Sone getRemoteSone(String id, boolean create) {
453 synchronized (remoteSones) {
454 Sone sone = remoteSones.get(id);
455 if ((sone == null) && create) {
457 remoteSones.put(id, sone);
464 * Returns whether the given Sone is a remote Sone.
468 * @return {@code true} if the given Sone is a remote Sone, {@code false}
471 public boolean isRemoteSone(Sone sone) {
472 synchronized (remoteSones) {
473 return remoteSones.containsKey(sone.getId());
478 * Returns whether the Sone with the given ID is a remote Sone.
481 * The ID of the Sone to check
482 * @return {@code true} if the Sone with the given ID is a remote Sone,
483 * {@code false} otherwise
485 public boolean isRemoteSone(String id) {
486 synchronized (remoteSones) {
487 return remoteSones.containsKey(id);
492 * Returns whether the given Sone is a new Sone. After this check, the Sone
493 * is marked as known, i.e. a second call with the same parameters will
494 * always yield {@code false}.
497 * The sone to check for
498 * @return {@code true} if the given Sone is new, false otherwise
500 public boolean isNewSone(Sone sone) {
501 synchronized (newSones) {
502 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
503 knownSones.add(sone.getId());
505 coreListenerManager.fireMarkSoneKnown(sone);
512 * Returns whether the given Sone has been modified.
515 * The Sone to check for modifications
516 * @return {@code true} if a modification has been detected in the Sone,
517 * {@code false} otherwise
519 public boolean isModifiedSone(Sone sone) {
520 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
524 * Returns the post with the given ID.
527 * The ID of the post to get
528 * @return The post, or {@code null} if there is no such post
530 public Post getPost(String postId) {
531 return getPost(postId, true);
535 * Returns the post with the given ID, optionally creating a new post.
538 * The ID of the post to get
540 * {@code true} it create a new post if no post with the given ID
541 * exists, {@code false} to return {@code null}
542 * @return The post, or {@code null} if there is no such post
544 public Post getPost(String postId, boolean create) {
545 synchronized (posts) {
546 Post post = posts.get(postId);
547 if ((post == null) && create) {
548 post = new Post(postId);
549 posts.put(postId, post);
556 * Returns whether the given post ID is new. After this method returns it is
557 * marked a known post ID.
561 * @return {@code true} if the post is considered to be new, {@code false}
564 public boolean isNewPost(String postId) {
565 return isNewPost(postId, true);
569 * Returns whether the given post ID is new. If {@code markAsKnown} is
570 * {@code true} then after this method returns the post ID is marked a known
576 * {@code true} to mark the post ID as known, {@code false} to
577 * not to mark it as known
578 * @return {@code true} if the post is considered to be new, {@code false}
581 public boolean isNewPost(String postId, boolean markAsKnown) {
582 synchronized (newPosts) {
583 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
585 Post post = getPost(postId, false);
595 * Returns the reply with the given ID. If there is no reply with the given
596 * ID yet, a new one is created.
599 * The ID of the reply to get
602 public Reply getReply(String replyId) {
603 return getReply(replyId, true);
607 * Returns the reply with the given ID. If there is no reply with the given
608 * ID yet, a new one is created, unless {@code create} is false in which
609 * case {@code null} is returned.
612 * The ID of the reply to get
614 * {@code true} to always return a {@link Reply}, {@code false}
615 * to return {@code null} if no reply can be found
616 * @return The reply, or {@code null} if there is no such reply
618 public Reply getReply(String replyId, boolean create) {
619 synchronized (replies) {
620 Reply reply = replies.get(replyId);
621 if (create && (reply == null)) {
622 reply = new Reply(replyId);
623 replies.put(replyId, reply);
630 * Returns all replies for the given post, order ascending by time.
633 * The post to get all replies for
634 * @return All replies for the given post
636 public List<Reply> getReplies(Post post) {
637 Set<Sone> sones = getSones();
638 List<Reply> replies = new ArrayList<Reply>();
639 for (Sone sone : sones) {
640 for (Reply reply : sone.getReplies()) {
641 if (reply.getPost().equals(post)) {
646 Collections.sort(replies, Reply.TIME_COMPARATOR);
651 * Returns whether the reply with the given ID is new.
654 * The ID of the reply to check
655 * @return {@code true} if the reply is considered to be new, {@code false}
658 public boolean isNewReply(String replyId) {
659 return isNewReply(replyId, true);
663 * Returns whether the reply with the given ID is new.
666 * The ID of the reply to check
668 * {@code true} to mark the reply as known, {@code false} to not
669 * to mark it as known
670 * @return {@code true} if the reply is considered to be new, {@code false}
673 public boolean isNewReply(String replyId, boolean markAsKnown) {
674 synchronized (newReplies) {
675 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
677 Reply reply = getReply(replyId, false);
679 markReplyKnown(reply);
687 * Returns all Sones that have liked the given post.
690 * The post to get the liking Sones for
691 * @return The Sones that like the given post
693 public Set<Sone> getLikes(Post post) {
694 Set<Sone> sones = new HashSet<Sone>();
695 for (Sone sone : getSones()) {
696 if (sone.getLikedPostIds().contains(post.getId())) {
704 * Returns all Sones that have liked the given reply.
707 * The reply to get the liking Sones for
708 * @return The Sones that like the given reply
710 public Set<Sone> getLikes(Reply reply) {
711 Set<Sone> sones = new HashSet<Sone>();
712 for (Sone sone : getSones()) {
713 if (sone.getLikedReplyIds().contains(reply.getId())) {
721 * Returns the album with the given ID, creating a new album if no album
722 * with the given ID can be found.
725 * The ID of the album
726 * @return The album with the given ID
728 public Album getAlbum(String albumId) {
729 return getAlbum(albumId, true);
733 * Returns the album with the given ID, optionally creating a new album if
734 * an album with the given ID can not be found.
737 * The ID of the album
738 * @return The album with the given ID, or {@code null} if no album with the
739 * given ID exists and {@code create} is {@code false}
741 public Album getAlbum(String albumId, boolean create) {
742 synchronized (albums) {
743 Album album = albums.get(albumId);
744 if (create && (album == null)) {
745 album = new Album(albumId);
746 albums.put(albumId, album);
757 * Locks the given Sone. A locked Sone will not be inserted by
758 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
764 public void lockSone(Sone sone) {
765 synchronized (lockedSones) {
766 if (lockedSones.add(sone)) {
767 coreListenerManager.fireSoneLocked(sone);
773 * Unlocks the given Sone.
775 * @see #lockSone(Sone)
779 public void unlockSone(Sone sone) {
780 synchronized (lockedSones) {
781 if (lockedSones.remove(sone)) {
782 coreListenerManager.fireSoneUnlocked(sone);
788 * Adds a local Sone from the given ID which has to be the ID of an own
792 * The ID of an own identity to add a Sone for
793 * @return The added (or already existing) Sone
795 public Sone addLocalSone(String id) {
796 synchronized (localSones) {
797 if (localSones.containsKey(id)) {
798 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
799 return localSones.get(id);
801 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
802 if (ownIdentity == null) {
803 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
806 return addLocalSone(ownIdentity);
811 * Adds a local Sone from the given own identity.
814 * The own identity to create a Sone from
815 * @return The added (or already existing) Sone
817 public Sone addLocalSone(OwnIdentity ownIdentity) {
818 if (ownIdentity == null) {
819 logger.log(Level.WARNING, "Given OwnIdentity is null!");
822 synchronized (localSones) {
825 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
826 } catch (MalformedURLException mue1) {
827 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
830 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
831 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
832 /* TODO - load posts ’n stuff */
833 localSones.put(ownIdentity.getId(), sone);
834 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
835 soneInserters.put(sone, soneInserter);
836 setSoneStatus(sone, SoneStatus.idle);
838 if (!isSoneRescueMode()) {
839 soneInserter.start();
841 new Thread(new Runnable() {
844 @SuppressWarnings("synthetic-access")
846 if (!isSoneRescueMode()) {
847 soneDownloader.fetchSone(sone);
850 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
851 coreListenerManager.fireRescuingSone(sone);
853 long edition = sone.getLatestEdition();
854 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
855 logger.log(Level.FINE, "Downloading edition " + edition + "…");
856 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
859 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
861 coreListenerManager.fireRescuedSone(sone);
862 soneInserter.start();
865 }, "Sone Downloader").start();
871 * Creates a new Sone for the given own identity.
874 * The own identity to create a Sone for
875 * @return The created Sone
877 public Sone createSone(OwnIdentity ownIdentity) {
878 identityManager.addContext(ownIdentity, "Sone");
879 Sone sone = addLocalSone(ownIdentity);
884 * Adds the Sone of the given identity.
887 * The identity whose Sone to add
888 * @return The added or already existing Sone
890 public Sone addRemoteSone(Identity identity) {
891 if (identity == null) {
892 logger.log(Level.WARNING, "Given Identity is null!");
895 synchronized (remoteSones) {
896 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
897 boolean newSone = sone.getRequestUri() == null;
898 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
899 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
901 synchronized (newSones) {
902 newSone = !knownSones.contains(sone.getId());
904 newSones.add(sone.getId());
908 coreListenerManager.fireNewSoneFound(sone);
911 remoteSones.put(identity.getId(), sone);
912 soneDownloader.addSone(sone);
913 setSoneStatus(sone, SoneStatus.unknown);
914 new Thread(new Runnable() {
917 @SuppressWarnings("synthetic-access")
919 soneDownloader.fetchSone(sone);
922 }, "Sone Downloader").start();
928 * Updates the stores Sone with the given Sone.
933 public void updateSone(Sone sone) {
934 if (hasSone(sone.getId())) {
935 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
936 Sone storedSone = getSone(sone.getId());
937 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
938 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
941 synchronized (posts) {
942 if (!soneRescueMode) {
943 for (Post post : storedSone.getPosts()) {
944 posts.remove(post.getId());
945 if (!sone.getPosts().contains(post)) {
946 coreListenerManager.firePostRemoved(post);
950 synchronized (newPosts) {
951 for (Post post : sone.getPosts()) {
952 post.setSone(getSone(post.getSone().getId()));
953 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
954 newPosts.add(post.getId());
955 coreListenerManager.fireNewPostFound(post);
957 posts.put(post.getId(), post);
961 synchronized (replies) {
962 if (!soneRescueMode) {
963 for (Reply reply : storedSone.getReplies()) {
964 replies.remove(reply.getId());
965 if (!sone.getReplies().contains(reply)) {
966 coreListenerManager.fireReplyRemoved(reply);
970 synchronized (newReplies) {
971 for (Reply reply : sone.getReplies()) {
972 reply.setSone(getSone(reply.getSone().getId()));
973 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
974 newReplies.add(reply.getId());
975 coreListenerManager.fireNewReplyFound(reply);
977 replies.put(reply.getId(), reply);
981 synchronized (storedSone) {
982 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
983 storedSone.setTime(sone.getTime());
985 storedSone.setClient(sone.getClient());
986 storedSone.setProfile(sone.getProfile());
987 if (soneRescueMode) {
988 for (Post post : sone.getPosts()) {
989 storedSone.addPost(post);
991 for (Reply reply : sone.getReplies()) {
992 storedSone.addReply(reply);
994 for (String likedPostId : sone.getLikedPostIds()) {
995 storedSone.addLikedPostId(likedPostId);
997 for (String likedReplyId : sone.getLikedReplyIds()) {
998 storedSone.addLikedReplyId(likedReplyId);
1001 storedSone.setPosts(sone.getPosts());
1002 storedSone.setReplies(sone.getReplies());
1003 storedSone.setLikePostIds(sone.getLikedPostIds());
1004 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1006 storedSone.setLatestEdition(sone.getLatestEdition());
1012 * Deletes the given Sone. This will remove the Sone from the
1013 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1014 * and remove the context from its identity.
1017 * The Sone to delete
1019 public void deleteSone(Sone sone) {
1020 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1021 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1024 synchronized (localSones) {
1025 if (!localSones.containsKey(sone.getId())) {
1026 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1029 localSones.remove(sone.getId());
1030 soneInserters.remove(sone).stop();
1032 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1033 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1035 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1036 } catch (ConfigurationException ce1) {
1037 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1042 * Loads and updates the given Sone from the configuration. If any error is
1043 * encountered, loading is aborted and the given Sone is not changed.
1046 * The Sone to load and update
1048 public void loadSone(Sone sone) {
1049 if (!isLocalSone(sone)) {
1050 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1055 String sonePrefix = "Sone/" + sone.getId();
1056 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1057 if (soneTime == null) {
1058 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1061 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1064 Profile profile = new Profile();
1065 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1066 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1067 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1068 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1069 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1070 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1073 Set<Post> posts = new HashSet<Post>();
1075 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1076 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1077 if (postId == null) {
1080 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1081 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1082 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1083 if ((postTime == 0) || (postText == null)) {
1084 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1087 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1088 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1089 post.setRecipient(getSone(postRecipientId));
1095 Set<Reply> replies = new HashSet<Reply>();
1097 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1098 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1099 if (replyId == null) {
1102 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1103 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1104 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1105 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1106 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1109 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1112 /* load post likes. */
1113 Set<String> likedPostIds = new HashSet<String>();
1115 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1116 if (likedPostId == null) {
1119 likedPostIds.add(likedPostId);
1122 /* load reply likes. */
1123 Set<String> likedReplyIds = new HashSet<String>();
1125 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1126 if (likedReplyId == null) {
1129 likedReplyIds.add(likedReplyId);
1133 Set<String> friends = new HashSet<String>();
1135 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1136 if (friendId == null) {
1139 friends.add(friendId);
1142 /* if we’re still here, Sone was loaded successfully. */
1143 synchronized (sone) {
1144 sone.setTime(soneTime);
1145 sone.setProfile(profile);
1146 sone.setPosts(posts);
1147 sone.setReplies(replies);
1148 sone.setLikePostIds(likedPostIds);
1149 sone.setLikeReplyIds(likedReplyIds);
1150 sone.setFriends(friends);
1151 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1153 synchronized (newSones) {
1154 for (String friend : friends) {
1155 knownSones.add(friend);
1158 synchronized (newPosts) {
1159 for (Post post : posts) {
1160 knownPosts.add(post.getId());
1163 synchronized (newReplies) {
1164 for (Reply reply : replies) {
1165 knownReplies.add(reply.getId());
1171 * Saves the given Sone. This will persist all local settings for the given
1172 * Sone, such as the friends list and similar, private options.
1177 public synchronized void saveSone(Sone sone) {
1178 if (!isLocalSone(sone)) {
1179 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1182 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1183 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1187 logger.log(Level.INFO, "Saving Sone: %s", sone);
1188 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1190 /* save Sone into configuration. */
1191 String sonePrefix = "Sone/" + sone.getId();
1192 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1193 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1196 Profile profile = sone.getProfile();
1197 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1198 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1199 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1200 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1201 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1202 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1205 int postCounter = 0;
1206 for (Post post : sone.getPosts()) {
1207 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1208 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1209 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1210 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1211 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1213 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1216 int replyCounter = 0;
1217 for (Reply reply : sone.getReplies()) {
1218 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1219 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1220 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1221 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1222 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1224 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1226 /* save post likes. */
1227 int postLikeCounter = 0;
1228 for (String postId : sone.getLikedPostIds()) {
1229 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1231 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1233 /* save reply likes. */
1234 int replyLikeCounter = 0;
1235 for (String replyId : sone.getLikedReplyIds()) {
1236 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1238 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1241 int friendCounter = 0;
1242 for (String friendId : sone.getFriends()) {
1243 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1245 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1247 configuration.save();
1248 logger.log(Level.INFO, "Sone %s saved.", sone);
1249 } catch (ConfigurationException ce1) {
1250 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1255 * Creates a new post.
1258 * The Sone that creates the post
1260 * The text of the post
1261 * @return The created post
1263 public Post createPost(Sone sone, String text) {
1264 return createPost(sone, System.currentTimeMillis(), text);
1268 * Creates a new post.
1271 * The Sone that creates the post
1273 * The time of the post
1275 * The text of the post
1276 * @return The created post
1278 public Post createPost(Sone sone, long time, String text) {
1279 return createPost(sone, null, time, text);
1283 * Creates a new post.
1286 * The Sone that creates the post
1288 * The recipient Sone, or {@code null} if this post does not have
1291 * The text of the post
1292 * @return The created post
1294 public Post createPost(Sone sone, Sone recipient, String text) {
1295 return createPost(sone, recipient, System.currentTimeMillis(), text);
1299 * Creates a new post.
1302 * The Sone that creates the post
1304 * The recipient Sone, or {@code null} if this post does not have
1307 * The time of the post
1309 * The text of the post
1310 * @return The created post
1312 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1313 if (!isLocalSone(sone)) {
1314 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1317 Post post = new Post(sone, time, text);
1318 if (recipient != null) {
1319 post.setRecipient(recipient);
1321 synchronized (posts) {
1322 posts.put(post.getId(), post);
1324 synchronized (newPosts) {
1325 knownPosts.add(post.getId());
1333 * Deletes the given post.
1336 * The post to delete
1338 public void deletePost(Post post) {
1339 if (!isLocalSone(post.getSone())) {
1340 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1343 post.getSone().removePost(post);
1344 synchronized (posts) {
1345 posts.remove(post.getId());
1347 saveSone(post.getSone());
1351 * Marks the given post as known, if it is currently a new post (according
1352 * to {@link #isNewPost(String)}).
1355 * The post to mark as known
1357 public void markPostKnown(Post post) {
1358 synchronized (newPosts) {
1359 if (newPosts.remove(post.getId())) {
1360 knownPosts.add(post.getId());
1361 coreListenerManager.fireMarkPostKnown(post);
1362 saveConfiguration();
1368 * Creates a new reply.
1371 * The Sone that creates the reply
1373 * The post that this reply refers to
1375 * The text of the reply
1376 * @return The created reply
1378 public Reply createReply(Sone sone, Post post, String text) {
1379 return createReply(sone, post, System.currentTimeMillis(), text);
1383 * Creates a new reply.
1386 * The Sone that creates the reply
1388 * The post that this reply refers to
1390 * The time of the reply
1392 * The text of the reply
1393 * @return The created reply
1395 public Reply createReply(Sone sone, Post post, long time, String text) {
1396 if (!isLocalSone(sone)) {
1397 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1400 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1401 synchronized (replies) {
1402 replies.put(reply.getId(), reply);
1404 synchronized (newReplies) {
1405 knownReplies.add(reply.getId());
1407 sone.addReply(reply);
1413 * Deletes the given reply.
1416 * The reply to delete
1418 public void deleteReply(Reply reply) {
1419 Sone sone = reply.getSone();
1420 if (!isLocalSone(sone)) {
1421 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1424 synchronized (replies) {
1425 replies.remove(reply.getId());
1427 sone.removeReply(reply);
1432 * Marks the given reply as known, if it is currently a new reply (according
1433 * to {@link #isNewReply(String)}).
1436 * The reply to mark as known
1438 public void markReplyKnown(Reply reply) {
1439 synchronized (newReplies) {
1440 if (newReplies.remove(reply.getId())) {
1441 knownReplies.add(reply.getId());
1442 coreListenerManager.fireMarkReplyKnown(reply);
1443 saveConfiguration();
1451 public void start() {
1452 loadConfiguration();
1453 updateChecker.addUpdateListener(this);
1454 updateChecker.start();
1460 public void stop() {
1461 synchronized (localSones) {
1462 for (SoneInserter soneInserter : soneInserters.values()) {
1463 soneInserter.stop();
1466 updateChecker.stop();
1467 updateChecker.removeUpdateListener(this);
1468 soneDownloader.stop();
1469 saveConfiguration();
1474 * Saves the current options.
1476 public void saveConfiguration() {
1477 synchronized (configuration) {
1478 if (storingConfiguration) {
1479 logger.log(Level.FINE, "Already storing configuration…");
1482 storingConfiguration = true;
1485 /* store the options first. */
1487 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1488 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1489 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1490 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1491 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1493 /* save known Sones. */
1494 int soneCounter = 0;
1495 synchronized (newSones) {
1496 for (String knownSoneId : knownSones) {
1497 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1499 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1502 /* save known posts. */
1503 int postCounter = 0;
1504 synchronized (newPosts) {
1505 for (String knownPostId : knownPosts) {
1506 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1508 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1511 /* save known replies. */
1512 int replyCounter = 0;
1513 synchronized (newReplies) {
1514 for (String knownReplyId : knownReplies) {
1515 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1517 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1521 configuration.save();
1523 } catch (ConfigurationException ce1) {
1524 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1526 synchronized (configuration) {
1527 storingConfiguration = false;
1537 * Loads the configuration.
1539 @SuppressWarnings("unchecked")
1540 private void loadConfiguration() {
1541 /* create options. */
1542 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1545 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1546 SoneInserter.setInsertionDelay(newValue);
1550 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1551 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1552 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1554 /* read options from configuration. */
1555 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1556 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1557 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1558 options.getBooleanOption("ClearOnNextRestart").set(null);
1559 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1560 if (clearConfiguration) {
1561 /* stop loading the configuration. */
1565 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1566 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1568 /* load known Sones. */
1569 int soneCounter = 0;
1571 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1572 if (knownSoneId == null) {
1575 synchronized (newSones) {
1576 knownSones.add(knownSoneId);
1580 /* load known posts. */
1581 int postCounter = 0;
1583 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1584 if (knownPostId == null) {
1587 synchronized (newPosts) {
1588 knownPosts.add(knownPostId);
1592 /* load known replies. */
1593 int replyCounter = 0;
1595 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1596 if (knownReplyId == null) {
1599 synchronized (newReplies) {
1600 knownReplies.add(knownReplyId);
1607 * Generate a Sone URI from the given URI and latest edition.
1610 * The URI to derive the Sone URI from
1611 * @return The derived URI
1613 private FreenetURI getSoneUri(String uriString) {
1615 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1617 } catch (MalformedURLException mue1) {
1618 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1624 // INTERFACE IdentityListener
1631 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1632 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1633 if (ownIdentity.hasContext("Sone")) {
1634 addLocalSone(ownIdentity);
1642 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1643 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1650 public void identityAdded(Identity identity) {
1651 logger.log(Level.FINEST, "Adding Identity: " + identity);
1652 addRemoteSone(identity);
1659 public void identityUpdated(final Identity identity) {
1660 new Thread(new Runnable() {
1663 @SuppressWarnings("synthetic-access")
1665 Sone sone = getRemoteSone(identity.getId());
1666 soneDownloader.fetchSone(sone);
1675 public void identityRemoved(Identity identity) {
1680 // INTERFACE UpdateListener
1687 public void updateFound(Version version, long releaseTime) {
1688 coreListenerManager.fireUpdateFound(version, releaseTime);