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.Profile.Field;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.TemporaryImage;
43 import net.pterodactylus.sone.freenet.wot.Identity;
44 import net.pterodactylus.sone.freenet.wot.IdentityListener;
45 import net.pterodactylus.sone.freenet.wot.IdentityManager;
46 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
47 import net.pterodactylus.sone.freenet.wot.Trust;
48 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
49 import net.pterodactylus.sone.main.SonePlugin;
50 import net.pterodactylus.util.config.Configuration;
51 import net.pterodactylus.util.config.ConfigurationException;
52 import net.pterodactylus.util.logging.Logging;
53 import net.pterodactylus.util.number.Numbers;
54 import net.pterodactylus.util.validation.Validation;
55 import net.pterodactylus.util.version.Version;
56 import freenet.keys.FreenetURI;
61 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63 public class Core implements IdentityListener, UpdateListener, ImageInsertListener {
66 * Enumeration for the possible states of a {@link Sone}.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public enum SoneStatus {
72 /** The Sone is unknown, i.e. not yet downloaded. */
75 /** The Sone is idle, i.e. not being downloaded or inserted. */
78 /** The Sone is currently being inserted. */
81 /** The Sone is currently being downloaded. */
86 private static final Logger logger = Logging.getLogger(Core.class);
89 private final Options options = new Options();
91 /** The preferences. */
92 private final Preferences preferences = new Preferences(options);
94 /** The core listener manager. */
95 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
97 /** The configuration. */
98 private Configuration configuration;
100 /** Whether we’re currently saving the configuration. */
101 private boolean storingConfiguration = false;
103 /** The identity manager. */
104 private final IdentityManager identityManager;
106 /** Interface to freenet. */
107 private final FreenetInterface freenetInterface;
109 /** The Sone downloader. */
110 private final SoneDownloader soneDownloader;
112 /** The image inserter. */
113 private final ImageInserter imageInserter;
115 /** The update checker. */
116 private final UpdateChecker updateChecker;
118 /** Whether the core has been stopped. */
119 private volatile boolean stopped;
121 /** The Sones’ statuses. */
122 /* synchronize access on itself. */
123 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
125 /** Locked local Sones. */
126 /* synchronize on itself. */
127 private final Set<Sone> lockedSones = new HashSet<Sone>();
129 /** Sone inserters. */
130 /* synchronize access on this on localSones. */
131 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
133 /** All local Sones. */
134 /* synchronize access on this on itself. */
135 private Map<String, Sone> localSones = new HashMap<String, Sone>();
137 /** All remote Sones. */
138 /* synchronize access on this on itself. */
139 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
141 /** All new Sones. */
142 private Set<String> newSones = new HashSet<String>();
144 /** All known Sones. */
145 /* synchronize access on {@link #newSones}. */
146 private Set<String> knownSones = new HashSet<String>();
149 private Map<String, Post> posts = new HashMap<String, Post>();
151 /** All new posts. */
152 private Set<String> newPosts = new HashSet<String>();
154 /** All known posts. */
155 /* synchronize access on {@link #newPosts}. */
156 private Set<String> knownPosts = new HashSet<String>();
159 private Map<String, Reply> replies = new HashMap<String, Reply>();
161 /** All new replies. */
162 private Set<String> newReplies = new HashSet<String>();
164 /** All known replies. */
165 private Set<String> knownReplies = new HashSet<String>();
167 /** All bookmarked posts. */
168 /* synchronize access on itself. */
169 private Set<String> bookmarkedPosts = new HashSet<String>();
171 /** Trusted identities, sorted by own identities. */
172 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
174 /** All known albums. */
175 private Map<String, Album> albums = new HashMap<String, Album>();
177 /** All known images. */
178 private Map<String, Image> images = new HashMap<String, Image>();
180 /** All temporary images. */
181 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
184 * Creates a new core.
186 * @param configuration
187 * The configuration of the core
188 * @param freenetInterface
189 * The freenet interface
190 * @param identityManager
191 * The identity manager
193 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
194 this.configuration = configuration;
195 this.freenetInterface = freenetInterface;
196 this.identityManager = identityManager;
197 this.soneDownloader = new SoneDownloader(this, freenetInterface);
198 this.imageInserter = new ImageInserter(this, freenetInterface);
199 this.updateChecker = new UpdateChecker(freenetInterface);
203 // LISTENER MANAGEMENT
207 * Adds a new core listener.
209 * @param coreListener
210 * The listener to add
212 public void addCoreListener(CoreListener coreListener) {
213 coreListenerManager.addListener(coreListener);
217 * Removes a core listener.
219 * @param coreListener
220 * The listener to remove
222 public void removeCoreListener(CoreListener coreListener) {
223 coreListenerManager.removeListener(coreListener);
231 * Sets the configuration to use. This will automatically save the current
232 * configuration to the given configuration.
234 * @param configuration
235 * The new configuration to use
237 public void setConfiguration(Configuration configuration) {
238 this.configuration = configuration;
243 * Returns the options used by the core.
245 * @return The options of the core
247 public Preferences getPreferences() {
252 * Returns the identity manager used by the core.
254 * @return The identity manager
256 public IdentityManager getIdentityManager() {
257 return identityManager;
261 * Returns the update checker.
263 * @return The update checker
265 public UpdateChecker getUpdateChecker() {
266 return updateChecker;
270 * Returns the status of the given Sone.
273 * The Sone to get the status for
274 * @return The status of the Sone
276 public SoneStatus getSoneStatus(Sone sone) {
277 synchronized (soneStatuses) {
278 return soneStatuses.get(sone);
283 * Sets the status of the given Sone.
286 * The Sone to set the status of
290 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
291 synchronized (soneStatuses) {
292 soneStatuses.put(sone, soneStatus);
297 * Returns whether the given Sone is currently locked.
301 * @return {@code true} if the Sone is locked, {@code false} if it is not
303 public boolean isLocked(Sone sone) {
304 synchronized (lockedSones) {
305 return lockedSones.contains(sone);
310 * Returns all Sones, remote and local.
314 public Set<Sone> getSones() {
315 Set<Sone> allSones = new HashSet<Sone>();
316 allSones.addAll(getLocalSones());
317 allSones.addAll(getRemoteSones());
322 * Returns the Sone with the given ID, regardless whether it’s local or
326 * The ID of the Sone to get
327 * @return The Sone with the given ID, or {@code null} if there is no such
330 public Sone getSone(String id) {
331 return getSone(id, true);
335 * Returns the Sone with the given ID, regardless whether it’s local or
339 * The ID of the Sone to get
341 * {@code true} to create a new Sone if none exists,
342 * {@code false} to return {@code null} if a Sone with the given
344 * @return The Sone with the given ID, or {@code null} if there is no such
347 public Sone getSone(String id, boolean create) {
348 if (isLocalSone(id)) {
349 return getLocalSone(id);
351 return getRemoteSone(id, create);
355 * Checks whether the core knows a Sone with the given ID.
359 * @return {@code true} if there is a Sone with the given ID, {@code false}
362 public boolean hasSone(String id) {
363 return isLocalSone(id) || isRemoteSone(id);
367 * Returns whether the given Sone is a local Sone.
370 * The Sone to check for its locality
371 * @return {@code true} if the given Sone is local, {@code false} otherwise
373 public boolean isLocalSone(Sone sone) {
374 synchronized (localSones) {
375 return localSones.containsKey(sone.getId());
380 * Returns whether the given ID is the ID of a local Sone.
383 * The Sone ID to check for its locality
384 * @return {@code true} if the given ID is a local Sone, {@code false}
387 public boolean isLocalSone(String id) {
388 synchronized (localSones) {
389 return localSones.containsKey(id);
394 * Returns all local Sones.
396 * @return All local Sones
398 public Set<Sone> getLocalSones() {
399 synchronized (localSones) {
400 return new HashSet<Sone>(localSones.values());
405 * Returns the local Sone with the given ID.
408 * The ID of the Sone to get
409 * @return The Sone with the given ID
411 public Sone getLocalSone(String id) {
412 return getLocalSone(id, true);
416 * Returns the local Sone with the given ID, optionally creating a new Sone.
421 * {@code true} to create a new Sone if none exists,
422 * {@code false} to return null if none exists
423 * @return The Sone with the given ID, or {@code null}
425 public Sone getLocalSone(String id, boolean create) {
426 synchronized (localSones) {
427 Sone sone = localSones.get(id);
428 if ((sone == null) && create) {
430 localSones.put(id, sone);
431 setSoneStatus(sone, SoneStatus.unknown);
438 * Returns all remote Sones.
440 * @return All remote Sones
442 public Set<Sone> getRemoteSones() {
443 synchronized (remoteSones) {
444 return new HashSet<Sone>(remoteSones.values());
449 * Returns the remote Sone with the given ID.
452 * The ID of the remote Sone to get
453 * @return The Sone with the given ID
455 public Sone getRemoteSone(String id) {
456 return getRemoteSone(id, true);
460 * Returns the remote Sone with the given ID.
463 * The ID of the remote Sone to get
465 * {@code true} to always create a Sone, {@code false} to return
466 * {@code null} if no Sone with the given ID exists
467 * @return The Sone with the given ID
469 public Sone getRemoteSone(String id, boolean create) {
470 synchronized (remoteSones) {
471 Sone sone = remoteSones.get(id);
472 if ((sone == null) && create) {
474 remoteSones.put(id, sone);
475 setSoneStatus(sone, SoneStatus.unknown);
482 * Returns whether the given Sone is a remote Sone.
486 * @return {@code true} if the given Sone is a remote Sone, {@code false}
489 public boolean isRemoteSone(Sone sone) {
490 synchronized (remoteSones) {
491 return remoteSones.containsKey(sone.getId());
496 * Returns whether the Sone with the given ID is a remote Sone.
499 * The ID of the Sone to check
500 * @return {@code true} if the Sone with the given ID is a remote Sone,
501 * {@code false} otherwise
503 public boolean isRemoteSone(String id) {
504 synchronized (remoteSones) {
505 return remoteSones.containsKey(id);
510 * Returns whether the Sone with the given ID is a new Sone.
513 * The ID of the sone to check for
514 * @return {@code true} if the given Sone is new, false otherwise
516 public boolean isNewSone(String soneId) {
517 synchronized (newSones) {
518 return !knownSones.contains(soneId) && newSones.contains(soneId);
523 * Returns whether the given Sone has been modified.
526 * The Sone to check for modifications
527 * @return {@code true} if a modification has been detected in the Sone,
528 * {@code false} otherwise
530 public boolean isModifiedSone(Sone sone) {
531 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
535 * Returns whether the target Sone is trusted by the origin Sone.
541 * @return {@code true} if the target Sone is trusted by the origin Sone
543 public boolean isSoneTrusted(Sone origin, Sone target) {
544 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
545 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
549 * Returns the post with the given ID.
552 * The ID of the post to get
553 * @return The post with the given ID, or a new post with the given ID
555 public Post getPost(String postId) {
556 return getPost(postId, true);
560 * Returns the post with the given ID, optionally creating a new post.
563 * The ID of the post to get
565 * {@code true} it create a new post if no post with the given ID
566 * exists, {@code false} to return {@code null}
567 * @return The post, or {@code null} if there is no such post
569 public Post getPost(String postId, boolean create) {
570 synchronized (posts) {
571 Post post = posts.get(postId);
572 if ((post == null) && create) {
573 post = new Post(postId);
574 posts.put(postId, post);
581 * Returns whether the given post ID is new.
585 * @return {@code true} if the post is considered to be new, {@code false}
588 public boolean isNewPost(String postId) {
589 synchronized (newPosts) {
590 return !knownPosts.contains(postId) && newPosts.contains(postId);
595 * Returns all posts that have the given Sone as recipient.
597 * @see Post#getRecipient()
599 * The recipient of the posts
600 * @return All posts that have the given Sone as recipient
602 public Set<Post> getDirectedPosts(Sone recipient) {
603 Validation.begin().isNotNull("Recipient", recipient).check();
604 Set<Post> directedPosts = new HashSet<Post>();
605 synchronized (posts) {
606 for (Post post : posts.values()) {
607 if (recipient.equals(post.getRecipient())) {
608 directedPosts.add(post);
612 return directedPosts;
616 * Returns the reply with the given ID. If there is no reply with the given
617 * ID yet, a new one is created.
620 * The ID of the reply to get
623 public Reply getReply(String replyId) {
624 return getReply(replyId, true);
628 * Returns the reply with the given ID. If there is no reply with the given
629 * ID yet, a new one is created, unless {@code create} is false in which
630 * case {@code null} is returned.
633 * The ID of the reply to get
635 * {@code true} to always return a {@link Reply}, {@code false}
636 * to return {@code null} if no reply can be found
637 * @return The reply, or {@code null} if there is no such reply
639 public Reply getReply(String replyId, boolean create) {
640 synchronized (replies) {
641 Reply reply = replies.get(replyId);
642 if (create && (reply == null)) {
643 reply = new Reply(replyId);
644 replies.put(replyId, reply);
651 * Returns all replies for the given post, order ascending by time.
654 * The post to get all replies for
655 * @return All replies for the given post
657 public List<Reply> getReplies(Post post) {
658 Set<Sone> sones = getSones();
659 List<Reply> replies = new ArrayList<Reply>();
660 for (Sone sone : sones) {
661 for (Reply reply : sone.getReplies()) {
662 if (reply.getPost().equals(post)) {
667 Collections.sort(replies, Reply.TIME_COMPARATOR);
672 * Returns whether the reply with the given ID is new.
675 * The ID of the reply to check
676 * @return {@code true} if the reply is considered to be new, {@code false}
679 public boolean isNewReply(String replyId) {
680 synchronized (newReplies) {
681 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
686 * Returns all Sones that have liked the given post.
689 * The post to get the liking Sones for
690 * @return The Sones that like the given post
692 public Set<Sone> getLikes(Post post) {
693 Set<Sone> sones = new HashSet<Sone>();
694 for (Sone sone : getSones()) {
695 if (sone.getLikedPostIds().contains(post.getId())) {
703 * Returns all Sones that have liked the given reply.
706 * The reply to get the liking Sones for
707 * @return The Sones that like the given reply
709 public Set<Sone> getLikes(Reply reply) {
710 Set<Sone> sones = new HashSet<Sone>();
711 for (Sone sone : getSones()) {
712 if (sone.getLikedReplyIds().contains(reply.getId())) {
720 * Returns whether the given post is bookmarked.
724 * @return {@code true} if the given post is bookmarked, {@code false}
727 public boolean isBookmarked(Post post) {
728 return isPostBookmarked(post.getId());
732 * Returns whether the post with the given ID is bookmarked.
735 * The ID of the post to check
736 * @return {@code true} if the post with the given ID is bookmarked,
737 * {@code false} otherwise
739 public boolean isPostBookmarked(String id) {
740 synchronized (bookmarkedPosts) {
741 return bookmarkedPosts.contains(id);
746 * Returns all currently known bookmarked posts.
748 * @return All bookmarked posts
750 public Set<Post> getBookmarkedPosts() {
751 Set<Post> posts = new HashSet<Post>();
752 synchronized (bookmarkedPosts) {
753 for (String bookmarkedPostId : bookmarkedPosts) {
754 Post post = getPost(bookmarkedPostId, false);
764 * Returns the album with the given ID, creating a new album if no album
765 * with the given ID can be found.
768 * The ID of the album
769 * @return The album with the given ID
771 public Album getAlbum(String albumId) {
772 return getAlbum(albumId, true);
776 * Returns the album with the given ID, optionally creating a new album if
777 * an album with the given ID can not be found.
780 * The ID of the album
782 * {@code true} to create a new album if none exists for the
784 * @return The album with the given ID, or {@code null} if no album with the
785 * given ID exists and {@code create} is {@code false}
787 public Album getAlbum(String albumId, boolean create) {
788 synchronized (albums) {
789 Album album = albums.get(albumId);
790 if (create && (album == null)) {
791 album = new Album(albumId);
792 albums.put(albumId, album);
799 * Returns the image with the given ID, creating it if necessary.
802 * The ID of the image
803 * @return The image with the given ID
805 public Image getImage(String imageId) {
806 return getImage(imageId, true);
810 * Returns the image with the given ID, optionally creating it if it does
814 * The ID of the image
816 * {@code true} to create an image if none exists with the given
818 * @return The image with the given ID, or {@code null} if none exists and
821 public Image getImage(String imageId, boolean create) {
822 synchronized (images) {
823 Image image = images.get(imageId);
824 if (create && (image == null)) {
825 image = new Image(imageId);
826 images.put(imageId, image);
833 * Returns the temporary image with the given ID.
836 * The ID of the temporary image
837 * @return The temporary image, or {@code null} if there is no temporary
838 * image with the given ID
840 public TemporaryImage getTemporaryImage(String imageId) {
841 synchronized (temporaryImages) {
842 return temporaryImages.get(imageId);
851 * Locks the given Sone. A locked Sone will not be inserted by
852 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
858 public void lockSone(Sone sone) {
859 synchronized (lockedSones) {
860 if (lockedSones.add(sone)) {
861 coreListenerManager.fireSoneLocked(sone);
867 * Unlocks the given Sone.
869 * @see #lockSone(Sone)
873 public void unlockSone(Sone sone) {
874 synchronized (lockedSones) {
875 if (lockedSones.remove(sone)) {
876 coreListenerManager.fireSoneUnlocked(sone);
882 * Adds a local Sone from the given ID which has to be the ID of an own
886 * The ID of an own identity to add a Sone for
887 * @return The added (or already existing) Sone
889 public Sone addLocalSone(String id) {
890 synchronized (localSones) {
891 if (localSones.containsKey(id)) {
892 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
893 return localSones.get(id);
895 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
896 if (ownIdentity == null) {
897 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
900 return addLocalSone(ownIdentity);
905 * Adds a local Sone from the given own identity.
908 * The own identity to create a Sone from
909 * @return The added (or already existing) Sone
911 public Sone addLocalSone(OwnIdentity ownIdentity) {
912 if (ownIdentity == null) {
913 logger.log(Level.WARNING, "Given OwnIdentity is null!");
916 synchronized (localSones) {
919 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
920 } catch (MalformedURLException mue1) {
921 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
924 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
925 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
926 /* TODO - load posts ’n stuff */
927 localSones.put(ownIdentity.getId(), sone);
928 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
929 soneInserters.put(sone, soneInserter);
930 setSoneStatus(sone, SoneStatus.idle);
932 if (!preferences.isSoneRescueMode()) {
933 soneInserter.start();
935 new Thread(new Runnable() {
938 @SuppressWarnings("synthetic-access")
940 if (!preferences.isSoneRescueMode()) {
943 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
944 coreListenerManager.fireRescuingSone(sone);
946 long edition = sone.getLatestEdition();
947 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
948 logger.log(Level.FINE, "Downloading edition " + edition + "…");
949 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
952 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
954 coreListenerManager.fireRescuedSone(sone);
955 soneInserter.start();
958 }, "Sone Downloader").start();
964 * Creates a new Sone for the given own identity.
967 * The own identity to create a Sone for
968 * @return The created Sone
970 public Sone createSone(OwnIdentity ownIdentity) {
972 ownIdentity.addContext("Sone");
973 } catch (WebOfTrustException wote1) {
974 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
977 Sone sone = addLocalSone(ownIdentity);
978 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
984 * Adds the Sone of the given identity.
987 * The identity whose Sone to add
988 * @return The added or already existing Sone
990 public Sone addRemoteSone(Identity identity) {
991 if (identity == null) {
992 logger.log(Level.WARNING, "Given Identity is null!");
995 synchronized (remoteSones) {
996 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
997 boolean newSone = sone.getRequestUri() == null;
998 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
999 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
1001 synchronized (newSones) {
1002 newSone = !knownSones.contains(sone.getId());
1004 newSones.add(sone.getId());
1008 coreListenerManager.fireNewSoneFound(sone);
1009 for (Sone localSone : getLocalSones()) {
1010 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
1011 localSone.addFriend(sone.getId());
1016 remoteSones.put(identity.getId(), sone);
1017 soneDownloader.addSone(sone);
1018 setSoneStatus(sone, SoneStatus.unknown);
1019 new Thread(new Runnable() {
1022 @SuppressWarnings("synthetic-access")
1024 soneDownloader.fetchSone(sone);
1027 }, "Sone Downloader").start();
1033 * Retrieves the trust relationship from the origin to the target. If the
1034 * trust relationship can not be retrieved, {@code null} is returned.
1036 * @see Identity#getTrust(OwnIdentity)
1038 * The origin of the trust tree
1040 * The target of the trust
1041 * @return The trust relationship
1043 public Trust getTrust(Sone origin, Sone target) {
1044 if (!isLocalSone(origin)) {
1045 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1048 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1052 * Sets the trust value of the given origin Sone for the target Sone.
1059 * The trust value (from {@code -100} to {@code 100})
1061 public void setTrust(Sone origin, Sone target, int trustValue) {
1062 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
1064 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1065 } catch (WebOfTrustException wote1) {
1066 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1071 * Removes any trust assignment for the given target Sone.
1078 public void removeTrust(Sone origin, Sone target) {
1079 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1081 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1082 } catch (WebOfTrustException wote1) {
1083 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1088 * Assigns the configured positive trust value for the given target.
1095 public void trustSone(Sone origin, Sone target) {
1096 setTrust(origin, target, preferences.getPositiveTrust());
1100 * Assigns the configured negative trust value for the given target.
1107 public void distrustSone(Sone origin, Sone target) {
1108 setTrust(origin, target, preferences.getNegativeTrust());
1112 * Removes the trust assignment for the given target.
1119 public void untrustSone(Sone origin, Sone target) {
1120 removeTrust(origin, target);
1124 * Updates the stores Sone with the given Sone.
1129 public void updateSone(Sone sone) {
1130 if (hasSone(sone.getId())) {
1131 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1132 Sone storedSone = getSone(sone.getId());
1133 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1134 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1137 synchronized (posts) {
1138 if (!soneRescueMode) {
1139 for (Post post : storedSone.getPosts()) {
1140 posts.remove(post.getId());
1141 if (!sone.getPosts().contains(post)) {
1142 coreListenerManager.firePostRemoved(post);
1146 List<Post> storedPosts = storedSone.getPosts();
1147 synchronized (newPosts) {
1148 for (Post post : sone.getPosts()) {
1149 post.setSone(storedSone);
1150 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1151 newPosts.add(post.getId());
1152 coreListenerManager.fireNewPostFound(post);
1154 posts.put(post.getId(), post);
1158 synchronized (replies) {
1159 if (!soneRescueMode) {
1160 for (Reply reply : storedSone.getReplies()) {
1161 replies.remove(reply.getId());
1162 if (!sone.getReplies().contains(reply)) {
1163 coreListenerManager.fireReplyRemoved(reply);
1167 Set<Reply> storedReplies = storedSone.getReplies();
1168 synchronized (newReplies) {
1169 for (Reply reply : sone.getReplies()) {
1170 reply.setSone(storedSone);
1171 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1172 newReplies.add(reply.getId());
1173 coreListenerManager.fireNewReplyFound(reply);
1175 replies.put(reply.getId(), reply);
1179 synchronized (storedSone) {
1180 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1181 storedSone.setTime(sone.getTime());
1183 storedSone.setClient(sone.getClient());
1184 storedSone.setProfile(sone.getProfile());
1185 if (soneRescueMode) {
1186 for (Post post : sone.getPosts()) {
1187 storedSone.addPost(post);
1189 for (Reply reply : sone.getReplies()) {
1190 storedSone.addReply(reply);
1192 for (String likedPostId : sone.getLikedPostIds()) {
1193 storedSone.addLikedPostId(likedPostId);
1195 for (String likedReplyId : sone.getLikedReplyIds()) {
1196 storedSone.addLikedReplyId(likedReplyId);
1199 storedSone.setPosts(sone.getPosts());
1200 storedSone.setReplies(sone.getReplies());
1201 storedSone.setLikePostIds(sone.getLikedPostIds());
1202 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1203 storedSone.setAlbums(sone.getAlbums());
1205 storedSone.setLatestEdition(sone.getLatestEdition());
1211 * Deletes the given Sone. This will remove the Sone from the
1212 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1213 * and remove the context from its identity.
1216 * The Sone to delete
1218 public void deleteSone(Sone sone) {
1219 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1220 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1223 synchronized (localSones) {
1224 if (!localSones.containsKey(sone.getId())) {
1225 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1228 localSones.remove(sone.getId());
1229 soneInserters.remove(sone).stop();
1232 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1233 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1234 } catch (WebOfTrustException wote1) {
1235 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1238 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1239 } catch (ConfigurationException ce1) {
1240 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1245 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1246 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1249 * The Sone to mark as known
1251 public void markSoneKnown(Sone sone) {
1252 synchronized (newSones) {
1253 if (newSones.remove(sone.getId())) {
1254 knownSones.add(sone.getId());
1255 coreListenerManager.fireMarkSoneKnown(sone);
1256 saveConfiguration();
1262 * Loads and updates the given Sone from the configuration. If any error is
1263 * encountered, loading is aborted and the given Sone is not changed.
1266 * The Sone to load and update
1268 public void loadSone(Sone sone) {
1269 if (!isLocalSone(sone)) {
1270 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1275 String sonePrefix = "Sone/" + sone.getId();
1276 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1277 if (soneTime == null) {
1278 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1281 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1284 Profile profile = new Profile();
1285 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1286 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1287 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1288 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1289 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1290 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1292 /* load profile fields. */
1294 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1295 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1296 if (fieldName == null) {
1299 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1300 profile.addField(fieldName).setValue(fieldValue);
1304 Set<Post> posts = new HashSet<Post>();
1306 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1307 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1308 if (postId == null) {
1311 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1312 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1313 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1314 if ((postTime == 0) || (postText == null)) {
1315 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1318 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1319 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1320 post.setRecipient(getSone(postRecipientId));
1326 Set<Reply> replies = new HashSet<Reply>();
1328 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1329 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1330 if (replyId == null) {
1333 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1334 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1335 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1336 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1337 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1340 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1343 /* load post likes. */
1344 Set<String> likedPostIds = new HashSet<String>();
1346 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1347 if (likedPostId == null) {
1350 likedPostIds.add(likedPostId);
1353 /* load reply likes. */
1354 Set<String> likedReplyIds = new HashSet<String>();
1356 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1357 if (likedReplyId == null) {
1360 likedReplyIds.add(likedReplyId);
1364 Set<String> friends = new HashSet<String>();
1366 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1367 if (friendId == null) {
1370 friends.add(friendId);
1374 List<Album> topLevelAlbums = new ArrayList<Album>();
1375 int albumCounter = 0;
1377 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1378 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1379 if (albumId == null) {
1382 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1383 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1384 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1385 if ((albumTitle == null) || (albumDescription == null)) {
1386 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1389 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription);
1390 if (albumParentId != null) {
1391 Album parentAlbum = getAlbum(albumParentId, false);
1392 if (parentAlbum == null) {
1393 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1396 parentAlbum.addAlbum(album);
1398 topLevelAlbums.add(album);
1403 int imageCounter = 0;
1405 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1406 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1407 if (imageId == null) {
1410 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1411 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1412 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1413 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1414 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1415 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1416 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1417 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1418 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1421 Album album = getAlbum(albumId, false);
1422 if (album == null) {
1423 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1426 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1427 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1428 album.addImage(image);
1432 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1433 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1435 /* if we’re still here, Sone was loaded successfully. */
1436 synchronized (sone) {
1437 sone.setTime(soneTime);
1438 sone.setProfile(profile);
1439 sone.setPosts(posts);
1440 sone.setReplies(replies);
1441 sone.setLikePostIds(likedPostIds);
1442 sone.setLikeReplyIds(likedReplyIds);
1443 sone.setFriends(friends);
1444 sone.setAlbums(topLevelAlbums);
1445 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1447 synchronized (newSones) {
1448 for (String friend : friends) {
1449 knownSones.add(friend);
1452 synchronized (newPosts) {
1453 for (Post post : posts) {
1454 knownPosts.add(post.getId());
1457 synchronized (newReplies) {
1458 for (Reply reply : replies) {
1459 knownReplies.add(reply.getId());
1465 * Saves the given Sone. This will persist all local settings for the given
1466 * Sone, such as the friends list and similar, private options.
1471 public synchronized void saveSone(Sone sone) {
1472 if (!isLocalSone(sone)) {
1473 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1476 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1477 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1481 logger.log(Level.INFO, "Saving Sone: %s", sone);
1483 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1485 /* save Sone into configuration. */
1486 String sonePrefix = "Sone/" + sone.getId();
1487 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1488 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1491 Profile profile = sone.getProfile();
1492 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1493 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1494 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1495 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1496 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1497 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1499 /* save profile fields. */
1500 int fieldCounter = 0;
1501 for (Field profileField : profile.getFields()) {
1502 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1503 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1504 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1506 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1509 int postCounter = 0;
1510 for (Post post : sone.getPosts()) {
1511 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1512 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1513 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1514 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1515 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1517 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1520 int replyCounter = 0;
1521 for (Reply reply : sone.getReplies()) {
1522 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1523 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1524 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1525 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1526 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1528 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1530 /* save post likes. */
1531 int postLikeCounter = 0;
1532 for (String postId : sone.getLikedPostIds()) {
1533 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1535 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1537 /* save reply likes. */
1538 int replyLikeCounter = 0;
1539 for (String replyId : sone.getLikedReplyIds()) {
1540 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1542 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1545 int friendCounter = 0;
1546 for (String friendId : sone.getFriends()) {
1547 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1549 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1551 /* save albums. first, collect in a flat structure, top-level first. */
1552 List<Album> albums = Sone.flattenAlbums(sone.getAlbums());
1554 int albumCounter = 0;
1555 for (Album album : albums) {
1556 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1557 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1558 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1559 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1560 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1562 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1565 int imageCounter = 0;
1566 for (Album album : albums) {
1567 for (Image image : album.getImages()) {
1568 if (!image.isInserted()) {
1571 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1572 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1573 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1574 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1575 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1576 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1577 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1578 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1579 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1582 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1585 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1587 configuration.save();
1588 logger.log(Level.INFO, "Sone %s saved.", sone);
1589 } catch (ConfigurationException ce1) {
1590 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1591 } catch (WebOfTrustException wote1) {
1592 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1597 * Creates a new post.
1600 * The Sone that creates the post
1602 * The text of the post
1603 * @return The created post
1605 public Post createPost(Sone sone, String text) {
1606 return createPost(sone, System.currentTimeMillis(), text);
1610 * Creates a new post.
1613 * The Sone that creates the post
1615 * The time of the post
1617 * The text of the post
1618 * @return The created post
1620 public Post createPost(Sone sone, long time, String text) {
1621 return createPost(sone, null, time, text);
1625 * Creates a new post.
1628 * The Sone that creates the post
1630 * The recipient Sone, or {@code null} if this post does not have
1633 * The text of the post
1634 * @return The created post
1636 public Post createPost(Sone sone, Sone recipient, String text) {
1637 return createPost(sone, recipient, System.currentTimeMillis(), text);
1641 * Creates a new post.
1644 * The Sone that creates the post
1646 * The recipient Sone, or {@code null} if this post does not have
1649 * The time of the post
1651 * The text of the post
1652 * @return The created post
1654 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1655 if (!isLocalSone(sone)) {
1656 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1659 Post post = new Post(sone, time, text);
1660 if (recipient != null) {
1661 post.setRecipient(recipient);
1663 synchronized (posts) {
1664 posts.put(post.getId(), post);
1666 synchronized (newPosts) {
1667 newPosts.add(post.getId());
1668 coreListenerManager.fireNewPostFound(post);
1676 * Deletes the given post.
1679 * The post to delete
1681 public void deletePost(Post post) {
1682 if (!isLocalSone(post.getSone())) {
1683 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1686 post.getSone().removePost(post);
1687 synchronized (posts) {
1688 posts.remove(post.getId());
1690 synchronized (newPosts) {
1691 markPostKnown(post);
1692 knownPosts.remove(post.getId());
1694 saveSone(post.getSone());
1698 * Marks the given post as known, if it is currently a new post (according
1699 * to {@link #isNewPost(String)}).
1702 * The post to mark as known
1704 public void markPostKnown(Post post) {
1705 synchronized (newPosts) {
1706 if (newPosts.remove(post.getId())) {
1707 knownPosts.add(post.getId());
1708 coreListenerManager.fireMarkPostKnown(post);
1709 saveConfiguration();
1715 * Bookmarks the given post.
1718 * The post to bookmark
1720 public void bookmark(Post post) {
1721 bookmarkPost(post.getId());
1725 * Bookmarks the post with the given ID.
1728 * The ID of the post to bookmark
1730 public void bookmarkPost(String id) {
1731 synchronized (bookmarkedPosts) {
1732 bookmarkedPosts.add(id);
1737 * Removes the given post from the bookmarks.
1740 * The post to unbookmark
1742 public void unbookmark(Post post) {
1743 unbookmarkPost(post.getId());
1747 * Removes the post with the given ID from the bookmarks.
1750 * The ID of the post to unbookmark
1752 public void unbookmarkPost(String id) {
1753 synchronized (bookmarkedPosts) {
1754 bookmarkedPosts.remove(id);
1759 * Creates a new reply.
1762 * The Sone that creates the reply
1764 * The post that this reply refers to
1766 * The text of the reply
1767 * @return The created reply
1769 public Reply createReply(Sone sone, Post post, String text) {
1770 return createReply(sone, post, System.currentTimeMillis(), text);
1774 * Creates a new reply.
1777 * The Sone that creates the reply
1779 * The post that this reply refers to
1781 * The time of the reply
1783 * The text of the reply
1784 * @return The created reply
1786 public Reply createReply(Sone sone, Post post, long time, String text) {
1787 if (!isLocalSone(sone)) {
1788 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1791 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1792 synchronized (replies) {
1793 replies.put(reply.getId(), reply);
1795 synchronized (newReplies) {
1796 newReplies.add(reply.getId());
1797 coreListenerManager.fireNewReplyFound(reply);
1799 sone.addReply(reply);
1805 * Deletes the given reply.
1808 * The reply to delete
1810 public void deleteReply(Reply reply) {
1811 Sone sone = reply.getSone();
1812 if (!isLocalSone(sone)) {
1813 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1816 synchronized (replies) {
1817 replies.remove(reply.getId());
1819 synchronized (newReplies) {
1820 markReplyKnown(reply);
1821 knownReplies.remove(reply.getId());
1823 sone.removeReply(reply);
1828 * Marks the given reply as known, if it is currently a new reply (according
1829 * to {@link #isNewReply(String)}).
1832 * The reply to mark as known
1834 public void markReplyKnown(Reply reply) {
1835 synchronized (newReplies) {
1836 if (newReplies.remove(reply.getId())) {
1837 knownReplies.add(reply.getId());
1838 coreListenerManager.fireMarkReplyKnown(reply);
1839 saveConfiguration();
1845 * Creates a new top-level album for the given Sone.
1848 * The Sone to create the album for
1849 * @return The new album
1851 public Album createAlbum(Sone sone) {
1852 return createAlbum(sone, null);
1856 * Creates a new album for the given Sone.
1859 * The Sone to create the album for
1861 * The parent of the album (may be {@code null} to create a
1863 * @return The new album
1865 public Album createAlbum(Sone sone, Album parent) {
1866 Album album = new Album();
1867 synchronized (albums) {
1868 albums.put(album.getId(), album);
1870 album.setSone(sone);
1871 if (parent != null) {
1872 parent.addAlbum(album);
1874 sone.addAlbum(album);
1880 * Deletes the given album. The owner of the album has to be a local Sone,
1881 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1884 * The album to remove
1886 public void deleteAlbum(Album album) {
1887 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1888 if (!album.isEmpty()) {
1891 if (album.getParent() == null) {
1892 album.getSone().removeAlbum(album);
1894 album.getParent().removeAlbum(album);
1896 synchronized (albums) {
1897 albums.remove(album.getId());
1899 saveSone(album.getSone());
1903 * Creates a new image.
1906 * The Sone creating the image
1908 * The album the image will be inserted into
1909 * @param temporaryImage
1910 * The temporary image to create the image from
1911 * @return The newly created image
1913 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1914 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", isLocalSone(sone)).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1915 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1916 album.addImage(image);
1917 synchronized (images) {
1918 images.put(image.getId(), image);
1920 imageInserter.insertImage(temporaryImage, image);
1925 * Deletes the given image. This method will also delete a matching
1928 * @see #deleteTemporaryImage(TemporaryImage)
1930 * The image to delete
1932 public void deleteImage(Image image) {
1933 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1934 deleteTemporaryImage(image.getId());
1935 image.getAlbum().removeImage(image);
1936 synchronized (images) {
1937 images.remove(image.getId());
1939 saveSone(image.getSone());
1943 * Creates a new temporary image.
1946 * The MIME type of the temporary image
1948 * The encoded data of the image
1949 * @return The temporary image
1951 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1952 TemporaryImage temporaryImage = new TemporaryImage();
1953 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1954 synchronized (temporaryImages) {
1955 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1957 return temporaryImage;
1961 * Deletes the given temporary image.
1963 * @param temporaryImage
1964 * The temporary image to delete
1966 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1967 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1968 deleteTemporaryImage(temporaryImage.getId());
1972 * Deletes the temporary image with the given ID.
1975 * The ID of the temporary image to delete
1977 public void deleteTemporaryImage(String imageId) {
1978 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1979 synchronized (temporaryImages) {
1980 temporaryImages.remove(imageId);
1982 Image image = getImage(imageId, false);
1983 if (image != null) {
1984 imageInserter.cancelImageInsert(image);
1991 public void start() {
1992 loadConfiguration();
1993 updateChecker.addUpdateListener(this);
1994 updateChecker.start();
2000 public void stop() {
2001 synchronized (localSones) {
2002 for (SoneInserter soneInserter : soneInserters.values()) {
2003 soneInserter.stop();
2006 updateChecker.stop();
2007 updateChecker.removeUpdateListener(this);
2008 soneDownloader.stop();
2009 saveConfiguration();
2014 * Saves the current options.
2016 public void saveConfiguration() {
2017 synchronized (configuration) {
2018 if (storingConfiguration) {
2019 logger.log(Level.FINE, "Already storing configuration…");
2022 storingConfiguration = true;
2025 /* store the options first. */
2027 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2028 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2029 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2030 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2031 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2032 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2033 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2034 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2035 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2037 /* save known Sones. */
2038 int soneCounter = 0;
2039 synchronized (newSones) {
2040 for (String knownSoneId : knownSones) {
2041 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2043 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2046 /* save known posts. */
2047 int postCounter = 0;
2048 synchronized (newPosts) {
2049 for (String knownPostId : knownPosts) {
2050 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2052 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2055 /* save known replies. */
2056 int replyCounter = 0;
2057 synchronized (newReplies) {
2058 for (String knownReplyId : knownReplies) {
2059 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2061 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2064 /* save bookmarked posts. */
2065 int bookmarkedPostCounter = 0;
2066 synchronized (bookmarkedPosts) {
2067 for (String bookmarkedPostId : bookmarkedPosts) {
2068 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2071 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2074 configuration.save();
2076 } catch (ConfigurationException ce1) {
2077 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2079 synchronized (configuration) {
2080 storingConfiguration = false;
2090 * Loads the configuration.
2092 @SuppressWarnings("unchecked")
2093 private void loadConfiguration() {
2094 /* create options. */
2095 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
2098 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2099 SoneInserter.setInsertionDelay(newValue);
2103 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10));
2104 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
2105 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25));
2106 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2107 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2108 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2109 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2111 /* read options from configuration. */
2112 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2113 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2114 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2115 options.getBooleanOption("ClearOnNextRestart").set(null);
2116 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2117 if (clearConfiguration) {
2118 /* stop loading the configuration. */
2122 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
2123 options.getIntegerOption("PostsPerPage").set(configuration.getIntValue("Option/PostsPerPage").getValue(null));
2124 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
2125 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
2126 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2127 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2129 /* load known Sones. */
2130 int soneCounter = 0;
2132 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2133 if (knownSoneId == null) {
2136 synchronized (newSones) {
2137 knownSones.add(knownSoneId);
2141 /* load known posts. */
2142 int postCounter = 0;
2144 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2145 if (knownPostId == null) {
2148 synchronized (newPosts) {
2149 knownPosts.add(knownPostId);
2153 /* load known replies. */
2154 int replyCounter = 0;
2156 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2157 if (knownReplyId == null) {
2160 synchronized (newReplies) {
2161 knownReplies.add(knownReplyId);
2165 /* load bookmarked posts. */
2166 int bookmarkedPostCounter = 0;
2168 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2169 if (bookmarkedPostId == null) {
2172 synchronized (bookmarkedPosts) {
2173 bookmarkedPosts.add(bookmarkedPostId);
2180 * Generate a Sone URI from the given URI and latest edition.
2183 * The URI to derive the Sone URI from
2184 * @return The derived URI
2186 private FreenetURI getSoneUri(String uriString) {
2188 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2190 } catch (MalformedURLException mue1) {
2191 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2197 // INTERFACE IdentityListener
2204 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2205 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2206 if (ownIdentity.hasContext("Sone")) {
2207 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2208 addLocalSone(ownIdentity);
2216 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2217 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2218 trustedIdentities.remove(ownIdentity);
2225 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2226 logger.log(Level.FINEST, "Adding Identity: " + identity);
2227 trustedIdentities.get(ownIdentity).add(identity);
2228 addRemoteSone(identity);
2235 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2236 new Thread(new Runnable() {
2239 @SuppressWarnings("synthetic-access")
2241 Sone sone = getRemoteSone(identity.getId());
2242 sone.setIdentity(identity);
2243 soneDownloader.addSone(sone);
2244 soneDownloader.fetchSone(sone);
2253 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2254 trustedIdentities.get(ownIdentity).remove(identity);
2258 // INTERFACE UpdateListener
2265 public void updateFound(Version version, long releaseTime, long latestEdition) {
2266 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2270 // INTERFACE ImageInsertListener
2277 public void imageInsertStarted(Image image) {
2278 logger.log(Level.WARNING, "Image insert started for " + image);
2279 coreListenerManager.fireImageInsertStarted(image);
2286 public void imageInsertAborted(Image image) {
2287 logger.log(Level.WARNING, "Image insert aborted for " + image);
2288 coreListenerManager.fireImageInsertAborted(image);
2295 public void imageInsertFinished(Image image, FreenetURI key) {
2296 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2297 image.setKey(key.toString());
2298 deleteTemporaryImage(image.getId());
2299 saveSone(image.getSone());
2300 coreListenerManager.fireImageInsertFinished(image);
2307 public void imageInsertFailed(Image image, Throwable cause) {
2308 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2309 coreListenerManager.fireImageInsertFailed(image, cause);
2313 * Convenience interface for external classes that want to access the core’s
2316 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2318 public static class Preferences {
2320 /** The wrapped options. */
2321 private final Options options;
2324 * Creates a new preferences object wrapped around the given options.
2327 * The options to wrap
2329 public Preferences(Options options) {
2330 this.options = options;
2334 * Returns the insertion delay.
2336 * @return The insertion delay
2338 public int getInsertionDelay() {
2339 return options.getIntegerOption("InsertionDelay").get();
2343 * Sets the insertion delay
2345 * @param insertionDelay
2346 * The new insertion delay, or {@code null} to restore it to
2348 * @return This preferences
2350 public Preferences setInsertionDelay(Integer insertionDelay) {
2351 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2356 * Returns the number of posts to show per page.
2358 * @return The number of posts to show per page
2360 public int getPostsPerPage() {
2361 return options.getIntegerOption("PostsPerPage").get();
2365 * Sets the number of posts to show per page.
2367 * @param postsPerPage
2368 * The number of posts to show per page
2369 * @return This preferences object
2371 public Preferences setPostsPerPage(Integer postsPerPage) {
2372 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2377 * Returns the positive trust.
2379 * @return The positive trust
2381 public int getPositiveTrust() {
2382 return options.getIntegerOption("PositiveTrust").get();
2386 * Sets the positive trust.
2388 * @param positiveTrust
2389 * The new positive trust, or {@code null} to restore it to
2391 * @return This preferences
2393 public Preferences setPositiveTrust(Integer positiveTrust) {
2394 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2399 * Returns the negative trust.
2401 * @return The negative trust
2403 public int getNegativeTrust() {
2404 return options.getIntegerOption("NegativeTrust").get();
2408 * Sets the negative trust.
2410 * @param negativeTrust
2411 * The negative trust, or {@code null} to restore it to the
2413 * @return The preferences
2415 public Preferences setNegativeTrust(Integer negativeTrust) {
2416 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2421 * Returns the trust comment. This is the comment that is set in the web
2422 * of trust when a trust value is assigned to an identity.
2424 * @return The trust comment
2426 public String getTrustComment() {
2427 return options.getStringOption("TrustComment").get();
2431 * Sets the trust comment.
2433 * @param trustComment
2434 * The trust comment, or {@code null} to restore it to the
2436 * @return This preferences
2438 public Preferences setTrustComment(String trustComment) {
2439 options.getStringOption("TrustComment").set(trustComment);
2444 * Returns whether the rescue mode is active.
2446 * @return {@code true} if the rescue mode is active, {@code false}
2449 public boolean isSoneRescueMode() {
2450 return options.getBooleanOption("SoneRescueMode").get();
2454 * Sets whether the rescue mode is active.
2456 * @param soneRescueMode
2457 * {@code true} if the rescue mode is active, {@code false}
2459 * @return This preferences
2461 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2462 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2467 * Returns whether Sone should clear its settings on the next restart.
2468 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2469 * to return {@code true} as well!
2471 * @return {@code true} if Sone should clear its settings on the next
2472 * restart, {@code false} otherwise
2474 public boolean isClearOnNextRestart() {
2475 return options.getBooleanOption("ClearOnNextRestart").get();
2479 * Sets whether Sone will clear its settings on the next restart.
2481 * @param clearOnNextRestart
2482 * {@code true} if Sone should clear its settings on the next
2483 * restart, {@code false} otherwise
2484 * @return This preferences
2486 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2487 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2492 * Returns whether Sone should really clear its settings on next
2493 * restart. This is a confirmation option that needs to be set in
2494 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2495 * settings on the next restart.
2497 * @return {@code true} if Sone should really clear its settings on the
2498 * next restart, {@code false} otherwise
2500 public boolean isReallyClearOnNextRestart() {
2501 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2505 * Sets whether Sone should really clear its settings on the next
2508 * @param reallyClearOnNextRestart
2509 * {@code true} if Sone should really clear its settings on
2510 * the next restart, {@code false} otherwise
2511 * @return This preferences
2513 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2514 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);