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.Image;
37 import net.pterodactylus.sone.data.Post;
38 import net.pterodactylus.sone.data.Profile;
39 import net.pterodactylus.sone.data.Reply;
40 import net.pterodactylus.sone.data.Sone;
41 import net.pterodactylus.sone.freenet.wot.Identity;
42 import net.pterodactylus.sone.freenet.wot.IdentityListener;
43 import net.pterodactylus.sone.freenet.wot.IdentityManager;
44 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
45 import net.pterodactylus.sone.main.SonePlugin;
46 import net.pterodactylus.util.config.Configuration;
47 import net.pterodactylus.util.config.ConfigurationException;
48 import net.pterodactylus.util.logging.Logging;
49 import net.pterodactylus.util.number.Numbers;
50 import net.pterodactylus.util.version.Version;
51 import freenet.keys.FreenetURI;
56 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
58 public class Core implements IdentityListener, UpdateListener {
61 * Enumeration for the possible states of a {@link Sone}.
63 * @author <a href="mailto:bombe@pterodactylus.net">David āBombeā Roden</a>
65 public enum SoneStatus {
67 /** The Sone is unknown, i.e. not yet downloaded. */
70 /** The Sone is idle, i.e. not being downloaded or inserted. */
73 /** The Sone is currently being inserted. */
76 /** The Sone is currently being downloaded. */
81 private static final Logger logger = Logging.getLogger(Core.class);
84 private final Options options = new Options();
86 /** The core listener manager. */
87 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
89 /** The configuration. */
90 private Configuration configuration;
92 /** Whether weāre currently saving the configuration. */
93 private boolean storingConfiguration = false;
95 /** The identity manager. */
96 private final IdentityManager identityManager;
98 /** Interface to freenet. */
99 private final FreenetInterface freenetInterface;
101 /** The Sone downloader. */
102 private final SoneDownloader soneDownloader;
104 /** The update checker. */
105 private final UpdateChecker updateChecker;
107 /** Whether the core has been stopped. */
108 private volatile boolean stopped;
110 /** The Sonesā statuses. */
111 /* synchronize access on itself. */
112 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
114 /** Locked local Sones. */
115 /* synchronize on itself. */
116 private final Set<Sone> lockedSones = new HashSet<Sone>();
118 /** Sone inserters. */
119 /* synchronize access on this on localSones. */
120 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
122 /** All local Sones. */
123 /* synchronize access on this on itself. */
124 private Map<String, Sone> localSones = new HashMap<String, Sone>();
126 /** All remote Sones. */
127 /* synchronize access on this on itself. */
128 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
130 /** All new Sones. */
131 private Set<String> newSones = new HashSet<String>();
133 /** All known Sones. */
134 /* synchronize access on {@link #newSones}. */
135 private Set<String> knownSones = new HashSet<String>();
138 private Map<String, Post> posts = new HashMap<String, Post>();
140 /** All new posts. */
141 private Set<String> newPosts = new HashSet<String>();
143 /** All known posts. */
144 /* synchronize access on {@link #newPosts}. */
145 private Set<String> knownPosts = new HashSet<String>();
148 private Map<String, Reply> replies = new HashMap<String, Reply>();
150 /** All new replies. */
151 private Set<String> newReplies = new HashSet<String>();
153 /** All known replies. */
154 private Set<String> knownReplies = new HashSet<String>();
156 /** All known albums. */
157 private Map<String, Album> albums = new HashMap<String, Album>();
159 /** All known images. */
160 private Map<String, Image> images = new HashMap<String, Image>();
163 * Creates a new core.
165 * @param configuration
166 * The configuration of the core
167 * @param freenetInterface
168 * The freenet interface
169 * @param identityManager
170 * The identity manager
172 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
173 this.configuration = configuration;
174 this.freenetInterface = freenetInterface;
175 this.identityManager = identityManager;
176 this.soneDownloader = new SoneDownloader(this, freenetInterface);
177 this.updateChecker = new UpdateChecker(freenetInterface);
181 // LISTENER MANAGEMENT
185 * Adds a new core listener.
187 * @param coreListener
188 * The listener to add
190 public void addCoreListener(CoreListener coreListener) {
191 coreListenerManager.addListener(coreListener);
195 * Removes a core listener.
197 * @param coreListener
198 * The listener to remove
200 public void removeCoreListener(CoreListener coreListener) {
201 coreListenerManager.removeListener(coreListener);
209 * Sets the configuration to use. This will automatically save the current
210 * configuration to the given configuration.
212 * @param configuration
213 * The new configuration to use
215 public void setConfiguration(Configuration configuration) {
216 this.configuration = configuration;
221 * Returns the options used by the core.
223 * @return The options of the core
225 public Options getOptions() {
230 * Returns whether the āSone rescue modeā is currently activated.
232 * @return {@code true} if the āSone rescue modeā is currently activated,
233 * {@code false} if it is not
235 public boolean isSoneRescueMode() {
236 return options.getBooleanOption("SoneRescueMode").get();
240 * Returns the identity manager used by the core.
242 * @return The identity manager
244 public IdentityManager getIdentityManager() {
245 return identityManager;
249 * Returns the update checker.
251 * @return The update checker
253 public UpdateChecker getUpdateChecker() {
254 return updateChecker;
258 * Returns the status of the given Sone.
261 * The Sone to get the status for
262 * @return The status of the Sone
264 public SoneStatus getSoneStatus(Sone sone) {
265 synchronized (soneStatuses) {
266 return soneStatuses.get(sone);
271 * Sets the status of the given Sone.
274 * The Sone to set the status of
278 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
279 synchronized (soneStatuses) {
280 soneStatuses.put(sone, soneStatus);
285 * Returns whether the given Sone is currently locked.
289 * @return {@code true} if the Sone is locked, {@code false} if it is not
291 public boolean isLocked(Sone sone) {
292 synchronized (lockedSones) {
293 return lockedSones.contains(sone);
298 * Returns all Sones, remote and local.
302 public Set<Sone> getSones() {
303 Set<Sone> allSones = new HashSet<Sone>();
304 allSones.addAll(getLocalSones());
305 allSones.addAll(getRemoteSones());
310 * Returns the Sone with the given ID, regardless whether itās local or
314 * The ID of the Sone to get
315 * @return The Sone with the given ID, or {@code null} if there is no such
318 public Sone getSone(String id) {
319 return getSone(id, true);
323 * Returns the Sone with the given ID, regardless whether itās local or
327 * The ID of the Sone to get
329 * {@code true} to create a new Sone if none exists,
330 * {@code false} to return {@code null} if a Sone with the given
332 * @return The Sone with the given ID, or {@code null} if there is no such
335 public Sone getSone(String id, boolean create) {
336 if (isLocalSone(id)) {
337 return getLocalSone(id);
339 return getRemoteSone(id, create);
343 * Checks whether the core knows a Sone with the given ID.
347 * @return {@code true} if there is a Sone with the given ID, {@code false}
350 public boolean hasSone(String id) {
351 return isLocalSone(id) || isRemoteSone(id);
355 * Returns whether the given Sone is a local Sone.
358 * The Sone to check for its locality
359 * @return {@code true} if the given Sone is local, {@code false} otherwise
361 public boolean isLocalSone(Sone sone) {
362 synchronized (localSones) {
363 return localSones.containsKey(sone.getId());
368 * Returns whether the given ID is the ID of a local Sone.
371 * The Sone ID to check for its locality
372 * @return {@code true} if the given ID is a local Sone, {@code false}
375 public boolean isLocalSone(String id) {
376 synchronized (localSones) {
377 return localSones.containsKey(id);
382 * Returns all local Sones.
384 * @return All local Sones
386 public Set<Sone> getLocalSones() {
387 synchronized (localSones) {
388 return new HashSet<Sone>(localSones.values());
393 * Returns the local Sone with the given ID.
396 * The ID of the Sone to get
397 * @return The Sone with the given ID
399 public Sone getLocalSone(String id) {
400 return getLocalSone(id, true);
404 * Returns the local Sone with the given ID, optionally creating a new Sone.
409 * {@code true} to create a new Sone if none exists,
410 * {@code false} to return null if none exists
411 * @return The Sone with the given ID, or {@code null}
413 public Sone getLocalSone(String id, boolean create) {
414 synchronized (localSones) {
415 Sone sone = localSones.get(id);
416 if ((sone == null) && create) {
418 localSones.put(id, sone);
425 * Returns all remote Sones.
427 * @return All remote Sones
429 public Set<Sone> getRemoteSones() {
430 synchronized (remoteSones) {
431 return new HashSet<Sone>(remoteSones.values());
436 * Returns the remote Sone with the given ID.
439 * The ID of the remote Sone to get
440 * @return The Sone with the given ID
442 public Sone getRemoteSone(String id) {
443 return getRemoteSone(id, true);
447 * Returns the remote Sone with the given ID.
450 * The ID of the remote Sone to get
452 * {@code true} to always create a Sone, {@code false} to return
453 * {@code null} if no Sone with the given ID exists
454 * @return The Sone with the given ID
456 public Sone getRemoteSone(String id, boolean create) {
457 synchronized (remoteSones) {
458 Sone sone = remoteSones.get(id);
459 if ((sone == null) && create) {
461 remoteSones.put(id, sone);
468 * Returns whether the given Sone is a remote Sone.
472 * @return {@code true} if the given Sone is a remote Sone, {@code false}
475 public boolean isRemoteSone(Sone sone) {
476 synchronized (remoteSones) {
477 return remoteSones.containsKey(sone.getId());
482 * Returns whether the Sone with the given ID is a remote Sone.
485 * The ID of the Sone to check
486 * @return {@code true} if the Sone with the given ID is a remote Sone,
487 * {@code false} otherwise
489 public boolean isRemoteSone(String id) {
490 synchronized (remoteSones) {
491 return remoteSones.containsKey(id);
496 * Returns whether the given Sone is a new Sone. After this check, the Sone
497 * is marked as known, i.e. a second call with the same parameters will
498 * always yield {@code false}.
501 * The sone to check for
502 * @return {@code true} if the given Sone is new, false otherwise
504 public boolean isNewSone(Sone sone) {
505 synchronized (newSones) {
506 boolean isNew = !knownSones.contains(sone.getId()) && newSones.remove(sone.getId());
507 knownSones.add(sone.getId());
509 coreListenerManager.fireMarkSoneKnown(sone);
516 * Returns whether the given Sone has been modified.
519 * The Sone to check for modifications
520 * @return {@code true} if a modification has been detected in the Sone,
521 * {@code false} otherwise
523 public boolean isModifiedSone(Sone sone) {
524 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
528 * Returns the post with the given ID.
531 * The ID of the post to get
532 * @return The post, or {@code null} if there is no such post
534 public Post getPost(String postId) {
535 return getPost(postId, true);
539 * Returns the post with the given ID, optionally creating a new post.
542 * The ID of the post to get
544 * {@code true} it create a new post if no post with the given ID
545 * exists, {@code false} to return {@code null}
546 * @return The post, or {@code null} if there is no such post
548 public Post getPost(String postId, boolean create) {
549 synchronized (posts) {
550 Post post = posts.get(postId);
551 if ((post == null) && create) {
552 post = new Post(postId);
553 posts.put(postId, post);
560 * Returns whether the given post ID is new. After this method returns it is
561 * marked a known post ID.
565 * @return {@code true} if the post is considered to be new, {@code false}
568 public boolean isNewPost(String postId) {
569 return isNewPost(postId, true);
573 * Returns whether the given post ID is new. If {@code markAsKnown} is
574 * {@code true} then after this method returns the post ID is marked a known
580 * {@code true} to mark the post ID as known, {@code false} to
581 * not to mark it as known
582 * @return {@code true} if the post is considered to be new, {@code false}
585 public boolean isNewPost(String postId, boolean markAsKnown) {
586 synchronized (newPosts) {
587 boolean isNew = !knownPosts.contains(postId) && newPosts.contains(postId);
589 Post post = getPost(postId, false);
599 * Returns the reply with the given ID. If there is no reply with the given
600 * ID yet, a new one is created.
603 * The ID of the reply to get
606 public Reply getReply(String replyId) {
607 return getReply(replyId, true);
611 * Returns the reply with the given ID. If there is no reply with the given
612 * ID yet, a new one is created, unless {@code create} is false in which
613 * case {@code null} is returned.
616 * The ID of the reply to get
618 * {@code true} to always return a {@link Reply}, {@code false}
619 * to return {@code null} if no reply can be found
620 * @return The reply, or {@code null} if there is no such reply
622 public Reply getReply(String replyId, boolean create) {
623 synchronized (replies) {
624 Reply reply = replies.get(replyId);
625 if (create && (reply == null)) {
626 reply = new Reply(replyId);
627 replies.put(replyId, reply);
634 * Returns all replies for the given post, order ascending by time.
637 * The post to get all replies for
638 * @return All replies for the given post
640 public List<Reply> getReplies(Post post) {
641 Set<Sone> sones = getSones();
642 List<Reply> replies = new ArrayList<Reply>();
643 for (Sone sone : sones) {
644 for (Reply reply : sone.getReplies()) {
645 if (reply.getPost().equals(post)) {
650 Collections.sort(replies, Reply.TIME_COMPARATOR);
655 * Returns whether the reply with the given ID is new.
658 * The ID of the reply to check
659 * @return {@code true} if the reply is considered to be new, {@code false}
662 public boolean isNewReply(String replyId) {
663 return isNewReply(replyId, true);
667 * Returns whether the reply with the given ID is new.
670 * The ID of the reply to check
672 * {@code true} to mark the reply as known, {@code false} to not
673 * to mark it as known
674 * @return {@code true} if the reply is considered to be new, {@code false}
677 public boolean isNewReply(String replyId, boolean markAsKnown) {
678 synchronized (newReplies) {
679 boolean isNew = !knownReplies.contains(replyId) && newReplies.contains(replyId);
681 Reply reply = getReply(replyId, false);
683 markReplyKnown(reply);
691 * Returns all Sones that have liked the given post.
694 * The post to get the liking Sones for
695 * @return The Sones that like the given post
697 public Set<Sone> getLikes(Post post) {
698 Set<Sone> sones = new HashSet<Sone>();
699 for (Sone sone : getSones()) {
700 if (sone.getLikedPostIds().contains(post.getId())) {
708 * Returns all Sones that have liked the given reply.
711 * The reply to get the liking Sones for
712 * @return The Sones that like the given reply
714 public Set<Sone> getLikes(Reply reply) {
715 Set<Sone> sones = new HashSet<Sone>();
716 for (Sone sone : getSones()) {
717 if (sone.getLikedReplyIds().contains(reply.getId())) {
725 * Returns the album with the given ID, creating a new album if no album
726 * with the given ID can be found.
729 * The ID of the album
730 * @return The album with the given ID
732 public Album getAlbum(String albumId) {
733 return getAlbum(albumId, true);
737 * Returns the album with the given ID, optionally creating a new album if
738 * an album with the given ID can not be found.
741 * The ID of the album
743 * {@code true} to create a new album if none exists for the
745 * @return The album with the given ID, or {@code null} if no album with the
746 * given ID exists and {@code create} is {@code false}
748 public Album getAlbum(String albumId, boolean create) {
749 synchronized (albums) {
750 Album album = albums.get(albumId);
751 if (create && (album == null)) {
752 album = new Album(albumId);
753 albums.put(albumId, album);
760 * Returns the image with the given ID, creating it if necessary.
763 * The ID of the image
764 * @return The image with the given ID
766 public Image getImage(String imageId) {
767 return getImage(imageId, true);
771 * Returns the image with the given ID, optionally creating it if it does
775 * The ID of the image
777 * {@code true} to create an image if none exists with the given
779 * @return The image with the given ID, or {@code null} if none exists and
782 public Image getImage(String imageId, boolean create) {
783 synchronized (images) {
784 Image image = images.get(imageId);
785 if (create && (image == null)) {
786 image = new Image(imageId);
787 images.put(imageId, image);
798 * Locks the given Sone. A locked Sone will not be inserted by
799 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
805 public void lockSone(Sone sone) {
806 synchronized (lockedSones) {
807 if (lockedSones.add(sone)) {
808 coreListenerManager.fireSoneLocked(sone);
814 * Unlocks the given Sone.
816 * @see #lockSone(Sone)
820 public void unlockSone(Sone sone) {
821 synchronized (lockedSones) {
822 if (lockedSones.remove(sone)) {
823 coreListenerManager.fireSoneUnlocked(sone);
829 * Adds a local Sone from the given ID which has to be the ID of an own
833 * The ID of an own identity to add a Sone for
834 * @return The added (or already existing) Sone
836 public Sone addLocalSone(String id) {
837 synchronized (localSones) {
838 if (localSones.containsKey(id)) {
839 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
840 return localSones.get(id);
842 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
843 if (ownIdentity == null) {
844 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
847 return addLocalSone(ownIdentity);
852 * Adds a local Sone from the given own identity.
855 * The own identity to create a Sone from
856 * @return The added (or already existing) Sone
858 public Sone addLocalSone(OwnIdentity ownIdentity) {
859 if (ownIdentity == null) {
860 logger.log(Level.WARNING, "Given OwnIdentity is null!");
863 synchronized (localSones) {
866 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
867 } catch (MalformedURLException mue1) {
868 logger.log(Level.SEVERE, "Could not convert the Identityās URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
871 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
872 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
873 /* TODO - load posts ān stuff */
874 localSones.put(ownIdentity.getId(), sone);
875 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
876 soneInserters.put(sone, soneInserter);
877 setSoneStatus(sone, SoneStatus.idle);
879 if (!isSoneRescueMode()) {
880 soneInserter.start();
882 new Thread(new Runnable() {
885 @SuppressWarnings("synthetic-access")
887 if (!isSoneRescueMode()) {
888 soneDownloader.fetchSone(sone);
891 logger.log(Level.INFO, "Trying to restore Sone from Freenetā¦");
892 coreListenerManager.fireRescuingSone(sone);
894 long edition = sone.getLatestEdition();
895 while (!stopped && (edition >= 0) && isSoneRescueMode()) {
896 logger.log(Level.FINE, "Downloading edition " + edition + "ā¦");
897 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
900 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserterā¦");
902 coreListenerManager.fireRescuedSone(sone);
903 soneInserter.start();
906 }, "Sone Downloader").start();
912 * Creates a new Sone for the given own identity.
915 * The own identity to create a Sone for
916 * @return The created Sone
918 public Sone createSone(OwnIdentity ownIdentity) {
919 identityManager.addContext(ownIdentity, "Sone");
920 Sone sone = addLocalSone(ownIdentity);
925 * Adds the Sone of the given identity.
928 * The identity whose Sone to add
929 * @return The added or already existing Sone
931 public Sone addRemoteSone(Identity identity) {
932 if (identity == null) {
933 logger.log(Level.WARNING, "Given Identity is null!");
936 synchronized (remoteSones) {
937 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
938 boolean newSone = sone.getRequestUri() == null;
939 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
940 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
942 synchronized (newSones) {
943 newSone = !knownSones.contains(sone.getId());
945 newSones.add(sone.getId());
949 coreListenerManager.fireNewSoneFound(sone);
952 remoteSones.put(identity.getId(), sone);
953 soneDownloader.addSone(sone);
954 setSoneStatus(sone, SoneStatus.unknown);
955 new Thread(new Runnable() {
958 @SuppressWarnings("synthetic-access")
960 soneDownloader.fetchSone(sone);
963 }, "Sone Downloader").start();
969 * Updates the stores Sone with the given Sone.
974 public void updateSone(Sone sone) {
975 if (hasSone(sone.getId())) {
976 boolean soneRescueMode = isLocalSone(sone) && isSoneRescueMode();
977 Sone storedSone = getSone(sone.getId());
978 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
979 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
982 synchronized (posts) {
983 if (!soneRescueMode) {
984 for (Post post : storedSone.getPosts()) {
985 posts.remove(post.getId());
986 if (!sone.getPosts().contains(post)) {
987 coreListenerManager.firePostRemoved(post);
991 synchronized (newPosts) {
992 for (Post post : sone.getPosts()) {
993 post.setSone(getSone(post.getSone().getId()));
994 if (!storedSone.getPosts().contains(post) && !knownPosts.contains(post.getId())) {
995 newPosts.add(post.getId());
996 coreListenerManager.fireNewPostFound(post);
998 posts.put(post.getId(), post);
1002 synchronized (replies) {
1003 if (!soneRescueMode) {
1004 for (Reply reply : storedSone.getReplies()) {
1005 replies.remove(reply.getId());
1006 if (!sone.getReplies().contains(reply)) {
1007 coreListenerManager.fireReplyRemoved(reply);
1011 synchronized (newReplies) {
1012 for (Reply reply : sone.getReplies()) {
1013 reply.setSone(getSone(reply.getSone().getId()));
1014 if (!storedSone.getReplies().contains(reply) && !knownReplies.contains(reply.getId())) {
1015 newReplies.add(reply.getId());
1016 coreListenerManager.fireNewReplyFound(reply);
1018 replies.put(reply.getId(), reply);
1022 synchronized (storedSone) {
1023 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1024 storedSone.setTime(sone.getTime());
1026 storedSone.setClient(sone.getClient());
1027 storedSone.setProfile(sone.getProfile());
1028 if (soneRescueMode) {
1029 for (Post post : sone.getPosts()) {
1030 storedSone.addPost(post);
1032 for (Reply reply : sone.getReplies()) {
1033 storedSone.addReply(reply);
1035 for (String likedPostId : sone.getLikedPostIds()) {
1036 storedSone.addLikedPostId(likedPostId);
1038 for (String likedReplyId : sone.getLikedReplyIds()) {
1039 storedSone.addLikedReplyId(likedReplyId);
1042 storedSone.setPosts(sone.getPosts());
1043 storedSone.setReplies(sone.getReplies());
1044 storedSone.setLikePostIds(sone.getLikedPostIds());
1045 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1047 storedSone.setLatestEdition(sone.getLatestEdition());
1053 * Deletes the given Sone. This will remove the Sone from the
1054 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1055 * and remove the context from its identity.
1058 * The Sone to delete
1060 public void deleteSone(Sone sone) {
1061 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1062 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1065 synchronized (localSones) {
1066 if (!localSones.containsKey(sone.getId())) {
1067 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1070 localSones.remove(sone.getId());
1071 soneInserters.remove(sone).stop();
1073 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1074 identityManager.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1076 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1077 } catch (ConfigurationException ce1) {
1078 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1083 * Loads and updates the given Sone from the configuration. If any error is
1084 * encountered, loading is aborted and the given Sone is not changed.
1087 * The Sone to load and update
1089 public void loadSone(Sone sone) {
1090 if (!isLocalSone(sone)) {
1091 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1096 String sonePrefix = "Sone/" + sone.getId();
1097 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1098 if (soneTime == null) {
1099 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1102 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1105 Profile profile = new Profile();
1106 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1107 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1108 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1109 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1110 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1111 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1114 Set<Post> posts = new HashSet<Post>();
1116 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1117 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1118 if (postId == null) {
1121 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1122 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1123 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1124 if ((postTime == 0) || (postText == null)) {
1125 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1128 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1129 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1130 post.setRecipient(getSone(postRecipientId));
1136 Set<Reply> replies = new HashSet<Reply>();
1138 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1139 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1140 if (replyId == null) {
1143 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1144 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1145 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1146 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1147 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1150 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1153 /* load post likes. */
1154 Set<String> likedPostIds = new HashSet<String>();
1156 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1157 if (likedPostId == null) {
1160 likedPostIds.add(likedPostId);
1163 /* load reply likes. */
1164 Set<String> likedReplyIds = new HashSet<String>();
1166 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1167 if (likedReplyId == null) {
1170 likedReplyIds.add(likedReplyId);
1174 Set<String> friends = new HashSet<String>();
1176 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1177 if (friendId == null) {
1180 friends.add(friendId);
1183 /* if weāre still here, Sone was loaded successfully. */
1184 synchronized (sone) {
1185 sone.setTime(soneTime);
1186 sone.setProfile(profile);
1187 sone.setPosts(posts);
1188 sone.setReplies(replies);
1189 sone.setLikePostIds(likedPostIds);
1190 sone.setLikeReplyIds(likedReplyIds);
1191 sone.setFriends(friends);
1192 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1194 synchronized (newSones) {
1195 for (String friend : friends) {
1196 knownSones.add(friend);
1199 synchronized (newPosts) {
1200 for (Post post : posts) {
1201 knownPosts.add(post.getId());
1204 synchronized (newReplies) {
1205 for (Reply reply : replies) {
1206 knownReplies.add(reply.getId());
1212 * Saves the given Sone. This will persist all local settings for the given
1213 * Sone, such as the friends list and similar, private options.
1218 public synchronized void saveSone(Sone sone) {
1219 if (!isLocalSone(sone)) {
1220 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1223 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1224 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1228 logger.log(Level.INFO, "Saving Sone: %s", sone);
1229 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1231 /* save Sone into configuration. */
1232 String sonePrefix = "Sone/" + sone.getId();
1233 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1234 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1237 Profile profile = sone.getProfile();
1238 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1239 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1240 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1241 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1242 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1243 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1246 int postCounter = 0;
1247 for (Post post : sone.getPosts()) {
1248 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1249 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1250 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1251 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1252 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1254 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1257 int replyCounter = 0;
1258 for (Reply reply : sone.getReplies()) {
1259 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1260 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1261 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1262 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1263 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1265 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1267 /* save post likes. */
1268 int postLikeCounter = 0;
1269 for (String postId : sone.getLikedPostIds()) {
1270 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1272 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1274 /* save reply likes. */
1275 int replyLikeCounter = 0;
1276 for (String replyId : sone.getLikedReplyIds()) {
1277 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1279 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1282 int friendCounter = 0;
1283 for (String friendId : sone.getFriends()) {
1284 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1286 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1288 configuration.save();
1289 logger.log(Level.INFO, "Sone %s saved.", sone);
1290 } catch (ConfigurationException ce1) {
1291 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1296 * Creates a new post.
1299 * The Sone that creates the post
1301 * The text of the post
1302 * @return The created post
1304 public Post createPost(Sone sone, String text) {
1305 return createPost(sone, System.currentTimeMillis(), text);
1309 * Creates a new post.
1312 * The Sone that creates the post
1314 * The time of the post
1316 * The text of the post
1317 * @return The created post
1319 public Post createPost(Sone sone, long time, String text) {
1320 return createPost(sone, null, time, text);
1324 * Creates a new post.
1327 * The Sone that creates the post
1329 * The recipient Sone, or {@code null} if this post does not have
1332 * The text of the post
1333 * @return The created post
1335 public Post createPost(Sone sone, Sone recipient, String text) {
1336 return createPost(sone, recipient, System.currentTimeMillis(), text);
1340 * Creates a new post.
1343 * The Sone that creates the post
1345 * The recipient Sone, or {@code null} if this post does not have
1348 * The time of the post
1350 * The text of the post
1351 * @return The created post
1353 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1354 if (!isLocalSone(sone)) {
1355 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1358 Post post = new Post(sone, time, text);
1359 if (recipient != null) {
1360 post.setRecipient(recipient);
1362 synchronized (posts) {
1363 posts.put(post.getId(), post);
1365 synchronized (newPosts) {
1366 knownPosts.add(post.getId());
1374 * Deletes the given post.
1377 * The post to delete
1379 public void deletePost(Post post) {
1380 if (!isLocalSone(post.getSone())) {
1381 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1384 post.getSone().removePost(post);
1385 synchronized (posts) {
1386 posts.remove(post.getId());
1388 saveSone(post.getSone());
1392 * Marks the given post as known, if it is currently a new post (according
1393 * to {@link #isNewPost(String)}).
1396 * The post to mark as known
1398 public void markPostKnown(Post post) {
1399 synchronized (newPosts) {
1400 if (newPosts.remove(post.getId())) {
1401 knownPosts.add(post.getId());
1402 coreListenerManager.fireMarkPostKnown(post);
1403 saveConfiguration();
1409 * Creates a new reply.
1412 * The Sone that creates the reply
1414 * The post that this reply refers to
1416 * The text of the reply
1417 * @return The created reply
1419 public Reply createReply(Sone sone, Post post, String text) {
1420 return createReply(sone, post, System.currentTimeMillis(), text);
1424 * Creates a new reply.
1427 * The Sone that creates the reply
1429 * The post that this reply refers to
1431 * The time of the reply
1433 * The text of the reply
1434 * @return The created reply
1436 public Reply createReply(Sone sone, Post post, long time, String text) {
1437 if (!isLocalSone(sone)) {
1438 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1441 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1442 synchronized (replies) {
1443 replies.put(reply.getId(), reply);
1445 synchronized (newReplies) {
1446 knownReplies.add(reply.getId());
1448 sone.addReply(reply);
1454 * Deletes the given reply.
1457 * The reply to delete
1459 public void deleteReply(Reply reply) {
1460 Sone sone = reply.getSone();
1461 if (!isLocalSone(sone)) {
1462 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1465 synchronized (replies) {
1466 replies.remove(reply.getId());
1468 sone.removeReply(reply);
1473 * Marks the given reply as known, if it is currently a new reply (according
1474 * to {@link #isNewReply(String)}).
1477 * The reply to mark as known
1479 public void markReplyKnown(Reply reply) {
1480 synchronized (newReplies) {
1481 if (newReplies.remove(reply.getId())) {
1482 knownReplies.add(reply.getId());
1483 coreListenerManager.fireMarkReplyKnown(reply);
1484 saveConfiguration();
1490 * Creates a new top-level album for the given Sone.
1493 * The Sone to create the album for
1494 * @return The new album
1496 public Album createAlbum(Sone sone) {
1497 return createAlbum(sone, null);
1501 * Creates a new album for the given Sone.
1504 * The Sone to create the album for
1506 * The parent of the album (may be {@code null} to create a
1508 * @return The new album
1510 public Album createAlbum(Sone sone, Album parent) {
1511 Album album = new Album();
1512 synchronized (albums) {
1513 albums.put(album.getId(), album);
1515 album.setSone(sone);
1516 if (parent != null) {
1517 parent.addAlbum(album);
1519 sone.addAlbum(album);
1526 public void start() {
1527 loadConfiguration();
1528 updateChecker.addUpdateListener(this);
1529 updateChecker.start();
1535 public void stop() {
1536 synchronized (localSones) {
1537 for (SoneInserter soneInserter : soneInserters.values()) {
1538 soneInserter.stop();
1541 updateChecker.stop();
1542 updateChecker.removeUpdateListener(this);
1543 soneDownloader.stop();
1544 saveConfiguration();
1549 * Saves the current options.
1551 public void saveConfiguration() {
1552 synchronized (configuration) {
1553 if (storingConfiguration) {
1554 logger.log(Level.FINE, "Already storing configurationā¦");
1557 storingConfiguration = true;
1560 /* store the options first. */
1562 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1563 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1564 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1565 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1566 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1568 /* save known Sones. */
1569 int soneCounter = 0;
1570 synchronized (newSones) {
1571 for (String knownSoneId : knownSones) {
1572 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1574 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1577 /* save known posts. */
1578 int postCounter = 0;
1579 synchronized (newPosts) {
1580 for (String knownPostId : knownPosts) {
1581 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1583 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1586 /* save known replies. */
1587 int replyCounter = 0;
1588 synchronized (newReplies) {
1589 for (String knownReplyId : knownReplies) {
1590 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1592 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1596 configuration.save();
1598 } catch (ConfigurationException ce1) {
1599 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1601 synchronized (configuration) {
1602 storingConfiguration = false;
1612 * Loads the configuration.
1614 @SuppressWarnings("unchecked")
1615 private void loadConfiguration() {
1616 /* create options. */
1617 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
1620 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1621 SoneInserter.setInsertionDelay(newValue);
1625 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
1626 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
1627 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
1629 /* read options from configuration. */
1630 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
1631 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
1632 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
1633 options.getBooleanOption("ClearOnNextRestart").set(null);
1634 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
1635 if (clearConfiguration) {
1636 /* stop loading the configuration. */
1640 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
1641 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
1643 /* load known Sones. */
1644 int soneCounter = 0;
1646 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1647 if (knownSoneId == null) {
1650 synchronized (newSones) {
1651 knownSones.add(knownSoneId);
1655 /* load known posts. */
1656 int postCounter = 0;
1658 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
1659 if (knownPostId == null) {
1662 synchronized (newPosts) {
1663 knownPosts.add(knownPostId);
1667 /* load known replies. */
1668 int replyCounter = 0;
1670 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
1671 if (knownReplyId == null) {
1674 synchronized (newReplies) {
1675 knownReplies.add(knownReplyId);
1682 * Generate a Sone URI from the given URI and latest edition.
1685 * The URI to derive the Sone URI from
1686 * @return The derived URI
1688 private FreenetURI getSoneUri(String uriString) {
1690 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
1692 } catch (MalformedURLException mue1) {
1693 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
1699 // INTERFACE IdentityListener
1706 public void ownIdentityAdded(OwnIdentity ownIdentity) {
1707 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
1708 if (ownIdentity.hasContext("Sone")) {
1709 addLocalSone(ownIdentity);
1717 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
1718 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
1725 public void identityAdded(Identity identity) {
1726 logger.log(Level.FINEST, "Adding Identity: " + identity);
1727 addRemoteSone(identity);
1734 public void identityUpdated(final Identity identity) {
1735 new Thread(new Runnable() {
1738 @SuppressWarnings("synthetic-access")
1740 Sone sone = getRemoteSone(identity.getId());
1741 soneDownloader.fetchSone(sone);
1750 public void identityRemoved(Identity identity) {
1755 // INTERFACE UpdateListener
1762 public void updateFound(Version version, long releaseTime) {
1763 coreListenerManager.fireUpdateFound(version, releaseTime);