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.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Reply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.TemporaryImage;
46 import net.pterodactylus.sone.data.Profile.Field;
47 import net.pterodactylus.sone.fcp.FcpInterface;
48 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
49 import net.pterodactylus.sone.freenet.wot.Identity;
50 import net.pterodactylus.sone.freenet.wot.IdentityListener;
51 import net.pterodactylus.sone.freenet.wot.IdentityManager;
52 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
53 import net.pterodactylus.sone.freenet.wot.Trust;
54 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
55 import net.pterodactylus.sone.main.SonePlugin;
56 import net.pterodactylus.util.config.Configuration;
57 import net.pterodactylus.util.config.ConfigurationException;
58 import net.pterodactylus.util.logging.Logging;
59 import net.pterodactylus.util.number.Numbers;
60 import net.pterodactylus.util.service.AbstractService;
61 import net.pterodactylus.util.thread.Ticker;
62 import net.pterodactylus.util.validation.EqualityValidator;
63 import net.pterodactylus.util.validation.IntegerRangeValidator;
64 import net.pterodactylus.util.validation.OrValidator;
65 import net.pterodactylus.util.validation.Validation;
66 import net.pterodactylus.util.version.Version;
67 import freenet.keys.FreenetURI;
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
74 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
77 * Enumeration for the possible states of a {@link Sone}.
79 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
81 public enum SoneStatus {
83 /** The Sone is unknown, i.e. not yet downloaded. */
86 /** The Sone is idle, i.e. not being downloaded or inserted. */
89 /** The Sone is currently being inserted. */
92 /** The Sone is currently being downloaded. */
97 private static final Logger logger = Logging.getLogger(Core.class);
100 private final Options options = new Options();
102 /** The preferences. */
103 private final Preferences preferences = new Preferences(options);
105 /** The core listener manager. */
106 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
108 /** The configuration. */
109 private Configuration configuration;
111 /** Whether we’re currently saving the configuration. */
112 private boolean storingConfiguration = false;
114 /** The identity manager. */
115 private final IdentityManager identityManager;
117 /** Interface to freenet. */
118 private final FreenetInterface freenetInterface;
120 /** The Sone downloader. */
121 private final SoneDownloader soneDownloader;
123 /** The image inserter. */
124 private final ImageInserter imageInserter;
126 /** Sone downloader thread-pool. */
127 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
129 /** The update checker. */
130 private final UpdateChecker updateChecker;
132 /** The FCP interface. */
133 private volatile FcpInterface fcpInterface;
135 /** The Sones’ statuses. */
136 /* synchronize access on itself. */
137 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
139 /** Locked local Sones. */
140 /* synchronize on itself. */
141 private final Set<Sone> lockedSones = new HashSet<Sone>();
143 /** Sone inserters. */
144 /* synchronize access on this on localSones. */
145 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
147 /** Sone rescuers. */
148 /* synchronize access on this on localSones. */
149 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
151 /** All local Sones. */
152 /* synchronize access on this on itself. */
153 private Map<String, Sone> localSones = new HashMap<String, Sone>();
155 /** All remote Sones. */
156 /* synchronize access on this on itself. */
157 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
159 /** All new Sones. */
160 private Set<String> newSones = new HashSet<String>();
162 /** All known Sones. */
163 /* synchronize access on {@link #newSones}. */
164 private Set<String> knownSones = new HashSet<String>();
167 private Map<String, Post> posts = new HashMap<String, Post>();
169 /** All new posts. */
170 private Set<String> newPosts = new HashSet<String>();
172 /** All known posts. */
173 /* synchronize access on {@link #newPosts}. */
174 private Set<String> knownPosts = new HashSet<String>();
177 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
179 /** All new replies. */
180 private Set<String> newReplies = new HashSet<String>();
182 /** All known replies. */
183 private Set<String> knownReplies = new HashSet<String>();
185 /** All bookmarked posts. */
186 /* synchronize access on itself. */
187 private Set<String> bookmarkedPosts = new HashSet<String>();
189 /** Trusted identities, sorted by own identities. */
190 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
192 /** All known albums. */
193 private Map<String, Album> albums = new HashMap<String, Album>();
195 /** All known images. */
196 private Map<String, Image> images = new HashMap<String, Image>();
198 /** All temporary images. */
199 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
201 /** Ticker for threads that mark own elements as known. */
202 private Ticker localElementTicker = new Ticker();
204 /** The time the configuration was last touched. */
205 private volatile long lastConfigurationUpdate;
208 * Creates a new core.
210 * @param configuration
211 * The configuration of the core
212 * @param freenetInterface
213 * The freenet interface
214 * @param identityManager
215 * The identity manager
217 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
219 this.configuration = configuration;
220 this.freenetInterface = freenetInterface;
221 this.identityManager = identityManager;
222 this.soneDownloader = new SoneDownloader(this, freenetInterface);
223 this.imageInserter = new ImageInserter(this, freenetInterface);
224 this.updateChecker = new UpdateChecker(freenetInterface);
228 // LISTENER MANAGEMENT
232 * Adds a new core listener.
234 * @param coreListener
235 * The listener to add
237 public void addCoreListener(CoreListener coreListener) {
238 coreListenerManager.addListener(coreListener);
242 * Removes a core listener.
244 * @param coreListener
245 * The listener to remove
247 public void removeCoreListener(CoreListener coreListener) {
248 coreListenerManager.removeListener(coreListener);
256 * Sets the configuration to use. This will automatically save the current
257 * configuration to the given configuration.
259 * @param configuration
260 * The new configuration to use
262 public void setConfiguration(Configuration configuration) {
263 this.configuration = configuration;
264 touchConfiguration();
268 * Returns the options used by the core.
270 * @return The options of the core
272 public Preferences getPreferences() {
277 * Returns the identity manager used by the core.
279 * @return The identity manager
281 public IdentityManager getIdentityManager() {
282 return identityManager;
286 * Returns the update checker.
288 * @return The update checker
290 public UpdateChecker getUpdateChecker() {
291 return updateChecker;
295 * Sets the FCP interface to use.
297 * @param fcpInterface
298 * The FCP interface to use
300 public void setFcpInterface(FcpInterface fcpInterface) {
301 this.fcpInterface = fcpInterface;
305 * Returns the status of the given Sone.
308 * The Sone to get the status for
309 * @return The status of the Sone
311 public SoneStatus getSoneStatus(Sone sone) {
312 synchronized (soneStatuses) {
313 return soneStatuses.get(sone);
318 * Sets the status of the given Sone.
321 * The Sone to set the status of
325 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
326 synchronized (soneStatuses) {
327 soneStatuses.put(sone, soneStatus);
332 * Returns the Sone rescuer for the given local Sone.
335 * The local Sone to get the rescuer for
336 * @return The Sone rescuer for the given Sone
338 public SoneRescuer getSoneRescuer(Sone sone) {
339 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
340 synchronized (localSones) {
341 SoneRescuer soneRescuer = soneRescuers.get(sone);
342 if (soneRescuer == null) {
343 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
344 soneRescuers.put(sone, soneRescuer);
352 * Returns whether the given Sone is currently locked.
356 * @return {@code true} if the Sone is locked, {@code false} if it is not
358 public boolean isLocked(Sone sone) {
359 synchronized (lockedSones) {
360 return lockedSones.contains(sone);
365 * Returns all Sones, remote and local.
369 public Set<Sone> getSones() {
370 Set<Sone> allSones = new HashSet<Sone>();
371 allSones.addAll(getLocalSones());
372 allSones.addAll(getRemoteSones());
377 * Returns the Sone with the given ID, regardless whether it’s local or
381 * The ID of the Sone to get
382 * @return The Sone with the given ID, or {@code null} if there is no such
385 public Sone getSone(String id) {
386 return getSone(id, true);
390 * Returns the Sone with the given ID, regardless whether it’s local or
394 * The ID of the Sone to get
396 * {@code true} to create a new Sone if none exists,
397 * {@code false} to return {@code null} if a Sone with the given
399 * @return The Sone with the given ID, or {@code null} if there is no such
403 public Sone getSone(String id, boolean create) {
404 if (isLocalSone(id)) {
405 return getLocalSone(id);
407 return getRemoteSone(id, create);
411 * Checks whether the core knows a Sone with the given ID.
415 * @return {@code true} if there is a Sone with the given ID, {@code false}
418 public boolean hasSone(String id) {
419 return isLocalSone(id) || isRemoteSone(id);
423 * Returns whether the given Sone is a local Sone.
426 * The Sone to check for its locality
427 * @return {@code true} if the given Sone is local, {@code false} otherwise
429 public boolean isLocalSone(Sone sone) {
430 synchronized (localSones) {
431 return localSones.containsKey(sone.getId());
436 * Returns whether the given ID is the ID of a local Sone.
439 * The Sone ID to check for its locality
440 * @return {@code true} if the given ID is a local Sone, {@code false}
443 public boolean isLocalSone(String id) {
444 synchronized (localSones) {
445 return localSones.containsKey(id);
450 * Returns all local Sones.
452 * @return All local Sones
454 public Set<Sone> getLocalSones() {
455 synchronized (localSones) {
456 return new HashSet<Sone>(localSones.values());
461 * Returns the local Sone with the given ID.
464 * The ID of the Sone to get
465 * @return The Sone with the given ID
467 public Sone getLocalSone(String id) {
468 return getLocalSone(id, true);
472 * Returns the local Sone with the given ID, optionally creating a new Sone.
477 * {@code true} to create a new Sone if none exists,
478 * {@code false} to return null if none exists
479 * @return The Sone with the given ID, or {@code null}
481 public Sone getLocalSone(String id, boolean create) {
482 synchronized (localSones) {
483 Sone sone = localSones.get(id);
484 if ((sone == null) && create) {
486 localSones.put(id, sone);
487 setSoneStatus(sone, SoneStatus.unknown);
494 * Returns all remote Sones.
496 * @return All remote Sones
498 public Set<Sone> getRemoteSones() {
499 synchronized (remoteSones) {
500 return new HashSet<Sone>(remoteSones.values());
505 * Returns the remote Sone with the given ID.
508 * The ID of the remote Sone to get
509 * @return The Sone with the given ID
511 public Sone getRemoteSone(String id) {
512 return getRemoteSone(id, true);
516 * Returns the remote Sone with the given ID.
519 * The ID of the remote Sone to get
521 * {@code true} to always create a Sone, {@code false} to return
522 * {@code null} if no Sone with the given ID exists
523 * @return The Sone with the given ID
525 public Sone getRemoteSone(String id, boolean create) {
526 synchronized (remoteSones) {
527 Sone sone = remoteSones.get(id);
528 if ((sone == null) && create) {
530 remoteSones.put(id, sone);
531 setSoneStatus(sone, SoneStatus.unknown);
538 * Returns whether the given Sone is a remote Sone.
542 * @return {@code true} if the given Sone is a remote Sone, {@code false}
545 public boolean isRemoteSone(Sone sone) {
546 synchronized (remoteSones) {
547 return remoteSones.containsKey(sone.getId());
552 * Returns whether the Sone with the given ID is a remote Sone.
555 * The ID of the Sone to check
556 * @return {@code true} if the Sone with the given ID is a remote Sone,
557 * {@code false} otherwise
559 public boolean isRemoteSone(String id) {
560 synchronized (remoteSones) {
561 return remoteSones.containsKey(id);
566 * Returns whether the Sone with the given ID is a new Sone.
569 * The ID of the sone to check for
570 * @return {@code true} if the given Sone is new, false otherwise
572 public boolean isNewSone(String soneId) {
573 synchronized (newSones) {
574 return !knownSones.contains(soneId) && newSones.contains(soneId);
579 * Returns whether the given Sone has been modified.
582 * The Sone to check for modifications
583 * @return {@code true} if a modification has been detected in the Sone,
584 * {@code false} otherwise
586 public boolean isModifiedSone(Sone sone) {
587 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
591 * Returns whether the target Sone is trusted by the origin Sone.
597 * @return {@code true} if the target Sone is trusted by the origin Sone
599 public boolean isSoneTrusted(Sone origin, Sone target) {
600 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
601 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
605 * Returns the post with the given ID.
608 * The ID of the post to get
609 * @return The post with the given ID, or a new post with the given ID
611 public Post getPost(String postId) {
612 return getPost(postId, true);
616 * Returns the post with the given ID, optionally creating a new post.
619 * The ID of the post to get
621 * {@code true} it create a new post if no post with the given ID
622 * exists, {@code false} to return {@code null}
623 * @return The post, or {@code null} if there is no such post
626 public Post getPost(String postId, boolean create) {
627 synchronized (posts) {
628 Post post = posts.get(postId);
629 if ((post == null) && create) {
630 post = new Post(postId);
631 posts.put(postId, post);
638 * Returns whether the given post ID is new.
642 * @return {@code true} if the post is considered to be new, {@code false}
645 public boolean isNewPost(String postId) {
646 synchronized (newPosts) {
647 return !knownPosts.contains(postId) && newPosts.contains(postId);
652 * Returns all posts that have the given Sone as recipient.
654 * @see Post#getRecipient()
656 * The recipient of the posts
657 * @return All posts that have the given Sone as recipient
659 public Set<Post> getDirectedPosts(Sone recipient) {
660 Validation.begin().isNotNull("Recipient", recipient).check();
661 Set<Post> directedPosts = new HashSet<Post>();
662 synchronized (posts) {
663 for (Post post : posts.values()) {
664 if (recipient.equals(post.getRecipient())) {
665 directedPosts.add(post);
669 return directedPosts;
673 * Returns the reply with the given ID. If there is no reply with the given
674 * ID yet, a new one is created.
677 * The ID of the reply to get
680 public PostReply getReply(String replyId) {
681 return getReply(replyId, true);
685 * Returns the reply with the given ID. If there is no reply with the given
686 * ID yet, a new one is created, unless {@code create} is false in which
687 * case {@code null} is returned.
690 * The ID of the reply to get
692 * {@code true} to always return a {@link Reply}, {@code false}
693 * to return {@code null} if no reply can be found
694 * @return The reply, or {@code null} if there is no such reply
696 public PostReply getReply(String replyId, boolean create) {
697 synchronized (replies) {
698 PostReply reply = replies.get(replyId);
699 if (create && (reply == null)) {
700 reply = new PostReply(replyId);
701 replies.put(replyId, reply);
708 * Returns all replies for the given post, order ascending by time.
711 * The post to get all replies for
712 * @return All replies for the given post
714 public List<PostReply> getReplies(Post post) {
715 Set<Sone> sones = getSones();
716 List<PostReply> replies = new ArrayList<PostReply>();
717 for (Sone sone : sones) {
718 for (PostReply reply : sone.getReplies()) {
719 if (reply.getPost().equals(post)) {
724 Collections.sort(replies, Reply.TIME_COMPARATOR);
729 * Returns whether the reply with the given ID is new.
732 * The ID of the reply to check
733 * @return {@code true} if the reply is considered to be new, {@code false}
736 public boolean isNewReply(String replyId) {
737 synchronized (newReplies) {
738 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
743 * Returns all Sones that have liked the given post.
746 * The post to get the liking Sones for
747 * @return The Sones that like the given post
749 public Set<Sone> getLikes(Post post) {
750 Set<Sone> sones = new HashSet<Sone>();
751 for (Sone sone : getSones()) {
752 if (sone.getLikedPostIds().contains(post.getId())) {
760 * Returns all Sones that have liked the given reply.
763 * The reply to get the liking Sones for
764 * @return The Sones that like the given reply
766 public Set<Sone> getLikes(PostReply reply) {
767 Set<Sone> sones = new HashSet<Sone>();
768 for (Sone sone : getSones()) {
769 if (sone.getLikedReplyIds().contains(reply.getId())) {
777 * Returns whether the given post is bookmarked.
781 * @return {@code true} if the given post is bookmarked, {@code false}
784 public boolean isBookmarked(Post post) {
785 return isPostBookmarked(post.getId());
789 * Returns whether the post with the given ID is bookmarked.
792 * The ID of the post to check
793 * @return {@code true} if the post with the given ID is bookmarked,
794 * {@code false} otherwise
796 public boolean isPostBookmarked(String id) {
797 synchronized (bookmarkedPosts) {
798 return bookmarkedPosts.contains(id);
803 * Returns all currently known bookmarked posts.
805 * @return All bookmarked posts
807 public Set<Post> getBookmarkedPosts() {
808 Set<Post> posts = new HashSet<Post>();
809 synchronized (bookmarkedPosts) {
810 for (String bookmarkedPostId : bookmarkedPosts) {
811 Post post = getPost(bookmarkedPostId, false);
821 * Returns the album with the given ID, creating a new album if no album
822 * with the given ID can be found.
825 * The ID of the album
826 * @return The album with the given ID
828 public Album getAlbum(String albumId) {
829 return getAlbum(albumId, true);
833 * Returns the album with the given ID, optionally creating a new album if
834 * an album with the given ID can not be found.
837 * The ID of the album
839 * {@code true} to create a new album if none exists for the
841 * @return The album with the given ID, or {@code null} if no album with the
842 * given ID exists and {@code create} is {@code false}
844 public Album getAlbum(String albumId, boolean create) {
845 synchronized (albums) {
846 Album album = albums.get(albumId);
847 if (create && (album == null)) {
848 album = new Album(albumId);
849 albums.put(albumId, album);
856 * Returns the image with the given ID, creating it if necessary.
859 * The ID of the image
860 * @return The image with the given ID
862 public Image getImage(String imageId) {
863 return getImage(imageId, true);
867 * Returns the image with the given ID, optionally creating it if it does
871 * The ID of the image
873 * {@code true} to create an image if none exists with the given
875 * @return The image with the given ID, or {@code null} if none exists and
878 public Image getImage(String imageId, boolean create) {
879 synchronized (images) {
880 Image image = images.get(imageId);
881 if (create && (image == null)) {
882 image = new Image(imageId);
883 images.put(imageId, image);
890 * Returns the temporary image with the given ID.
893 * The ID of the temporary image
894 * @return The temporary image, or {@code null} if there is no temporary
895 * image with the given ID
897 public TemporaryImage getTemporaryImage(String imageId) {
898 synchronized (temporaryImages) {
899 return temporaryImages.get(imageId);
908 * Locks the given Sone. A locked Sone will not be inserted by
909 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
915 public void lockSone(Sone sone) {
916 synchronized (lockedSones) {
917 if (lockedSones.add(sone)) {
918 coreListenerManager.fireSoneLocked(sone);
924 * Unlocks the given Sone.
926 * @see #lockSone(Sone)
930 public void unlockSone(Sone sone) {
931 synchronized (lockedSones) {
932 if (lockedSones.remove(sone)) {
933 coreListenerManager.fireSoneUnlocked(sone);
939 * Adds a local Sone from the given ID which has to be the ID of an own
943 * The ID of an own identity to add a Sone for
944 * @return The added (or already existing) Sone
946 public Sone addLocalSone(String id) {
947 synchronized (localSones) {
948 if (localSones.containsKey(id)) {
949 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
950 return localSones.get(id);
952 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
953 if (ownIdentity == null) {
954 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
957 return addLocalSone(ownIdentity);
962 * Adds a local Sone from the given own identity.
965 * The own identity to create a Sone from
966 * @return The added (or already existing) Sone
968 public Sone addLocalSone(OwnIdentity ownIdentity) {
969 if (ownIdentity == null) {
970 logger.log(Level.WARNING, "Given OwnIdentity is null!");
973 synchronized (localSones) {
976 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
977 } catch (MalformedURLException mue1) {
978 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
981 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
982 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
983 /* TODO - load posts ’n stuff */
984 localSones.put(ownIdentity.getId(), sone);
985 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
986 soneInserter.addSoneInsertListener(this);
987 soneInserters.put(sone, soneInserter);
988 setSoneStatus(sone, SoneStatus.idle);
990 soneInserter.start();
996 * Creates a new Sone for the given own identity.
999 * The own identity to create a Sone for
1000 * @return The created Sone
1002 public Sone createSone(OwnIdentity ownIdentity) {
1004 ownIdentity.addContext("Sone");
1005 } catch (WebOfTrustException wote1) {
1006 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
1009 Sone sone = addLocalSone(ownIdentity);
1010 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1011 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1012 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1013 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1014 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1015 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
1016 touchConfiguration();
1021 * Adds the Sone of the given identity.
1024 * The identity whose Sone to add
1025 * @return The added or already existing Sone
1027 public Sone addRemoteSone(Identity identity) {
1028 if (identity == null) {
1029 logger.log(Level.WARNING, "Given Identity is null!");
1032 synchronized (remoteSones) {
1033 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
1034 boolean newSone = sone.getRequestUri() == null;
1035 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
1036 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
1038 synchronized (newSones) {
1039 newSone = !knownSones.contains(sone.getId());
1041 newSones.add(sone.getId());
1045 coreListenerManager.fireNewSoneFound(sone);
1046 for (Sone localSone : getLocalSones()) {
1047 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
1048 localSone.addFriend(sone.getId());
1049 touchConfiguration();
1054 remoteSones.put(identity.getId(), sone);
1055 soneDownloader.addSone(sone);
1056 setSoneStatus(sone, SoneStatus.unknown);
1057 soneDownloaders.execute(new Runnable() {
1060 @SuppressWarnings("synthetic-access")
1062 soneDownloader.fetchSone(sone, sone.getRequestUri());
1071 * Retrieves the trust relationship from the origin to the target. If the
1072 * trust relationship can not be retrieved, {@code null} is returned.
1074 * @see Identity#getTrust(OwnIdentity)
1076 * The origin of the trust tree
1078 * The target of the trust
1079 * @return The trust relationship
1081 public Trust getTrust(Sone origin, Sone target) {
1082 if (!isLocalSone(origin)) {
1083 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1086 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1090 * Sets the trust value of the given origin Sone for the target Sone.
1097 * The trust value (from {@code -100} to {@code 100})
1099 public void setTrust(Sone origin, Sone target, int trustValue) {
1100 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();
1102 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1103 } catch (WebOfTrustException wote1) {
1104 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1109 * Removes any trust assignment for the given target Sone.
1116 public void removeTrust(Sone origin, Sone target) {
1117 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1119 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1120 } catch (WebOfTrustException wote1) {
1121 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1126 * Assigns the configured positive trust value for the given target.
1133 public void trustSone(Sone origin, Sone target) {
1134 setTrust(origin, target, preferences.getPositiveTrust());
1138 * Assigns the configured negative trust value for the given target.
1145 public void distrustSone(Sone origin, Sone target) {
1146 setTrust(origin, target, preferences.getNegativeTrust());
1150 * Removes the trust assignment for the given target.
1157 public void untrustSone(Sone origin, Sone target) {
1158 removeTrust(origin, target);
1162 * Updates the stored Sone with the given Sone.
1167 public void updateSone(Sone sone) {
1168 updateSone(sone, false);
1172 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1173 * {@code true}, an older Sone than the current Sone can be given to restore
1177 * The Sone to update
1178 * @param soneRescueMode
1179 * {@code true} if the stored Sone should be updated regardless
1180 * of the age of the given Sone
1182 public void updateSone(Sone sone, boolean soneRescueMode) {
1183 if (hasSone(sone.getId())) {
1184 Sone storedSone = getSone(sone.getId());
1185 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1186 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1189 synchronized (posts) {
1190 if (!soneRescueMode) {
1191 for (Post post : storedSone.getPosts()) {
1192 posts.remove(post.getId());
1193 if (!sone.getPosts().contains(post)) {
1194 coreListenerManager.firePostRemoved(post);
1198 List<Post> storedPosts = storedSone.getPosts();
1199 synchronized (newPosts) {
1200 for (Post post : sone.getPosts()) {
1201 post.setSone(storedSone);
1202 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1203 newPosts.add(post.getId());
1204 coreListenerManager.fireNewPostFound(post);
1206 posts.put(post.getId(), post);
1210 synchronized (replies) {
1211 if (!soneRescueMode) {
1212 for (PostReply reply : storedSone.getReplies()) {
1213 replies.remove(reply.getId());
1214 if (!sone.getReplies().contains(reply)) {
1215 coreListenerManager.fireReplyRemoved(reply);
1219 Set<PostReply> storedReplies = storedSone.getReplies();
1220 synchronized (newReplies) {
1221 for (PostReply reply : sone.getReplies()) {
1222 reply.setSone(storedSone);
1223 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1224 newReplies.add(reply.getId());
1225 coreListenerManager.fireNewReplyFound(reply);
1227 replies.put(reply.getId(), reply);
1231 synchronized (albums) {
1232 synchronized (images) {
1233 for (Album album : storedSone.getAlbums()) {
1234 albums.remove(album.getId());
1235 for (Image image : album.getImages()) {
1236 images.remove(image.getId());
1239 for (Album album : sone.getAlbums()) {
1240 albums.put(album.getId(), album);
1241 for (Image image : album.getImages()) {
1242 images.put(image.getId(), image);
1247 synchronized (storedSone) {
1248 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1249 storedSone.setTime(sone.getTime());
1251 storedSone.setClient(sone.getClient());
1252 storedSone.setProfile(sone.getProfile());
1253 if (soneRescueMode) {
1254 for (Post post : sone.getPosts()) {
1255 storedSone.addPost(post);
1257 for (PostReply reply : sone.getReplies()) {
1258 storedSone.addReply(reply);
1260 for (String likedPostId : sone.getLikedPostIds()) {
1261 storedSone.addLikedPostId(likedPostId);
1263 for (String likedReplyId : sone.getLikedReplyIds()) {
1264 storedSone.addLikedReplyId(likedReplyId);
1266 for (Album album : sone.getAlbums()) {
1267 storedSone.addAlbum(album);
1270 storedSone.setPosts(sone.getPosts());
1271 storedSone.setReplies(sone.getReplies());
1272 storedSone.setLikePostIds(sone.getLikedPostIds());
1273 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1274 storedSone.setAlbums(sone.getAlbums());
1276 storedSone.setLatestEdition(sone.getLatestEdition());
1282 * Deletes the given Sone. This will remove the Sone from the
1283 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1284 * and remove the context from its identity.
1287 * The Sone to delete
1289 public void deleteSone(Sone sone) {
1290 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1291 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1294 synchronized (localSones) {
1295 if (!localSones.containsKey(sone.getId())) {
1296 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1299 localSones.remove(sone.getId());
1300 SoneInserter soneInserter = soneInserters.remove(sone);
1301 soneInserter.removeSoneInsertListener(this);
1302 soneInserter.stop();
1305 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1306 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1307 } catch (WebOfTrustException wote1) {
1308 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1311 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1312 } catch (ConfigurationException ce1) {
1313 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1318 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1319 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1322 * The Sone to mark as known
1324 public void markSoneKnown(Sone sone) {
1325 synchronized (newSones) {
1326 if (newSones.remove(sone.getId())) {
1327 knownSones.add(sone.getId());
1328 coreListenerManager.fireMarkSoneKnown(sone);
1329 touchConfiguration();
1335 * Loads and updates the given Sone from the configuration. If any error is
1336 * encountered, loading is aborted and the given Sone is not changed.
1339 * The Sone to load and update
1341 public void loadSone(Sone sone) {
1342 if (!isLocalSone(sone)) {
1343 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1347 /* initialize options. */
1348 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1349 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1350 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1351 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1352 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1355 String sonePrefix = "Sone/" + sone.getId();
1356 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1357 if (soneTime == null) {
1358 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1361 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1364 Profile profile = new Profile();
1365 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1366 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1367 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1368 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1369 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1370 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1372 /* load profile fields. */
1374 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1375 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1376 if (fieldName == null) {
1379 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1380 profile.addField(fieldName).setValue(fieldValue);
1384 Set<Post> posts = new HashSet<Post>();
1386 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1387 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1388 if (postId == null) {
1391 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1392 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1393 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1394 if ((postTime == 0) || (postText == null)) {
1395 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1398 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1399 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1400 post.setRecipient(getSone(postRecipientId));
1406 Set<PostReply> replies = new HashSet<PostReply>();
1408 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1409 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1410 if (replyId == null) {
1413 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1414 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1415 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1416 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1417 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1420 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1423 /* load post likes. */
1424 Set<String> likedPostIds = new HashSet<String>();
1426 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1427 if (likedPostId == null) {
1430 likedPostIds.add(likedPostId);
1433 /* load reply likes. */
1434 Set<String> likedReplyIds = new HashSet<String>();
1436 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1437 if (likedReplyId == null) {
1440 likedReplyIds.add(likedReplyId);
1444 Set<String> friends = new HashSet<String>();
1446 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1447 if (friendId == null) {
1450 friends.add(friendId);
1454 List<Album> topLevelAlbums = new ArrayList<Album>();
1455 int albumCounter = 0;
1457 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1458 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1459 if (albumId == null) {
1462 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1463 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1464 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1465 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1466 if ((albumTitle == null) || (albumDescription == null)) {
1467 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1470 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1471 if (albumParentId != null) {
1472 Album parentAlbum = getAlbum(albumParentId, false);
1473 if (parentAlbum == null) {
1474 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1477 parentAlbum.addAlbum(album);
1479 topLevelAlbums.add(album);
1484 int imageCounter = 0;
1486 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1487 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1488 if (imageId == null) {
1491 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1492 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1493 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1494 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1495 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1496 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1497 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1498 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1499 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1502 Album album = getAlbum(albumId, false);
1503 if (album == null) {
1504 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1507 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1508 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1509 album.addImage(image);
1513 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1514 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1515 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1516 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1517 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1519 /* if we’re still here, Sone was loaded successfully. */
1520 synchronized (sone) {
1521 sone.setTime(soneTime);
1522 sone.setProfile(profile);
1523 sone.setPosts(posts);
1524 sone.setReplies(replies);
1525 sone.setLikePostIds(likedPostIds);
1526 sone.setLikeReplyIds(likedReplyIds);
1527 sone.setFriends(friends);
1528 sone.setAlbums(topLevelAlbums);
1529 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1531 synchronized (newSones) {
1532 for (String friend : friends) {
1533 knownSones.add(friend);
1536 synchronized (newPosts) {
1537 for (Post post : posts) {
1538 knownPosts.add(post.getId());
1541 synchronized (newReplies) {
1542 for (PostReply reply : replies) {
1543 knownReplies.add(reply.getId());
1549 * Creates a new post.
1552 * The Sone that creates the post
1554 * The text of the post
1555 * @return The created post
1557 public Post createPost(Sone sone, String text) {
1558 return createPost(sone, System.currentTimeMillis(), text);
1562 * Creates a new post.
1565 * The Sone that creates the post
1567 * The time of the post
1569 * The text of the post
1570 * @return The created post
1572 public Post createPost(Sone sone, long time, String text) {
1573 return createPost(sone, null, time, text);
1577 * Creates a new post.
1580 * The Sone that creates the post
1582 * The recipient Sone, or {@code null} if this post does not have
1585 * The text of the post
1586 * @return The created post
1588 public Post createPost(Sone sone, Sone recipient, String text) {
1589 return createPost(sone, recipient, System.currentTimeMillis(), text);
1593 * Creates a new post.
1596 * The Sone that creates the post
1598 * The recipient Sone, or {@code null} if this post does not have
1601 * The time of the post
1603 * The text of the post
1604 * @return The created post
1606 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1607 if (!isLocalSone(sone)) {
1608 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1611 final Post post = new Post(sone, time, text);
1612 if (recipient != null) {
1613 post.setRecipient(recipient);
1615 synchronized (posts) {
1616 posts.put(post.getId(), post);
1618 synchronized (newPosts) {
1619 newPosts.add(post.getId());
1620 coreListenerManager.fireNewPostFound(post);
1623 touchConfiguration();
1624 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1631 markPostKnown(post);
1633 }, "Mark " + post + " read.");
1638 * Deletes the given post.
1641 * The post to delete
1643 public void deletePost(Post post) {
1644 if (!isLocalSone(post.getSone())) {
1645 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1648 post.getSone().removePost(post);
1649 synchronized (posts) {
1650 posts.remove(post.getId());
1652 coreListenerManager.firePostRemoved(post);
1653 synchronized (newPosts) {
1654 markPostKnown(post);
1655 knownPosts.remove(post.getId());
1657 touchConfiguration();
1661 * Marks the given post as known, if it is currently a new post (according
1662 * to {@link #isNewPost(String)}).
1665 * The post to mark as known
1667 public void markPostKnown(Post post) {
1668 synchronized (newPosts) {
1669 if (newPosts.remove(post.getId())) {
1670 knownPosts.add(post.getId());
1671 coreListenerManager.fireMarkPostKnown(post);
1672 touchConfiguration();
1678 * Bookmarks the given post.
1681 * The post to bookmark
1683 public void bookmark(Post post) {
1684 bookmarkPost(post.getId());
1688 * Bookmarks the post with the given ID.
1691 * The ID of the post to bookmark
1693 public void bookmarkPost(String id) {
1694 synchronized (bookmarkedPosts) {
1695 bookmarkedPosts.add(id);
1700 * Removes the given post from the bookmarks.
1703 * The post to unbookmark
1705 public void unbookmark(Post post) {
1706 unbookmarkPost(post.getId());
1710 * Removes the post with the given ID from the bookmarks.
1713 * The ID of the post to unbookmark
1715 public void unbookmarkPost(String id) {
1716 synchronized (bookmarkedPosts) {
1717 bookmarkedPosts.remove(id);
1722 * Creates a new reply.
1725 * The Sone that creates the reply
1727 * The post that this reply refers to
1729 * The text of the reply
1730 * @return The created reply
1732 public PostReply createReply(Sone sone, Post post, String text) {
1733 return createReply(sone, post, System.currentTimeMillis(), text);
1737 * Creates a new reply.
1740 * The Sone that creates the reply
1742 * The post that this reply refers to
1744 * The time of the reply
1746 * The text of the reply
1747 * @return The created reply
1749 public PostReply createReply(Sone sone, Post post, long time, String text) {
1750 if (!isLocalSone(sone)) {
1751 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1754 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1755 synchronized (replies) {
1756 replies.put(reply.getId(), reply);
1758 synchronized (newReplies) {
1759 newReplies.add(reply.getId());
1760 coreListenerManager.fireNewReplyFound(reply);
1762 sone.addReply(reply);
1763 touchConfiguration();
1764 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1771 markReplyKnown(reply);
1773 }, "Mark " + reply + " read.");
1778 * Deletes the given reply.
1781 * The reply to delete
1783 public void deleteReply(PostReply reply) {
1784 Sone sone = reply.getSone();
1785 if (!isLocalSone(sone)) {
1786 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1789 synchronized (replies) {
1790 replies.remove(reply.getId());
1792 synchronized (newReplies) {
1793 markReplyKnown(reply);
1794 knownReplies.remove(reply.getId());
1796 sone.removeReply(reply);
1797 touchConfiguration();
1801 * Marks the given reply as known, if it is currently a new reply (according
1802 * to {@link #isNewReply(String)}).
1805 * The reply to mark as known
1807 public void markReplyKnown(PostReply reply) {
1808 synchronized (newReplies) {
1809 if (newReplies.remove(reply.getId())) {
1810 knownReplies.add(reply.getId());
1811 coreListenerManager.fireMarkReplyKnown(reply);
1812 touchConfiguration();
1818 * Creates a new top-level album for the given Sone.
1821 * The Sone to create the album for
1822 * @return The new album
1824 public Album createAlbum(Sone sone) {
1825 return createAlbum(sone, null);
1829 * Creates a new album for the given Sone.
1832 * The Sone to create the album for
1834 * The parent of the album (may be {@code null} to create a
1836 * @return The new album
1838 public Album createAlbum(Sone sone, Album parent) {
1839 Album album = new Album();
1840 synchronized (albums) {
1841 albums.put(album.getId(), album);
1843 album.setSone(sone);
1844 if (parent != null) {
1845 parent.addAlbum(album);
1847 sone.addAlbum(album);
1853 * Deletes the given album. The owner of the album has to be a local Sone,
1854 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1857 * The album to remove
1859 public void deleteAlbum(Album album) {
1860 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1861 if (!album.isEmpty()) {
1864 if (album.getParent() == null) {
1865 album.getSone().removeAlbum(album);
1867 album.getParent().removeAlbum(album);
1869 synchronized (albums) {
1870 albums.remove(album.getId());
1872 saveSone(album.getSone());
1876 * Creates a new image.
1879 * The Sone creating the image
1881 * The album the image will be inserted into
1882 * @param temporaryImage
1883 * The temporary image to create the image from
1884 * @return The newly created image
1886 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1887 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();
1888 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1889 album.addImage(image);
1890 synchronized (images) {
1891 images.put(image.getId(), image);
1893 imageInserter.insertImage(temporaryImage, image);
1898 * Deletes the given image. This method will also delete a matching
1901 * @see #deleteTemporaryImage(TemporaryImage)
1903 * The image to delete
1905 public void deleteImage(Image image) {
1906 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1907 deleteTemporaryImage(image.getId());
1908 image.getAlbum().removeImage(image);
1909 synchronized (images) {
1910 images.remove(image.getId());
1912 saveSone(image.getSone());
1916 * Creates a new temporary image.
1919 * The MIME type of the temporary image
1921 * The encoded data of the image
1922 * @return The temporary image
1924 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1925 TemporaryImage temporaryImage = new TemporaryImage();
1926 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1927 synchronized (temporaryImages) {
1928 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1930 return temporaryImage;
1934 * Deletes the given temporary image.
1936 * @param temporaryImage
1937 * The temporary image to delete
1939 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1940 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1941 deleteTemporaryImage(temporaryImage.getId());
1945 * Deletes the temporary image with the given ID.
1948 * The ID of the temporary image to delete
1950 public void deleteTemporaryImage(String imageId) {
1951 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1952 synchronized (temporaryImages) {
1953 temporaryImages.remove(imageId);
1955 Image image = getImage(imageId, false);
1956 if (image != null) {
1957 imageInserter.cancelImageInsert(image);
1962 * Notifies the core that the configuration, either of the core or of a
1963 * single local Sone, has changed, and that the configuration should be
1966 public void touchConfiguration() {
1967 lastConfigurationUpdate = System.currentTimeMillis();
1978 public void serviceStart() {
1979 loadConfiguration();
1980 updateChecker.addUpdateListener(this);
1981 updateChecker.start();
1988 public void serviceRun() {
1989 long lastSaved = System.currentTimeMillis();
1990 while (!shouldStop()) {
1992 long now = System.currentTimeMillis();
1993 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1994 for (Sone localSone : getLocalSones()) {
1995 saveSone(localSone);
1997 saveConfiguration();
2007 public void serviceStop() {
2008 synchronized (localSones) {
2009 for (SoneInserter soneInserter : soneInserters.values()) {
2010 soneInserter.removeSoneInsertListener(this);
2011 soneInserter.stop();
2014 updateChecker.stop();
2015 updateChecker.removeUpdateListener(this);
2016 soneDownloader.stop();
2024 * Saves the given Sone. This will persist all local settings for the given
2025 * Sone, such as the friends list and similar, private options.
2030 private synchronized void saveSone(Sone sone) {
2031 if (!isLocalSone(sone)) {
2032 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2035 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2036 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2040 logger.log(Level.INFO, "Saving Sone: %s", sone);
2042 /* save Sone into configuration. */
2043 String sonePrefix = "Sone/" + sone.getId();
2044 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2045 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2048 Profile profile = sone.getProfile();
2049 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2050 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2051 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2052 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2053 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2054 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2056 /* save profile fields. */
2057 int fieldCounter = 0;
2058 for (Field profileField : profile.getFields()) {
2059 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2060 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2061 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2063 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2066 int postCounter = 0;
2067 for (Post post : sone.getPosts()) {
2068 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2069 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2070 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2071 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2072 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2074 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2077 int replyCounter = 0;
2078 for (PostReply reply : sone.getReplies()) {
2079 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2080 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2081 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2082 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2083 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2085 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2087 /* save post likes. */
2088 int postLikeCounter = 0;
2089 for (String postId : sone.getLikedPostIds()) {
2090 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2092 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2094 /* save reply likes. */
2095 int replyLikeCounter = 0;
2096 for (String replyId : sone.getLikedReplyIds()) {
2097 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2099 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2102 int friendCounter = 0;
2103 for (String friendId : sone.getFriends()) {
2104 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2106 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2108 /* save albums. first, collect in a flat structure, top-level first. */
2109 List<Album> albums = sone.getAllAlbums();
2111 int albumCounter = 0;
2112 for (Album album : albums) {
2113 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2114 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2115 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2116 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2117 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2118 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2120 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2123 int imageCounter = 0;
2124 for (Album album : albums) {
2125 for (Image image : album.getImages()) {
2126 if (!image.isInserted()) {
2129 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2130 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2131 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2132 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2133 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2134 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2135 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2136 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2137 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2140 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2143 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2144 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2145 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2146 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2147 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2149 configuration.save();
2151 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2153 logger.log(Level.INFO, "Sone %s saved.", sone);
2154 } catch (ConfigurationException ce1) {
2155 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2156 } catch (WebOfTrustException wote1) {
2157 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2162 * Saves the current options.
2164 private void saveConfiguration() {
2165 synchronized (configuration) {
2166 if (storingConfiguration) {
2167 logger.log(Level.FINE, "Already storing configuration…");
2170 storingConfiguration = true;
2173 /* store the options first. */
2175 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2176 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2177 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2178 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2179 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2180 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2181 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2182 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2183 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2184 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2185 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2186 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2187 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2188 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2190 /* save known Sones. */
2191 int soneCounter = 0;
2192 synchronized (newSones) {
2193 for (String knownSoneId : knownSones) {
2194 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2196 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2199 /* save known posts. */
2200 int postCounter = 0;
2201 synchronized (newPosts) {
2202 for (String knownPostId : knownPosts) {
2203 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2205 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2208 /* save known replies. */
2209 int replyCounter = 0;
2210 synchronized (newReplies) {
2211 for (String knownReplyId : knownReplies) {
2212 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2214 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2217 /* save bookmarked posts. */
2218 int bookmarkedPostCounter = 0;
2219 synchronized (bookmarkedPosts) {
2220 for (String bookmarkedPostId : bookmarkedPosts) {
2221 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2224 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2227 configuration.save();
2229 } catch (ConfigurationException ce1) {
2230 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2232 synchronized (configuration) {
2233 storingConfiguration = false;
2239 * Loads the configuration.
2241 @SuppressWarnings("unchecked")
2242 private void loadConfiguration() {
2243 /* create options. */
2244 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2247 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2248 SoneInserter.setInsertionDelay(newValue);
2252 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2253 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2254 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2255 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2256 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2257 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2258 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2259 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2262 @SuppressWarnings("synthetic-access")
2263 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2264 fcpInterface.setActive(newValue);
2267 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2270 @SuppressWarnings("synthetic-access")
2271 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2272 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2276 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2277 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2278 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2280 /* read options from configuration. */
2281 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2282 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2283 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2284 options.getBooleanOption("ClearOnNextRestart").set(null);
2285 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2286 if (clearConfiguration) {
2287 /* stop loading the configuration. */
2291 loadConfigurationValue("InsertionDelay");
2292 loadConfigurationValue("PostsPerPage");
2293 loadConfigurationValue("CharactersPerPost");
2294 loadConfigurationValue("PostCutOffLength");
2295 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2296 loadConfigurationValue("PositiveTrust");
2297 loadConfigurationValue("NegativeTrust");
2298 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2299 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2300 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2301 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2303 /* load known Sones. */
2304 int soneCounter = 0;
2306 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2307 if (knownSoneId == null) {
2310 synchronized (newSones) {
2311 knownSones.add(knownSoneId);
2315 /* load known posts. */
2316 int postCounter = 0;
2318 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2319 if (knownPostId == null) {
2322 synchronized (newPosts) {
2323 knownPosts.add(knownPostId);
2327 /* load known replies. */
2328 int replyCounter = 0;
2330 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2331 if (knownReplyId == null) {
2334 synchronized (newReplies) {
2335 knownReplies.add(knownReplyId);
2339 /* load bookmarked posts. */
2340 int bookmarkedPostCounter = 0;
2342 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2343 if (bookmarkedPostId == null) {
2346 synchronized (bookmarkedPosts) {
2347 bookmarkedPosts.add(bookmarkedPostId);
2354 * Loads an {@link Integer} configuration value for the option with the
2355 * given name, logging validation failures.
2358 * The name of the option to load
2360 private void loadConfigurationValue(String optionName) {
2362 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2363 } catch (IllegalArgumentException iae1) {
2364 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2369 * Generate a Sone URI from the given URI and latest edition.
2372 * The URI to derive the Sone URI from
2373 * @return The derived URI
2375 private FreenetURI getSoneUri(String uriString) {
2377 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2379 } catch (MalformedURLException mue1) {
2380 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2386 // INTERFACE IdentityListener
2393 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2394 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2395 if (ownIdentity.hasContext("Sone")) {
2396 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2397 addLocalSone(ownIdentity);
2405 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2406 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2407 trustedIdentities.remove(ownIdentity);
2414 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2415 logger.log(Level.FINEST, "Adding Identity: " + identity);
2416 trustedIdentities.get(ownIdentity).add(identity);
2417 addRemoteSone(identity);
2424 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2425 new Thread(new Runnable() {
2428 @SuppressWarnings("synthetic-access")
2430 Sone sone = getRemoteSone(identity.getId());
2431 sone.setIdentity(identity);
2432 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2433 soneDownloader.addSone(sone);
2434 soneDownloader.fetchSone(sone);
2443 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2444 trustedIdentities.get(ownIdentity).remove(identity);
2445 boolean foundIdentity = false;
2446 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2447 if (trustedIdentity.getKey().equals(ownIdentity)) {
2450 if (trustedIdentity.getValue().contains(identity)) {
2451 foundIdentity = true;
2454 if (foundIdentity) {
2455 /* some local identity still trusts this identity, don’t remove. */
2458 Sone sone = getSone(identity.getId(), false);
2460 /* TODO - we don’t have the Sone anymore. should this happen? */
2463 synchronized (posts) {
2464 synchronized (newPosts) {
2465 for (Post post : sone.getPosts()) {
2466 posts.remove(post.getId());
2467 newPosts.remove(post.getId());
2468 coreListenerManager.firePostRemoved(post);
2472 synchronized (replies) {
2473 synchronized (newReplies) {
2474 for (PostReply reply : sone.getReplies()) {
2475 replies.remove(reply.getId());
2476 newReplies.remove(reply.getId());
2477 coreListenerManager.fireReplyRemoved(reply);
2481 synchronized (remoteSones) {
2482 remoteSones.remove(identity.getId());
2484 synchronized (newSones) {
2485 newSones.remove(identity.getId());
2486 coreListenerManager.fireSoneRemoved(sone);
2491 // INTERFACE UpdateListener
2498 public void updateFound(Version version, long releaseTime, long latestEdition) {
2499 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2503 // INTERFACE ImageInsertListener
2510 public void insertStarted(Sone sone) {
2511 coreListenerManager.fireSoneInserting(sone);
2518 public void insertFinished(Sone sone, long insertDuration) {
2519 coreListenerManager.fireSoneInserted(sone, insertDuration);
2526 public void insertAborted(Sone sone, Throwable cause) {
2527 coreListenerManager.fireSoneInsertAborted(sone, cause);
2531 // SONEINSERTLISTENER METHODS
2538 public void imageInsertStarted(Image image) {
2539 logger.log(Level.WARNING, "Image insert started for " + image);
2540 coreListenerManager.fireImageInsertStarted(image);
2547 public void imageInsertAborted(Image image) {
2548 logger.log(Level.WARNING, "Image insert aborted for " + image);
2549 coreListenerManager.fireImageInsertAborted(image);
2556 public void imageInsertFinished(Image image, FreenetURI key) {
2557 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2558 image.setKey(key.toString());
2559 deleteTemporaryImage(image.getId());
2560 saveSone(image.getSone());
2561 coreListenerManager.fireImageInsertFinished(image);
2568 public void imageInsertFailed(Image image, Throwable cause) {
2569 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2570 coreListenerManager.fireImageInsertFailed(image, cause);
2574 * Convenience interface for external classes that want to access the core’s
2577 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2579 public static class Preferences {
2581 /** The wrapped options. */
2582 private final Options options;
2585 * Creates a new preferences object wrapped around the given options.
2588 * The options to wrap
2590 public Preferences(Options options) {
2591 this.options = options;
2595 * Returns the insertion delay.
2597 * @return The insertion delay
2599 public int getInsertionDelay() {
2600 return options.getIntegerOption("InsertionDelay").get();
2604 * Validates the given insertion delay.
2606 * @param insertionDelay
2607 * The insertion delay to validate
2608 * @return {@code true} if the given insertion delay was valid, {@code
2611 public boolean validateInsertionDelay(Integer insertionDelay) {
2612 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2616 * Sets the insertion delay
2618 * @param insertionDelay
2619 * The new insertion delay, or {@code null} to restore it to
2621 * @return This preferences
2623 public Preferences setInsertionDelay(Integer insertionDelay) {
2624 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2629 * Returns the number of posts to show per page.
2631 * @return The number of posts to show per page
2633 public int getPostsPerPage() {
2634 return options.getIntegerOption("PostsPerPage").get();
2638 * Validates the number of posts per page.
2640 * @param postsPerPage
2641 * The number of posts per page
2642 * @return {@code true} if the number of posts per page was valid,
2643 * {@code false} otherwise
2645 public boolean validatePostsPerPage(Integer postsPerPage) {
2646 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2650 * Sets the number of posts to show per page.
2652 * @param postsPerPage
2653 * The number of posts to show per page
2654 * @return This preferences object
2656 public Preferences setPostsPerPage(Integer postsPerPage) {
2657 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2662 * Returns the number of characters per post, or <code>-1</code> if the
2663 * posts should not be cut off.
2665 * @return The numbers of characters per post
2667 public int getCharactersPerPost() {
2668 return options.getIntegerOption("CharactersPerPost").get();
2672 * Validates the number of characters per post.
2674 * @param charactersPerPost
2675 * The number of characters per post
2676 * @return {@code true} if the number of characters per post was valid,
2677 * {@code false} otherwise
2679 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2680 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2684 * Sets the number of characters per post.
2686 * @param charactersPerPost
2687 * The number of characters per post, or <code>-1</code> to
2688 * not cut off the posts
2689 * @return This preferences objects
2691 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2692 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2697 * Returns the number of characters the shortened post should have.
2699 * @return The number of characters of the snippet
2701 public int getPostCutOffLength() {
2702 return options.getIntegerOption("PostCutOffLength").get();
2706 * Validates the number of characters after which to cut off the post.
2708 * @param postCutOffLength
2709 * The number of characters of the snippet
2710 * @return {@code true} if the number of characters of the snippet is
2711 * valid, {@code false} otherwise
2713 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2714 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2718 * Sets the number of characters the shortened post should have.
2720 * @param postCutOffLength
2721 * The number of characters of the snippet
2722 * @return This preferences
2724 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2725 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2730 * Returns whether Sone requires full access to be even visible.
2732 * @return {@code true} if Sone requires full access, {@code false}
2735 public boolean isRequireFullAccess() {
2736 return options.getBooleanOption("RequireFullAccess").get();
2740 * Sets whether Sone requires full access to be even visible.
2742 * @param requireFullAccess
2743 * {@code true} if Sone requires full access, {@code false}
2746 public void setRequireFullAccess(Boolean requireFullAccess) {
2747 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2751 * Returns the positive trust.
2753 * @return The positive trust
2755 public int getPositiveTrust() {
2756 return options.getIntegerOption("PositiveTrust").get();
2760 * Validates the positive trust.
2762 * @param positiveTrust
2763 * The positive trust to validate
2764 * @return {@code true} if the positive trust was valid, {@code false}
2767 public boolean validatePositiveTrust(Integer positiveTrust) {
2768 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2772 * Sets the positive trust.
2774 * @param positiveTrust
2775 * The new positive trust, or {@code null} to restore it to
2777 * @return This preferences
2779 public Preferences setPositiveTrust(Integer positiveTrust) {
2780 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2785 * Returns the negative trust.
2787 * @return The negative trust
2789 public int getNegativeTrust() {
2790 return options.getIntegerOption("NegativeTrust").get();
2794 * Validates the negative trust.
2796 * @param negativeTrust
2797 * The negative trust to validate
2798 * @return {@code true} if the negative trust was valid, {@code false}
2801 public boolean validateNegativeTrust(Integer negativeTrust) {
2802 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2806 * Sets the negative trust.
2808 * @param negativeTrust
2809 * The negative trust, or {@code null} to restore it to the
2811 * @return The preferences
2813 public Preferences setNegativeTrust(Integer negativeTrust) {
2814 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2819 * Returns the trust comment. This is the comment that is set in the web
2820 * of trust when a trust value is assigned to an identity.
2822 * @return The trust comment
2824 public String getTrustComment() {
2825 return options.getStringOption("TrustComment").get();
2829 * Sets the trust comment.
2831 * @param trustComment
2832 * The trust comment, or {@code null} to restore it to the
2834 * @return This preferences
2836 public Preferences setTrustComment(String trustComment) {
2837 options.getStringOption("TrustComment").set(trustComment);
2842 * Returns whether the {@link FcpInterface FCP interface} is currently
2845 * @see FcpInterface#setActive(boolean)
2846 * @return {@code true} if the FCP interface is currently active,
2847 * {@code false} otherwise
2849 public boolean isFcpInterfaceActive() {
2850 return options.getBooleanOption("ActivateFcpInterface").get();
2854 * Sets whether the {@link FcpInterface FCP interface} is currently
2857 * @see FcpInterface#setActive(boolean)
2858 * @param fcpInterfaceActive
2859 * {@code true} to activate the FCP interface, {@code false}
2860 * to deactivate the FCP interface
2861 * @return This preferences object
2863 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2864 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2869 * Returns the action level for which full access to the FCP interface
2872 * @return The action level for which full access to the FCP interface
2875 public FullAccessRequired getFcpFullAccessRequired() {
2876 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2880 * Sets the action level for which full access to the FCP interface is
2883 * @param fcpFullAccessRequired
2885 * @return This preferences
2887 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2888 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2893 * Returns whether Sone should clear its settings on the next restart.
2894 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2895 * to return {@code true} as well!
2897 * @return {@code true} if Sone should clear its settings on the next
2898 * restart, {@code false} otherwise
2900 public boolean isClearOnNextRestart() {
2901 return options.getBooleanOption("ClearOnNextRestart").get();
2905 * Sets whether Sone will clear its settings on the next restart.
2907 * @param clearOnNextRestart
2908 * {@code true} if Sone should clear its settings on the next
2909 * restart, {@code false} otherwise
2910 * @return This preferences
2912 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2913 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2918 * Returns whether Sone should really clear its settings on next
2919 * restart. This is a confirmation option that needs to be set in
2920 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2921 * settings on the next restart.
2923 * @return {@code true} if Sone should really clear its settings on the
2924 * next restart, {@code false} otherwise
2926 public boolean isReallyClearOnNextRestart() {
2927 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2931 * Sets whether Sone should really clear its settings on the next
2934 * @param reallyClearOnNextRestart
2935 * {@code true} if Sone should really clear its settings on
2936 * the next restart, {@code false} otherwise
2937 * @return This preferences
2939 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2940 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);