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 /** The times Sones were followed. */
140 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
142 /** Locked local Sones. */
143 /* synchronize on itself. */
144 private final Set<Sone> lockedSones = new HashSet<Sone>();
146 /** Sone inserters. */
147 /* synchronize access on this on localSones. */
148 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
150 /** Sone rescuers. */
151 /* synchronize access on this on localSones. */
152 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
154 /** All local Sones. */
155 /* synchronize access on this on itself. */
156 private Map<String, Sone> localSones = new HashMap<String, Sone>();
158 /** All remote Sones. */
159 /* synchronize access on this on itself. */
160 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
162 /** All new Sones. */
163 private Set<String> newSones = new HashSet<String>();
165 /** All known Sones. */
166 /* synchronize access on {@link #newSones}. */
167 private Set<String> knownSones = new HashSet<String>();
170 private Map<String, Post> posts = new HashMap<String, Post>();
172 /** All new posts. */
173 private Set<String> newPosts = new HashSet<String>();
175 /** All known posts. */
176 /* synchronize access on {@link #newPosts}. */
177 private Set<String> knownPosts = new HashSet<String>();
180 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
182 /** All new replies. */
183 private Set<String> newReplies = new HashSet<String>();
185 /** All known replies. */
186 private Set<String> knownReplies = new HashSet<String>();
188 /** All bookmarked posts. */
189 /* synchronize access on itself. */
190 private Set<String> bookmarkedPosts = new HashSet<String>();
192 /** Trusted identities, sorted by own identities. */
193 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
195 /** All known albums. */
196 private Map<String, Album> albums = new HashMap<String, Album>();
198 /** All known images. */
199 private Map<String, Image> images = new HashMap<String, Image>();
201 /** All temporary images. */
202 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
204 /** Ticker for threads that mark own elements as known. */
205 private Ticker localElementTicker = new Ticker();
207 /** The time the configuration was last touched. */
208 private volatile long lastConfigurationUpdate;
211 * Creates a new core.
213 * @param configuration
214 * The configuration of the core
215 * @param freenetInterface
216 * The freenet interface
217 * @param identityManager
218 * The identity manager
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226 this.imageInserter = new ImageInserter(this, freenetInterface);
227 this.updateChecker = new UpdateChecker(freenetInterface);
231 // LISTENER MANAGEMENT
235 * Adds a new core listener.
237 * @param coreListener
238 * The listener to add
240 public void addCoreListener(CoreListener coreListener) {
241 coreListenerManager.addListener(coreListener);
245 * Removes a core listener.
247 * @param coreListener
248 * The listener to remove
250 public void removeCoreListener(CoreListener coreListener) {
251 coreListenerManager.removeListener(coreListener);
259 * Sets the configuration to use. This will automatically save the current
260 * configuration to the given configuration.
262 * @param configuration
263 * The new configuration to use
265 public void setConfiguration(Configuration configuration) {
266 this.configuration = configuration;
267 touchConfiguration();
271 * Returns the options used by the core.
273 * @return The options of the core
275 public Preferences getPreferences() {
280 * Returns the identity manager used by the core.
282 * @return The identity manager
284 public IdentityManager getIdentityManager() {
285 return identityManager;
289 * Returns the update checker.
291 * @return The update checker
293 public UpdateChecker getUpdateChecker() {
294 return updateChecker;
298 * Sets the FCP interface to use.
300 * @param fcpInterface
301 * The FCP interface to use
303 public void setFcpInterface(FcpInterface fcpInterface) {
304 this.fcpInterface = fcpInterface;
308 * Returns the status of the given Sone.
311 * The Sone to get the status for
312 * @return The status of the Sone
314 public SoneStatus getSoneStatus(Sone sone) {
315 synchronized (soneStatuses) {
316 return soneStatuses.get(sone);
321 * Sets the status of the given Sone.
324 * The Sone to set the status of
328 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
329 synchronized (soneStatuses) {
330 soneStatuses.put(sone, soneStatus);
335 * Returns the Sone rescuer for the given local Sone.
338 * The local Sone to get the rescuer for
339 * @return The Sone rescuer for the given Sone
341 public SoneRescuer getSoneRescuer(Sone sone) {
342 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
343 synchronized (localSones) {
344 SoneRescuer soneRescuer = soneRescuers.get(sone);
345 if (soneRescuer == null) {
346 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
347 soneRescuers.put(sone, soneRescuer);
355 * Returns whether the given Sone is currently locked.
359 * @return {@code true} if the Sone is locked, {@code false} if it is not
361 public boolean isLocked(Sone sone) {
362 synchronized (lockedSones) {
363 return lockedSones.contains(sone);
368 * Returns all Sones, remote and local.
372 public Set<Sone> getSones() {
373 Set<Sone> allSones = new HashSet<Sone>();
374 allSones.addAll(getLocalSones());
375 allSones.addAll(getRemoteSones());
380 * Returns the Sone with the given ID, regardless whether it’s local or
384 * The ID of the Sone to get
385 * @return The Sone with the given ID, or {@code null} if there is no such
388 public Sone getSone(String id) {
389 return getSone(id, true);
393 * Returns the Sone with the given ID, regardless whether it’s local or
397 * The ID of the Sone to get
399 * {@code true} to create a new Sone if none exists,
400 * {@code false} to return {@code null} if a Sone with the given
402 * @return The Sone with the given ID, or {@code null} if there is no such
406 public Sone getSone(String id, boolean create) {
407 if (isLocalSone(id)) {
408 return getLocalSone(id);
410 return getRemoteSone(id, create);
414 * Checks whether the core knows a Sone with the given ID.
418 * @return {@code true} if there is a Sone with the given ID, {@code false}
421 public boolean hasSone(String id) {
422 return isLocalSone(id) || isRemoteSone(id);
426 * Returns whether the given Sone is a local Sone.
429 * The Sone to check for its locality
430 * @return {@code true} if the given Sone is local, {@code false} otherwise
432 public boolean isLocalSone(Sone sone) {
433 synchronized (localSones) {
434 return localSones.containsKey(sone.getId());
439 * Returns whether the given ID is the ID of a local Sone.
442 * The Sone ID to check for its locality
443 * @return {@code true} if the given ID is a local Sone, {@code false}
446 public boolean isLocalSone(String id) {
447 synchronized (localSones) {
448 return localSones.containsKey(id);
453 * Returns all local Sones.
455 * @return All local Sones
457 public Set<Sone> getLocalSones() {
458 synchronized (localSones) {
459 return new HashSet<Sone>(localSones.values());
464 * Returns the local Sone with the given ID.
467 * The ID of the Sone to get
468 * @return The Sone with the given ID
470 public Sone getLocalSone(String id) {
471 return getLocalSone(id, true);
475 * Returns the local Sone with the given ID, optionally creating a new Sone.
480 * {@code true} to create a new Sone if none exists,
481 * {@code false} to return null if none exists
482 * @return The Sone with the given ID, or {@code null}
484 public Sone getLocalSone(String id, boolean create) {
485 synchronized (localSones) {
486 Sone sone = localSones.get(id);
487 if ((sone == null) && create) {
489 localSones.put(id, sone);
490 setSoneStatus(sone, SoneStatus.unknown);
497 * Returns all remote Sones.
499 * @return All remote Sones
501 public Set<Sone> getRemoteSones() {
502 synchronized (remoteSones) {
503 return new HashSet<Sone>(remoteSones.values());
508 * Returns the remote Sone with the given ID.
511 * The ID of the remote Sone to get
512 * @return The Sone with the given ID
514 public Sone getRemoteSone(String id) {
515 return getRemoteSone(id, true);
519 * Returns the remote Sone with the given ID.
522 * The ID of the remote Sone to get
524 * {@code true} to always create a Sone, {@code false} to return
525 * {@code null} if no Sone with the given ID exists
526 * @return The Sone with the given ID
528 public Sone getRemoteSone(String id, boolean create) {
529 synchronized (remoteSones) {
530 Sone sone = remoteSones.get(id);
531 if ((sone == null) && create) {
533 remoteSones.put(id, sone);
534 setSoneStatus(sone, SoneStatus.unknown);
541 * Returns whether the given Sone is a remote Sone.
545 * @return {@code true} if the given Sone is a remote Sone, {@code false}
548 public boolean isRemoteSone(Sone sone) {
549 synchronized (remoteSones) {
550 return remoteSones.containsKey(sone.getId());
555 * Returns whether the Sone with the given ID is a remote Sone.
558 * The ID of the Sone to check
559 * @return {@code true} if the Sone with the given ID is a remote Sone,
560 * {@code false} otherwise
562 public boolean isRemoteSone(String id) {
563 synchronized (remoteSones) {
564 return remoteSones.containsKey(id);
569 * Returns whether the Sone with the given ID is a new Sone.
572 * The ID of the sone to check for
573 * @return {@code true} if the given Sone is new, false otherwise
575 public boolean isNewSone(String soneId) {
576 synchronized (newSones) {
577 return !knownSones.contains(soneId) && newSones.contains(soneId);
582 * Returns whether the given Sone has been modified.
585 * The Sone to check for modifications
586 * @return {@code true} if a modification has been detected in the Sone,
587 * {@code false} otherwise
589 public boolean isModifiedSone(Sone sone) {
590 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
594 * Returns the time when the given was first followed by any local Sone.
597 * The Sone to get the time for
598 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
599 * been followed, or {@link Long#MAX_VALUE}
601 public long getSoneFollowingTime(Sone sone) {
602 synchronized (soneFollowingTimes) {
603 if (soneFollowingTimes.containsKey(sone)) {
604 return soneFollowingTimes.get(sone);
606 return Long.MAX_VALUE;
611 * Returns whether the target Sone is trusted by the origin Sone.
617 * @return {@code true} if the target Sone is trusted by the origin Sone
619 public boolean isSoneTrusted(Sone origin, Sone target) {
620 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
621 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
625 * Returns the post with the given ID.
628 * The ID of the post to get
629 * @return The post with the given ID, or a new post with the given ID
631 public Post getPost(String postId) {
632 return getPost(postId, true);
636 * Returns the post with the given ID, optionally creating a new post.
639 * The ID of the post to get
641 * {@code true} it create a new post if no post with the given ID
642 * exists, {@code false} to return {@code null}
643 * @return The post, or {@code null} if there is no such post
646 public Post getPost(String postId, boolean create) {
647 synchronized (posts) {
648 Post post = posts.get(postId);
649 if ((post == null) && create) {
650 post = new Post(postId);
651 posts.put(postId, post);
658 * Returns whether the given post ID is new.
662 * @return {@code true} if the post is considered to be new, {@code false}
665 public boolean isNewPost(String postId) {
666 synchronized (newPosts) {
667 return !knownPosts.contains(postId) && newPosts.contains(postId);
672 * Returns all posts that have the given Sone as recipient.
674 * @see Post#getRecipient()
676 * The recipient of the posts
677 * @return All posts that have the given Sone as recipient
679 public Set<Post> getDirectedPosts(Sone recipient) {
680 Validation.begin().isNotNull("Recipient", recipient).check();
681 Set<Post> directedPosts = new HashSet<Post>();
682 synchronized (posts) {
683 for (Post post : posts.values()) {
684 if (recipient.equals(post.getRecipient())) {
685 directedPosts.add(post);
689 return directedPosts;
693 * Returns the reply with the given ID. If there is no reply with the given
694 * ID yet, a new one is created.
697 * The ID of the reply to get
700 public PostReply getReply(String replyId) {
701 return getReply(replyId, true);
705 * Returns the reply with the given ID. If there is no reply with the given
706 * ID yet, a new one is created, unless {@code create} is false in which
707 * case {@code null} is returned.
710 * The ID of the reply to get
712 * {@code true} to always return a {@link Reply}, {@code false}
713 * to return {@code null} if no reply can be found
714 * @return The reply, or {@code null} if there is no such reply
716 public PostReply getReply(String replyId, boolean create) {
717 synchronized (replies) {
718 PostReply reply = replies.get(replyId);
719 if (create && (reply == null)) {
720 reply = new PostReply(replyId);
721 replies.put(replyId, reply);
728 * Returns all replies for the given post, order ascending by time.
731 * The post to get all replies for
732 * @return All replies for the given post
734 public List<PostReply> getReplies(Post post) {
735 Set<Sone> sones = getSones();
736 List<PostReply> replies = new ArrayList<PostReply>();
737 for (Sone sone : sones) {
738 for (PostReply reply : sone.getReplies()) {
739 if (reply.getPost().equals(post)) {
744 Collections.sort(replies, Reply.TIME_COMPARATOR);
749 * Returns whether the reply with the given ID is new.
752 * The ID of the reply to check
753 * @return {@code true} if the reply is considered to be new, {@code false}
756 public boolean isNewReply(String replyId) {
757 synchronized (newReplies) {
758 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
763 * Returns all Sones that have liked the given post.
766 * The post to get the liking Sones for
767 * @return The Sones that like the given post
769 public Set<Sone> getLikes(Post post) {
770 Set<Sone> sones = new HashSet<Sone>();
771 for (Sone sone : getSones()) {
772 if (sone.getLikedPostIds().contains(post.getId())) {
780 * Returns all Sones that have liked the given reply.
783 * The reply to get the liking Sones for
784 * @return The Sones that like the given reply
786 public Set<Sone> getLikes(PostReply reply) {
787 Set<Sone> sones = new HashSet<Sone>();
788 for (Sone sone : getSones()) {
789 if (sone.getLikedReplyIds().contains(reply.getId())) {
797 * Returns whether the given post is bookmarked.
801 * @return {@code true} if the given post is bookmarked, {@code false}
804 public boolean isBookmarked(Post post) {
805 return isPostBookmarked(post.getId());
809 * Returns whether the post with the given ID is bookmarked.
812 * The ID of the post to check
813 * @return {@code true} if the post with the given ID is bookmarked,
814 * {@code false} otherwise
816 public boolean isPostBookmarked(String id) {
817 synchronized (bookmarkedPosts) {
818 return bookmarkedPosts.contains(id);
823 * Returns all currently known bookmarked posts.
825 * @return All bookmarked posts
827 public Set<Post> getBookmarkedPosts() {
828 Set<Post> posts = new HashSet<Post>();
829 synchronized (bookmarkedPosts) {
830 for (String bookmarkedPostId : bookmarkedPosts) {
831 Post post = getPost(bookmarkedPostId, false);
841 * Returns the album with the given ID, creating a new album if no album
842 * with the given ID can be found.
845 * The ID of the album
846 * @return The album with the given ID
848 public Album getAlbum(String albumId) {
849 return getAlbum(albumId, true);
853 * Returns the album with the given ID, optionally creating a new album if
854 * an album with the given ID can not be found.
857 * The ID of the album
859 * {@code true} to create a new album if none exists for the
861 * @return The album with the given ID, or {@code null} if no album with the
862 * given ID exists and {@code create} is {@code false}
864 public Album getAlbum(String albumId, boolean create) {
865 synchronized (albums) {
866 Album album = albums.get(albumId);
867 if (create && (album == null)) {
868 album = new Album(albumId);
869 albums.put(albumId, album);
876 * Returns the image with the given ID, creating it if necessary.
879 * The ID of the image
880 * @return The image with the given ID
882 public Image getImage(String imageId) {
883 return getImage(imageId, true);
887 * Returns the image with the given ID, optionally creating it if it does
891 * The ID of the image
893 * {@code true} to create an image if none exists with the given
895 * @return The image with the given ID, or {@code null} if none exists and
898 public Image getImage(String imageId, boolean create) {
899 synchronized (images) {
900 Image image = images.get(imageId);
901 if (create && (image == null)) {
902 image = new Image(imageId);
903 images.put(imageId, image);
910 * Returns the temporary image with the given ID.
913 * The ID of the temporary image
914 * @return The temporary image, or {@code null} if there is no temporary
915 * image with the given ID
917 public TemporaryImage getTemporaryImage(String imageId) {
918 synchronized (temporaryImages) {
919 return temporaryImages.get(imageId);
928 * Locks the given Sone. A locked Sone will not be inserted by
929 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
935 public void lockSone(Sone sone) {
936 synchronized (lockedSones) {
937 if (lockedSones.add(sone)) {
938 coreListenerManager.fireSoneLocked(sone);
944 * Unlocks the given Sone.
946 * @see #lockSone(Sone)
950 public void unlockSone(Sone sone) {
951 synchronized (lockedSones) {
952 if (lockedSones.remove(sone)) {
953 coreListenerManager.fireSoneUnlocked(sone);
959 * Adds a local Sone from the given ID which has to be the ID of an own
963 * The ID of an own identity to add a Sone for
964 * @return The added (or already existing) Sone
966 public Sone addLocalSone(String id) {
967 synchronized (localSones) {
968 if (localSones.containsKey(id)) {
969 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
970 return localSones.get(id);
972 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
973 if (ownIdentity == null) {
974 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
977 return addLocalSone(ownIdentity);
982 * Adds a local Sone from the given own identity.
985 * The own identity to create a Sone from
986 * @return The added (or already existing) Sone
988 public Sone addLocalSone(OwnIdentity ownIdentity) {
989 if (ownIdentity == null) {
990 logger.log(Level.WARNING, "Given OwnIdentity is null!");
993 synchronized (localSones) {
996 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
997 } catch (MalformedURLException mue1) {
998 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
1001 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
1002 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
1003 /* TODO - load posts ’n stuff */
1004 localSones.put(ownIdentity.getId(), sone);
1005 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
1006 soneInserter.addSoneInsertListener(this);
1007 soneInserters.put(sone, soneInserter);
1008 setSoneStatus(sone, SoneStatus.idle);
1010 soneInserter.start();
1016 * Creates a new Sone for the given own identity.
1018 * @param ownIdentity
1019 * The own identity to create a Sone for
1020 * @return The created Sone
1022 public Sone createSone(OwnIdentity ownIdentity) {
1024 ownIdentity.addContext("Sone");
1025 } catch (WebOfTrustException wote1) {
1026 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
1029 Sone sone = addLocalSone(ownIdentity);
1030 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1031 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1032 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1033 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1034 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1035 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
1036 touchConfiguration();
1041 * Adds the Sone of the given identity.
1044 * The identity whose Sone to add
1045 * @return The added or already existing Sone
1047 public Sone addRemoteSone(Identity identity) {
1048 if (identity == null) {
1049 logger.log(Level.WARNING, "Given Identity is null!");
1052 synchronized (remoteSones) {
1053 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
1054 boolean newSone = sone.getRequestUri() == null;
1055 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
1056 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
1058 synchronized (newSones) {
1059 newSone = !knownSones.contains(sone.getId());
1061 newSones.add(sone.getId());
1065 coreListenerManager.fireNewSoneFound(sone);
1066 for (Sone localSone : getLocalSones()) {
1067 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
1068 followSone(localSone, sone);
1073 remoteSones.put(identity.getId(), sone);
1074 soneDownloader.addSone(sone);
1075 setSoneStatus(sone, SoneStatus.unknown);
1076 soneDownloaders.execute(new Runnable() {
1079 @SuppressWarnings("synthetic-access")
1081 soneDownloader.fetchSone(sone, sone.getRequestUri());
1090 * Lets the given local Sone follow the Sone with the given ID.
1093 * The local Sone that should follow another Sone
1095 * The ID of the Sone to follow
1097 public void followSone(Sone sone, String soneId) {
1098 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1099 followSone(sone, getSone(soneId));
1103 * Lets the given local Sone follow the other given Sone. If the given Sone
1104 * was not followed by any local Sone before, this will mark all elements of
1105 * the followed Sone as read that have been created before the current
1109 * The local Sone that should follow the other Sone
1110 * @param followedSone
1111 * The Sone that should be followed
1113 public void followSone(Sone sone, Sone followedSone) {
1114 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
1115 sone.addFriend(followedSone.getId());
1116 synchronized (soneFollowingTimes) {
1117 if (!soneFollowingTimes.containsKey(followedSone)) {
1118 long now = System.currentTimeMillis();
1119 soneFollowingTimes.put(followedSone, now);
1120 for (Post post : followedSone.getPosts()) {
1121 if (post.getTime() < now) {
1122 markPostKnown(post);
1125 for (PostReply reply : followedSone.getReplies()) {
1126 if (reply.getTime() < now) {
1127 markReplyKnown(reply);
1132 touchConfiguration();
1136 * Lets the given local Sone unfollow the Sone with the given ID.
1139 * The local Sone that should unfollow another Sone
1141 * The ID of the Sone being unfollowed
1143 public void unfollowSone(Sone sone, String soneId) {
1144 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1145 unfollowSone(sone, getSone(soneId, false));
1149 * Lets the given local Sone unfollow the other given Sone. If the given
1150 * local Sone is the last local Sone that followed the given Sone, its
1151 * following time will be removed.
1154 * The local Sone that should unfollow another Sone
1155 * @param unfollowedSone
1156 * The Sone being unfollowed
1158 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1159 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1160 sone.removeFriend(unfollowedSone.getId());
1161 boolean unfollowedSoneStillFollowed = false;
1162 for (Sone localSone : getLocalSones()) {
1163 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1165 if (!unfollowedSoneStillFollowed) {
1166 synchronized (soneFollowingTimes) {
1167 soneFollowingTimes.remove(unfollowedSone);
1170 touchConfiguration();
1174 * Retrieves the trust relationship from the origin to the target. If the
1175 * trust relationship can not be retrieved, {@code null} is returned.
1177 * @see Identity#getTrust(OwnIdentity)
1179 * The origin of the trust tree
1181 * The target of the trust
1182 * @return The trust relationship
1184 public Trust getTrust(Sone origin, Sone target) {
1185 if (!isLocalSone(origin)) {
1186 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1189 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1193 * Sets the trust value of the given origin Sone for the target Sone.
1200 * The trust value (from {@code -100} to {@code 100})
1202 public void setTrust(Sone origin, Sone target, int trustValue) {
1203 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();
1205 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1206 } catch (WebOfTrustException wote1) {
1207 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1212 * Removes any trust assignment for the given target Sone.
1219 public void removeTrust(Sone origin, Sone target) {
1220 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1222 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1223 } catch (WebOfTrustException wote1) {
1224 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1229 * Assigns the configured positive trust value for the given target.
1236 public void trustSone(Sone origin, Sone target) {
1237 setTrust(origin, target, preferences.getPositiveTrust());
1241 * Assigns the configured negative trust value for the given target.
1248 public void distrustSone(Sone origin, Sone target) {
1249 setTrust(origin, target, preferences.getNegativeTrust());
1253 * Removes the trust assignment for the given target.
1260 public void untrustSone(Sone origin, Sone target) {
1261 removeTrust(origin, target);
1265 * Updates the stored Sone with the given Sone.
1270 public void updateSone(Sone sone) {
1271 updateSone(sone, false);
1275 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1276 * {@code true}, an older Sone than the current Sone can be given to restore
1280 * The Sone to update
1281 * @param soneRescueMode
1282 * {@code true} if the stored Sone should be updated regardless
1283 * of the age of the given Sone
1285 public void updateSone(Sone sone, boolean soneRescueMode) {
1286 if (hasSone(sone.getId())) {
1287 Sone storedSone = getSone(sone.getId());
1288 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1289 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1292 synchronized (posts) {
1293 if (!soneRescueMode) {
1294 for (Post post : storedSone.getPosts()) {
1295 posts.remove(post.getId());
1296 if (!sone.getPosts().contains(post)) {
1297 coreListenerManager.firePostRemoved(post);
1301 List<Post> storedPosts = storedSone.getPosts();
1302 synchronized (newPosts) {
1303 for (Post post : sone.getPosts()) {
1304 post.setSone(storedSone);
1305 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1306 newPosts.add(post.getId());
1307 coreListenerManager.fireNewPostFound(post);
1309 posts.put(post.getId(), post);
1313 synchronized (replies) {
1314 if (!soneRescueMode) {
1315 for (PostReply reply : storedSone.getReplies()) {
1316 replies.remove(reply.getId());
1317 if (!sone.getReplies().contains(reply)) {
1318 coreListenerManager.fireReplyRemoved(reply);
1322 Set<PostReply> storedReplies = storedSone.getReplies();
1323 synchronized (newReplies) {
1324 for (PostReply reply : sone.getReplies()) {
1325 reply.setSone(storedSone);
1326 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1327 newReplies.add(reply.getId());
1328 coreListenerManager.fireNewReplyFound(reply);
1330 replies.put(reply.getId(), reply);
1334 synchronized (albums) {
1335 synchronized (images) {
1336 for (Album album : storedSone.getAlbums()) {
1337 albums.remove(album.getId());
1338 for (Image image : album.getImages()) {
1339 images.remove(image.getId());
1342 for (Album album : sone.getAlbums()) {
1343 albums.put(album.getId(), album);
1344 for (Image image : album.getImages()) {
1345 images.put(image.getId(), image);
1350 synchronized (storedSone) {
1351 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1352 storedSone.setTime(sone.getTime());
1354 storedSone.setClient(sone.getClient());
1355 storedSone.setProfile(sone.getProfile());
1356 if (soneRescueMode) {
1357 for (Post post : sone.getPosts()) {
1358 storedSone.addPost(post);
1360 for (PostReply reply : sone.getReplies()) {
1361 storedSone.addReply(reply);
1363 for (String likedPostId : sone.getLikedPostIds()) {
1364 storedSone.addLikedPostId(likedPostId);
1366 for (String likedReplyId : sone.getLikedReplyIds()) {
1367 storedSone.addLikedReplyId(likedReplyId);
1369 for (Album album : sone.getAlbums()) {
1370 storedSone.addAlbum(album);
1373 storedSone.setPosts(sone.getPosts());
1374 storedSone.setReplies(sone.getReplies());
1375 storedSone.setLikePostIds(sone.getLikedPostIds());
1376 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1377 storedSone.setAlbums(sone.getAlbums());
1379 storedSone.setLatestEdition(sone.getLatestEdition());
1385 * Deletes the given Sone. This will remove the Sone from the
1386 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1387 * and remove the context from its identity.
1390 * The Sone to delete
1392 public void deleteSone(Sone sone) {
1393 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1394 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1397 synchronized (localSones) {
1398 if (!localSones.containsKey(sone.getId())) {
1399 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1402 localSones.remove(sone.getId());
1403 SoneInserter soneInserter = soneInserters.remove(sone);
1404 soneInserter.removeSoneInsertListener(this);
1405 soneInserter.stop();
1408 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1409 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1410 } catch (WebOfTrustException wote1) {
1411 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1414 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1415 } catch (ConfigurationException ce1) {
1416 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1421 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1422 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1425 * The Sone to mark as known
1427 public void markSoneKnown(Sone sone) {
1428 synchronized (newSones) {
1429 if (newSones.remove(sone.getId())) {
1430 knownSones.add(sone.getId());
1431 coreListenerManager.fireMarkSoneKnown(sone);
1432 touchConfiguration();
1438 * Loads and updates the given Sone from the configuration. If any error is
1439 * encountered, loading is aborted and the given Sone is not changed.
1442 * The Sone to load and update
1444 public void loadSone(Sone sone) {
1445 if (!isLocalSone(sone)) {
1446 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1450 /* initialize options. */
1451 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1452 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1453 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1454 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1455 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1458 String sonePrefix = "Sone/" + sone.getId();
1459 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1460 if (soneTime == null) {
1461 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1464 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1467 Profile profile = new Profile();
1468 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1469 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1470 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1471 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1472 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1473 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1475 /* load profile fields. */
1477 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1478 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1479 if (fieldName == null) {
1482 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1483 profile.addField(fieldName).setValue(fieldValue);
1487 Set<Post> posts = new HashSet<Post>();
1489 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1490 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1491 if (postId == null) {
1494 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1495 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1496 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1497 if ((postTime == 0) || (postText == null)) {
1498 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1501 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1502 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1503 post.setRecipient(getSone(postRecipientId));
1509 Set<PostReply> replies = new HashSet<PostReply>();
1511 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1512 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1513 if (replyId == null) {
1516 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1517 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1518 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1519 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1520 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1523 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1526 /* load post likes. */
1527 Set<String> likedPostIds = new HashSet<String>();
1529 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1530 if (likedPostId == null) {
1533 likedPostIds.add(likedPostId);
1536 /* load reply likes. */
1537 Set<String> likedReplyIds = new HashSet<String>();
1539 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1540 if (likedReplyId == null) {
1543 likedReplyIds.add(likedReplyId);
1547 Set<String> friends = new HashSet<String>();
1549 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1550 if (friendId == null) {
1553 friends.add(friendId);
1557 List<Album> topLevelAlbums = new ArrayList<Album>();
1558 int albumCounter = 0;
1560 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1561 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1562 if (albumId == null) {
1565 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1566 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1567 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1568 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1569 if ((albumTitle == null) || (albumDescription == null)) {
1570 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1573 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1574 if (albumParentId != null) {
1575 Album parentAlbum = getAlbum(albumParentId, false);
1576 if (parentAlbum == null) {
1577 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1580 parentAlbum.addAlbum(album);
1582 topLevelAlbums.add(album);
1587 int imageCounter = 0;
1589 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1590 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1591 if (imageId == null) {
1594 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1595 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1596 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1597 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1598 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1599 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1600 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1601 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1602 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1605 Album album = getAlbum(albumId, false);
1606 if (album == null) {
1607 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1610 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1611 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1612 album.addImage(image);
1616 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1617 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1618 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1619 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1620 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1622 /* if we’re still here, Sone was loaded successfully. */
1623 synchronized (sone) {
1624 sone.setTime(soneTime);
1625 sone.setProfile(profile);
1626 sone.setPosts(posts);
1627 sone.setReplies(replies);
1628 sone.setLikePostIds(likedPostIds);
1629 sone.setLikeReplyIds(likedReplyIds);
1630 for (String friendId : friends) {
1631 followSone(sone, friendId);
1633 sone.setAlbums(topLevelAlbums);
1634 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1636 synchronized (newSones) {
1637 for (String friend : friends) {
1638 knownSones.add(friend);
1641 synchronized (newPosts) {
1642 for (Post post : posts) {
1643 knownPosts.add(post.getId());
1646 synchronized (newReplies) {
1647 for (PostReply reply : replies) {
1648 knownReplies.add(reply.getId());
1654 * Creates a new post.
1657 * The Sone that creates the post
1659 * The text of the post
1660 * @return The created post
1662 public Post createPost(Sone sone, String text) {
1663 return createPost(sone, System.currentTimeMillis(), text);
1667 * Creates a new post.
1670 * The Sone that creates the post
1672 * The time of the post
1674 * The text of the post
1675 * @return The created post
1677 public Post createPost(Sone sone, long time, String text) {
1678 return createPost(sone, null, time, text);
1682 * Creates a new post.
1685 * The Sone that creates the post
1687 * The recipient Sone, or {@code null} if this post does not have
1690 * The text of the post
1691 * @return The created post
1693 public Post createPost(Sone sone, Sone recipient, String text) {
1694 return createPost(sone, recipient, System.currentTimeMillis(), text);
1698 * Creates a new post.
1701 * The Sone that creates the post
1703 * The recipient Sone, or {@code null} if this post does not have
1706 * The time of the post
1708 * The text of the post
1709 * @return The created post
1711 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1712 if (!isLocalSone(sone)) {
1713 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1716 final Post post = new Post(sone, time, text);
1717 if (recipient != null) {
1718 post.setRecipient(recipient);
1720 synchronized (posts) {
1721 posts.put(post.getId(), post);
1723 synchronized (newPosts) {
1724 newPosts.add(post.getId());
1725 coreListenerManager.fireNewPostFound(post);
1728 touchConfiguration();
1729 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1736 markPostKnown(post);
1738 }, "Mark " + post + " read.");
1743 * Deletes the given post.
1746 * The post to delete
1748 public void deletePost(Post post) {
1749 if (!isLocalSone(post.getSone())) {
1750 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1753 post.getSone().removePost(post);
1754 synchronized (posts) {
1755 posts.remove(post.getId());
1757 coreListenerManager.firePostRemoved(post);
1758 synchronized (newPosts) {
1759 markPostKnown(post);
1760 knownPosts.remove(post.getId());
1762 touchConfiguration();
1766 * Marks the given post as known, if it is currently a new post (according
1767 * to {@link #isNewPost(String)}).
1770 * The post to mark as known
1772 public void markPostKnown(Post post) {
1773 synchronized (newPosts) {
1774 if (newPosts.remove(post.getId())) {
1775 knownPosts.add(post.getId());
1776 coreListenerManager.fireMarkPostKnown(post);
1777 touchConfiguration();
1783 * Bookmarks the given post.
1786 * The post to bookmark
1788 public void bookmark(Post post) {
1789 bookmarkPost(post.getId());
1793 * Bookmarks the post with the given ID.
1796 * The ID of the post to bookmark
1798 public void bookmarkPost(String id) {
1799 synchronized (bookmarkedPosts) {
1800 bookmarkedPosts.add(id);
1805 * Removes the given post from the bookmarks.
1808 * The post to unbookmark
1810 public void unbookmark(Post post) {
1811 unbookmarkPost(post.getId());
1815 * Removes the post with the given ID from the bookmarks.
1818 * The ID of the post to unbookmark
1820 public void unbookmarkPost(String id) {
1821 synchronized (bookmarkedPosts) {
1822 bookmarkedPosts.remove(id);
1827 * Creates a new reply.
1830 * The Sone that creates the reply
1832 * The post that this reply refers to
1834 * The text of the reply
1835 * @return The created reply
1837 public PostReply createReply(Sone sone, Post post, String text) {
1838 return createReply(sone, post, System.currentTimeMillis(), text);
1842 * Creates a new reply.
1845 * The Sone that creates the reply
1847 * The post that this reply refers to
1849 * The time of the reply
1851 * The text of the reply
1852 * @return The created reply
1854 public PostReply createReply(Sone sone, Post post, long time, String text) {
1855 if (!isLocalSone(sone)) {
1856 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1859 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1860 synchronized (replies) {
1861 replies.put(reply.getId(), reply);
1863 synchronized (newReplies) {
1864 newReplies.add(reply.getId());
1865 coreListenerManager.fireNewReplyFound(reply);
1867 sone.addReply(reply);
1868 touchConfiguration();
1869 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1876 markReplyKnown(reply);
1878 }, "Mark " + reply + " read.");
1883 * Deletes the given reply.
1886 * The reply to delete
1888 public void deleteReply(PostReply reply) {
1889 Sone sone = reply.getSone();
1890 if (!isLocalSone(sone)) {
1891 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1894 synchronized (replies) {
1895 replies.remove(reply.getId());
1897 synchronized (newReplies) {
1898 markReplyKnown(reply);
1899 knownReplies.remove(reply.getId());
1901 sone.removeReply(reply);
1902 touchConfiguration();
1906 * Marks the given reply as known, if it is currently a new reply (according
1907 * to {@link #isNewReply(String)}).
1910 * The reply to mark as known
1912 public void markReplyKnown(PostReply reply) {
1913 synchronized (newReplies) {
1914 if (newReplies.remove(reply.getId())) {
1915 knownReplies.add(reply.getId());
1916 coreListenerManager.fireMarkReplyKnown(reply);
1917 touchConfiguration();
1923 * Creates a new top-level album for the given Sone.
1926 * The Sone to create the album for
1927 * @return The new album
1929 public Album createAlbum(Sone sone) {
1930 return createAlbum(sone, null);
1934 * Creates a new album for the given Sone.
1937 * The Sone to create the album for
1939 * The parent of the album (may be {@code null} to create a
1941 * @return The new album
1943 public Album createAlbum(Sone sone, Album parent) {
1944 Album album = new Album();
1945 synchronized (albums) {
1946 albums.put(album.getId(), album);
1948 album.setSone(sone);
1949 if (parent != null) {
1950 parent.addAlbum(album);
1952 sone.addAlbum(album);
1958 * Deletes the given album. The owner of the album has to be a local Sone,
1959 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1962 * The album to remove
1964 public void deleteAlbum(Album album) {
1965 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1966 if (!album.isEmpty()) {
1969 if (album.getParent() == null) {
1970 album.getSone().removeAlbum(album);
1972 album.getParent().removeAlbum(album);
1974 synchronized (albums) {
1975 albums.remove(album.getId());
1977 saveSone(album.getSone());
1981 * Creates a new image.
1984 * The Sone creating the image
1986 * The album the image will be inserted into
1987 * @param temporaryImage
1988 * The temporary image to create the image from
1989 * @return The newly created image
1991 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1992 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();
1993 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1994 album.addImage(image);
1995 synchronized (images) {
1996 images.put(image.getId(), image);
1998 imageInserter.insertImage(temporaryImage, image);
2003 * Deletes the given image. This method will also delete a matching
2006 * @see #deleteTemporaryImage(TemporaryImage)
2008 * The image to delete
2010 public void deleteImage(Image image) {
2011 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
2012 deleteTemporaryImage(image.getId());
2013 image.getAlbum().removeImage(image);
2014 synchronized (images) {
2015 images.remove(image.getId());
2017 saveSone(image.getSone());
2021 * Creates a new temporary image.
2024 * The MIME type of the temporary image
2026 * The encoded data of the image
2027 * @return The temporary image
2029 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
2030 TemporaryImage temporaryImage = new TemporaryImage();
2031 temporaryImage.setMimeType(mimeType).setImageData(imageData);
2032 synchronized (temporaryImages) {
2033 temporaryImages.put(temporaryImage.getId(), temporaryImage);
2035 return temporaryImage;
2039 * Deletes the given temporary image.
2041 * @param temporaryImage
2042 * The temporary image to delete
2044 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
2045 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
2046 deleteTemporaryImage(temporaryImage.getId());
2050 * Deletes the temporary image with the given ID.
2053 * The ID of the temporary image to delete
2055 public void deleteTemporaryImage(String imageId) {
2056 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
2057 synchronized (temporaryImages) {
2058 temporaryImages.remove(imageId);
2060 Image image = getImage(imageId, false);
2061 if (image != null) {
2062 imageInserter.cancelImageInsert(image);
2067 * Notifies the core that the configuration, either of the core or of a
2068 * single local Sone, has changed, and that the configuration should be
2071 public void touchConfiguration() {
2072 lastConfigurationUpdate = System.currentTimeMillis();
2083 public void serviceStart() {
2084 loadConfiguration();
2085 updateChecker.addUpdateListener(this);
2086 updateChecker.start();
2093 public void serviceRun() {
2094 long lastSaved = System.currentTimeMillis();
2095 while (!shouldStop()) {
2097 long now = System.currentTimeMillis();
2098 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
2099 for (Sone localSone : getLocalSones()) {
2100 saveSone(localSone);
2102 saveConfiguration();
2112 public void serviceStop() {
2113 synchronized (localSones) {
2114 for (SoneInserter soneInserter : soneInserters.values()) {
2115 soneInserter.removeSoneInsertListener(this);
2116 soneInserter.stop();
2119 updateChecker.stop();
2120 updateChecker.removeUpdateListener(this);
2121 soneDownloader.stop();
2129 * Saves the given Sone. This will persist all local settings for the given
2130 * Sone, such as the friends list and similar, private options.
2135 private synchronized void saveSone(Sone sone) {
2136 if (!isLocalSone(sone)) {
2137 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2140 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2141 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2145 logger.log(Level.INFO, "Saving Sone: %s", sone);
2147 /* save Sone into configuration. */
2148 String sonePrefix = "Sone/" + sone.getId();
2149 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2150 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2153 Profile profile = sone.getProfile();
2154 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2155 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2156 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2157 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2158 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2159 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2161 /* save profile fields. */
2162 int fieldCounter = 0;
2163 for (Field profileField : profile.getFields()) {
2164 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2165 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2166 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2168 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2171 int postCounter = 0;
2172 for (Post post : sone.getPosts()) {
2173 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2174 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2175 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2176 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2177 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2179 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2182 int replyCounter = 0;
2183 for (PostReply reply : sone.getReplies()) {
2184 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2185 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2186 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2187 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2188 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2190 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2192 /* save post likes. */
2193 int postLikeCounter = 0;
2194 for (String postId : sone.getLikedPostIds()) {
2195 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2197 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2199 /* save reply likes. */
2200 int replyLikeCounter = 0;
2201 for (String replyId : sone.getLikedReplyIds()) {
2202 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2204 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2207 int friendCounter = 0;
2208 for (String friendId : sone.getFriends()) {
2209 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2211 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2213 /* save albums. first, collect in a flat structure, top-level first. */
2214 List<Album> albums = sone.getAllAlbums();
2216 int albumCounter = 0;
2217 for (Album album : albums) {
2218 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2219 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2220 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2221 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2222 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2223 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2225 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2228 int imageCounter = 0;
2229 for (Album album : albums) {
2230 for (Image image : album.getImages()) {
2231 if (!image.isInserted()) {
2234 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2235 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2236 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2237 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2238 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2239 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2240 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2241 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2242 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2245 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2248 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2249 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2250 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2251 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2252 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2254 configuration.save();
2256 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2258 logger.log(Level.INFO, "Sone %s saved.", sone);
2259 } catch (ConfigurationException ce1) {
2260 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2261 } catch (WebOfTrustException wote1) {
2262 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2267 * Saves the current options.
2269 private void saveConfiguration() {
2270 synchronized (configuration) {
2271 if (storingConfiguration) {
2272 logger.log(Level.FINE, "Already storing configuration…");
2275 storingConfiguration = true;
2278 /* store the options first. */
2280 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2281 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2282 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2283 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2284 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2285 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2286 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2287 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2288 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2289 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2290 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2291 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2292 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2293 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2295 /* save known Sones. */
2296 int soneCounter = 0;
2297 synchronized (newSones) {
2298 for (String knownSoneId : knownSones) {
2299 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2301 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2304 /* save Sone following times. */
2306 synchronized (soneFollowingTimes) {
2307 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2308 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2309 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2312 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2315 /* save known posts. */
2316 int postCounter = 0;
2317 synchronized (newPosts) {
2318 for (String knownPostId : knownPosts) {
2319 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2321 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2324 /* save known replies. */
2325 int replyCounter = 0;
2326 synchronized (newReplies) {
2327 for (String knownReplyId : knownReplies) {
2328 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2330 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2333 /* save bookmarked posts. */
2334 int bookmarkedPostCounter = 0;
2335 synchronized (bookmarkedPosts) {
2336 for (String bookmarkedPostId : bookmarkedPosts) {
2337 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2340 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2343 configuration.save();
2345 } catch (ConfigurationException ce1) {
2346 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2348 synchronized (configuration) {
2349 storingConfiguration = false;
2355 * Loads the configuration.
2357 @SuppressWarnings("unchecked")
2358 private void loadConfiguration() {
2359 /* create options. */
2360 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2363 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2364 SoneInserter.setInsertionDelay(newValue);
2368 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2369 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2370 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2371 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2372 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2373 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2374 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2375 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2378 @SuppressWarnings("synthetic-access")
2379 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2380 fcpInterface.setActive(newValue);
2383 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2386 @SuppressWarnings("synthetic-access")
2387 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2388 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2392 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2393 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2394 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2396 /* read options from configuration. */
2397 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2398 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2399 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2400 options.getBooleanOption("ClearOnNextRestart").set(null);
2401 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2402 if (clearConfiguration) {
2403 /* stop loading the configuration. */
2407 loadConfigurationValue("InsertionDelay");
2408 loadConfigurationValue("PostsPerPage");
2409 loadConfigurationValue("CharactersPerPost");
2410 loadConfigurationValue("PostCutOffLength");
2411 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2412 loadConfigurationValue("PositiveTrust");
2413 loadConfigurationValue("NegativeTrust");
2414 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2415 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2416 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2417 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2419 /* load known Sones. */
2420 int soneCounter = 0;
2422 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2423 if (knownSoneId == null) {
2426 synchronized (newSones) {
2427 knownSones.add(knownSoneId);
2431 /* load Sone following times. */
2434 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2435 if (soneId == null) {
2438 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2439 synchronized (soneFollowingTimes) {
2440 soneFollowingTimes.put(getSone(soneId), time);
2445 /* load known posts. */
2446 int postCounter = 0;
2448 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2449 if (knownPostId == null) {
2452 synchronized (newPosts) {
2453 knownPosts.add(knownPostId);
2457 /* load known replies. */
2458 int replyCounter = 0;
2460 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2461 if (knownReplyId == null) {
2464 synchronized (newReplies) {
2465 knownReplies.add(knownReplyId);
2469 /* load bookmarked posts. */
2470 int bookmarkedPostCounter = 0;
2472 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2473 if (bookmarkedPostId == null) {
2476 synchronized (bookmarkedPosts) {
2477 bookmarkedPosts.add(bookmarkedPostId);
2484 * Loads an {@link Integer} configuration value for the option with the
2485 * given name, logging validation failures.
2488 * The name of the option to load
2490 private void loadConfigurationValue(String optionName) {
2492 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2493 } catch (IllegalArgumentException iae1) {
2494 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2499 * Generate a Sone URI from the given URI and latest edition.
2502 * The URI to derive the Sone URI from
2503 * @return The derived URI
2505 private FreenetURI getSoneUri(String uriString) {
2507 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2509 } catch (MalformedURLException mue1) {
2510 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2516 // INTERFACE IdentityListener
2523 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2524 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2525 if (ownIdentity.hasContext("Sone")) {
2526 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2527 addLocalSone(ownIdentity);
2535 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2536 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2537 trustedIdentities.remove(ownIdentity);
2544 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2545 logger.log(Level.FINEST, "Adding Identity: " + identity);
2546 trustedIdentities.get(ownIdentity).add(identity);
2547 addRemoteSone(identity);
2554 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2555 new Thread(new Runnable() {
2558 @SuppressWarnings("synthetic-access")
2560 Sone sone = getRemoteSone(identity.getId());
2561 sone.setIdentity(identity);
2562 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2563 soneDownloader.addSone(sone);
2564 soneDownloader.fetchSone(sone);
2573 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2574 trustedIdentities.get(ownIdentity).remove(identity);
2575 boolean foundIdentity = false;
2576 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2577 if (trustedIdentity.getKey().equals(ownIdentity)) {
2580 if (trustedIdentity.getValue().contains(identity)) {
2581 foundIdentity = true;
2584 if (foundIdentity) {
2585 /* some local identity still trusts this identity, don’t remove. */
2588 Sone sone = getSone(identity.getId(), false);
2590 /* TODO - we don’t have the Sone anymore. should this happen? */
2593 synchronized (posts) {
2594 synchronized (newPosts) {
2595 for (Post post : sone.getPosts()) {
2596 posts.remove(post.getId());
2597 newPosts.remove(post.getId());
2598 coreListenerManager.firePostRemoved(post);
2602 synchronized (replies) {
2603 synchronized (newReplies) {
2604 for (PostReply reply : sone.getReplies()) {
2605 replies.remove(reply.getId());
2606 newReplies.remove(reply.getId());
2607 coreListenerManager.fireReplyRemoved(reply);
2611 synchronized (remoteSones) {
2612 remoteSones.remove(identity.getId());
2614 synchronized (newSones) {
2615 newSones.remove(identity.getId());
2616 coreListenerManager.fireSoneRemoved(sone);
2621 // INTERFACE UpdateListener
2628 public void updateFound(Version version, long releaseTime, long latestEdition) {
2629 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2633 // INTERFACE ImageInsertListener
2640 public void insertStarted(Sone sone) {
2641 coreListenerManager.fireSoneInserting(sone);
2648 public void insertFinished(Sone sone, long insertDuration) {
2649 coreListenerManager.fireSoneInserted(sone, insertDuration);
2656 public void insertAborted(Sone sone, Throwable cause) {
2657 coreListenerManager.fireSoneInsertAborted(sone, cause);
2661 // SONEINSERTLISTENER METHODS
2668 public void imageInsertStarted(Image image) {
2669 logger.log(Level.WARNING, "Image insert started for " + image);
2670 coreListenerManager.fireImageInsertStarted(image);
2677 public void imageInsertAborted(Image image) {
2678 logger.log(Level.WARNING, "Image insert aborted for " + image);
2679 coreListenerManager.fireImageInsertAborted(image);
2686 public void imageInsertFinished(Image image, FreenetURI key) {
2687 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2688 image.setKey(key.toString());
2689 deleteTemporaryImage(image.getId());
2690 saveSone(image.getSone());
2691 coreListenerManager.fireImageInsertFinished(image);
2698 public void imageInsertFailed(Image image, Throwable cause) {
2699 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2700 coreListenerManager.fireImageInsertFailed(image, cause);
2704 * Convenience interface for external classes that want to access the core’s
2707 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2709 public static class Preferences {
2711 /** The wrapped options. */
2712 private final Options options;
2715 * Creates a new preferences object wrapped around the given options.
2718 * The options to wrap
2720 public Preferences(Options options) {
2721 this.options = options;
2725 * Returns the insertion delay.
2727 * @return The insertion delay
2729 public int getInsertionDelay() {
2730 return options.getIntegerOption("InsertionDelay").get();
2734 * Validates the given insertion delay.
2736 * @param insertionDelay
2737 * The insertion delay to validate
2738 * @return {@code true} if the given insertion delay was valid, {@code
2741 public boolean validateInsertionDelay(Integer insertionDelay) {
2742 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2746 * Sets the insertion delay
2748 * @param insertionDelay
2749 * The new insertion delay, or {@code null} to restore it to
2751 * @return This preferences
2753 public Preferences setInsertionDelay(Integer insertionDelay) {
2754 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2759 * Returns the number of posts to show per page.
2761 * @return The number of posts to show per page
2763 public int getPostsPerPage() {
2764 return options.getIntegerOption("PostsPerPage").get();
2768 * Validates the number of posts per page.
2770 * @param postsPerPage
2771 * The number of posts per page
2772 * @return {@code true} if the number of posts per page was valid,
2773 * {@code false} otherwise
2775 public boolean validatePostsPerPage(Integer postsPerPage) {
2776 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2780 * Sets the number of posts to show per page.
2782 * @param postsPerPage
2783 * The number of posts to show per page
2784 * @return This preferences object
2786 public Preferences setPostsPerPage(Integer postsPerPage) {
2787 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2792 * Returns the number of characters per post, or <code>-1</code> if the
2793 * posts should not be cut off.
2795 * @return The numbers of characters per post
2797 public int getCharactersPerPost() {
2798 return options.getIntegerOption("CharactersPerPost").get();
2802 * Validates the number of characters per post.
2804 * @param charactersPerPost
2805 * The number of characters per post
2806 * @return {@code true} if the number of characters per post was valid,
2807 * {@code false} otherwise
2809 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2810 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2814 * Sets the number of characters per post.
2816 * @param charactersPerPost
2817 * The number of characters per post, or <code>-1</code> to
2818 * not cut off the posts
2819 * @return This preferences objects
2821 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2822 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2827 * Returns the number of characters the shortened post should have.
2829 * @return The number of characters of the snippet
2831 public int getPostCutOffLength() {
2832 return options.getIntegerOption("PostCutOffLength").get();
2836 * Validates the number of characters after which to cut off the post.
2838 * @param postCutOffLength
2839 * The number of characters of the snippet
2840 * @return {@code true} if the number of characters of the snippet is
2841 * valid, {@code false} otherwise
2843 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2844 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2848 * Sets the number of characters the shortened post should have.
2850 * @param postCutOffLength
2851 * The number of characters of the snippet
2852 * @return This preferences
2854 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2855 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2860 * Returns whether Sone requires full access to be even visible.
2862 * @return {@code true} if Sone requires full access, {@code false}
2865 public boolean isRequireFullAccess() {
2866 return options.getBooleanOption("RequireFullAccess").get();
2870 * Sets whether Sone requires full access to be even visible.
2872 * @param requireFullAccess
2873 * {@code true} if Sone requires full access, {@code false}
2876 public void setRequireFullAccess(Boolean requireFullAccess) {
2877 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2881 * Returns the positive trust.
2883 * @return The positive trust
2885 public int getPositiveTrust() {
2886 return options.getIntegerOption("PositiveTrust").get();
2890 * Validates the positive trust.
2892 * @param positiveTrust
2893 * The positive trust to validate
2894 * @return {@code true} if the positive trust was valid, {@code false}
2897 public boolean validatePositiveTrust(Integer positiveTrust) {
2898 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2902 * Sets the positive trust.
2904 * @param positiveTrust
2905 * The new positive trust, or {@code null} to restore it to
2907 * @return This preferences
2909 public Preferences setPositiveTrust(Integer positiveTrust) {
2910 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2915 * Returns the negative trust.
2917 * @return The negative trust
2919 public int getNegativeTrust() {
2920 return options.getIntegerOption("NegativeTrust").get();
2924 * Validates the negative trust.
2926 * @param negativeTrust
2927 * The negative trust to validate
2928 * @return {@code true} if the negative trust was valid, {@code false}
2931 public boolean validateNegativeTrust(Integer negativeTrust) {
2932 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2936 * Sets the negative trust.
2938 * @param negativeTrust
2939 * The negative trust, or {@code null} to restore it to the
2941 * @return The preferences
2943 public Preferences setNegativeTrust(Integer negativeTrust) {
2944 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2949 * Returns the trust comment. This is the comment that is set in the web
2950 * of trust when a trust value is assigned to an identity.
2952 * @return The trust comment
2954 public String getTrustComment() {
2955 return options.getStringOption("TrustComment").get();
2959 * Sets the trust comment.
2961 * @param trustComment
2962 * The trust comment, or {@code null} to restore it to the
2964 * @return This preferences
2966 public Preferences setTrustComment(String trustComment) {
2967 options.getStringOption("TrustComment").set(trustComment);
2972 * Returns whether the {@link FcpInterface FCP interface} is currently
2975 * @see FcpInterface#setActive(boolean)
2976 * @return {@code true} if the FCP interface is currently active,
2977 * {@code false} otherwise
2979 public boolean isFcpInterfaceActive() {
2980 return options.getBooleanOption("ActivateFcpInterface").get();
2984 * Sets whether the {@link FcpInterface FCP interface} is currently
2987 * @see FcpInterface#setActive(boolean)
2988 * @param fcpInterfaceActive
2989 * {@code true} to activate the FCP interface, {@code false}
2990 * to deactivate the FCP interface
2991 * @return This preferences object
2993 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2994 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2999 * Returns the action level for which full access to the FCP interface
3002 * @return The action level for which full access to the FCP interface
3005 public FullAccessRequired getFcpFullAccessRequired() {
3006 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
3010 * Sets the action level for which full access to the FCP interface is
3013 * @param fcpFullAccessRequired
3015 * @return This preferences
3017 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
3018 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
3023 * Returns whether Sone should clear its settings on the next restart.
3024 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
3025 * to return {@code true} as well!
3027 * @return {@code true} if Sone should clear its settings on the next
3028 * restart, {@code false} otherwise
3030 public boolean isClearOnNextRestart() {
3031 return options.getBooleanOption("ClearOnNextRestart").get();
3035 * Sets whether Sone will clear its settings on the next restart.
3037 * @param clearOnNextRestart
3038 * {@code true} if Sone should clear its settings on the next
3039 * restart, {@code false} otherwise
3040 * @return This preferences
3042 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
3043 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
3048 * Returns whether Sone should really clear its settings on next
3049 * restart. This is a confirmation option that needs to be set in
3050 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
3051 * settings on the next restart.
3053 * @return {@code true} if Sone should really clear its settings on the
3054 * next restart, {@code false} otherwise
3056 public boolean isReallyClearOnNextRestart() {
3057 return options.getBooleanOption("ReallyClearOnNextRestart").get();
3061 * Sets whether Sone should really clear its settings on the next
3064 * @param reallyClearOnNextRestart
3065 * {@code true} if Sone should really clear its settings on
3066 * the next restart, {@code false} otherwise
3067 * @return This preferences
3069 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
3070 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);