2 * Sone - Core.java - Copyright © 2010–2012 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.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
40 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
41 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
42 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
43 import net.pterodactylus.sone.data.Album;
44 import net.pterodactylus.sone.data.Client;
45 import net.pterodactylus.sone.data.Image;
46 import net.pterodactylus.sone.data.Post;
47 import net.pterodactylus.sone.data.PostReply;
48 import net.pterodactylus.sone.data.Profile;
49 import net.pterodactylus.sone.data.Profile.Field;
50 import net.pterodactylus.sone.data.Reply;
51 import net.pterodactylus.sone.data.Sone;
52 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
53 import net.pterodactylus.sone.data.Sone.SoneStatus;
54 import net.pterodactylus.sone.data.TemporaryImage;
55 import net.pterodactylus.sone.data.impl.PostImpl;
56 import net.pterodactylus.sone.fcp.FcpInterface;
57 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
58 import net.pterodactylus.sone.freenet.wot.Identity;
59 import net.pterodactylus.sone.freenet.wot.IdentityListener;
60 import net.pterodactylus.sone.freenet.wot.IdentityManager;
61 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
62 import net.pterodactylus.sone.main.SonePlugin;
63 import net.pterodactylus.util.config.Configuration;
64 import net.pterodactylus.util.config.ConfigurationException;
65 import net.pterodactylus.util.logging.Logging;
66 import net.pterodactylus.util.number.Numbers;
67 import net.pterodactylus.util.service.AbstractService;
68 import net.pterodactylus.util.thread.NamedThreadFactory;
69 import net.pterodactylus.util.thread.Ticker;
70 import net.pterodactylus.util.validation.EqualityValidator;
71 import net.pterodactylus.util.validation.IntegerRangeValidator;
72 import net.pterodactylus.util.validation.OrValidator;
73 import net.pterodactylus.util.validation.Validation;
74 import net.pterodactylus.util.version.Version;
76 import com.google.common.base.Predicate;
77 import com.google.common.collect.Collections2;
78 import com.google.common.eventbus.EventBus;
79 import com.google.inject.Inject;
81 import freenet.keys.FreenetURI;
86 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
88 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
91 private static final Logger logger = Logging.getLogger(Core.class);
93 /** The start time. */
94 private final long startupTime = System.currentTimeMillis();
97 private final Options options = new Options();
99 /** The preferences. */
100 private final Preferences preferences = new Preferences(options);
102 /** The core listener manager. */
103 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
105 /** The event bus. */
106 private final EventBus eventBus;
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, new NamedThreadFactory("Sone Downloader %2$d"));
129 /** The update checker. */
130 private final UpdateChecker updateChecker;
132 /** The trust updater. */
133 private final WebOfTrustUpdater webOfTrustUpdater;
135 /** The FCP interface. */
136 private volatile FcpInterface fcpInterface;
138 /** The times Sones were followed. */
139 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
141 /** Locked local Sones. */
142 /* synchronize on itself. */
143 private final Set<Sone> lockedSones = new HashSet<Sone>();
145 /** Sone inserters. */
146 /* synchronize access on this on sones. */
147 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
149 /** Sone rescuers. */
150 /* synchronize access on this on sones. */
151 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
154 /* synchronize access on this on itself. */
155 private final Map<String, Sone> sones = new HashMap<String, Sone>();
157 /** All known Sones. */
158 private final Set<String> knownSones = new HashSet<String>();
161 private final Map<String, Post> posts = new HashMap<String, Post>();
163 /** All known posts. */
164 private final Set<String> knownPosts = new HashSet<String>();
167 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
169 /** All known replies. */
170 private final Set<String> knownReplies = new HashSet<String>();
172 /** All bookmarked posts. */
173 /* synchronize access on itself. */
174 private final Set<String> bookmarkedPosts = new HashSet<String>();
176 /** Trusted identities, sorted by own identities. */
177 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
179 /** All known albums. */
180 private final Map<String, Album> albums = new HashMap<String, Album>();
182 /** All known images. */
183 private final Map<String, Image> images = new HashMap<String, Image>();
185 /** All temporary images. */
186 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
188 /** Ticker for threads that mark own elements as known. */
189 private final Ticker localElementTicker = new Ticker();
191 /** The time the configuration was last touched. */
192 private volatile long lastConfigurationUpdate;
195 * Creates a new core.
197 * @param configuration
198 * The configuration of the core
199 * @param freenetInterface
200 * The freenet interface
201 * @param identityManager
202 * The identity manager
203 * @param webOfTrustUpdater
204 * The WebOfTrust updater
209 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
211 this.configuration = configuration;
212 this.freenetInterface = freenetInterface;
213 this.identityManager = identityManager;
214 this.soneDownloader = new SoneDownloader(this, freenetInterface);
215 this.imageInserter = new ImageInserter(this, freenetInterface);
216 this.updateChecker = new UpdateChecker(freenetInterface);
217 this.webOfTrustUpdater = webOfTrustUpdater;
218 this.eventBus = eventBus;
222 // LISTENER MANAGEMENT
226 * Adds a new core listener.
228 * @param coreListener
229 * The listener to add
231 public void addCoreListener(CoreListener coreListener) {
232 coreListenerManager.addListener(coreListener);
236 * Removes a core listener.
238 * @param coreListener
239 * The listener to remove
241 public void removeCoreListener(CoreListener coreListener) {
242 coreListenerManager.removeListener(coreListener);
250 * Returns the time Sone was started.
252 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
254 public long getStartupTime() {
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 Sone rescuer for the given local Sone.
311 * The local Sone to get the rescuer for
312 * @return The Sone rescuer for the given Sone
314 public SoneRescuer getSoneRescuer(Sone sone) {
315 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
316 synchronized (sones) {
317 SoneRescuer soneRescuer = soneRescuers.get(sone);
318 if (soneRescuer == null) {
319 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
320 soneRescuers.put(sone, soneRescuer);
328 * Returns whether the given Sone is currently locked.
332 * @return {@code true} if the Sone is locked, {@code false} if it is not
334 public boolean isLocked(Sone sone) {
335 synchronized (lockedSones) {
336 return lockedSones.contains(sone);
341 * Returns all Sones, remote and local.
345 public Set<Sone> getSones() {
346 return new HashSet<Sone>(sones.values());
350 * Returns the Sone with the given ID, regardless whether it’s local or
354 * The ID of the Sone to get
355 * @return The Sone with the given ID, or {@code null} if there is no such
358 public Sone getSone(String id) {
359 return getSone(id, true);
363 * Returns the Sone with the given ID, regardless whether it’s local or
367 * The ID of the Sone to get
369 * {@code true} to create a new Sone if none exists,
370 * {@code false} to return {@code null} if a Sone with the given
372 * @return The Sone with the given ID, or {@code null} if there is no such
376 public Sone getSone(String id, boolean create) {
377 synchronized (sones) {
378 if (!sones.containsKey(id)) {
379 Sone sone = new Sone(id, false);
382 return sones.get(id);
387 * Checks whether the core knows a Sone with the given ID.
391 * @return {@code true} if there is a Sone with the given ID, {@code false}
394 public boolean hasSone(String id) {
395 synchronized (sones) {
396 return sones.containsKey(id);
401 * Returns all local Sones.
403 * @return All local Sones
405 public Collection<Sone> getLocalSones() {
406 synchronized (sones) {
407 return Collections2.filter(sones.values(), new Predicate<Sone>() {
410 public boolean apply(Sone sone) {
411 return sone.isLocal();
418 * Returns the local Sone with the given ID, optionally creating a new Sone.
423 * {@code true} to create a new Sone if none exists,
424 * {@code false} to return null if none exists
425 * @return The Sone with the given ID, or {@code null}
427 public Sone getLocalSone(String id, boolean create) {
428 synchronized (sones) {
429 Sone sone = sones.get(id);
430 if ((sone == null) && create) {
431 sone = new Sone(id, true);
434 if ((sone != null) && !sone.isLocal()) {
435 sone = new Sone(id, true);
443 * Returns all remote Sones.
445 * @return All remote Sones
447 public Collection<Sone> getRemoteSones() {
448 synchronized (sones) {
449 return Collections2.filter(sones.values(), new Predicate<Sone>() {
452 public boolean apply(Sone sone) {
453 return !sone.isLocal();
460 * Returns the remote Sone with the given ID.
463 * The ID of the remote Sone to get
465 * {@code true} to always create a Sone, {@code false} to return
466 * {@code null} if no Sone with the given ID exists
467 * @return The Sone with the given ID
469 public Sone getRemoteSone(String id, boolean create) {
470 synchronized (sones) {
471 Sone sone = sones.get(id);
472 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
473 sone = new Sone(id, false);
481 * Returns whether the given Sone has been modified.
484 * The Sone to check for modifications
485 * @return {@code true} if a modification has been detected in the Sone,
486 * {@code false} otherwise
488 public boolean isModifiedSone(Sone sone) {
489 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
493 * Returns the time when the given was first followed by any local Sone.
496 * The Sone to get the time for
497 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
498 * been followed, or {@link Long#MAX_VALUE}
500 public long getSoneFollowingTime(Sone sone) {
501 synchronized (soneFollowingTimes) {
502 if (soneFollowingTimes.containsKey(sone)) {
503 return soneFollowingTimes.get(sone);
505 return Long.MAX_VALUE;
510 * Returns whether the target Sone is trusted by the origin Sone.
516 * @return {@code true} if the target Sone is trusted by the origin Sone
518 public boolean isSoneTrusted(Sone origin, Sone target) {
519 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
520 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
524 * Returns the post with the given ID.
527 * The ID of the post to get
528 * @return The post with the given ID, or a new post with the given ID
530 public Post getPost(String postId) {
531 return getPost(postId, true);
535 * Returns the post with the given ID, optionally creating a new post.
538 * The ID of the post to get
540 * {@code true} it create a new post if no post with the given ID
541 * exists, {@code false} to return {@code null}
542 * @return The post, or {@code null} if there is no such post
545 public Post getPost(String postId, boolean create) {
546 synchronized (posts) {
547 Post post = posts.get(postId);
548 if ((post == null) && create) {
549 post = new PostImpl(postId);
550 posts.put(postId, post);
557 * Returns all posts that have the given Sone as recipient.
559 * @see Post#getRecipient()
561 * The recipient of the posts
562 * @return All posts that have the given Sone as recipient
564 public Set<Post> getDirectedPosts(Sone recipient) {
565 Validation.begin().isNotNull("Recipient", recipient).check();
566 Set<Post> directedPosts = new HashSet<Post>();
567 synchronized (posts) {
568 for (Post post : posts.values()) {
569 if (recipient.equals(post.getRecipient())) {
570 directedPosts.add(post);
574 return directedPosts;
578 * Returns the reply with the given ID. If there is no reply with the given
579 * ID yet, a new one is created, unless {@code create} is false in which
580 * case {@code null} is returned.
583 * The ID of the reply to get
585 * {@code true} to always return a {@link Reply}, {@code false}
586 * to return {@code null} if no reply can be found
587 * @return The reply, or {@code null} if there is no such reply
589 public PostReply getPostReply(String replyId, boolean create) {
590 synchronized (replies) {
591 PostReply reply = replies.get(replyId);
592 if (create && (reply == null)) {
593 reply = new PostReply(replyId);
594 replies.put(replyId, reply);
601 * Returns all replies for the given post, order ascending by time.
604 * The post to get all replies for
605 * @return All replies for the given post
607 public List<PostReply> getReplies(Post post) {
608 Set<Sone> sones = getSones();
609 List<PostReply> replies = new ArrayList<PostReply>();
610 for (Sone sone : sones) {
611 for (PostReply reply : sone.getReplies()) {
612 if (reply.getPost().equals(post)) {
617 Collections.sort(replies, Reply.TIME_COMPARATOR);
622 * Returns all Sones that have liked the given post.
625 * The post to get the liking Sones for
626 * @return The Sones that like the given post
628 public Set<Sone> getLikes(Post post) {
629 Set<Sone> sones = new HashSet<Sone>();
630 for (Sone sone : getSones()) {
631 if (sone.getLikedPostIds().contains(post.getId())) {
639 * Returns all Sones that have liked the given reply.
642 * The reply to get the liking Sones for
643 * @return The Sones that like the given reply
645 public Set<Sone> getLikes(PostReply reply) {
646 Set<Sone> sones = new HashSet<Sone>();
647 for (Sone sone : getSones()) {
648 if (sone.getLikedReplyIds().contains(reply.getId())) {
656 * Returns whether the given post is bookmarked.
660 * @return {@code true} if the given post is bookmarked, {@code false}
663 public boolean isBookmarked(Post post) {
664 return isPostBookmarked(post.getId());
668 * Returns whether the post with the given ID is bookmarked.
671 * The ID of the post to check
672 * @return {@code true} if the post with the given ID is bookmarked,
673 * {@code false} otherwise
675 public boolean isPostBookmarked(String id) {
676 synchronized (bookmarkedPosts) {
677 return bookmarkedPosts.contains(id);
682 * Returns all currently known bookmarked posts.
684 * @return All bookmarked posts
686 public Set<Post> getBookmarkedPosts() {
687 Set<Post> posts = new HashSet<Post>();
688 synchronized (bookmarkedPosts) {
689 for (String bookmarkedPostId : bookmarkedPosts) {
690 Post post = getPost(bookmarkedPostId, false);
700 * Returns the album with the given ID, creating a new album if no album
701 * with the given ID can be found.
704 * The ID of the album
705 * @return The album with the given ID
707 public Album getAlbum(String albumId) {
708 return getAlbum(albumId, true);
712 * Returns the album with the given ID, optionally creating a new album if
713 * an album with the given ID can not be found.
716 * The ID of the album
718 * {@code true} to create a new album if none exists for the
720 * @return The album with the given ID, or {@code null} if no album with the
721 * given ID exists and {@code create} is {@code false}
723 public Album getAlbum(String albumId, boolean create) {
724 synchronized (albums) {
725 Album album = albums.get(albumId);
726 if (create && (album == null)) {
727 album = new Album(albumId);
728 albums.put(albumId, album);
735 * Returns the image with the given ID, creating it if necessary.
738 * The ID of the image
739 * @return The image with the given ID
741 public Image getImage(String imageId) {
742 return getImage(imageId, true);
746 * Returns the image with the given ID, optionally creating it if it does
750 * The ID of the image
752 * {@code true} to create an image if none exists with the given
754 * @return The image with the given ID, or {@code null} if none exists and
757 public Image getImage(String imageId, boolean create) {
758 synchronized (images) {
759 Image image = images.get(imageId);
760 if (create && (image == null)) {
761 image = new Image(imageId);
762 images.put(imageId, image);
769 * Returns the temporary image with the given ID.
772 * The ID of the temporary image
773 * @return The temporary image, or {@code null} if there is no temporary
774 * image with the given ID
776 public TemporaryImage getTemporaryImage(String imageId) {
777 synchronized (temporaryImages) {
778 return temporaryImages.get(imageId);
787 * Locks the given Sone. A locked Sone will not be inserted by
788 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
794 public void lockSone(Sone sone) {
795 synchronized (lockedSones) {
796 if (lockedSones.add(sone)) {
797 coreListenerManager.fireSoneLocked(sone);
803 * Unlocks the given Sone.
805 * @see #lockSone(Sone)
809 public void unlockSone(Sone sone) {
810 synchronized (lockedSones) {
811 if (lockedSones.remove(sone)) {
812 coreListenerManager.fireSoneUnlocked(sone);
818 * Adds a local Sone from the given own identity.
821 * The own identity to create a Sone from
822 * @return The added (or already existing) Sone
824 public Sone addLocalSone(OwnIdentity ownIdentity) {
825 if (ownIdentity == null) {
826 logger.log(Level.WARNING, "Given OwnIdentity is null!");
829 synchronized (sones) {
832 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
833 } catch (MalformedURLException mue1) {
834 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
837 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
838 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
840 /* TODO - load posts ’n stuff */
841 sones.put(ownIdentity.getId(), sone);
842 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
843 soneInserter.addSoneInsertListener(this);
844 soneInserters.put(sone, soneInserter);
845 sone.setStatus(SoneStatus.idle);
847 soneInserter.start();
853 * Creates a new Sone for the given own identity.
856 * The own identity to create a Sone for
857 * @return The created Sone
859 public Sone createSone(OwnIdentity ownIdentity) {
860 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
861 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
864 Sone sone = addLocalSone(ownIdentity);
865 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
866 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
867 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
868 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
869 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
870 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
872 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
873 touchConfiguration();
878 * Adds the Sone of the given identity.
881 * The identity whose Sone to add
882 * @return The added or already existing Sone
884 public Sone addRemoteSone(Identity identity) {
885 if (identity == null) {
886 logger.log(Level.WARNING, "Given Identity is null!");
889 synchronized (sones) {
890 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
891 boolean newSone = sone.getRequestUri() == null;
892 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
893 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
895 synchronized (knownSones) {
896 newSone = !knownSones.contains(sone.getId());
898 sone.setKnown(!newSone);
900 eventBus.post(new NewSoneFoundEvent(sone));
901 for (Sone localSone : getLocalSones()) {
902 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
903 followSone(localSone, sone);
908 soneDownloader.addSone(sone);
909 soneDownloaders.execute(new Runnable() {
912 @SuppressWarnings("synthetic-access")
914 soneDownloader.fetchSone(sone, sone.getRequestUri());
923 * Lets the given local Sone follow the Sone with the given ID.
926 * The local Sone that should follow another Sone
928 * The ID of the Sone to follow
930 public void followSone(Sone sone, String soneId) {
931 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
932 Sone followedSone = getSone(soneId, true);
933 if (followedSone == null) {
934 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
937 followSone(sone, getSone(soneId));
941 * Lets the given local Sone follow the other given Sone. If the given Sone
942 * was not followed by any local Sone before, this will mark all elements of
943 * the followed Sone as read that have been created before the current
947 * The local Sone that should follow the other Sone
948 * @param followedSone
949 * The Sone that should be followed
951 public void followSone(Sone sone, Sone followedSone) {
952 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
953 sone.addFriend(followedSone.getId());
954 synchronized (soneFollowingTimes) {
955 if (!soneFollowingTimes.containsKey(followedSone)) {
956 long now = System.currentTimeMillis();
957 soneFollowingTimes.put(followedSone, now);
958 for (Post post : followedSone.getPosts()) {
959 if (post.getTime() < now) {
963 for (PostReply reply : followedSone.getReplies()) {
964 if (reply.getTime() < now) {
965 markReplyKnown(reply);
970 touchConfiguration();
974 * Lets the given local Sone unfollow the Sone with the given ID.
977 * The local Sone that should unfollow another Sone
979 * The ID of the Sone being unfollowed
981 public void unfollowSone(Sone sone, String soneId) {
982 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
983 unfollowSone(sone, getSone(soneId, false));
987 * Lets the given local Sone unfollow the other given Sone. If the given
988 * local Sone is the last local Sone that followed the given Sone, its
989 * following time will be removed.
992 * The local Sone that should unfollow another Sone
993 * @param unfollowedSone
994 * The Sone being unfollowed
996 public void unfollowSone(Sone sone, Sone unfollowedSone) {
997 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
998 sone.removeFriend(unfollowedSone.getId());
999 boolean unfollowedSoneStillFollowed = false;
1000 for (Sone localSone : getLocalSones()) {
1001 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1003 if (!unfollowedSoneStillFollowed) {
1004 synchronized (soneFollowingTimes) {
1005 soneFollowingTimes.remove(unfollowedSone);
1008 touchConfiguration();
1012 * Sets the trust value of the given origin Sone for the target Sone.
1019 * The trust value (from {@code -100} to {@code 100})
1021 public void setTrust(Sone origin, Sone target, int trustValue) {
1022 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();
1023 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1027 * Removes any trust assignment for the given target Sone.
1034 public void removeTrust(Sone origin, Sone target) {
1035 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1036 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1040 * Assigns the configured positive trust value for the given target.
1047 public void trustSone(Sone origin, Sone target) {
1048 setTrust(origin, target, preferences.getPositiveTrust());
1052 * Assigns the configured negative trust value for the given target.
1059 public void distrustSone(Sone origin, Sone target) {
1060 setTrust(origin, target, preferences.getNegativeTrust());
1064 * Removes the trust assignment for the given target.
1071 public void untrustSone(Sone origin, Sone target) {
1072 removeTrust(origin, target);
1076 * Updates the stored Sone with the given Sone.
1081 public void updateSone(Sone sone) {
1082 updateSone(sone, false);
1086 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1087 * {@code true}, an older Sone than the current Sone can be given to restore
1091 * The Sone to update
1092 * @param soneRescueMode
1093 * {@code true} if the stored Sone should be updated regardless
1094 * of the age of the given Sone
1096 public void updateSone(Sone sone, boolean soneRescueMode) {
1097 if (hasSone(sone.getId())) {
1098 Sone storedSone = getSone(sone.getId());
1099 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1100 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1103 synchronized (posts) {
1104 if (!soneRescueMode) {
1105 for (Post post : storedSone.getPosts()) {
1106 posts.remove(post.getId());
1107 if (!sone.getPosts().contains(post)) {
1108 coreListenerManager.firePostRemoved(post);
1112 List<Post> storedPosts = storedSone.getPosts();
1113 synchronized (knownPosts) {
1114 for (Post post : sone.getPosts()) {
1115 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1116 if (!storedPosts.contains(post)) {
1117 if (post.getTime() < getSoneFollowingTime(sone)) {
1118 knownPosts.add(post.getId());
1119 post.setKnown(true);
1120 } else if (!knownPosts.contains(post.getId())) {
1121 eventBus.post(new NewPostFoundEvent(post));
1124 posts.put(post.getId(), post);
1128 synchronized (replies) {
1129 if (!soneRescueMode) {
1130 for (PostReply reply : storedSone.getReplies()) {
1131 replies.remove(reply.getId());
1132 if (!sone.getReplies().contains(reply)) {
1133 coreListenerManager.fireReplyRemoved(reply);
1137 Set<PostReply> storedReplies = storedSone.getReplies();
1138 synchronized (knownReplies) {
1139 for (PostReply reply : sone.getReplies()) {
1140 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1141 if (!storedReplies.contains(reply)) {
1142 if (reply.getTime() < getSoneFollowingTime(sone)) {
1143 knownReplies.add(reply.getId());
1144 reply.setKnown(true);
1145 } else if (!knownReplies.contains(reply.getId())) {
1146 eventBus.post(new NewPostReplyFoundEvent(reply));
1149 replies.put(reply.getId(), reply);
1153 synchronized (albums) {
1154 synchronized (images) {
1155 for (Album album : storedSone.getAlbums()) {
1156 albums.remove(album.getId());
1157 for (Image image : album.getImages()) {
1158 images.remove(image.getId());
1161 for (Album album : sone.getAlbums()) {
1162 albums.put(album.getId(), album);
1163 for (Image image : album.getImages()) {
1164 images.put(image.getId(), image);
1169 synchronized (storedSone) {
1170 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1171 storedSone.setTime(sone.getTime());
1173 storedSone.setClient(sone.getClient());
1174 storedSone.setProfile(sone.getProfile());
1175 if (soneRescueMode) {
1176 for (Post post : sone.getPosts()) {
1177 storedSone.addPost(post);
1179 for (PostReply reply : sone.getReplies()) {
1180 storedSone.addReply(reply);
1182 for (String likedPostId : sone.getLikedPostIds()) {
1183 storedSone.addLikedPostId(likedPostId);
1185 for (String likedReplyId : sone.getLikedReplyIds()) {
1186 storedSone.addLikedReplyId(likedReplyId);
1188 for (Album album : sone.getAlbums()) {
1189 storedSone.addAlbum(album);
1192 storedSone.setPosts(sone.getPosts());
1193 storedSone.setReplies(sone.getReplies());
1194 storedSone.setLikePostIds(sone.getLikedPostIds());
1195 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1196 storedSone.setAlbums(sone.getAlbums());
1198 storedSone.setLatestEdition(sone.getLatestEdition());
1204 * Deletes the given Sone. This will remove the Sone from the
1205 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1206 * remove the context from its identity.
1209 * The Sone to delete
1211 public void deleteSone(Sone sone) {
1212 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1213 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1216 synchronized (sones) {
1217 if (!getLocalSones().contains(sone)) {
1218 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1221 sones.remove(sone.getId());
1222 SoneInserter soneInserter = soneInserters.remove(sone);
1223 soneInserter.removeSoneInsertListener(this);
1224 soneInserter.stop();
1226 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1227 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1229 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1230 } catch (ConfigurationException ce1) {
1231 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1236 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1237 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1240 * The Sone to mark as known
1242 public void markSoneKnown(Sone sone) {
1243 if (!sone.isKnown()) {
1244 sone.setKnown(true);
1245 synchronized (knownSones) {
1246 knownSones.add(sone.getId());
1248 eventBus.post(new MarkSoneKnownEvent(sone));
1249 touchConfiguration();
1254 * Loads and updates the given Sone from the configuration. If any error is
1255 * encountered, loading is aborted and the given Sone is not changed.
1258 * The Sone to load and update
1260 public void loadSone(Sone sone) {
1261 if (!sone.isLocal()) {
1262 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1266 /* initialize options. */
1267 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1268 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1269 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1270 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1271 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1272 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1275 String sonePrefix = "Sone/" + sone.getId();
1276 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1277 if (soneTime == null) {
1278 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1281 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1284 Profile profile = new Profile(sone);
1285 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1286 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1287 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1288 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1289 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1290 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1292 /* load profile fields. */
1294 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1295 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1296 if (fieldName == null) {
1299 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1300 profile.addField(fieldName).setValue(fieldValue);
1304 Set<Post> posts = new HashSet<Post>();
1306 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1307 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1308 if (postId == null) {
1311 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1312 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1313 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1314 if ((postTime == 0) || (postText == null)) {
1315 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1318 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1319 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1320 post.setRecipient(getSone(postRecipientId));
1326 Set<PostReply> replies = new HashSet<PostReply>();
1328 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1329 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1330 if (replyId == null) {
1333 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1334 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1335 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1336 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1337 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1340 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1343 /* load post likes. */
1344 Set<String> likedPostIds = new HashSet<String>();
1346 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1347 if (likedPostId == null) {
1350 likedPostIds.add(likedPostId);
1353 /* load reply likes. */
1354 Set<String> likedReplyIds = new HashSet<String>();
1356 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1357 if (likedReplyId == null) {
1360 likedReplyIds.add(likedReplyId);
1364 Set<String> friends = new HashSet<String>();
1366 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1367 if (friendId == null) {
1370 friends.add(friendId);
1374 List<Album> topLevelAlbums = new ArrayList<Album>();
1375 int albumCounter = 0;
1377 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1378 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1379 if (albumId == null) {
1382 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1383 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1384 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1385 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1386 if ((albumTitle == null) || (albumDescription == null)) {
1387 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1390 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1391 if (albumParentId != null) {
1392 Album parentAlbum = getAlbum(albumParentId, false);
1393 if (parentAlbum == null) {
1394 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1397 parentAlbum.addAlbum(album);
1399 if (!topLevelAlbums.contains(album)) {
1400 topLevelAlbums.add(album);
1406 int imageCounter = 0;
1408 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1409 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1410 if (imageId == null) {
1413 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1414 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1415 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1416 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1417 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1418 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1419 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1420 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1421 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1424 Album album = getAlbum(albumId, false);
1425 if (album == null) {
1426 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1429 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1430 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1431 album.addImage(image);
1435 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1436 if (avatarId != null) {
1437 profile.setAvatar(getImage(avatarId, false));
1441 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1442 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1443 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1444 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1445 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1446 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1448 /* if we’re still here, Sone was loaded successfully. */
1449 synchronized (sone) {
1450 sone.setTime(soneTime);
1451 sone.setProfile(profile);
1452 sone.setPosts(posts);
1453 sone.setReplies(replies);
1454 sone.setLikePostIds(likedPostIds);
1455 sone.setLikeReplyIds(likedReplyIds);
1456 for (String friendId : friends) {
1457 followSone(sone, friendId);
1459 sone.setAlbums(topLevelAlbums);
1460 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1462 synchronized (knownSones) {
1463 for (String friend : friends) {
1464 knownSones.add(friend);
1467 synchronized (knownPosts) {
1468 for (Post post : posts) {
1469 knownPosts.add(post.getId());
1472 synchronized (knownReplies) {
1473 for (PostReply reply : replies) {
1474 knownReplies.add(reply.getId());
1480 * Creates a new post.
1483 * The Sone that creates the post
1485 * The text of the post
1486 * @return The created post
1488 public Post createPost(Sone sone, String text) {
1489 return createPost(sone, System.currentTimeMillis(), text);
1493 * Creates a new post.
1496 * The Sone that creates the post
1498 * The time of the post
1500 * The text of the post
1501 * @return The created post
1503 public Post createPost(Sone sone, long time, String text) {
1504 return createPost(sone, null, time, text);
1508 * Creates a new post.
1511 * The Sone that creates the post
1513 * The recipient Sone, or {@code null} if this post does not have
1516 * The text of the post
1517 * @return The created post
1519 public Post createPost(Sone sone, Sone recipient, String text) {
1520 return createPost(sone, recipient, System.currentTimeMillis(), text);
1524 * Creates a new post.
1527 * The Sone that creates the post
1529 * The recipient Sone, or {@code null} if this post does not have
1532 * The time of the post
1534 * The text of the post
1535 * @return The created post
1537 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1538 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1539 if (!sone.isLocal()) {
1540 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1543 final Post post = new PostImpl(sone, time, text);
1544 if (recipient != null) {
1545 post.setRecipient(recipient);
1547 synchronized (posts) {
1548 posts.put(post.getId(), post);
1550 eventBus.post(new NewPostFoundEvent(post));
1552 touchConfiguration();
1553 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1560 markPostKnown(post);
1562 }, "Mark " + post + " read.");
1567 * Deletes the given post.
1570 * The post to delete
1572 public void deletePost(Post post) {
1573 if (!post.getSone().isLocal()) {
1574 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1577 post.getSone().removePost(post);
1578 synchronized (posts) {
1579 posts.remove(post.getId());
1581 coreListenerManager.firePostRemoved(post);
1582 markPostKnown(post);
1583 touchConfiguration();
1587 * Marks the given post as known, if it is currently not a known post
1588 * (according to {@link Post#isKnown()}).
1591 * The post to mark as known
1593 public void markPostKnown(Post post) {
1594 post.setKnown(true);
1595 synchronized (knownPosts) {
1596 eventBus.post(new MarkPostKnownEvent(post));
1597 if (knownPosts.add(post.getId())) {
1598 touchConfiguration();
1601 for (PostReply reply : getReplies(post)) {
1602 markReplyKnown(reply);
1607 * Bookmarks the given post.
1610 * The post to bookmark
1612 public void bookmark(Post post) {
1613 bookmarkPost(post.getId());
1617 * Bookmarks the post with the given ID.
1620 * The ID of the post to bookmark
1622 public void bookmarkPost(String id) {
1623 synchronized (bookmarkedPosts) {
1624 bookmarkedPosts.add(id);
1629 * Removes the given post from the bookmarks.
1632 * The post to unbookmark
1634 public void unbookmark(Post post) {
1635 unbookmarkPost(post.getId());
1639 * Removes the post with the given ID from the bookmarks.
1642 * The ID of the post to unbookmark
1644 public void unbookmarkPost(String id) {
1645 synchronized (bookmarkedPosts) {
1646 bookmarkedPosts.remove(id);
1651 * Creates a new reply.
1654 * The Sone that creates the reply
1656 * The post that this reply refers to
1658 * The text of the reply
1659 * @return The created reply
1661 public PostReply createReply(Sone sone, Post post, String text) {
1662 return createReply(sone, post, System.currentTimeMillis(), text);
1666 * Creates a new reply.
1669 * The Sone that creates the reply
1671 * The post that this reply refers to
1673 * The time of the reply
1675 * The text of the reply
1676 * @return The created reply
1678 public PostReply createReply(Sone sone, Post post, long time, String text) {
1679 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1680 if (!sone.isLocal()) {
1681 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1684 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1685 synchronized (replies) {
1686 replies.put(reply.getId(), reply);
1688 synchronized (knownReplies) {
1689 eventBus.post(new NewPostReplyFoundEvent(reply));
1691 sone.addReply(reply);
1692 touchConfiguration();
1693 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1700 markReplyKnown(reply);
1702 }, "Mark " + reply + " read.");
1707 * Deletes the given reply.
1710 * The reply to delete
1712 public void deleteReply(PostReply reply) {
1713 Sone sone = reply.getSone();
1714 if (!sone.isLocal()) {
1715 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1718 synchronized (replies) {
1719 replies.remove(reply.getId());
1721 synchronized (knownReplies) {
1722 markReplyKnown(reply);
1723 knownReplies.remove(reply.getId());
1725 sone.removeReply(reply);
1726 touchConfiguration();
1730 * Marks the given reply as known, if it is currently not a known reply
1731 * (according to {@link Reply#isKnown()}).
1734 * The reply to mark as known
1736 public void markReplyKnown(PostReply reply) {
1737 reply.setKnown(true);
1738 synchronized (knownReplies) {
1739 coreListenerManager.fireMarkReplyKnown(reply);
1740 if (knownReplies.add(reply.getId())) {
1741 touchConfiguration();
1747 * Creates a new top-level album for the given Sone.
1750 * The Sone to create the album for
1751 * @return The new album
1753 public Album createAlbum(Sone sone) {
1754 return createAlbum(sone, null);
1758 * Creates a new album for the given Sone.
1761 * The Sone to create the album for
1763 * The parent of the album (may be {@code null} to create a
1765 * @return The new album
1767 public Album createAlbum(Sone sone, Album parent) {
1768 Album album = new Album();
1769 synchronized (albums) {
1770 albums.put(album.getId(), album);
1772 album.setSone(sone);
1773 if (parent != null) {
1774 parent.addAlbum(album);
1776 sone.addAlbum(album);
1782 * Deletes the given album. The owner of the album has to be a local Sone,
1783 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1786 * The album to remove
1788 public void deleteAlbum(Album album) {
1789 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1790 if (!album.isEmpty()) {
1793 if (album.getParent() == null) {
1794 album.getSone().removeAlbum(album);
1796 album.getParent().removeAlbum(album);
1798 synchronized (albums) {
1799 albums.remove(album.getId());
1801 touchConfiguration();
1805 * Creates a new image.
1808 * The Sone creating the image
1810 * The album the image will be inserted into
1811 * @param temporaryImage
1812 * The temporary image to create the image from
1813 * @return The newly created image
1815 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1816 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1817 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1818 album.addImage(image);
1819 synchronized (images) {
1820 images.put(image.getId(), image);
1822 imageInserter.insertImage(temporaryImage, image);
1827 * Deletes the given image. This method will also delete a matching
1830 * @see #deleteTemporaryImage(TemporaryImage)
1832 * The image to delete
1834 public void deleteImage(Image image) {
1835 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1836 deleteTemporaryImage(image.getId());
1837 image.getAlbum().removeImage(image);
1838 synchronized (images) {
1839 images.remove(image.getId());
1841 touchConfiguration();
1845 * Creates a new temporary image.
1848 * The MIME type of the temporary image
1850 * The encoded data of the image
1851 * @return The temporary image
1853 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1854 TemporaryImage temporaryImage = new TemporaryImage();
1855 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1856 synchronized (temporaryImages) {
1857 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1859 return temporaryImage;
1863 * Deletes the given temporary image.
1865 * @param temporaryImage
1866 * The temporary image to delete
1868 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1869 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1870 deleteTemporaryImage(temporaryImage.getId());
1874 * Deletes the temporary image with the given ID.
1877 * The ID of the temporary image to delete
1879 public void deleteTemporaryImage(String imageId) {
1880 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1881 synchronized (temporaryImages) {
1882 temporaryImages.remove(imageId);
1884 Image image = getImage(imageId, false);
1885 if (image != null) {
1886 imageInserter.cancelImageInsert(image);
1891 * Notifies the core that the configuration, either of the core or of a
1892 * single local Sone, has changed, and that the configuration should be
1895 public void touchConfiguration() {
1896 lastConfigurationUpdate = System.currentTimeMillis();
1907 public void serviceStart() {
1908 loadConfiguration();
1909 updateChecker.addUpdateListener(this);
1910 updateChecker.start();
1911 identityManager.addIdentityListener(this);
1912 identityManager.start();
1913 webOfTrustUpdater.init();
1914 webOfTrustUpdater.start();
1921 public void serviceRun() {
1922 long lastSaved = System.currentTimeMillis();
1923 while (!shouldStop()) {
1925 long now = System.currentTimeMillis();
1926 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1927 for (Sone localSone : getLocalSones()) {
1928 saveSone(localSone);
1930 saveConfiguration();
1940 public void serviceStop() {
1941 synchronized (sones) {
1942 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1943 soneInserter.getValue().removeSoneInsertListener(this);
1944 soneInserter.getValue().stop();
1945 saveSone(soneInserter.getKey());
1948 saveConfiguration();
1949 webOfTrustUpdater.stop();
1950 updateChecker.stop();
1951 updateChecker.removeUpdateListener(this);
1952 soneDownloader.stop();
1953 identityManager.removeIdentityListener(this);
1954 identityManager.stop();
1962 * Saves the given Sone. This will persist all local settings for the given
1963 * Sone, such as the friends list and similar, private options.
1968 private synchronized void saveSone(Sone sone) {
1969 if (!sone.isLocal()) {
1970 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1973 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1974 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1978 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1980 /* save Sone into configuration. */
1981 String sonePrefix = "Sone/" + sone.getId();
1982 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1983 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1986 Profile profile = sone.getProfile();
1987 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1988 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1989 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1990 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1991 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1992 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1993 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1995 /* save profile fields. */
1996 int fieldCounter = 0;
1997 for (Field profileField : profile.getFields()) {
1998 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1999 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2000 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2002 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2005 int postCounter = 0;
2006 for (Post post : sone.getPosts()) {
2007 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2008 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2009 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2010 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2011 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2013 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2016 int replyCounter = 0;
2017 for (PostReply reply : sone.getReplies()) {
2018 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2019 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2020 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2021 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2022 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2024 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2026 /* save post likes. */
2027 int postLikeCounter = 0;
2028 for (String postId : sone.getLikedPostIds()) {
2029 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2031 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2033 /* save reply likes. */
2034 int replyLikeCounter = 0;
2035 for (String replyId : sone.getLikedReplyIds()) {
2036 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2038 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2041 int friendCounter = 0;
2042 for (String friendId : sone.getFriends()) {
2043 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2045 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2047 /* save albums. first, collect in a flat structure, top-level first. */
2048 List<Album> albums = sone.getAllAlbums();
2050 int albumCounter = 0;
2051 for (Album album : albums) {
2052 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2053 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2054 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2055 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2056 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2057 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2059 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2062 int imageCounter = 0;
2063 for (Album album : albums) {
2064 for (Image image : album.getImages()) {
2065 if (!image.isInserted()) {
2068 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2069 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2070 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2071 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2072 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2073 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2074 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2075 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2076 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2079 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2082 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2083 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2084 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2085 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2086 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2087 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2089 configuration.save();
2091 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2093 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2094 } catch (ConfigurationException ce1) {
2095 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2100 * Saves the current options.
2102 private void saveConfiguration() {
2103 synchronized (configuration) {
2104 if (storingConfiguration) {
2105 logger.log(Level.FINE, "Already storing configuration…");
2108 storingConfiguration = true;
2111 /* store the options first. */
2113 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2114 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2115 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2116 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2117 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2118 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2119 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2120 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2121 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2122 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2123 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2124 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2126 /* save known Sones. */
2127 int soneCounter = 0;
2128 synchronized (knownSones) {
2129 for (String knownSoneId : knownSones) {
2130 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2132 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2135 /* save Sone following times. */
2137 synchronized (soneFollowingTimes) {
2138 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2139 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2140 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2143 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2146 /* save known posts. */
2147 int postCounter = 0;
2148 synchronized (knownPosts) {
2149 for (String knownPostId : knownPosts) {
2150 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2152 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2155 /* save known replies. */
2156 int replyCounter = 0;
2157 synchronized (knownReplies) {
2158 for (String knownReplyId : knownReplies) {
2159 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2161 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2164 /* save bookmarked posts. */
2165 int bookmarkedPostCounter = 0;
2166 synchronized (bookmarkedPosts) {
2167 for (String bookmarkedPostId : bookmarkedPosts) {
2168 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2171 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2174 configuration.save();
2176 } catch (ConfigurationException ce1) {
2177 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2179 synchronized (configuration) {
2180 storingConfiguration = false;
2186 * Loads the configuration.
2188 @SuppressWarnings("unchecked")
2189 private void loadConfiguration() {
2190 /* create options. */
2191 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2194 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2195 SoneInserter.setInsertionDelay(newValue);
2199 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2200 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2201 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2202 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2203 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2204 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2205 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2206 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2207 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2210 @SuppressWarnings("synthetic-access")
2211 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2212 fcpInterface.setActive(newValue);
2215 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2218 @SuppressWarnings("synthetic-access")
2219 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2220 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2225 loadConfigurationValue("InsertionDelay");
2226 loadConfigurationValue("PostsPerPage");
2227 loadConfigurationValue("ImagesPerPage");
2228 loadConfigurationValue("CharactersPerPost");
2229 loadConfigurationValue("PostCutOffLength");
2230 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2231 loadConfigurationValue("PositiveTrust");
2232 loadConfigurationValue("NegativeTrust");
2233 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2234 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2235 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2237 /* load known Sones. */
2238 int soneCounter = 0;
2240 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2241 if (knownSoneId == null) {
2244 synchronized (knownSones) {
2245 knownSones.add(knownSoneId);
2249 /* load Sone following times. */
2252 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2253 if (soneId == null) {
2256 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2257 Sone followedSone = getSone(soneId);
2258 if (followedSone == null) {
2259 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2261 synchronized (soneFollowingTimes) {
2262 soneFollowingTimes.put(getSone(soneId), time);
2268 /* load known posts. */
2269 int postCounter = 0;
2271 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2272 if (knownPostId == null) {
2275 synchronized (knownPosts) {
2276 knownPosts.add(knownPostId);
2280 /* load known replies. */
2281 int replyCounter = 0;
2283 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2284 if (knownReplyId == null) {
2287 synchronized (knownReplies) {
2288 knownReplies.add(knownReplyId);
2292 /* load bookmarked posts. */
2293 int bookmarkedPostCounter = 0;
2295 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2296 if (bookmarkedPostId == null) {
2299 synchronized (bookmarkedPosts) {
2300 bookmarkedPosts.add(bookmarkedPostId);
2307 * Loads an {@link Integer} configuration value for the option with the
2308 * given name, logging validation failures.
2311 * The name of the option to load
2313 private void loadConfigurationValue(String optionName) {
2315 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2316 } catch (IllegalArgumentException iae1) {
2317 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2322 * Generate a Sone URI from the given URI and latest edition.
2325 * The URI to derive the Sone URI from
2326 * @return The derived URI
2328 private static FreenetURI getSoneUri(String uriString) {
2330 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2332 } catch (MalformedURLException mue1) {
2333 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2339 // INTERFACE IdentityListener
2346 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2347 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2348 if (ownIdentity.hasContext("Sone")) {
2349 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2350 addLocalSone(ownIdentity);
2358 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2359 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2360 trustedIdentities.remove(ownIdentity);
2367 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2368 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2369 trustedIdentities.get(ownIdentity).add(identity);
2370 addRemoteSone(identity);
2377 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2378 soneDownloaders.execute(new Runnable() {
2381 @SuppressWarnings("synthetic-access")
2383 Sone sone = getRemoteSone(identity.getId(), false);
2384 sone.setIdentity(identity);
2385 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2386 soneDownloader.addSone(sone);
2387 soneDownloader.fetchSone(sone);
2396 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2397 trustedIdentities.get(ownIdentity).remove(identity);
2398 boolean foundIdentity = false;
2399 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2400 if (trustedIdentity.getKey().equals(ownIdentity)) {
2403 if (trustedIdentity.getValue().contains(identity)) {
2404 foundIdentity = true;
2407 if (foundIdentity) {
2408 /* some local identity still trusts this identity, don’t remove. */
2411 Sone sone = getSone(identity.getId(), false);
2413 /* TODO - we don’t have the Sone anymore. should this happen? */
2416 synchronized (posts) {
2417 synchronized (knownPosts) {
2418 for (Post post : sone.getPosts()) {
2419 posts.remove(post.getId());
2420 coreListenerManager.firePostRemoved(post);
2424 synchronized (replies) {
2425 synchronized (knownReplies) {
2426 for (PostReply reply : sone.getReplies()) {
2427 replies.remove(reply.getId());
2428 coreListenerManager.fireReplyRemoved(reply);
2432 synchronized (sones) {
2433 sones.remove(identity.getId());
2435 coreListenerManager.fireSoneRemoved(sone);
2439 // INTERFACE UpdateListener
2446 public void updateFound(Version version, long releaseTime, long latestEdition) {
2447 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2451 // INTERFACE ImageInsertListener
2458 public void insertStarted(Sone sone) {
2459 coreListenerManager.fireSoneInserting(sone);
2466 public void insertFinished(Sone sone, long insertDuration) {
2467 coreListenerManager.fireSoneInserted(sone, insertDuration);
2474 public void insertAborted(Sone sone, Throwable cause) {
2475 coreListenerManager.fireSoneInsertAborted(sone, cause);
2479 // SONEINSERTLISTENER METHODS
2486 public void imageInsertStarted(Image image) {
2487 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2488 coreListenerManager.fireImageInsertStarted(image);
2495 public void imageInsertAborted(Image image) {
2496 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2497 coreListenerManager.fireImageInsertAborted(image);
2504 public void imageInsertFinished(Image image, FreenetURI key) {
2505 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2506 image.setKey(key.toString());
2507 deleteTemporaryImage(image.getId());
2508 touchConfiguration();
2509 coreListenerManager.fireImageInsertFinished(image);
2516 public void imageInsertFailed(Image image, Throwable cause) {
2517 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2518 coreListenerManager.fireImageInsertFailed(image, cause);
2522 * Convenience interface for external classes that want to access the core’s
2525 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2527 public static class Preferences {
2529 /** The wrapped options. */
2530 private final Options options;
2533 * Creates a new preferences object wrapped around the given options.
2536 * The options to wrap
2538 public Preferences(Options options) {
2539 this.options = options;
2543 * Returns the insertion delay.
2545 * @return The insertion delay
2547 public int getInsertionDelay() {
2548 return options.getIntegerOption("InsertionDelay").get();
2552 * Validates the given insertion delay.
2554 * @param insertionDelay
2555 * The insertion delay to validate
2556 * @return {@code true} if the given insertion delay was valid,
2557 * {@code false} otherwise
2559 public boolean validateInsertionDelay(Integer insertionDelay) {
2560 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2564 * Sets the insertion delay
2566 * @param insertionDelay
2567 * The new insertion delay, or {@code null} to restore it to
2569 * @return This preferences
2571 public Preferences setInsertionDelay(Integer insertionDelay) {
2572 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2577 * Returns the number of posts to show per page.
2579 * @return The number of posts to show per page
2581 public int getPostsPerPage() {
2582 return options.getIntegerOption("PostsPerPage").get();
2586 * Validates the number of posts per page.
2588 * @param postsPerPage
2589 * The number of posts per page
2590 * @return {@code true} if the number of posts per page was valid,
2591 * {@code false} otherwise
2593 public boolean validatePostsPerPage(Integer postsPerPage) {
2594 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2598 * Sets the number of posts to show per page.
2600 * @param postsPerPage
2601 * The number of posts to show per page
2602 * @return This preferences object
2604 public Preferences setPostsPerPage(Integer postsPerPage) {
2605 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2610 * Returns the number of images to show per page.
2612 * @return The number of images to show per page
2614 public int getImagesPerPage() {
2615 return options.getIntegerOption("ImagesPerPage").get();
2619 * Validates the number of images per page.
2621 * @param imagesPerPage
2622 * The number of images per page
2623 * @return {@code true} if the number of images per page was valid,
2624 * {@code false} otherwise
2626 public boolean validateImagesPerPage(Integer imagesPerPage) {
2627 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2631 * Sets the number of images per page.
2633 * @param imagesPerPage
2634 * The number of images per page
2635 * @return This preferences object
2637 public Preferences setImagesPerPage(Integer imagesPerPage) {
2638 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2643 * Returns the number of characters per post, or <code>-1</code> if the
2644 * posts should not be cut off.
2646 * @return The numbers of characters per post
2648 public int getCharactersPerPost() {
2649 return options.getIntegerOption("CharactersPerPost").get();
2653 * Validates the number of characters per post.
2655 * @param charactersPerPost
2656 * The number of characters per post
2657 * @return {@code true} if the number of characters per post was valid,
2658 * {@code false} otherwise
2660 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2661 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2665 * Sets the number of characters per post.
2667 * @param charactersPerPost
2668 * The number of characters per post, or <code>-1</code> to
2669 * not cut off the posts
2670 * @return This preferences objects
2672 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2673 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2678 * Returns the number of characters the shortened post should have.
2680 * @return The number of characters of the snippet
2682 public int getPostCutOffLength() {
2683 return options.getIntegerOption("PostCutOffLength").get();
2687 * Validates the number of characters after which to cut off the post.
2689 * @param postCutOffLength
2690 * The number of characters of the snippet
2691 * @return {@code true} if the number of characters of the snippet is
2692 * valid, {@code false} otherwise
2694 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2695 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2699 * Sets the number of characters the shortened post should have.
2701 * @param postCutOffLength
2702 * The number of characters of the snippet
2703 * @return This preferences
2705 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2706 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2711 * Returns whether Sone requires full access to be even visible.
2713 * @return {@code true} if Sone requires full access, {@code false}
2716 public boolean isRequireFullAccess() {
2717 return options.getBooleanOption("RequireFullAccess").get();
2721 * Sets whether Sone requires full access to be even visible.
2723 * @param requireFullAccess
2724 * {@code true} if Sone requires full access, {@code false}
2727 public void setRequireFullAccess(Boolean requireFullAccess) {
2728 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2732 * Returns the positive trust.
2734 * @return The positive trust
2736 public int getPositiveTrust() {
2737 return options.getIntegerOption("PositiveTrust").get();
2741 * Validates the positive trust.
2743 * @param positiveTrust
2744 * The positive trust to validate
2745 * @return {@code true} if the positive trust was valid, {@code false}
2748 public boolean validatePositiveTrust(Integer positiveTrust) {
2749 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2753 * Sets the positive trust.
2755 * @param positiveTrust
2756 * The new positive trust, or {@code null} to restore it to
2758 * @return This preferences
2760 public Preferences setPositiveTrust(Integer positiveTrust) {
2761 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2766 * Returns the negative trust.
2768 * @return The negative trust
2770 public int getNegativeTrust() {
2771 return options.getIntegerOption("NegativeTrust").get();
2775 * Validates the negative trust.
2777 * @param negativeTrust
2778 * The negative trust to validate
2779 * @return {@code true} if the negative trust was valid, {@code false}
2782 public boolean validateNegativeTrust(Integer negativeTrust) {
2783 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2787 * Sets the negative trust.
2789 * @param negativeTrust
2790 * The negative trust, or {@code null} to restore it to the
2792 * @return The preferences
2794 public Preferences setNegativeTrust(Integer negativeTrust) {
2795 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2800 * Returns the trust comment. This is the comment that is set in the web
2801 * of trust when a trust value is assigned to an identity.
2803 * @return The trust comment
2805 public String getTrustComment() {
2806 return options.getStringOption("TrustComment").get();
2810 * Sets the trust comment.
2812 * @param trustComment
2813 * The trust comment, or {@code null} to restore it to the
2815 * @return This preferences
2817 public Preferences setTrustComment(String trustComment) {
2818 options.getStringOption("TrustComment").set(trustComment);
2823 * Returns whether the {@link FcpInterface FCP interface} is currently
2826 * @see FcpInterface#setActive(boolean)
2827 * @return {@code true} if the FCP interface is currently active,
2828 * {@code false} otherwise
2830 public boolean isFcpInterfaceActive() {
2831 return options.getBooleanOption("ActivateFcpInterface").get();
2835 * Sets whether the {@link FcpInterface FCP interface} is currently
2838 * @see FcpInterface#setActive(boolean)
2839 * @param fcpInterfaceActive
2840 * {@code true} to activate the FCP interface, {@code false}
2841 * to deactivate the FCP interface
2842 * @return This preferences object
2844 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2845 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2850 * Returns the action level for which full access to the FCP interface
2853 * @return The action level for which full access to the FCP interface
2856 public FullAccessRequired getFcpFullAccessRequired() {
2857 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2861 * Sets the action level for which full access to the FCP interface is
2864 * @param fcpFullAccessRequired
2866 * @return This preferences
2868 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2869 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);