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
739 * {@code true} to create a new album if none exists for the
741 * @return The album with the given ID, or {@code null} if no album with the
742 * given ID exists and {@code create} is {@code false}
744 public Album getAlbum(String albumId, boolean create) {
745 synchronized (albums) {
746 Album album = albums.get(albumId);
747 if (create && (album == null)) {
748 album = new Album(albumId);
749 albums.put(albumId, album);
760 * Locks the given Sone. A locked Sone will not be inserted by
761 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
767 public void lockSone(Sone sone) {
768 synchronized (lockedSones) {
769 if (lockedSones.add(sone)) {
770 coreListenerManager.fireSoneLocked(sone);
776 * Unlocks the given Sone.
778 * @see #lockSone(Sone)
782 public void unlockSone(Sone sone) {
783 synchronized (lockedSones) {
784 if (lockedSones.remove(sone)) {
785 coreListenerManager.fireSoneUnlocked(sone);
791 * Adds a local Sone from the given ID which has to be the ID of an own
795 * The ID of an own identity to add a Sone for
796 * @return The added (or already existing) Sone
798 public Sone addLocalSone(String id) {
799 synchronized (localSones) {
800 if (localSones.containsKey(id)) {
801 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
802 return localSones.get(id);
804 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
805 if (ownIdentity == null) {
806 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
809 return addLocalSone(ownIdentity);
814 * Adds a local Sone from the given own identity.
817 * The own identity to create a Sone from
818 * @return The added (or already existing) Sone
820 public Sone addLocalSone(OwnIdentity ownIdentity) {
821 if (ownIdentity == null) {
822 logger.log(Level.WARNING, "Given OwnIdentity is null!");
825 synchronized (localSones) {
828 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
829 } catch (MalformedURLException mue1) {
830 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
833 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
834 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
835 /* TODO - load posts ’n stuff */
836 localSones.put(ownIdentity.getId(), sone);
837 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
838 soneInserters.put(sone, soneInserter);
839 setSoneStatus(sone, SoneStatus.idle);
841 if (!isSoneRescueMode()) {
842 soneInserter.start();
844 new Thread(new Runnable() {
847 @SuppressWarnings("synthetic-access")
849 if (!isSoneRescueMode()) {
850 soneDownloader.fetchSone(sone);
853 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
854 coreListenerManager.fireRescuingSone(sone);
856 long edition = sone.getLatestEdition();
857 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
858 logger.log(Level.FINE, "Downloading edition " + edition + "…");
859 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
862 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
864 coreListenerManager.fireRescuedSone(sone);
865 soneInserter.start();
868 }, "Sone Downloader").start();
874 * Creates a new Sone for the given own identity.
877 * The own identity to create a Sone for
878 * @return The created Sone
880 public Sone createSone(OwnIdentity ownIdentity) {
881 identityManager.addContext(ownIdentity, "Sone");
882 Sone sone = addLocalSone(ownIdentity);
887 * Adds the Sone of the given identity.
890 * The identity whose Sone to add
891 * @return The added or already existing Sone
893 public Sone addRemoteSone(Identity identity) {
894 if (identity == null) {
895 logger.log(Level.WARNING, "Given Identity is null!");
898 synchronized (remoteSones) {
899 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
900 boolean newSone = sone.getRequestUri() == null;
901 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
902 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
904 synchronized (newSones) {
905 newSone = !knownSones.contains(sone.getId());
907 newSones.add(sone.getId());
911 coreListenerManager.fireNewSoneFound(sone);
914 remoteSones.put(identity.getId(), sone);
915 soneDownloader.addSone(sone);
916 setSoneStatus(sone, SoneStatus.unknown);
917 new Thread(new Runnable() {
920 @SuppressWarnings("synthetic-access")
922 soneDownloader.fetchSone(sone);
925 }, "Sone Downloader").start();
931 * Updates the stores Sone with the given Sone.
936 public void updateSone(Sone sone) {
937 if (hasSone(sone.getId())) {
938 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
939 Sone storedSone = getSone(sone.getId());
940 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
941 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
944 synchronized (posts) {
945 if (!soneRescueMode) {
946 for (Post post : storedSone.getPosts()) {
947 posts.remove(post.getId());
948 if (!sone.getPosts().contains(post)) {
949 coreListenerManager.firePostRemoved(post);
953 synchronized (newPosts) {
954 for (Post post : sone.getPosts()) {
955 post.setSone(getSone(post.getSone().getId()));
956 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
957 newPosts.add(post.getId());
958 coreListenerManager.fireNewPostFound(post);
960 posts.put(post.getId(), post);
964 synchronized (replies) {
965 if (!soneRescueMode) {
966 for (Reply reply : storedSone.getReplies()) {
967 replies.remove(reply.getId());
968 if (!sone.getReplies().contains(reply)) {
969 coreListenerManager.fireReplyRemoved(reply);
973 synchronized (newReplies) {
974 for (Reply reply : sone.getReplies()) {
975 reply.setSone(getSone(reply.getSone().getId()));
976 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
977 newReplies.add(reply.getId());
978 coreListenerManager.fireNewReplyFound(reply);
980 replies.put(reply.getId(), reply);
984 synchronized (storedSone) {
985 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
986 storedSone.setTime(sone.getTime());
988 storedSone.setClient(sone.getClient());
989 storedSone.setProfile(sone.getProfile());
990 if (soneRescueMode) {
991 for (Post post : sone.getPosts()) {
992 storedSone.addPost(post);
994 for (Reply reply : sone.getReplies()) {
995 storedSone.addReply(reply);
997 for (String likedPostId : sone.getLikedPostIds()) {
998 storedSone.addLikedPostId(likedPostId);
1000 for (String likedReplyId : sone.getLikedReplyIds()) {
1001 storedSone.addLikedReplyId(likedReplyId);
1004 storedSone.setPosts(sone.getPosts());
1005 storedSone.setReplies(sone.getReplies());
1006 storedSone.setLikePostIds(sone.getLikedPostIds());
1007 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1009 storedSone.setLatestEdition(sone.getLatestEdition());
1015 * Deletes the given Sone. This will remove the Sone from the
1016 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1017 * and remove the context from its identity.
1020 * The Sone to delete
1022 public void deleteSone(Sone sone) {
1023 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1024 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1027 synchronized (localSones) {
1028 if (!localSones.containsKey(sone.getId())) {
1029 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1032 localSones.remove(sone.getId());
1033 soneInserters.remove(sone).stop();
1035 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1036 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1038 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1039 } catch (ConfigurationException ce1) {
1040 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1045 * Loads and updates the given Sone from the configuration. If any error is
1046 * encountered, loading is aborted and the given Sone is not changed.
1049 * The Sone to load and update
1051 public void loadSone(Sone sone) {
1052 if (!isLocalSone(sone)) {
1053 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1058 String sonePrefix = "Sone/" + sone.getId();
1059 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1060 if (soneTime == null) {
1061 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1064 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1067 Profile profile = new Profile();
1068 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1069 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1070 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1071 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1072 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1073 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1076 Set<Post> posts = new HashSet<Post>();
1078 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1079 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1080 if (postId == null) {
1083 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1084 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1085 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1086 if ((postTime == 0) || (postText == null)) {
1087 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1090 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1091 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1092 post.setRecipient(getSone(postRecipientId));
1098 Set<Reply> replies = new HashSet<Reply>();
1100 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1101 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1102 if (replyId == null) {
1105 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1106 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1107 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1108 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1109 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1112 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1115 /* load post likes. */
1116 Set<String> likedPostIds = new HashSet<String>();
1118 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1119 if (likedPostId == null) {
1122 likedPostIds.add(likedPostId);
1125 /* load reply likes. */
1126 Set<String> likedReplyIds = new HashSet<String>();
1128 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1129 if (likedReplyId == null) {
1132 likedReplyIds.add(likedReplyId);
1136 Set<String> friends = new HashSet<String>();
1138 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1139 if (friendId == null) {
1142 friends.add(friendId);
1145 /* if we’re still here, Sone was loaded successfully. */
1146 synchronized (sone) {
1147 sone.setTime(soneTime);
1148 sone.setProfile(profile);
1149 sone.setPosts(posts);
1150 sone.setReplies(replies);
1151 sone.setLikePostIds(likedPostIds);
1152 sone.setLikeReplyIds(likedReplyIds);
1153 sone.setFriends(friends);
1154 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1156 synchronized (newSones) {
1157 for (String friend : friends) {
1158 knownSones.add(friend);
1161 synchronized (newPosts) {
1162 for (Post post : posts) {
1163 knownPosts.add(post.getId());
1166 synchronized (newReplies) {
1167 for (Reply reply : replies) {
1168 knownReplies.add(reply.getId());
1174 * Saves the given Sone. This will persist all local settings for the given
1175 * Sone, such as the friends list and similar, private options.
1180 public synchronized void saveSone(Sone sone) {
1181 if (!isLocalSone(sone)) {
1182 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1185 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1186 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1190 logger.log(Level.INFO, "Saving Sone: %s", sone);
1191 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1193 /* save Sone into configuration. */
1194 String sonePrefix = "Sone/" + sone.getId();
1195 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1196 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1199 Profile profile = sone.getProfile();
1200 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1201 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1202 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1203 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1204 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1205 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1208 int postCounter = 0;
1209 for (Post post : sone.getPosts()) {
1210 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1211 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1212 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1213 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1214 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1216 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1219 int replyCounter = 0;
1220 for (Reply reply : sone.getReplies()) {
1221 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1222 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1223 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1224 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1225 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1227 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1229 /* save post likes. */
1230 int postLikeCounter = 0;
1231 for (String postId : sone.getLikedPostIds()) {
1232 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1234 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1236 /* save reply likes. */
1237 int replyLikeCounter = 0;
1238 for (String replyId : sone.getLikedReplyIds()) {
1239 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1241 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1244 int friendCounter = 0;
1245 for (String friendId : sone.getFriends()) {
1246 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1248 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1250 configuration.save();
1251 logger.log(Level.INFO, "Sone %s saved.", sone);
1252 } catch (ConfigurationException ce1) {
1253 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1258 * Creates a new post.
1261 * The Sone that creates the post
1263 * The text of the post
1264 * @return The created post
1266 public Post createPost(Sone sone, String text) {
1267 return createPost(sone, System.currentTimeMillis(), text);
1271 * Creates a new post.
1274 * The Sone that creates the post
1276 * The time of the post
1278 * The text of the post
1279 * @return The created post
1281 public Post createPost(Sone sone, long time, String text) {
1282 return createPost(sone, null, time, text);
1286 * Creates a new post.
1289 * The Sone that creates the post
1291 * The recipient Sone, or {@code null} if this post does not have
1294 * The text of the post
1295 * @return The created post
1297 public Post createPost(Sone sone, Sone recipient, String text) {
1298 return createPost(sone, recipient, System.currentTimeMillis(), text);
1302 * Creates a new post.
1305 * The Sone that creates the post
1307 * The recipient Sone, or {@code null} if this post does not have
1310 * The time of the post
1312 * The text of the post
1313 * @return The created post
1315 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1316 if (!isLocalSone(sone)) {
1317 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1320 Post post = new Post(sone, time, text);
1321 if (recipient != null) {
1322 post.setRecipient(recipient);
1324 synchronized (posts) {
1325 posts.put(post.getId(), post);
1327 synchronized (newPosts) {
1328 knownPosts.add(post.getId());
1336 * Deletes the given post.
1339 * The post to delete
1341 public void deletePost(Post post) {
1342 if (!isLocalSone(post.getSone())) {
1343 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1346 post.getSone().removePost(post);
1347 synchronized (posts) {
1348 posts.remove(post.getId());
1350 saveSone(post.getSone());
1354 * Marks the given post as known, if it is currently a new post (according
1355 * to {@link #isNewPost(String)}).
1358 * The post to mark as known
1360 public void markPostKnown(Post post) {
1361 synchronized (newPosts) {
1362 if (newPosts.remove(post.getId())) {
1363 knownPosts.add(post.getId());
1364 coreListenerManager.fireMarkPostKnown(post);
1365 saveConfiguration();
1371 * Creates a new reply.
1374 * The Sone that creates the reply
1376 * The post that this reply refers to
1378 * The text of the reply
1379 * @return The created reply
1381 public Reply createReply(Sone sone, Post post, String text) {
1382 return createReply(sone, post, System.currentTimeMillis(), text);
1386 * Creates a new reply.
1389 * The Sone that creates the reply
1391 * The post that this reply refers to
1393 * The time of the reply
1395 * The text of the reply
1396 * @return The created reply
1398 public Reply createReply(Sone sone, Post post, long time, String text) {
1399 if (!isLocalSone(sone)) {
1400 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1403 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1404 synchronized (replies) {
1405 replies.put(reply.getId(), reply);
1407 synchronized (newReplies) {
1408 knownReplies.add(reply.getId());
1410 sone.addReply(reply);
1416 * Deletes the given reply.
1419 * The reply to delete
1421 public void deleteReply(Reply reply) {
1422 Sone sone = reply.getSone();
1423 if (!isLocalSone(sone)) {
1424 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1427 synchronized (replies) {
1428 replies.remove(reply.getId());
1430 sone.removeReply(reply);
1435 * Marks the given reply as known, if it is currently a new reply (according
1436 * to {@link #isNewReply(String)}).
1439 * The reply to mark as known
1441 public void markReplyKnown(Reply reply) {
1442 synchronized (newReplies) {
1443 if (newReplies.remove(reply.getId())) {
1444 knownReplies.add(reply.getId());
1445 coreListenerManager.fireMarkReplyKnown(reply);
1446 saveConfiguration();
1454 public void start() {
1455 loadConfiguration();
1456 updateChecker.addUpdateListener(this);
1457 updateChecker.start();
1463 public void stop() {
1464 synchronized (localSones) {
1465 for (SoneInserter soneInserter : soneInserters.values()) {
1466 soneInserter.stop();
1469 updateChecker.stop();
1470 updateChecker.removeUpdateListener(this);
1471 soneDownloader.stop();
1472 saveConfiguration();
1477 * Saves the current options.
1479 public void saveConfiguration() {
1480 synchronized (configuration) {
1481 if (storingConfiguration) {
1482 logger.log(Level.FINE, "Already storing configuration…");
1485 storingConfiguration = true;
1488 /* store the options first. */
1490 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1491 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1492 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1493 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1494 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1496 /* save known Sones. */
1497 int soneCounter = 0;
1498 synchronized (newSones) {
1499 for (String knownSoneId : knownSones) {
1500 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1502 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1505 /* save known posts. */
1506 int postCounter = 0;
1507 synchronized (newPosts) {
1508 for (String knownPostId : knownPosts) {
1509 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1511 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1514 /* save known replies. */
1515 int replyCounter = 0;
1516 synchronized (newReplies) {
1517 for (String knownReplyId : knownReplies) {
1518 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1520 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1524 configuration.save();
1526 } catch (ConfigurationException ce1) {
1527 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1529 synchronized (configuration) {
1530 storingConfiguration = false;
1540 * Loads the configuration.
1542 @SuppressWarnings("unchecked")
1543 private void loadConfiguration() {
1544 /* create options. */
1545 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1548 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1549 SoneInserter.setInsertionDelay(newValue);
1553 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1554 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1555 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1557 /* read options from configuration. */
1558 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1559 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1560 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1561 options.getBooleanOption("ClearOnNextRestart").set(null);
1562 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1563 if (clearConfiguration) {
1564 /* stop loading the configuration. */
1568 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1569 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1571 /* load known Sones. */
1572 int soneCounter = 0;
1574 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1575 if (knownSoneId == null) {
1578 synchronized (newSones) {
1579 knownSones.add(knownSoneId);
1583 /* load known posts. */
1584 int postCounter = 0;
1586 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1587 if (knownPostId == null) {
1590 synchronized (newPosts) {
1591 knownPosts.add(knownPostId);
1595 /* load known replies. */
1596 int replyCounter = 0;
1598 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1599 if (knownReplyId == null) {
1602 synchronized (newReplies) {
1603 knownReplies.add(knownReplyId);
1610 * Generate a Sone URI from the given URI and latest edition.
1613 * The URI to derive the Sone URI from
1614 * @return The derived URI
1616 private FreenetURI getSoneUri(String uriString) {
1618 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1620 } catch (MalformedURLException mue1) {
1621 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1627 // INTERFACE IdentityListener
1634 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1635 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1636 if (ownIdentity.hasContext("Sone")) {
1637 addLocalSone(ownIdentity);
1645 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1646 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1653 public void identityAdded(Identity identity) {
1654 logger.log(Level.FINEST, "Adding Identity: " + identity);
1655 addRemoteSone(identity);
1662 public void identityUpdated(final Identity identity) {
1663 new Thread(new Runnable() {
1666 @SuppressWarnings("synthetic-access")
1668 Sone sone = getRemoteSone(identity.getId());
1669 soneDownloader.fetchSone(sone);
1678 public void identityRemoved(Identity identity) {
1683 // INTERFACE UpdateListener
1690 public void updateFound(Version version, long releaseTime) {
1691 coreListenerManager.fireUpdateFound(version, releaseTime);