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 {
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 update checker. */
113 private final UpdateChecker updateChecker;
115 /** Whether the core has been stopped. */
116 private volatile boolean stopped;
118 /** The Sones’ statuses. */
119 /* synchronize access on itself. */
120 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
122 /** Locked local Sones. */
123 /* synchronize on itself. */
124 private final Set<Sone> lockedSones = new HashSet<Sone>();
126 /** Sone inserters. */
127 /* synchronize access on this on localSones. */
128 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
130 /** All local Sones. */
131 /* synchronize access on this on itself. */
132 private Map<String, Sone> localSones = new HashMap<String, Sone>();
134 /** All remote Sones. */
135 /* synchronize access on this on itself. */
136 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
138 /** All new Sones. */
139 private Set<String> newSones = new HashSet<String>();
141 /** All known Sones. */
142 /* synchronize access on {@link #newSones}. */
143 private Set<String> knownSones = new HashSet<String>();
146 private Map<String, Post> posts = new HashMap<String, Post>();
148 /** All new posts. */
149 private Set<String> newPosts = new HashSet<String>();
151 /** All known posts. */
152 /* synchronize access on {@link #newPosts}. */
153 private Set<String> knownPosts = new HashSet<String>();
156 private Map<String, Reply> replies = new HashMap<String, Reply>();
158 /** All new replies. */
159 private Set<String> newReplies = new HashSet<String>();
161 /** All known replies. */
162 private Set<String> knownReplies = new HashSet<String>();
164 /** All bookmarked posts. */
165 /* synchronize access on itself. */
166 private Set<String> bookmarkedPosts = new HashSet<String>();
168 /** Trusted identities, sorted by own identities. */
169 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
171 /** All known albums. */
172 private Map<String, Album> albums = new HashMap<String, Album>();
174 /** All known images. */
175 private Map<String, Image> images = new HashMap<String, Image>();
177 /** All temporary images. */
178 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
181 * Creates a new core.
183 * @param configuration
184 * The configuration of the core
185 * @param freenetInterface
186 * The freenet interface
187 * @param identityManager
188 * The identity manager
190 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
191 this.configuration = configuration;
192 this.freenetInterface = freenetInterface;
193 this.identityManager = identityManager;
194 this.soneDownloader = new SoneDownloader(this, freenetInterface);
195 this.updateChecker = new UpdateChecker(freenetInterface);
199 // LISTENER MANAGEMENT
203 * Adds a new core listener.
205 * @param coreListener
206 * The listener to add
208 public void addCoreListener(CoreListener coreListener) {
209 coreListenerManager.addListener(coreListener);
213 * Removes a core listener.
215 * @param coreListener
216 * The listener to remove
218 public void removeCoreListener(CoreListener coreListener) {
219 coreListenerManager.removeListener(coreListener);
227 * Sets the configuration to use. This will automatically save the current
228 * configuration to the given configuration.
230 * @param configuration
231 * The new configuration to use
233 public void setConfiguration(Configuration configuration) {
234 this.configuration = configuration;
239 * Returns the options used by the core.
241 * @return The options of the core
243 public Preferences getPreferences() {
248 * Returns the identity manager used by the core.
250 * @return The identity manager
252 public IdentityManager getIdentityManager() {
253 return identityManager;
257 * Returns the update checker.
259 * @return The update checker
261 public UpdateChecker getUpdateChecker() {
262 return updateChecker;
266 * Returns the status of the given Sone.
269 * The Sone to get the status for
270 * @return The status of the Sone
272 public SoneStatus getSoneStatus(Sone sone) {
273 synchronized (soneStatuses) {
274 return soneStatuses.get(sone);
279 * Sets the status of the given Sone.
282 * The Sone to set the status of
286 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
287 synchronized (soneStatuses) {
288 soneStatuses.put(sone, soneStatus);
293 * Returns whether the given Sone is currently locked.
297 * @return {@code true} if the Sone is locked, {@code false} if it is not
299 public boolean isLocked(Sone sone) {
300 synchronized (lockedSones) {
301 return lockedSones.contains(sone);
306 * Returns all Sones, remote and local.
310 public Set<Sone> getSones() {
311 Set<Sone> allSones = new HashSet<Sone>();
312 allSones.addAll(getLocalSones());
313 allSones.addAll(getRemoteSones());
318 * Returns the Sone with the given ID, regardless whether it’s local or
322 * The ID of the Sone to get
323 * @return The Sone with the given ID, or {@code null} if there is no such
326 public Sone getSone(String id) {
327 return getSone(id, true);
331 * Returns the Sone with the given ID, regardless whether it’s local or
335 * The ID of the Sone to get
337 * {@code true} to create a new Sone if none exists,
338 * {@code false} to return {@code null} if a Sone with the given
340 * @return The Sone with the given ID, or {@code null} if there is no such
343 public Sone getSone(String id, boolean create) {
344 if (isLocalSone(id)) {
345 return getLocalSone(id);
347 return getRemoteSone(id, create);
351 * Checks whether the core knows a Sone with the given ID.
355 * @return {@code true} if there is a Sone with the given ID, {@code false}
358 public boolean hasSone(String id) {
359 return isLocalSone(id) || isRemoteSone(id);
363 * Returns whether the given Sone is a local Sone.
366 * The Sone to check for its locality
367 * @return {@code true} if the given Sone is local, {@code false} otherwise
369 public boolean isLocalSone(Sone sone) {
370 synchronized (localSones) {
371 return localSones.containsKey(sone.getId());
376 * Returns whether the given ID is the ID of a local Sone.
379 * The Sone ID to check for its locality
380 * @return {@code true} if the given ID is a local Sone, {@code false}
383 public boolean isLocalSone(String id) {
384 synchronized (localSones) {
385 return localSones.containsKey(id);
390 * Returns all local Sones.
392 * @return All local Sones
394 public Set<Sone> getLocalSones() {
395 synchronized (localSones) {
396 return new HashSet<Sone>(localSones.values());
401 * Returns the local Sone with the given ID.
404 * The ID of the Sone to get
405 * @return The Sone with the given ID
407 public Sone getLocalSone(String id) {
408 return getLocalSone(id, true);
412 * Returns the local Sone with the given ID, optionally creating a new Sone.
417 * {@code true} to create a new Sone if none exists,
418 * {@code false} to return null if none exists
419 * @return The Sone with the given ID, or {@code null}
421 public Sone getLocalSone(String id, boolean create) {
422 synchronized (localSones) {
423 Sone sone = localSones.get(id);
424 if ((sone == null) && create) {
426 localSones.put(id, sone);
427 setSoneStatus(sone, SoneStatus.unknown);
434 * Returns all remote Sones.
436 * @return All remote Sones
438 public Set<Sone> getRemoteSones() {
439 synchronized (remoteSones) {
440 return new HashSet<Sone>(remoteSones.values());
445 * Returns the remote Sone with the given ID.
448 * The ID of the remote Sone to get
449 * @return The Sone with the given ID
451 public Sone getRemoteSone(String id) {
452 return getRemoteSone(id, true);
456 * Returns the remote Sone with the given ID.
459 * The ID of the remote Sone to get
461 * {@code true} to always create a Sone, {@code false} to return
462 * {@code null} if no Sone with the given ID exists
463 * @return The Sone with the given ID
465 public Sone getRemoteSone(String id, boolean create) {
466 synchronized (remoteSones) {
467 Sone sone = remoteSones.get(id);
468 if ((sone == null) && create) {
470 remoteSones.put(id, sone);
471 setSoneStatus(sone, SoneStatus.unknown);
478 * Returns whether the given Sone is a remote Sone.
482 * @return {@code true} if the given Sone is a remote Sone, {@code false}
485 public boolean isRemoteSone(Sone sone) {
486 synchronized (remoteSones) {
487 return remoteSones.containsKey(sone.getId());
492 * Returns whether the Sone with the given ID is a remote Sone.
495 * The ID of the Sone to check
496 * @return {@code true} if the Sone with the given ID is a remote Sone,
497 * {@code false} otherwise
499 public boolean isRemoteSone(String id) {
500 synchronized (remoteSones) {
501 return remoteSones.containsKey(id);
506 * Returns whether the Sone with the given ID is a new Sone.
509 * The ID of the sone to check for
510 * @return {@code true} if the given Sone is new, false otherwise
512 public boolean isNewSone(String soneId) {
513 synchronized (newSones) {
514 return !knownSones.contains(soneId) && newSones.contains(soneId);
519 * Returns whether the given Sone has been modified.
522 * The Sone to check for modifications
523 * @return {@code true} if a modification has been detected in the Sone,
524 * {@code false} otherwise
526 public boolean isModifiedSone(Sone sone) {
527 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
531 * Returns whether the target Sone is trusted by the origin Sone.
537 * @return {@code true} if the target Sone is trusted by the origin Sone
539 public boolean isSoneTrusted(Sone origin, Sone target) {
540 return trustedIdentities.containsKey(origin) && trustedIdentities.get(origin.getIdentity()).contains(target);
544 * Returns the post with the given ID.
547 * The ID of the post to get
548 * @return The post, or {@code null} if there is no such post
550 public Post getPost(String postId) {
551 return getPost(postId, true);
555 * Returns the post with the given ID, optionally creating a new post.
558 * The ID of the post to get
560 * {@code true} it create a new post if no post with the given ID
561 * exists, {@code false} to return {@code null}
562 * @return The post, or {@code null} if there is no such post
564 public Post getPost(String postId, boolean create) {
565 synchronized (posts) {
566 Post post = posts.get(postId);
567 if ((post == null) && create) {
568 post = new Post(postId);
569 posts.put(postId, post);
576 * Returns whether the given post ID is new.
580 * @return {@code true} if the post is considered to be new, {@code false}
583 public boolean isNewPost(String postId) {
584 synchronized (newPosts) {
585 return !knownPosts.contains(postId) && newPosts.contains(postId);
590 * Returns the reply with the given ID. If there is no reply with the given
591 * ID yet, a new one is created.
594 * The ID of the reply to get
597 public Reply getReply(String replyId) {
598 return getReply(replyId, true);
602 * Returns the reply with the given ID. If there is no reply with the given
603 * ID yet, a new one is created, unless {@code create} is false in which
604 * case {@code null} is returned.
607 * The ID of the reply to get
609 * {@code true} to always return a {@link Reply}, {@code false}
610 * to return {@code null} if no reply can be found
611 * @return The reply, or {@code null} if there is no such reply
613 public Reply getReply(String replyId, boolean create) {
614 synchronized (replies) {
615 Reply reply = replies.get(replyId);
616 if (create && (reply == null)) {
617 reply = new Reply(replyId);
618 replies.put(replyId, reply);
625 * Returns all replies for the given post, order ascending by time.
628 * The post to get all replies for
629 * @return All replies for the given post
631 public List<Reply> getReplies(Post post) {
632 Set<Sone> sones = getSones();
633 List<Reply> replies = new ArrayList<Reply>();
634 for (Sone sone : sones) {
635 for (Reply reply : sone.getReplies()) {
636 if (reply.getPost().equals(post)) {
641 Collections.sort(replies, Reply.TIME_COMPARATOR);
646 * Returns whether the reply with the given ID is new.
649 * The ID of the reply to check
650 * @return {@code true} if the reply is considered to be new, {@code false}
653 public boolean isNewReply(String replyId) {
654 synchronized (newReplies) {
655 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
660 * Returns all Sones that have liked the given post.
663 * The post to get the liking Sones for
664 * @return The Sones that like the given post
666 public Set<Sone> getLikes(Post post) {
667 Set<Sone> sones = new HashSet<Sone>();
668 for (Sone sone : getSones()) {
669 if (sone.getLikedPostIds().contains(post.getId())) {
677 * Returns all Sones that have liked the given reply.
680 * The reply to get the liking Sones for
681 * @return The Sones that like the given reply
683 public Set<Sone> getLikes(Reply reply) {
684 Set<Sone> sones = new HashSet<Sone>();
685 for (Sone sone : getSones()) {
686 if (sone.getLikedReplyIds().contains(reply.getId())) {
694 * Returns whether the given post is bookmarked.
698 * @return {@code true} if the given post is bookmarked, {@code false}
701 public boolean isBookmarked(Post post) {
702 return isPostBookmarked(post.getId());
706 * Returns whether the post with the given ID is bookmarked.
709 * The ID of the post to check
710 * @return {@code true} if the post with the given ID is bookmarked,
711 * {@code false} otherwise
713 public boolean isPostBookmarked(String id) {
714 synchronized (bookmarkedPosts) {
715 return bookmarkedPosts.contains(id);
720 * Returns all currently known bookmarked posts.
722 * @return All bookmarked posts
724 public Set<Post> getBookmarkedPosts() {
725 Set<Post> posts = new HashSet<Post>();
726 synchronized (bookmarkedPosts) {
727 for (String bookmarkedPostId : bookmarkedPosts) {
728 Post post = getPost(bookmarkedPostId, false);
738 * Returns the album with the given ID, creating a new album if no album
739 * with the given ID can be found.
742 * The ID of the album
743 * @return The album with the given ID
745 public Album getAlbum(String albumId) {
746 return getAlbum(albumId, true);
750 * Returns the album with the given ID, optionally creating a new album if
751 * an album with the given ID can not be found.
754 * The ID of the album
756 * {@code true} to create a new album if none exists for the
758 * @return The album with the given ID, or {@code null} if no album with the
759 * given ID exists and {@code create} is {@code false}
761 public Album getAlbum(String albumId, boolean create) {
762 synchronized (albums) {
763 Album album = albums.get(albumId);
764 if (create && (album == null)) {
765 album = new Album(albumId);
766 albums.put(albumId, album);
773 * Returns the image with the given ID, creating it if necessary.
776 * The ID of the image
777 * @return The image with the given ID
779 public Image getImage(String imageId) {
780 return getImage(imageId, true);
784 * Returns the image with the given ID, optionally creating it if it does
788 * The ID of the image
790 * {@code true} to create an image if none exists with the given
792 * @return The image with the given ID, or {@code null} if none exists and
795 public Image getImage(String imageId, boolean create) {
796 synchronized (images) {
797 Image image = images.get(imageId);
798 if (create && (image == null)) {
799 image = new Image(imageId);
800 images.put(imageId, image);
807 * Returns the temporary image with the given ID.
810 * The ID of the temporary image
811 * @return The temporary image, or {@code null} if there is no temporary
812 * image with the given ID
814 public TemporaryImage getTemporaryImage(String imageId) {
815 synchronized (temporaryImages) {
816 return temporaryImages.get(imageId);
825 * Locks the given Sone. A locked Sone will not be inserted by
826 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
832 public void lockSone(Sone sone) {
833 synchronized (lockedSones) {
834 if (lockedSones.add(sone)) {
835 coreListenerManager.fireSoneLocked(sone);
841 * Unlocks the given Sone.
843 * @see #lockSone(Sone)
847 public void unlockSone(Sone sone) {
848 synchronized (lockedSones) {
849 if (lockedSones.remove(sone)) {
850 coreListenerManager.fireSoneUnlocked(sone);
856 * Adds a local Sone from the given ID which has to be the ID of an own
860 * The ID of an own identity to add a Sone for
861 * @return The added (or already existing) Sone
863 public Sone addLocalSone(String id) {
864 synchronized (localSones) {
865 if (localSones.containsKey(id)) {
866 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
867 return localSones.get(id);
869 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
870 if (ownIdentity == null) {
871 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
874 return addLocalSone(ownIdentity);
879 * Adds a local Sone from the given own identity.
882 * The own identity to create a Sone from
883 * @return The added (or already existing) Sone
885 public Sone addLocalSone(OwnIdentity ownIdentity) {
886 if (ownIdentity == null) {
887 logger.log(Level.WARNING, "Given OwnIdentity is null!");
890 synchronized (localSones) {
893 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
894 } catch (MalformedURLException mue1) {
895 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
898 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
899 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
900 /* TODO - load posts ’n stuff */
901 localSones.put(ownIdentity.getId(), sone);
902 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
903 soneInserters.put(sone, soneInserter);
904 setSoneStatus(sone, SoneStatus.idle);
906 if (!preferences.isSoneRescueMode()) {
907 soneInserter.start();
909 new Thread(new Runnable() {
912 @SuppressWarnings("synthetic-access")
914 if (!preferences.isSoneRescueMode()) {
915 soneDownloader.fetchSone(sone);
918 logger.log(Level.INFO, "Trying to restore Sone from Freenet…");
919 coreListenerManager.fireRescuingSone(sone);
921 long edition = sone.getLatestEdition();
922 while (!stopped && (edition >= 0) && preferences.isSoneRescueMode()) {
923 logger.log(Level.FINE, "Downloading edition " + edition + "…");
924 soneDownloader.fetchSone(sone, sone.getRequestUri().setKeyType("SSK").setDocName("Sone-" + edition));
927 logger.log(Level.INFO, "Finished restoring Sone from Freenet, starting Inserter…");
929 coreListenerManager.fireRescuedSone(sone);
930 soneInserter.start();
933 }, "Sone Downloader").start();
939 * Creates a new Sone for the given own identity.
942 * The own identity to create a Sone for
943 * @return The created Sone
945 public Sone createSone(OwnIdentity ownIdentity) {
947 ownIdentity.addContext("Sone");
948 } catch (WebOfTrustException wote1) {
949 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
952 Sone sone = addLocalSone(ownIdentity);
957 * Adds the Sone of the given identity.
960 * The identity whose Sone to add
961 * @return The added or already existing Sone
963 public Sone addRemoteSone(Identity identity) {
964 if (identity == null) {
965 logger.log(Level.WARNING, "Given Identity is null!");
968 synchronized (remoteSones) {
969 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
970 boolean newSone = sone.getRequestUri() == null;
971 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
972 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
974 synchronized (newSones) {
975 newSone = !knownSones.contains(sone.getId());
977 newSones.add(sone.getId());
981 coreListenerManager.fireNewSoneFound(sone);
984 remoteSones.put(identity.getId(), sone);
985 soneDownloader.addSone(sone);
986 setSoneStatus(sone, SoneStatus.unknown);
987 new Thread(new Runnable() {
990 @SuppressWarnings("synthetic-access")
992 soneDownloader.fetchSone(sone);
995 }, "Sone Downloader").start();
1001 * Retrieves the trust relationship from the origin to the target. If the
1002 * trust relationship can not be retrieved, {@code null} is returned.
1004 * @see Identity#getTrust(OwnIdentity)
1006 * The origin of the trust tree
1008 * The target of the trust
1009 * @return The trust relationship
1011 public Trust getTrust(Sone origin, Sone target) {
1012 if (!isLocalSone(origin)) {
1013 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1016 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1020 * Sets the trust value of the given origin Sone for the target Sone.
1027 * The trust value (from {@code -100} to {@code 100})
1029 public void setTrust(Sone origin, Sone target, int trustValue) {
1030 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();
1032 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1033 } catch (WebOfTrustException wote1) {
1034 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1039 * Removes any trust assignment for the given target Sone.
1046 public void removeTrust(Sone origin, Sone target) {
1047 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1049 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1050 } catch (WebOfTrustException wote1) {
1051 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1056 * Assigns the configured positive trust value for the given target.
1063 public void trustSone(Sone origin, Sone target) {
1064 setTrust(origin, target, preferences.getPositiveTrust());
1068 * Assigns the configured negative trust value for the given target.
1075 public void distrustSone(Sone origin, Sone target) {
1076 setTrust(origin, target, preferences.getNegativeTrust());
1080 * Removes the trust assignment for the given target.
1087 public void untrustSone(Sone origin, Sone target) {
1088 removeTrust(origin, target);
1092 * Updates the stores Sone with the given Sone.
1097 public void updateSone(Sone sone) {
1098 if (hasSone(sone.getId())) {
1099 boolean soneRescueMode = isLocalSone(sone) && preferences.isSoneRescueMode();
1100 Sone storedSone = getSone(sone.getId());
1101 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1102 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1105 synchronized (posts) {
1106 if (!soneRescueMode) {
1107 for (Post post : storedSone.getPosts()) {
1108 posts.remove(post.getId());
1109 if (!sone.getPosts().contains(post)) {
1110 coreListenerManager.firePostRemoved(post);
1114 List<Post> storedPosts = storedSone.getPosts();
1115 synchronized (newPosts) {
1116 for (Post post : sone.getPosts()) {
1117 post.setSone(storedSone);
1118 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1119 newPosts.add(post.getId());
1120 coreListenerManager.fireNewPostFound(post);
1122 posts.put(post.getId(), post);
1126 synchronized (replies) {
1127 if (!soneRescueMode) {
1128 for (Reply reply : storedSone.getReplies()) {
1129 replies.remove(reply.getId());
1130 if (!sone.getReplies().contains(reply)) {
1131 coreListenerManager.fireReplyRemoved(reply);
1135 Set<Reply> storedReplies = storedSone.getReplies();
1136 synchronized (newReplies) {
1137 for (Reply reply : sone.getReplies()) {
1138 reply.setSone(storedSone);
1139 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1140 newReplies.add(reply.getId());
1141 coreListenerManager.fireNewReplyFound(reply);
1143 replies.put(reply.getId(), reply);
1147 synchronized (storedSone) {
1148 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1149 storedSone.setTime(sone.getTime());
1151 storedSone.setClient(sone.getClient());
1152 storedSone.setProfile(sone.getProfile());
1153 if (soneRescueMode) {
1154 for (Post post : sone.getPosts()) {
1155 storedSone.addPost(post);
1157 for (Reply reply : sone.getReplies()) {
1158 storedSone.addReply(reply);
1160 for (String likedPostId : sone.getLikedPostIds()) {
1161 storedSone.addLikedPostId(likedPostId);
1163 for (String likedReplyId : sone.getLikedReplyIds()) {
1164 storedSone.addLikedReplyId(likedReplyId);
1167 storedSone.setPosts(sone.getPosts());
1168 storedSone.setReplies(sone.getReplies());
1169 storedSone.setLikePostIds(sone.getLikedPostIds());
1170 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1172 storedSone.setLatestEdition(sone.getLatestEdition());
1178 * Deletes the given Sone. This will remove the Sone from the
1179 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1180 * and remove the context from its identity.
1183 * The Sone to delete
1185 public void deleteSone(Sone sone) {
1186 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1187 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1190 synchronized (localSones) {
1191 if (!localSones.containsKey(sone.getId())) {
1192 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1195 localSones.remove(sone.getId());
1196 soneInserters.remove(sone).stop();
1199 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1200 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1201 } catch (WebOfTrustException wote1) {
1202 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1205 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1206 } catch (ConfigurationException ce1) {
1207 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1212 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1213 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1216 * The Sone to mark as known
1218 public void markSoneKnown(Sone sone) {
1219 synchronized (newSones) {
1220 if (newSones.remove(sone.getId())) {
1221 knownSones.add(sone.getId());
1222 coreListenerManager.fireMarkSoneKnown(sone);
1223 saveConfiguration();
1229 * Loads and updates the given Sone from the configuration. If any error is
1230 * encountered, loading is aborted and the given Sone is not changed.
1233 * The Sone to load and update
1235 public void loadSone(Sone sone) {
1236 if (!isLocalSone(sone)) {
1237 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1242 String sonePrefix = "Sone/" + sone.getId();
1243 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1244 if (soneTime == null) {
1245 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1248 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1251 Profile profile = new Profile();
1252 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1253 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1254 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1255 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1256 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1257 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1259 /* load profile fields. */
1261 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1262 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1263 if (fieldName == null) {
1266 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1267 profile.addField(fieldName).setValue(fieldValue);
1271 Set<Post> posts = new HashSet<Post>();
1273 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1274 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1275 if (postId == null) {
1278 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1279 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1280 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1281 if ((postTime == 0) || (postText == null)) {
1282 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1285 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1286 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1287 post.setRecipient(getSone(postRecipientId));
1293 Set<Reply> replies = new HashSet<Reply>();
1295 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1296 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1297 if (replyId == null) {
1300 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1301 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1302 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1303 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1304 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1307 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1310 /* load post likes. */
1311 Set<String> likedPostIds = new HashSet<String>();
1313 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1314 if (likedPostId == null) {
1317 likedPostIds.add(likedPostId);
1320 /* load reply likes. */
1321 Set<String> likedReplyIds = new HashSet<String>();
1323 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1324 if (likedReplyId == null) {
1327 likedReplyIds.add(likedReplyId);
1331 Set<String> friends = new HashSet<String>();
1333 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1334 if (friendId == null) {
1337 friends.add(friendId);
1341 List<Album> topLevelAlbums = new ArrayList<Album>();
1343 String albumPrefix = sonePrefix + "/Albums/" + albums.size();
1344 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1345 if (albumId == null) {
1348 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1349 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1350 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1351 if ((albumTitle == null) || (albumDescription == null)) {
1352 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1355 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription);
1356 if (albumParentId != null) {
1357 Album parentAlbum = getAlbum(albumParentId, false);
1358 if (parentAlbum == null) {
1359 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1362 parentAlbum.addAlbum(album);
1364 topLevelAlbums.add(album);
1369 int imageCounter = 0;
1371 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1372 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1373 if (imageId == null) {
1376 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1377 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1378 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1379 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1380 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1381 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1382 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1383 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1384 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1387 Album album = getAlbum(albumId, false);
1388 if (album == null) {
1389 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1392 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1393 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1394 album.addImage(image);
1398 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1399 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1401 /* if we’re still here, Sone was loaded successfully. */
1402 synchronized (sone) {
1403 sone.setTime(soneTime);
1404 sone.setProfile(profile);
1405 sone.setPosts(posts);
1406 sone.setReplies(replies);
1407 sone.setLikePostIds(likedPostIds);
1408 sone.setLikeReplyIds(likedReplyIds);
1409 sone.setFriends(friends);
1410 sone.setAlbums(topLevelAlbums);
1411 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1413 synchronized (newSones) {
1414 for (String friend : friends) {
1415 knownSones.add(friend);
1418 synchronized (newPosts) {
1419 for (Post post : posts) {
1420 knownPosts.add(post.getId());
1423 synchronized (newReplies) {
1424 for (Reply reply : replies) {
1425 knownReplies.add(reply.getId());
1431 * Saves the given Sone. This will persist all local settings for the given
1432 * Sone, such as the friends list and similar, private options.
1437 public synchronized void saveSone(Sone sone) {
1438 if (!isLocalSone(sone)) {
1439 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
1442 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1443 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
1447 logger.log(Level.INFO, "Saving Sone: %s", sone);
1449 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1451 /* save Sone into configuration. */
1452 String sonePrefix = "Sone/" + sone.getId();
1453 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1454 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1457 Profile profile = sone.getProfile();
1458 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1459 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1460 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1461 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1462 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1463 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1465 /* save profile fields. */
1466 int fieldCounter = 0;
1467 for (Field profileField : profile.getFields()) {
1468 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1469 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1470 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1472 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1475 int postCounter = 0;
1476 for (Post post : sone.getPosts()) {
1477 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1478 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1479 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1480 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1481 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1483 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1486 int replyCounter = 0;
1487 for (Reply reply : sone.getReplies()) {
1488 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1489 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1490 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1491 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1492 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1494 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1496 /* save post likes. */
1497 int postLikeCounter = 0;
1498 for (String postId : sone.getLikedPostIds()) {
1499 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1501 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1503 /* save reply likes. */
1504 int replyLikeCounter = 0;
1505 for (String replyId : sone.getLikedReplyIds()) {
1506 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1508 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1511 int friendCounter = 0;
1512 for (String friendId : sone.getFriends()) {
1513 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1515 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1517 /* save albums. first, collect in a flat structure, top-level first. */
1518 List<Album> albums = new ArrayList<Album>();
1519 albums.addAll(sone.getAlbums());
1520 int lastAlbumIndex = 0;
1521 while (lastAlbumIndex < albums.size()) {
1522 int previousAlbumCount = albums.size();
1523 for (Album album : new ArrayList<Album>(albums.subList(lastAlbumIndex, albums.size()))) {
1524 albums.addAll(album.getAlbums());
1526 lastAlbumIndex = previousAlbumCount;
1529 int albumCounter = 0;
1530 for (Album album : albums) {
1531 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1532 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1533 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1534 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1535 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1537 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1540 int imageCounter = 0;
1541 for (Album album : albums) {
1542 for (Image image : album.getImages()) {
1543 if (!image.isInserted()) {
1546 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1547 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1548 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1549 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1550 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1551 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1552 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1553 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1554 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1557 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1560 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1562 configuration.save();
1563 logger.log(Level.INFO, "Sone %s saved.", sone);
1564 } catch (ConfigurationException ce1) {
1565 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
1566 } catch (WebOfTrustException wote1) {
1567 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
1572 * Creates a new post.
1575 * The Sone that creates the post
1577 * The text of the post
1578 * @return The created post
1580 public Post createPost(Sone sone, String text) {
1581 return createPost(sone, System.currentTimeMillis(), text);
1585 * Creates a new post.
1588 * The Sone that creates the post
1590 * The time of the post
1592 * The text of the post
1593 * @return The created post
1595 public Post createPost(Sone sone, long time, String text) {
1596 return createPost(sone, null, time, text);
1600 * Creates a new post.
1603 * The Sone that creates the post
1605 * The recipient Sone, or {@code null} if this post does not have
1608 * The text of the post
1609 * @return The created post
1611 public Post createPost(Sone sone, Sone recipient, String text) {
1612 return createPost(sone, recipient, System.currentTimeMillis(), text);
1616 * Creates a new post.
1619 * The Sone that creates the post
1621 * The recipient Sone, or {@code null} if this post does not have
1624 * The time of the post
1626 * The text of the post
1627 * @return The created post
1629 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1630 if (!isLocalSone(sone)) {
1631 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1634 Post post = new Post(sone, time, text);
1635 if (recipient != null) {
1636 post.setRecipient(recipient);
1638 synchronized (posts) {
1639 posts.put(post.getId(), post);
1641 synchronized (newPosts) {
1642 knownPosts.add(post.getId());
1650 * Deletes the given post.
1653 * The post to delete
1655 public void deletePost(Post post) {
1656 if (!isLocalSone(post.getSone())) {
1657 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1660 post.getSone().removePost(post);
1661 synchronized (posts) {
1662 posts.remove(post.getId());
1664 saveSone(post.getSone());
1668 * Marks the given post as known, if it is currently a new post (according
1669 * to {@link #isNewPost(String)}).
1672 * The post to mark as known
1674 public void markPostKnown(Post post) {
1675 synchronized (newPosts) {
1676 if (newPosts.remove(post.getId())) {
1677 knownPosts.add(post.getId());
1678 coreListenerManager.fireMarkPostKnown(post);
1679 saveConfiguration();
1685 * Bookmarks the given post.
1688 * The post to bookmark
1690 public void bookmark(Post post) {
1691 bookmarkPost(post.getId());
1695 * Bookmarks the post with the given ID.
1698 * The ID of the post to bookmark
1700 public void bookmarkPost(String id) {
1701 synchronized (bookmarkedPosts) {
1702 bookmarkedPosts.add(id);
1707 * Removes the given post from the bookmarks.
1710 * The post to unbookmark
1712 public void unbookmark(Post post) {
1713 unbookmarkPost(post.getId());
1717 * Removes the post with the given ID from the bookmarks.
1720 * The ID of the post to unbookmark
1722 public void unbookmarkPost(String id) {
1723 synchronized (bookmarkedPosts) {
1724 bookmarkedPosts.remove(id);
1729 * Creates a new reply.
1732 * The Sone that creates the reply
1734 * The post that this reply refers to
1736 * The text of the reply
1737 * @return The created reply
1739 public Reply createReply(Sone sone, Post post, String text) {
1740 return createReply(sone, post, System.currentTimeMillis(), text);
1744 * Creates a new reply.
1747 * The Sone that creates the reply
1749 * The post that this reply refers to
1751 * The time of the reply
1753 * The text of the reply
1754 * @return The created reply
1756 public Reply createReply(Sone sone, Post post, long time, String text) {
1757 if (!isLocalSone(sone)) {
1758 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1761 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1762 synchronized (replies) {
1763 replies.put(reply.getId(), reply);
1765 synchronized (newReplies) {
1766 knownReplies.add(reply.getId());
1768 sone.addReply(reply);
1774 * Deletes the given reply.
1777 * The reply to delete
1779 public void deleteReply(Reply reply) {
1780 Sone sone = reply.getSone();
1781 if (!isLocalSone(sone)) {
1782 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1785 synchronized (replies) {
1786 replies.remove(reply.getId());
1788 sone.removeReply(reply);
1793 * Marks the given reply as known, if it is currently a new reply (according
1794 * to {@link #isNewReply(String)}).
1797 * The reply to mark as known
1799 public void markReplyKnown(Reply reply) {
1800 synchronized (newReplies) {
1801 if (newReplies.remove(reply.getId())) {
1802 knownReplies.add(reply.getId());
1803 coreListenerManager.fireMarkReplyKnown(reply);
1804 saveConfiguration();
1810 * Creates a new top-level album for the given Sone.
1813 * The Sone to create the album for
1814 * @return The new album
1816 public Album createAlbum(Sone sone) {
1817 return createAlbum(sone, null);
1821 * Creates a new album for the given Sone.
1824 * The Sone to create the album for
1826 * The parent of the album (may be {@code null} to create a
1828 * @return The new album
1830 public Album createAlbum(Sone sone, Album parent) {
1831 Album album = new Album();
1832 synchronized (albums) {
1833 albums.put(album.getId(), album);
1835 album.setSone(sone);
1836 if (parent != null) {
1837 parent.addAlbum(album);
1839 sone.addAlbum(album);
1845 * Creates a new image.
1848 * The Sone creating the image
1850 * The album the image will be inserted into
1851 * @param temporaryImage
1852 * The temporary image to create the image from
1853 * @return The newly created image
1855 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1856 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();
1857 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1858 album.addImage(image);
1859 synchronized (images) {
1860 images.put(image.getId(), image);
1866 * Creates a new temporary image.
1869 * The MIME type of the temporary image
1871 * The encoded data of the image
1872 * @return The temporary image
1874 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1875 TemporaryImage temporaryImage = new TemporaryImage();
1876 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1877 synchronized (temporaryImages) {
1878 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1880 return temporaryImage;
1884 * Deletes the given temporary image.
1886 * @param temporaryImage
1887 * The temporary image to delete
1889 public void deteleTemporaryImage(TemporaryImage temporaryImage) {
1890 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1891 deleteTemporaryImage(temporaryImage.getId());
1895 * Deletes the temporary image with the given ID.
1898 * The ID of the temporary image to delete
1900 public void deleteTemporaryImage(String imageId) {
1901 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1902 synchronized (temporaryImages) {
1903 temporaryImages.remove(imageId);
1910 public void start() {
1911 loadConfiguration();
1912 updateChecker.addUpdateListener(this);
1913 updateChecker.start();
1919 public void stop() {
1920 synchronized (localSones) {
1921 for (SoneInserter soneInserter : soneInserters.values()) {
1922 soneInserter.stop();
1925 updateChecker.stop();
1926 updateChecker.removeUpdateListener(this);
1927 soneDownloader.stop();
1928 saveConfiguration();
1933 * Saves the current options.
1935 public void saveConfiguration() {
1936 synchronized (configuration) {
1937 if (storingConfiguration) {
1938 logger.log(Level.FINE, "Already storing configuration…");
1941 storingConfiguration = true;
1944 /* store the options first. */
1946 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1947 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1948 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1949 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1950 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1951 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
1952 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
1953 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
1955 /* save known Sones. */
1956 int soneCounter = 0;
1957 synchronized (newSones) {
1958 for (String knownSoneId : knownSones) {
1959 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1961 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1964 /* save known posts. */
1965 int postCounter = 0;
1966 synchronized (newPosts) {
1967 for (String knownPostId : knownPosts) {
1968 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
1970 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
1973 /* save known replies. */
1974 int replyCounter = 0;
1975 synchronized (newReplies) {
1976 for (String knownReplyId : knownReplies) {
1977 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
1979 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
1982 /* save bookmarked posts. */
1983 int bookmarkedPostCounter = 0;
1984 synchronized (bookmarkedPosts) {
1985 for (String bookmarkedPostId : bookmarkedPosts) {
1986 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1989 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1992 configuration.save();
1994 } catch (ConfigurationException ce1) {
1995 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1997 synchronized (configuration) {
1998 storingConfiguration = false;
2008 * Loads the configuration.
2010 @SuppressWarnings("unchecked")
2011 private void loadConfiguration() {
2012 /* create options. */
2013 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
2016 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2017 SoneInserter.setInsertionDelay(newValue);
2021 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75));
2022 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-100));
2023 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2024 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2025 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2026 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2028 /* read options from configuration. */
2029 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2030 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2031 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2032 options.getBooleanOption("ClearOnNextRestart").set(null);
2033 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2034 if (clearConfiguration) {
2035 /* stop loading the configuration. */
2039 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
2040 options.getIntegerOption("PositiveTrust").set(configuration.getIntValue("Option/PositiveTrust").getValue(null));
2041 options.getIntegerOption("NegativeTrust").set(configuration.getIntValue("Option/NegativeTrust").getValue(null));
2042 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2043 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2045 /* load known Sones. */
2046 int soneCounter = 0;
2048 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2049 if (knownSoneId == null) {
2052 synchronized (newSones) {
2053 knownSones.add(knownSoneId);
2057 /* load known posts. */
2058 int postCounter = 0;
2060 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2061 if (knownPostId == null) {
2064 synchronized (newPosts) {
2065 knownPosts.add(knownPostId);
2069 /* load known replies. */
2070 int replyCounter = 0;
2072 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2073 if (knownReplyId == null) {
2076 synchronized (newReplies) {
2077 knownReplies.add(knownReplyId);
2081 /* load bookmarked posts. */
2082 int bookmarkedPostCounter = 0;
2084 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2085 if (bookmarkedPostId == null) {
2088 synchronized (bookmarkedPosts) {
2089 bookmarkedPosts.add(bookmarkedPostId);
2096 * Generate a Sone URI from the given URI and latest edition.
2099 * The URI to derive the Sone URI from
2100 * @return The derived URI
2102 private FreenetURI getSoneUri(String uriString) {
2104 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2106 } catch (MalformedURLException mue1) {
2107 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2113 // INTERFACE IdentityListener
2120 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2121 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2122 if (ownIdentity.hasContext("Sone")) {
2123 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2124 addLocalSone(ownIdentity);
2132 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2133 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2134 trustedIdentities.remove(ownIdentity);
2141 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2142 logger.log(Level.FINEST, "Adding Identity: " + identity);
2143 trustedIdentities.get(ownIdentity).add(identity);
2144 addRemoteSone(identity);
2151 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2152 new Thread(new Runnable() {
2155 @SuppressWarnings("synthetic-access")
2157 Sone sone = getRemoteSone(identity.getId());
2158 sone.setIdentity(identity);
2159 soneDownloader.addSone(sone);
2160 soneDownloader.fetchSone(sone);
2169 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2170 trustedIdentities.get(ownIdentity).remove(identity);
2174 // INTERFACE UpdateListener
2181 public void updateFound(Version version, long releaseTime, long latestEdition) {
2182 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2186 * Convenience interface for external classes that want to access the core’s
2189 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2191 public static class Preferences {
2193 /** The wrapped options. */
2194 private final Options options;
2197 * Creates a new preferences object wrapped around the given options.
2200 * The options to wrap
2202 public Preferences(Options options) {
2203 this.options = options;
2207 * Returns the insertion delay.
2209 * @return The insertion delay
2211 public int getInsertionDelay() {
2212 return options.getIntegerOption("InsertionDelay").get();
2216 * Sets the insertion delay
2218 * @param insertionDelay
2219 * The new insertion delay, or {@code null} to restore it to
2221 * @return This preferences
2223 public Preferences setInsertionDelay(Integer insertionDelay) {
2224 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2229 * Returns the positive trust.
2231 * @return The positive trust
2233 public int getPositiveTrust() {
2234 return options.getIntegerOption("PositiveTrust").get();
2238 * Sets the positive trust.
2240 * @param positiveTrust
2241 * The new positive trust, or {@code null} to restore it to
2243 * @return This preferences
2245 public Preferences setPositiveTrust(Integer positiveTrust) {
2246 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2251 * Returns the negative trust.
2253 * @return The negative trust
2255 public int getNegativeTrust() {
2256 return options.getIntegerOption("NegativeTrust").get();
2260 * Sets the negative trust.
2262 * @param negativeTrust
2263 * The negative trust, or {@code null} to restore it to the
2265 * @return The preferences
2267 public Preferences setNegativeTrust(Integer negativeTrust) {
2268 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2273 * Returns the trust comment. This is the comment that is set in the web
2274 * of trust when a trust value is assigned to an identity.
2276 * @return The trust comment
2278 public String getTrustComment() {
2279 return options.getStringOption("TrustComment").get();
2283 * Sets the trust comment.
2285 * @param trustComment
2286 * The trust comment, or {@code null} to restore it to the
2288 * @return This preferences
2290 public Preferences setTrustComment(String trustComment) {
2291 options.getStringOption("TrustComment").set(trustComment);
2296 * Returns whether the rescue mode is active.
2298 * @return {@code true} if the rescue mode is active, {@code false}
2301 public boolean isSoneRescueMode() {
2302 return options.getBooleanOption("SoneRescueMode").get();
2306 * Sets whether the rescue mode is active.
2308 * @param soneRescueMode
2309 * {@code true} if the rescue mode is active, {@code false}
2311 * @return This preferences
2313 public Preferences setSoneRescueMode(Boolean soneRescueMode) {
2314 options.getBooleanOption("SoneRescueMode").set(soneRescueMode);
2319 * Returns whether Sone should clear its settings on the next restart.
2320 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2321 * to return {@code true} as well!
2323 * @return {@code true} if Sone should clear its settings on the next
2324 * restart, {@code false} otherwise
2326 public boolean isClearOnNextRestart() {
2327 return options.getBooleanOption("ClearOnNextRestart").get();
2331 * Sets whether Sone will clear its settings on the next restart.
2333 * @param clearOnNextRestart
2334 * {@code true} if Sone should clear its settings on the next
2335 * restart, {@code false} otherwise
2336 * @return This preferences
2338 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2339 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2344 * Returns whether Sone should really clear its settings on next
2345 * restart. This is a confirmation option that needs to be set in
2346 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2347 * settings on the next restart.
2349 * @return {@code true} if Sone should really clear its settings on the
2350 * next restart, {@code false} otherwise
2352 public boolean isReallyClearOnNextRestart() {
2353 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2357 * Sets whether Sone should really clear its settings on the next
2360 * @param reallyClearOnNextRestart
2361 * {@code true} if Sone should really clear its settings on
2362 * the next restart, {@code false} otherwise
2363 * @return This preferences
2365 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2366 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);