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.NewPostFoundEvent;
39 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
40 import net.pterodactylus.sone.data.Album;
41 import net.pterodactylus.sone.data.Client;
42 import net.pterodactylus.sone.data.Image;
43 import net.pterodactylus.sone.data.Post;
44 import net.pterodactylus.sone.data.PostReply;
45 import net.pterodactylus.sone.data.Profile;
46 import net.pterodactylus.sone.data.Profile.Field;
47 import net.pterodactylus.sone.data.Reply;
48 import net.pterodactylus.sone.data.Sone;
49 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
50 import net.pterodactylus.sone.data.Sone.SoneStatus;
51 import net.pterodactylus.sone.data.TemporaryImage;
52 import net.pterodactylus.sone.data.impl.PostImpl;
53 import net.pterodactylus.sone.fcp.FcpInterface;
54 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
55 import net.pterodactylus.sone.freenet.wot.Identity;
56 import net.pterodactylus.sone.freenet.wot.IdentityListener;
57 import net.pterodactylus.sone.freenet.wot.IdentityManager;
58 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
59 import net.pterodactylus.sone.main.SonePlugin;
60 import net.pterodactylus.util.config.Configuration;
61 import net.pterodactylus.util.config.ConfigurationException;
62 import net.pterodactylus.util.logging.Logging;
63 import net.pterodactylus.util.number.Numbers;
64 import net.pterodactylus.util.service.AbstractService;
65 import net.pterodactylus.util.thread.NamedThreadFactory;
66 import net.pterodactylus.util.thread.Ticker;
67 import net.pterodactylus.util.validation.EqualityValidator;
68 import net.pterodactylus.util.validation.IntegerRangeValidator;
69 import net.pterodactylus.util.validation.OrValidator;
70 import net.pterodactylus.util.validation.Validation;
71 import net.pterodactylus.util.version.Version;
73 import com.google.common.base.Predicate;
74 import com.google.common.collect.Collections2;
75 import com.google.common.eventbus.EventBus;
76 import com.google.inject.Inject;
78 import freenet.keys.FreenetURI;
83 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
85 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
88 private static final Logger logger = Logging.getLogger(Core.class);
90 /** The start time. */
91 private final long startupTime = System.currentTimeMillis();
94 private final Options options = new Options();
96 /** The preferences. */
97 private final Preferences preferences = new Preferences(options);
99 /** The core listener manager. */
100 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
102 /** The event bus. */
103 private final EventBus eventBus;
105 /** The configuration. */
106 private Configuration configuration;
108 /** Whether we’re currently saving the configuration. */
109 private boolean storingConfiguration = false;
111 /** The identity manager. */
112 private final IdentityManager identityManager;
114 /** Interface to freenet. */
115 private final FreenetInterface freenetInterface;
117 /** The Sone downloader. */
118 private final SoneDownloader soneDownloader;
120 /** The image inserter. */
121 private final ImageInserter imageInserter;
123 /** Sone downloader thread-pool. */
124 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
126 /** The update checker. */
127 private final UpdateChecker updateChecker;
129 /** The trust updater. */
130 private final WebOfTrustUpdater webOfTrustUpdater;
132 /** The FCP interface. */
133 private volatile FcpInterface fcpInterface;
135 /** The times Sones were followed. */
136 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
138 /** Locked local Sones. */
139 /* synchronize on itself. */
140 private final Set<Sone> lockedSones = new HashSet<Sone>();
142 /** Sone inserters. */
143 /* synchronize access on this on sones. */
144 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
146 /** Sone rescuers. */
147 /* synchronize access on this on sones. */
148 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
151 /* synchronize access on this on itself. */
152 private final Map<String, Sone> sones = new HashMap<String, Sone>();
154 /** All known Sones. */
155 private final Set<String> knownSones = new HashSet<String>();
158 private final Map<String, Post> posts = new HashMap<String, Post>();
160 /** All known posts. */
161 private final Set<String> knownPosts = new HashSet<String>();
164 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
166 /** All known replies. */
167 private final Set<String> knownReplies = new HashSet<String>();
169 /** All bookmarked posts. */
170 /* synchronize access on itself. */
171 private final Set<String> bookmarkedPosts = new HashSet<String>();
173 /** Trusted identities, sorted by own identities. */
174 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
176 /** All known albums. */
177 private final Map<String, Album> albums = new HashMap<String, Album>();
179 /** All known images. */
180 private final Map<String, Image> images = new HashMap<String, Image>();
182 /** All temporary images. */
183 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
185 /** Ticker for threads that mark own elements as known. */
186 private final Ticker localElementTicker = new Ticker();
188 /** The time the configuration was last touched. */
189 private volatile long lastConfigurationUpdate;
192 * Creates a new core.
194 * @param configuration
195 * The configuration of the core
196 * @param freenetInterface
197 * The freenet interface
198 * @param identityManager
199 * The identity manager
200 * @param webOfTrustUpdater
201 * The WebOfTrust updater
206 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
208 this.configuration = configuration;
209 this.freenetInterface = freenetInterface;
210 this.identityManager = identityManager;
211 this.soneDownloader = new SoneDownloader(this, freenetInterface);
212 this.imageInserter = new ImageInserter(this, freenetInterface);
213 this.updateChecker = new UpdateChecker(freenetInterface);
214 this.webOfTrustUpdater = webOfTrustUpdater;
215 this.eventBus = eventBus;
219 // LISTENER MANAGEMENT
223 * Adds a new core listener.
225 * @param coreListener
226 * The listener to add
228 public void addCoreListener(CoreListener coreListener) {
229 coreListenerManager.addListener(coreListener);
233 * Removes a core listener.
235 * @param coreListener
236 * The listener to remove
238 public void removeCoreListener(CoreListener coreListener) {
239 coreListenerManager.removeListener(coreListener);
247 * Returns the time Sone was started.
249 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
251 public long getStartupTime() {
256 * Sets the configuration to use. This will automatically save the current
257 * configuration to the given configuration.
259 * @param configuration
260 * The new configuration to use
262 public void setConfiguration(Configuration configuration) {
263 this.configuration = configuration;
264 touchConfiguration();
268 * Returns the options used by the core.
270 * @return The options of the core
272 public Preferences getPreferences() {
277 * Returns the identity manager used by the core.
279 * @return The identity manager
281 public IdentityManager getIdentityManager() {
282 return identityManager;
286 * Returns the update checker.
288 * @return The update checker
290 public UpdateChecker getUpdateChecker() {
291 return updateChecker;
295 * Sets the FCP interface to use.
297 * @param fcpInterface
298 * The FCP interface to use
300 public void setFcpInterface(FcpInterface fcpInterface) {
301 this.fcpInterface = fcpInterface;
305 * Returns the Sone rescuer for the given local Sone.
308 * The local Sone to get the rescuer for
309 * @return The Sone rescuer for the given Sone
311 public SoneRescuer getSoneRescuer(Sone sone) {
312 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
313 synchronized (sones) {
314 SoneRescuer soneRescuer = soneRescuers.get(sone);
315 if (soneRescuer == null) {
316 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
317 soneRescuers.put(sone, soneRescuer);
325 * Returns whether the given Sone is currently locked.
329 * @return {@code true} if the Sone is locked, {@code false} if it is not
331 public boolean isLocked(Sone sone) {
332 synchronized (lockedSones) {
333 return lockedSones.contains(sone);
338 * Returns all Sones, remote and local.
342 public Set<Sone> getSones() {
343 return new HashSet<Sone>(sones.values());
347 * Returns the Sone with the given ID, regardless whether it’s local or
351 * The ID of the Sone to get
352 * @return The Sone with the given ID, or {@code null} if there is no such
355 public Sone getSone(String id) {
356 return getSone(id, true);
360 * Returns the Sone with the given ID, regardless whether it’s local or
364 * The ID of the Sone to get
366 * {@code true} to create a new Sone if none exists,
367 * {@code false} to return {@code null} if a Sone with the given
369 * @return The Sone with the given ID, or {@code null} if there is no such
373 public Sone getSone(String id, boolean create) {
374 synchronized (sones) {
375 if (!sones.containsKey(id)) {
376 Sone sone = new Sone(id, false);
379 return sones.get(id);
384 * Checks whether the core knows a Sone with the given ID.
388 * @return {@code true} if there is a Sone with the given ID, {@code false}
391 public boolean hasSone(String id) {
392 synchronized (sones) {
393 return sones.containsKey(id);
398 * Returns all local Sones.
400 * @return All local Sones
402 public Collection<Sone> getLocalSones() {
403 synchronized (sones) {
404 return Collections2.filter(sones.values(), new Predicate<Sone>() {
407 public boolean apply(Sone sone) {
408 return sone.isLocal();
415 * Returns the local Sone with the given ID, optionally creating a new Sone.
420 * {@code true} to create a new Sone if none exists,
421 * {@code false} to return null if none exists
422 * @return The Sone with the given ID, or {@code null}
424 public Sone getLocalSone(String id, boolean create) {
425 synchronized (sones) {
426 Sone sone = sones.get(id);
427 if ((sone == null) && create) {
428 sone = new Sone(id, true);
431 if ((sone != null) && !sone.isLocal()) {
432 sone = new Sone(id, true);
440 * Returns all remote Sones.
442 * @return All remote Sones
444 public Collection<Sone> getRemoteSones() {
445 synchronized (sones) {
446 return Collections2.filter(sones.values(), new Predicate<Sone>() {
449 public boolean apply(Sone sone) {
450 return !sone.isLocal();
457 * Returns the remote Sone with the given ID.
460 * The ID of the remote Sone to get
462 * {@code true} to always create a Sone, {@code false} to return
463 * {@code null} if no Sone with the given ID exists
464 * @return The Sone with the given ID
466 public Sone getRemoteSone(String id, boolean create) {
467 synchronized (sones) {
468 Sone sone = sones.get(id);
469 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
470 sone = new Sone(id, false);
478 * Returns whether the given Sone has been modified.
481 * The Sone to check for modifications
482 * @return {@code true} if a modification has been detected in the Sone,
483 * {@code false} otherwise
485 public boolean isModifiedSone(Sone sone) {
486 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
490 * Returns the time when the given was first followed by any local Sone.
493 * The Sone to get the time for
494 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
495 * been followed, or {@link Long#MAX_VALUE}
497 public long getSoneFollowingTime(Sone sone) {
498 synchronized (soneFollowingTimes) {
499 if (soneFollowingTimes.containsKey(sone)) {
500 return soneFollowingTimes.get(sone);
502 return Long.MAX_VALUE;
507 * Returns whether the target Sone is trusted by the origin Sone.
513 * @return {@code true} if the target Sone is trusted by the origin Sone
515 public boolean isSoneTrusted(Sone origin, Sone target) {
516 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
517 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
521 * Returns the post with the given ID.
524 * The ID of the post to get
525 * @return The post with the given ID, or a new post with the given ID
527 public Post getPost(String postId) {
528 return getPost(postId, true);
532 * Returns the post with the given ID, optionally creating a new post.
535 * The ID of the post to get
537 * {@code true} it create a new post if no post with the given ID
538 * exists, {@code false} to return {@code null}
539 * @return The post, or {@code null} if there is no such post
542 public Post getPost(String postId, boolean create) {
543 synchronized (posts) {
544 Post post = posts.get(postId);
545 if ((post == null) && create) {
546 post = new PostImpl(postId);
547 posts.put(postId, post);
554 * Returns all posts that have the given Sone as recipient.
556 * @see Post#getRecipient()
558 * The recipient of the posts
559 * @return All posts that have the given Sone as recipient
561 public Set<Post> getDirectedPosts(Sone recipient) {
562 Validation.begin().isNotNull("Recipient", recipient).check();
563 Set<Post> directedPosts = new HashSet<Post>();
564 synchronized (posts) {
565 for (Post post : posts.values()) {
566 if (recipient.equals(post.getRecipient())) {
567 directedPosts.add(post);
571 return directedPosts;
575 * Returns the reply with the given ID. If there is no reply with the given
576 * ID yet, a new one is created, unless {@code create} is false in which
577 * case {@code null} is returned.
580 * The ID of the reply to get
582 * {@code true} to always return a {@link Reply}, {@code false}
583 * to return {@code null} if no reply can be found
584 * @return The reply, or {@code null} if there is no such reply
586 public PostReply getPostReply(String replyId, boolean create) {
587 synchronized (replies) {
588 PostReply reply = replies.get(replyId);
589 if (create && (reply == null)) {
590 reply = new PostReply(replyId);
591 replies.put(replyId, reply);
598 * Returns all replies for the given post, order ascending by time.
601 * The post to get all replies for
602 * @return All replies for the given post
604 public List<PostReply> getReplies(Post post) {
605 Set<Sone> sones = getSones();
606 List<PostReply> replies = new ArrayList<PostReply>();
607 for (Sone sone : sones) {
608 for (PostReply reply : sone.getReplies()) {
609 if (reply.getPost().equals(post)) {
614 Collections.sort(replies, Reply.TIME_COMPARATOR);
619 * Returns all Sones that have liked the given post.
622 * The post to get the liking Sones for
623 * @return The Sones that like the given post
625 public Set<Sone> getLikes(Post post) {
626 Set<Sone> sones = new HashSet<Sone>();
627 for (Sone sone : getSones()) {
628 if (sone.getLikedPostIds().contains(post.getId())) {
636 * Returns all Sones that have liked the given reply.
639 * The reply to get the liking Sones for
640 * @return The Sones that like the given reply
642 public Set<Sone> getLikes(PostReply reply) {
643 Set<Sone> sones = new HashSet<Sone>();
644 for (Sone sone : getSones()) {
645 if (sone.getLikedReplyIds().contains(reply.getId())) {
653 * Returns whether the given post is bookmarked.
657 * @return {@code true} if the given post is bookmarked, {@code false}
660 public boolean isBookmarked(Post post) {
661 return isPostBookmarked(post.getId());
665 * Returns whether the post with the given ID is bookmarked.
668 * The ID of the post to check
669 * @return {@code true} if the post with the given ID is bookmarked,
670 * {@code false} otherwise
672 public boolean isPostBookmarked(String id) {
673 synchronized (bookmarkedPosts) {
674 return bookmarkedPosts.contains(id);
679 * Returns all currently known bookmarked posts.
681 * @return All bookmarked posts
683 public Set<Post> getBookmarkedPosts() {
684 Set<Post> posts = new HashSet<Post>();
685 synchronized (bookmarkedPosts) {
686 for (String bookmarkedPostId : bookmarkedPosts) {
687 Post post = getPost(bookmarkedPostId, false);
697 * Returns the album with the given ID, creating a new album if no album
698 * with the given ID can be found.
701 * The ID of the album
702 * @return The album with the given ID
704 public Album getAlbum(String albumId) {
705 return getAlbum(albumId, true);
709 * Returns the album with the given ID, optionally creating a new album if
710 * an album with the given ID can not be found.
713 * The ID of the album
715 * {@code true} to create a new album if none exists for the
717 * @return The album with the given ID, or {@code null} if no album with the
718 * given ID exists and {@code create} is {@code false}
720 public Album getAlbum(String albumId, boolean create) {
721 synchronized (albums) {
722 Album album = albums.get(albumId);
723 if (create && (album == null)) {
724 album = new Album(albumId);
725 albums.put(albumId, album);
732 * Returns the image with the given ID, creating it if necessary.
735 * The ID of the image
736 * @return The image with the given ID
738 public Image getImage(String imageId) {
739 return getImage(imageId, true);
743 * Returns the image with the given ID, optionally creating it if it does
747 * The ID of the image
749 * {@code true} to create an image if none exists with the given
751 * @return The image with the given ID, or {@code null} if none exists and
754 public Image getImage(String imageId, boolean create) {
755 synchronized (images) {
756 Image image = images.get(imageId);
757 if (create && (image == null)) {
758 image = new Image(imageId);
759 images.put(imageId, image);
766 * Returns the temporary image with the given ID.
769 * The ID of the temporary image
770 * @return The temporary image, or {@code null} if there is no temporary
771 * image with the given ID
773 public TemporaryImage getTemporaryImage(String imageId) {
774 synchronized (temporaryImages) {
775 return temporaryImages.get(imageId);
784 * Locks the given Sone. A locked Sone will not be inserted by
785 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
791 public void lockSone(Sone sone) {
792 synchronized (lockedSones) {
793 if (lockedSones.add(sone)) {
794 coreListenerManager.fireSoneLocked(sone);
800 * Unlocks the given Sone.
802 * @see #lockSone(Sone)
806 public void unlockSone(Sone sone) {
807 synchronized (lockedSones) {
808 if (lockedSones.remove(sone)) {
809 coreListenerManager.fireSoneUnlocked(sone);
815 * Adds a local Sone from the given own identity.
818 * The own identity to create a Sone from
819 * @return The added (or already existing) Sone
821 public Sone addLocalSone(OwnIdentity ownIdentity) {
822 if (ownIdentity == null) {
823 logger.log(Level.WARNING, "Given OwnIdentity is null!");
826 synchronized (sones) {
829 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
830 } catch (MalformedURLException mue1) {
831 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
834 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
835 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
837 /* TODO - load posts ’n stuff */
838 sones.put(ownIdentity.getId(), sone);
839 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
840 soneInserter.addSoneInsertListener(this);
841 soneInserters.put(sone, soneInserter);
842 sone.setStatus(SoneStatus.idle);
844 soneInserter.start();
850 * Creates a new Sone for the given own identity.
853 * The own identity to create a Sone for
854 * @return The created Sone
856 public Sone createSone(OwnIdentity ownIdentity) {
857 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
858 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
861 Sone sone = addLocalSone(ownIdentity);
862 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
863 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
864 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
865 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
866 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
867 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
869 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
870 touchConfiguration();
875 * Adds the Sone of the given identity.
878 * The identity whose Sone to add
879 * @return The added or already existing Sone
881 public Sone addRemoteSone(Identity identity) {
882 if (identity == null) {
883 logger.log(Level.WARNING, "Given Identity is null!");
886 synchronized (sones) {
887 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
888 boolean newSone = sone.getRequestUri() == null;
889 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
890 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
892 synchronized (knownSones) {
893 newSone = !knownSones.contains(sone.getId());
895 sone.setKnown(!newSone);
897 eventBus.post(new NewSoneFoundEvent(sone));
898 for (Sone localSone : getLocalSones()) {
899 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
900 followSone(localSone, sone);
905 soneDownloader.addSone(sone);
906 soneDownloaders.execute(new Runnable() {
909 @SuppressWarnings("synthetic-access")
911 soneDownloader.fetchSone(sone, sone.getRequestUri());
920 * Lets the given local Sone follow the Sone with the given ID.
923 * The local Sone that should follow another Sone
925 * The ID of the Sone to follow
927 public void followSone(Sone sone, String soneId) {
928 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
929 Sone followedSone = getSone(soneId, true);
930 if (followedSone == null) {
931 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
934 followSone(sone, getSone(soneId));
938 * Lets the given local Sone follow the other given Sone. If the given Sone
939 * was not followed by any local Sone before, this will mark all elements of
940 * the followed Sone as read that have been created before the current
944 * The local Sone that should follow the other Sone
945 * @param followedSone
946 * The Sone that should be followed
948 public void followSone(Sone sone, Sone followedSone) {
949 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
950 sone.addFriend(followedSone.getId());
951 synchronized (soneFollowingTimes) {
952 if (!soneFollowingTimes.containsKey(followedSone)) {
953 long now = System.currentTimeMillis();
954 soneFollowingTimes.put(followedSone, now);
955 for (Post post : followedSone.getPosts()) {
956 if (post.getTime() < now) {
960 for (PostReply reply : followedSone.getReplies()) {
961 if (reply.getTime() < now) {
962 markReplyKnown(reply);
967 touchConfiguration();
971 * Lets the given local Sone unfollow the Sone with the given ID.
974 * The local Sone that should unfollow another Sone
976 * The ID of the Sone being unfollowed
978 public void unfollowSone(Sone sone, String soneId) {
979 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
980 unfollowSone(sone, getSone(soneId, false));
984 * Lets the given local Sone unfollow the other given Sone. If the given
985 * local Sone is the last local Sone that followed the given Sone, its
986 * following time will be removed.
989 * The local Sone that should unfollow another Sone
990 * @param unfollowedSone
991 * The Sone being unfollowed
993 public void unfollowSone(Sone sone, Sone unfollowedSone) {
994 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
995 sone.removeFriend(unfollowedSone.getId());
996 boolean unfollowedSoneStillFollowed = false;
997 for (Sone localSone : getLocalSones()) {
998 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1000 if (!unfollowedSoneStillFollowed) {
1001 synchronized (soneFollowingTimes) {
1002 soneFollowingTimes.remove(unfollowedSone);
1005 touchConfiguration();
1009 * Sets the trust value of the given origin Sone for the target Sone.
1016 * The trust value (from {@code -100} to {@code 100})
1018 public void setTrust(Sone origin, Sone target, int trustValue) {
1019 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();
1020 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1024 * Removes any trust assignment for the given target Sone.
1031 public void removeTrust(Sone origin, Sone target) {
1032 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1033 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1037 * Assigns the configured positive trust value for the given target.
1044 public void trustSone(Sone origin, Sone target) {
1045 setTrust(origin, target, preferences.getPositiveTrust());
1049 * Assigns the configured negative trust value for the given target.
1056 public void distrustSone(Sone origin, Sone target) {
1057 setTrust(origin, target, preferences.getNegativeTrust());
1061 * Removes the trust assignment for the given target.
1068 public void untrustSone(Sone origin, Sone target) {
1069 removeTrust(origin, target);
1073 * Updates the stored Sone with the given Sone.
1078 public void updateSone(Sone sone) {
1079 updateSone(sone, false);
1083 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1084 * {@code true}, an older Sone than the current Sone can be given to restore
1088 * The Sone to update
1089 * @param soneRescueMode
1090 * {@code true} if the stored Sone should be updated regardless
1091 * of the age of the given Sone
1093 public void updateSone(Sone sone, boolean soneRescueMode) {
1094 if (hasSone(sone.getId())) {
1095 Sone storedSone = getSone(sone.getId());
1096 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1097 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1100 synchronized (posts) {
1101 if (!soneRescueMode) {
1102 for (Post post : storedSone.getPosts()) {
1103 posts.remove(post.getId());
1104 if (!sone.getPosts().contains(post)) {
1105 coreListenerManager.firePostRemoved(post);
1109 List<Post> storedPosts = storedSone.getPosts();
1110 synchronized (knownPosts) {
1111 for (Post post : sone.getPosts()) {
1112 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1113 if (!storedPosts.contains(post)) {
1114 if (post.getTime() < getSoneFollowingTime(sone)) {
1115 knownPosts.add(post.getId());
1116 post.setKnown(true);
1117 } else if (!knownPosts.contains(post.getId())) {
1118 eventBus.post(new NewPostFoundEvent(post));
1121 posts.put(post.getId(), post);
1125 synchronized (replies) {
1126 if (!soneRescueMode) {
1127 for (PostReply reply : storedSone.getReplies()) {
1128 replies.remove(reply.getId());
1129 if (!sone.getReplies().contains(reply)) {
1130 coreListenerManager.fireReplyRemoved(reply);
1134 Set<PostReply> storedReplies = storedSone.getReplies();
1135 synchronized (knownReplies) {
1136 for (PostReply reply : sone.getReplies()) {
1137 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1138 if (!storedReplies.contains(reply)) {
1139 if (reply.getTime() < getSoneFollowingTime(sone)) {
1140 knownReplies.add(reply.getId());
1141 reply.setKnown(true);
1142 } else if (!knownReplies.contains(reply.getId())) {
1143 coreListenerManager.fireNewReplyFound(reply);
1146 replies.put(reply.getId(), reply);
1150 synchronized (albums) {
1151 synchronized (images) {
1152 for (Album album : storedSone.getAlbums()) {
1153 albums.remove(album.getId());
1154 for (Image image : album.getImages()) {
1155 images.remove(image.getId());
1158 for (Album album : sone.getAlbums()) {
1159 albums.put(album.getId(), album);
1160 for (Image image : album.getImages()) {
1161 images.put(image.getId(), image);
1166 synchronized (storedSone) {
1167 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1168 storedSone.setTime(sone.getTime());
1170 storedSone.setClient(sone.getClient());
1171 storedSone.setProfile(sone.getProfile());
1172 if (soneRescueMode) {
1173 for (Post post : sone.getPosts()) {
1174 storedSone.addPost(post);
1176 for (PostReply reply : sone.getReplies()) {
1177 storedSone.addReply(reply);
1179 for (String likedPostId : sone.getLikedPostIds()) {
1180 storedSone.addLikedPostId(likedPostId);
1182 for (String likedReplyId : sone.getLikedReplyIds()) {
1183 storedSone.addLikedReplyId(likedReplyId);
1185 for (Album album : sone.getAlbums()) {
1186 storedSone.addAlbum(album);
1189 storedSone.setPosts(sone.getPosts());
1190 storedSone.setReplies(sone.getReplies());
1191 storedSone.setLikePostIds(sone.getLikedPostIds());
1192 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1193 storedSone.setAlbums(sone.getAlbums());
1195 storedSone.setLatestEdition(sone.getLatestEdition());
1201 * Deletes the given Sone. This will remove the Sone from the
1202 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1203 * remove the context from its identity.
1206 * The Sone to delete
1208 public void deleteSone(Sone sone) {
1209 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1210 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1213 synchronized (sones) {
1214 if (!getLocalSones().contains(sone)) {
1215 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1218 sones.remove(sone.getId());
1219 SoneInserter soneInserter = soneInserters.remove(sone);
1220 soneInserter.removeSoneInsertListener(this);
1221 soneInserter.stop();
1223 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1224 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1226 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1227 } catch (ConfigurationException ce1) {
1228 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1233 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1234 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1237 * The Sone to mark as known
1239 public void markSoneKnown(Sone sone) {
1240 if (!sone.isKnown()) {
1241 sone.setKnown(true);
1242 synchronized (knownSones) {
1243 knownSones.add(sone.getId());
1245 coreListenerManager.fireMarkSoneKnown(sone);
1246 touchConfiguration();
1251 * Loads and updates the given Sone from the configuration. If any error is
1252 * encountered, loading is aborted and the given Sone is not changed.
1255 * The Sone to load and update
1257 public void loadSone(Sone sone) {
1258 if (!sone.isLocal()) {
1259 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1263 /* initialize options. */
1264 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1265 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1266 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1267 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1268 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1269 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1272 String sonePrefix = "Sone/" + sone.getId();
1273 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1274 if (soneTime == null) {
1275 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1278 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1281 Profile profile = new Profile(sone);
1282 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1283 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1284 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1285 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1286 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1287 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1289 /* load profile fields. */
1291 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1292 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1293 if (fieldName == null) {
1296 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1297 profile.addField(fieldName).setValue(fieldValue);
1301 Set<Post> posts = new HashSet<Post>();
1303 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1304 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1305 if (postId == null) {
1308 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1309 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1310 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1311 if ((postTime == 0) || (postText == null)) {
1312 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1315 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1316 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1317 post.setRecipient(getSone(postRecipientId));
1323 Set<PostReply> replies = new HashSet<PostReply>();
1325 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1326 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1327 if (replyId == null) {
1330 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1331 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1332 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1333 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1334 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1337 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1340 /* load post likes. */
1341 Set<String> likedPostIds = new HashSet<String>();
1343 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1344 if (likedPostId == null) {
1347 likedPostIds.add(likedPostId);
1350 /* load reply likes. */
1351 Set<String> likedReplyIds = new HashSet<String>();
1353 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1354 if (likedReplyId == null) {
1357 likedReplyIds.add(likedReplyId);
1361 Set<String> friends = new HashSet<String>();
1363 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1364 if (friendId == null) {
1367 friends.add(friendId);
1371 List<Album> topLevelAlbums = new ArrayList<Album>();
1372 int albumCounter = 0;
1374 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1375 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1376 if (albumId == null) {
1379 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1380 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1381 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1382 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1383 if ((albumTitle == null) || (albumDescription == null)) {
1384 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1387 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1388 if (albumParentId != null) {
1389 Album parentAlbum = getAlbum(albumParentId, false);
1390 if (parentAlbum == null) {
1391 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1394 parentAlbum.addAlbum(album);
1396 if (!topLevelAlbums.contains(album)) {
1397 topLevelAlbums.add(album);
1403 int imageCounter = 0;
1405 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1406 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1407 if (imageId == null) {
1410 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1411 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1412 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1413 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1414 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1415 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1416 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1417 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1418 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1421 Album album = getAlbum(albumId, false);
1422 if (album == null) {
1423 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1426 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1427 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1428 album.addImage(image);
1432 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1433 if (avatarId != null) {
1434 profile.setAvatar(getImage(avatarId, false));
1438 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1439 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1440 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1441 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1442 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1443 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1445 /* if we’re still here, Sone was loaded successfully. */
1446 synchronized (sone) {
1447 sone.setTime(soneTime);
1448 sone.setProfile(profile);
1449 sone.setPosts(posts);
1450 sone.setReplies(replies);
1451 sone.setLikePostIds(likedPostIds);
1452 sone.setLikeReplyIds(likedReplyIds);
1453 for (String friendId : friends) {
1454 followSone(sone, friendId);
1456 sone.setAlbums(topLevelAlbums);
1457 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1459 synchronized (knownSones) {
1460 for (String friend : friends) {
1461 knownSones.add(friend);
1464 synchronized (knownPosts) {
1465 for (Post post : posts) {
1466 knownPosts.add(post.getId());
1469 synchronized (knownReplies) {
1470 for (PostReply reply : replies) {
1471 knownReplies.add(reply.getId());
1477 * Creates a new post.
1480 * The Sone that creates the post
1482 * The text of the post
1483 * @return The created post
1485 public Post createPost(Sone sone, String text) {
1486 return createPost(sone, System.currentTimeMillis(), text);
1490 * Creates a new post.
1493 * The Sone that creates the post
1495 * The time of the post
1497 * The text of the post
1498 * @return The created post
1500 public Post createPost(Sone sone, long time, String text) {
1501 return createPost(sone, null, time, text);
1505 * Creates a new post.
1508 * The Sone that creates the post
1510 * The recipient Sone, or {@code null} if this post does not have
1513 * The text of the post
1514 * @return The created post
1516 public Post createPost(Sone sone, Sone recipient, String text) {
1517 return createPost(sone, recipient, System.currentTimeMillis(), text);
1521 * Creates a new post.
1524 * The Sone that creates the post
1526 * The recipient Sone, or {@code null} if this post does not have
1529 * The time of the post
1531 * The text of the post
1532 * @return The created post
1534 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1535 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1536 if (!sone.isLocal()) {
1537 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1540 final Post post = new PostImpl(sone, time, text);
1541 if (recipient != null) {
1542 post.setRecipient(recipient);
1544 synchronized (posts) {
1545 posts.put(post.getId(), post);
1547 eventBus.post(new NewPostFoundEvent(post));
1549 touchConfiguration();
1550 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1557 markPostKnown(post);
1559 }, "Mark " + post + " read.");
1564 * Deletes the given post.
1567 * The post to delete
1569 public void deletePost(Post post) {
1570 if (!post.getSone().isLocal()) {
1571 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1574 post.getSone().removePost(post);
1575 synchronized (posts) {
1576 posts.remove(post.getId());
1578 coreListenerManager.firePostRemoved(post);
1579 markPostKnown(post);
1580 touchConfiguration();
1584 * Marks the given post as known, if it is currently not a known post
1585 * (according to {@link Post#isKnown()}).
1588 * The post to mark as known
1590 public void markPostKnown(Post post) {
1591 post.setKnown(true);
1592 synchronized (knownPosts) {
1593 coreListenerManager.fireMarkPostKnown(post);
1594 if (knownPosts.add(post.getId())) {
1595 touchConfiguration();
1598 for (PostReply reply : getReplies(post)) {
1599 markReplyKnown(reply);
1604 * Bookmarks the given post.
1607 * The post to bookmark
1609 public void bookmark(Post post) {
1610 bookmarkPost(post.getId());
1614 * Bookmarks the post with the given ID.
1617 * The ID of the post to bookmark
1619 public void bookmarkPost(String id) {
1620 synchronized (bookmarkedPosts) {
1621 bookmarkedPosts.add(id);
1626 * Removes the given post from the bookmarks.
1629 * The post to unbookmark
1631 public void unbookmark(Post post) {
1632 unbookmarkPost(post.getId());
1636 * Removes the post with the given ID from the bookmarks.
1639 * The ID of the post to unbookmark
1641 public void unbookmarkPost(String id) {
1642 synchronized (bookmarkedPosts) {
1643 bookmarkedPosts.remove(id);
1648 * Creates a new reply.
1651 * The Sone that creates the reply
1653 * The post that this reply refers to
1655 * The text of the reply
1656 * @return The created reply
1658 public PostReply createReply(Sone sone, Post post, String text) {
1659 return createReply(sone, post, System.currentTimeMillis(), text);
1663 * Creates a new reply.
1666 * The Sone that creates the reply
1668 * The post that this reply refers to
1670 * The time of the reply
1672 * The text of the reply
1673 * @return The created reply
1675 public PostReply createReply(Sone sone, Post post, long time, String text) {
1676 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1677 if (!sone.isLocal()) {
1678 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1681 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1682 synchronized (replies) {
1683 replies.put(reply.getId(), reply);
1685 synchronized (knownReplies) {
1686 coreListenerManager.fireNewReplyFound(reply);
1688 sone.addReply(reply);
1689 touchConfiguration();
1690 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1697 markReplyKnown(reply);
1699 }, "Mark " + reply + " read.");
1704 * Deletes the given reply.
1707 * The reply to delete
1709 public void deleteReply(PostReply reply) {
1710 Sone sone = reply.getSone();
1711 if (!sone.isLocal()) {
1712 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1715 synchronized (replies) {
1716 replies.remove(reply.getId());
1718 synchronized (knownReplies) {
1719 markReplyKnown(reply);
1720 knownReplies.remove(reply.getId());
1722 sone.removeReply(reply);
1723 touchConfiguration();
1727 * Marks the given reply as known, if it is currently not a known reply
1728 * (according to {@link Reply#isKnown()}).
1731 * The reply to mark as known
1733 public void markReplyKnown(PostReply reply) {
1734 reply.setKnown(true);
1735 synchronized (knownReplies) {
1736 coreListenerManager.fireMarkReplyKnown(reply);
1737 if (knownReplies.add(reply.getId())) {
1738 touchConfiguration();
1744 * Creates a new top-level album for the given Sone.
1747 * The Sone to create the album for
1748 * @return The new album
1750 public Album createAlbum(Sone sone) {
1751 return createAlbum(sone, null);
1755 * Creates a new album for the given Sone.
1758 * The Sone to create the album for
1760 * The parent of the album (may be {@code null} to create a
1762 * @return The new album
1764 public Album createAlbum(Sone sone, Album parent) {
1765 Album album = new Album();
1766 synchronized (albums) {
1767 albums.put(album.getId(), album);
1769 album.setSone(sone);
1770 if (parent != null) {
1771 parent.addAlbum(album);
1773 sone.addAlbum(album);
1779 * Deletes the given album. The owner of the album has to be a local Sone,
1780 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1783 * The album to remove
1785 public void deleteAlbum(Album album) {
1786 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1787 if (!album.isEmpty()) {
1790 if (album.getParent() == null) {
1791 album.getSone().removeAlbum(album);
1793 album.getParent().removeAlbum(album);
1795 synchronized (albums) {
1796 albums.remove(album.getId());
1798 touchConfiguration();
1802 * Creates a new image.
1805 * The Sone creating the image
1807 * The album the image will be inserted into
1808 * @param temporaryImage
1809 * The temporary image to create the image from
1810 * @return The newly created image
1812 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1813 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();
1814 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1815 album.addImage(image);
1816 synchronized (images) {
1817 images.put(image.getId(), image);
1819 imageInserter.insertImage(temporaryImage, image);
1824 * Deletes the given image. This method will also delete a matching
1827 * @see #deleteTemporaryImage(TemporaryImage)
1829 * The image to delete
1831 public void deleteImage(Image image) {
1832 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1833 deleteTemporaryImage(image.getId());
1834 image.getAlbum().removeImage(image);
1835 synchronized (images) {
1836 images.remove(image.getId());
1838 touchConfiguration();
1842 * Creates a new temporary image.
1845 * The MIME type of the temporary image
1847 * The encoded data of the image
1848 * @return The temporary image
1850 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1851 TemporaryImage temporaryImage = new TemporaryImage();
1852 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1853 synchronized (temporaryImages) {
1854 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1856 return temporaryImage;
1860 * Deletes the given temporary image.
1862 * @param temporaryImage
1863 * The temporary image to delete
1865 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1866 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1867 deleteTemporaryImage(temporaryImage.getId());
1871 * Deletes the temporary image with the given ID.
1874 * The ID of the temporary image to delete
1876 public void deleteTemporaryImage(String imageId) {
1877 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1878 synchronized (temporaryImages) {
1879 temporaryImages.remove(imageId);
1881 Image image = getImage(imageId, false);
1882 if (image != null) {
1883 imageInserter.cancelImageInsert(image);
1888 * Notifies the core that the configuration, either of the core or of a
1889 * single local Sone, has changed, and that the configuration should be
1892 public void touchConfiguration() {
1893 lastConfigurationUpdate = System.currentTimeMillis();
1904 public void serviceStart() {
1905 loadConfiguration();
1906 updateChecker.addUpdateListener(this);
1907 updateChecker.start();
1908 identityManager.addIdentityListener(this);
1909 identityManager.start();
1910 webOfTrustUpdater.init();
1911 webOfTrustUpdater.start();
1918 public void serviceRun() {
1919 long lastSaved = System.currentTimeMillis();
1920 while (!shouldStop()) {
1922 long now = System.currentTimeMillis();
1923 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1924 for (Sone localSone : getLocalSones()) {
1925 saveSone(localSone);
1927 saveConfiguration();
1937 public void serviceStop() {
1938 synchronized (sones) {
1939 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1940 soneInserter.getValue().removeSoneInsertListener(this);
1941 soneInserter.getValue().stop();
1942 saveSone(soneInserter.getKey());
1945 saveConfiguration();
1946 webOfTrustUpdater.stop();
1947 updateChecker.stop();
1948 updateChecker.removeUpdateListener(this);
1949 soneDownloader.stop();
1950 identityManager.removeIdentityListener(this);
1951 identityManager.stop();
1959 * Saves the given Sone. This will persist all local settings for the given
1960 * Sone, such as the friends list and similar, private options.
1965 private synchronized void saveSone(Sone sone) {
1966 if (!sone.isLocal()) {
1967 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1970 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1971 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1975 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1977 /* save Sone into configuration. */
1978 String sonePrefix = "Sone/" + sone.getId();
1979 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1980 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1983 Profile profile = sone.getProfile();
1984 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1985 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1986 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1987 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1988 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1989 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1990 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1992 /* save profile fields. */
1993 int fieldCounter = 0;
1994 for (Field profileField : profile.getFields()) {
1995 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1996 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1997 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1999 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2002 int postCounter = 0;
2003 for (Post post : sone.getPosts()) {
2004 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2005 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2006 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2007 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2008 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2010 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2013 int replyCounter = 0;
2014 for (PostReply reply : sone.getReplies()) {
2015 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2016 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2017 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2018 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2019 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2021 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2023 /* save post likes. */
2024 int postLikeCounter = 0;
2025 for (String postId : sone.getLikedPostIds()) {
2026 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2028 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2030 /* save reply likes. */
2031 int replyLikeCounter = 0;
2032 for (String replyId : sone.getLikedReplyIds()) {
2033 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2035 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2038 int friendCounter = 0;
2039 for (String friendId : sone.getFriends()) {
2040 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2042 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2044 /* save albums. first, collect in a flat structure, top-level first. */
2045 List<Album> albums = sone.getAllAlbums();
2047 int albumCounter = 0;
2048 for (Album album : albums) {
2049 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2050 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2051 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2052 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2053 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2054 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2056 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2059 int imageCounter = 0;
2060 for (Album album : albums) {
2061 for (Image image : album.getImages()) {
2062 if (!image.isInserted()) {
2065 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2066 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2067 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2068 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2069 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2070 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2071 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2072 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2073 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2076 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2079 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2080 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2081 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2082 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2083 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2084 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2086 configuration.save();
2088 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2090 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2091 } catch (ConfigurationException ce1) {
2092 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2097 * Saves the current options.
2099 private void saveConfiguration() {
2100 synchronized (configuration) {
2101 if (storingConfiguration) {
2102 logger.log(Level.FINE, "Already storing configuration…");
2105 storingConfiguration = true;
2108 /* store the options first. */
2110 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2111 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2112 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2113 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2114 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2115 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2116 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2117 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2118 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2119 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2120 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2121 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2123 /* save known Sones. */
2124 int soneCounter = 0;
2125 synchronized (knownSones) {
2126 for (String knownSoneId : knownSones) {
2127 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2129 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2132 /* save Sone following times. */
2134 synchronized (soneFollowingTimes) {
2135 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2136 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2137 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2140 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2143 /* save known posts. */
2144 int postCounter = 0;
2145 synchronized (knownPosts) {
2146 for (String knownPostId : knownPosts) {
2147 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2149 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2152 /* save known replies. */
2153 int replyCounter = 0;
2154 synchronized (knownReplies) {
2155 for (String knownReplyId : knownReplies) {
2156 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2158 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2161 /* save bookmarked posts. */
2162 int bookmarkedPostCounter = 0;
2163 synchronized (bookmarkedPosts) {
2164 for (String bookmarkedPostId : bookmarkedPosts) {
2165 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2168 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2171 configuration.save();
2173 } catch (ConfigurationException ce1) {
2174 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2176 synchronized (configuration) {
2177 storingConfiguration = false;
2183 * Loads the configuration.
2185 @SuppressWarnings("unchecked")
2186 private void loadConfiguration() {
2187 /* create options. */
2188 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2191 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2192 SoneInserter.setInsertionDelay(newValue);
2196 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2197 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2198 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2199 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2200 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2201 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2202 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2203 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2204 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2207 @SuppressWarnings("synthetic-access")
2208 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2209 fcpInterface.setActive(newValue);
2212 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2215 @SuppressWarnings("synthetic-access")
2216 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2217 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2222 loadConfigurationValue("InsertionDelay");
2223 loadConfigurationValue("PostsPerPage");
2224 loadConfigurationValue("ImagesPerPage");
2225 loadConfigurationValue("CharactersPerPost");
2226 loadConfigurationValue("PostCutOffLength");
2227 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2228 loadConfigurationValue("PositiveTrust");
2229 loadConfigurationValue("NegativeTrust");
2230 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2231 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2232 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2234 /* load known Sones. */
2235 int soneCounter = 0;
2237 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2238 if (knownSoneId == null) {
2241 synchronized (knownSones) {
2242 knownSones.add(knownSoneId);
2246 /* load Sone following times. */
2249 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2250 if (soneId == null) {
2253 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2254 Sone followedSone = getSone(soneId);
2255 if (followedSone == null) {
2256 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2258 synchronized (soneFollowingTimes) {
2259 soneFollowingTimes.put(getSone(soneId), time);
2265 /* load known posts. */
2266 int postCounter = 0;
2268 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2269 if (knownPostId == null) {
2272 synchronized (knownPosts) {
2273 knownPosts.add(knownPostId);
2277 /* load known replies. */
2278 int replyCounter = 0;
2280 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2281 if (knownReplyId == null) {
2284 synchronized (knownReplies) {
2285 knownReplies.add(knownReplyId);
2289 /* load bookmarked posts. */
2290 int bookmarkedPostCounter = 0;
2292 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2293 if (bookmarkedPostId == null) {
2296 synchronized (bookmarkedPosts) {
2297 bookmarkedPosts.add(bookmarkedPostId);
2304 * Loads an {@link Integer} configuration value for the option with the
2305 * given name, logging validation failures.
2308 * The name of the option to load
2310 private void loadConfigurationValue(String optionName) {
2312 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2313 } catch (IllegalArgumentException iae1) {
2314 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2319 * Generate a Sone URI from the given URI and latest edition.
2322 * The URI to derive the Sone URI from
2323 * @return The derived URI
2325 private static FreenetURI getSoneUri(String uriString) {
2327 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2329 } catch (MalformedURLException mue1) {
2330 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2336 // INTERFACE IdentityListener
2343 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2344 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2345 if (ownIdentity.hasContext("Sone")) {
2346 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2347 addLocalSone(ownIdentity);
2355 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2356 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2357 trustedIdentities.remove(ownIdentity);
2364 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2365 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2366 trustedIdentities.get(ownIdentity).add(identity);
2367 addRemoteSone(identity);
2374 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2375 soneDownloaders.execute(new Runnable() {
2378 @SuppressWarnings("synthetic-access")
2380 Sone sone = getRemoteSone(identity.getId(), false);
2381 sone.setIdentity(identity);
2382 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2383 soneDownloader.addSone(sone);
2384 soneDownloader.fetchSone(sone);
2393 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2394 trustedIdentities.get(ownIdentity).remove(identity);
2395 boolean foundIdentity = false;
2396 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2397 if (trustedIdentity.getKey().equals(ownIdentity)) {
2400 if (trustedIdentity.getValue().contains(identity)) {
2401 foundIdentity = true;
2404 if (foundIdentity) {
2405 /* some local identity still trusts this identity, don’t remove. */
2408 Sone sone = getSone(identity.getId(), false);
2410 /* TODO - we don’t have the Sone anymore. should this happen? */
2413 synchronized (posts) {
2414 synchronized (knownPosts) {
2415 for (Post post : sone.getPosts()) {
2416 posts.remove(post.getId());
2417 coreListenerManager.firePostRemoved(post);
2421 synchronized (replies) {
2422 synchronized (knownReplies) {
2423 for (PostReply reply : sone.getReplies()) {
2424 replies.remove(reply.getId());
2425 coreListenerManager.fireReplyRemoved(reply);
2429 synchronized (sones) {
2430 sones.remove(identity.getId());
2432 coreListenerManager.fireSoneRemoved(sone);
2436 // INTERFACE UpdateListener
2443 public void updateFound(Version version, long releaseTime, long latestEdition) {
2444 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2448 // INTERFACE ImageInsertListener
2455 public void insertStarted(Sone sone) {
2456 coreListenerManager.fireSoneInserting(sone);
2463 public void insertFinished(Sone sone, long insertDuration) {
2464 coreListenerManager.fireSoneInserted(sone, insertDuration);
2471 public void insertAborted(Sone sone, Throwable cause) {
2472 coreListenerManager.fireSoneInsertAborted(sone, cause);
2476 // SONEINSERTLISTENER METHODS
2483 public void imageInsertStarted(Image image) {
2484 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2485 coreListenerManager.fireImageInsertStarted(image);
2492 public void imageInsertAborted(Image image) {
2493 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2494 coreListenerManager.fireImageInsertAborted(image);
2501 public void imageInsertFinished(Image image, FreenetURI key) {
2502 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2503 image.setKey(key.toString());
2504 deleteTemporaryImage(image.getId());
2505 touchConfiguration();
2506 coreListenerManager.fireImageInsertFinished(image);
2513 public void imageInsertFailed(Image image, Throwable cause) {
2514 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2515 coreListenerManager.fireImageInsertFailed(image, cause);
2519 * Convenience interface for external classes that want to access the core’s
2522 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2524 public static class Preferences {
2526 /** The wrapped options. */
2527 private final Options options;
2530 * Creates a new preferences object wrapped around the given options.
2533 * The options to wrap
2535 public Preferences(Options options) {
2536 this.options = options;
2540 * Returns the insertion delay.
2542 * @return The insertion delay
2544 public int getInsertionDelay() {
2545 return options.getIntegerOption("InsertionDelay").get();
2549 * Validates the given insertion delay.
2551 * @param insertionDelay
2552 * The insertion delay to validate
2553 * @return {@code true} if the given insertion delay was valid,
2554 * {@code false} otherwise
2556 public boolean validateInsertionDelay(Integer insertionDelay) {
2557 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2561 * Sets the insertion delay
2563 * @param insertionDelay
2564 * The new insertion delay, or {@code null} to restore it to
2566 * @return This preferences
2568 public Preferences setInsertionDelay(Integer insertionDelay) {
2569 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2574 * Returns the number of posts to show per page.
2576 * @return The number of posts to show per page
2578 public int getPostsPerPage() {
2579 return options.getIntegerOption("PostsPerPage").get();
2583 * Validates the number of posts per page.
2585 * @param postsPerPage
2586 * The number of posts per page
2587 * @return {@code true} if the number of posts per page was valid,
2588 * {@code false} otherwise
2590 public boolean validatePostsPerPage(Integer postsPerPage) {
2591 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2595 * Sets the number of posts to show per page.
2597 * @param postsPerPage
2598 * The number of posts to show per page
2599 * @return This preferences object
2601 public Preferences setPostsPerPage(Integer postsPerPage) {
2602 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2607 * Returns the number of images to show per page.
2609 * @return The number of images to show per page
2611 public int getImagesPerPage() {
2612 return options.getIntegerOption("ImagesPerPage").get();
2616 * Validates the number of images per page.
2618 * @param imagesPerPage
2619 * The number of images per page
2620 * @return {@code true} if the number of images per page was valid,
2621 * {@code false} otherwise
2623 public boolean validateImagesPerPage(Integer imagesPerPage) {
2624 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2628 * Sets the number of images per page.
2630 * @param imagesPerPage
2631 * The number of images per page
2632 * @return This preferences object
2634 public Preferences setImagesPerPage(Integer imagesPerPage) {
2635 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2640 * Returns the number of characters per post, or <code>-1</code> if the
2641 * posts should not be cut off.
2643 * @return The numbers of characters per post
2645 public int getCharactersPerPost() {
2646 return options.getIntegerOption("CharactersPerPost").get();
2650 * Validates the number of characters per post.
2652 * @param charactersPerPost
2653 * The number of characters per post
2654 * @return {@code true} if the number of characters per post was valid,
2655 * {@code false} otherwise
2657 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2658 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2662 * Sets the number of characters per post.
2664 * @param charactersPerPost
2665 * The number of characters per post, or <code>-1</code> to
2666 * not cut off the posts
2667 * @return This preferences objects
2669 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2670 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2675 * Returns the number of characters the shortened post should have.
2677 * @return The number of characters of the snippet
2679 public int getPostCutOffLength() {
2680 return options.getIntegerOption("PostCutOffLength").get();
2684 * Validates the number of characters after which to cut off the post.
2686 * @param postCutOffLength
2687 * The number of characters of the snippet
2688 * @return {@code true} if the number of characters of the snippet is
2689 * valid, {@code false} otherwise
2691 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2692 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2696 * Sets the number of characters the shortened post should have.
2698 * @param postCutOffLength
2699 * The number of characters of the snippet
2700 * @return This preferences
2702 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2703 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2708 * Returns whether Sone requires full access to be even visible.
2710 * @return {@code true} if Sone requires full access, {@code false}
2713 public boolean isRequireFullAccess() {
2714 return options.getBooleanOption("RequireFullAccess").get();
2718 * Sets whether Sone requires full access to be even visible.
2720 * @param requireFullAccess
2721 * {@code true} if Sone requires full access, {@code false}
2724 public void setRequireFullAccess(Boolean requireFullAccess) {
2725 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2729 * Returns the positive trust.
2731 * @return The positive trust
2733 public int getPositiveTrust() {
2734 return options.getIntegerOption("PositiveTrust").get();
2738 * Validates the positive trust.
2740 * @param positiveTrust
2741 * The positive trust to validate
2742 * @return {@code true} if the positive trust was valid, {@code false}
2745 public boolean validatePositiveTrust(Integer positiveTrust) {
2746 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2750 * Sets the positive trust.
2752 * @param positiveTrust
2753 * The new positive trust, or {@code null} to restore it to
2755 * @return This preferences
2757 public Preferences setPositiveTrust(Integer positiveTrust) {
2758 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2763 * Returns the negative trust.
2765 * @return The negative trust
2767 public int getNegativeTrust() {
2768 return options.getIntegerOption("NegativeTrust").get();
2772 * Validates the negative trust.
2774 * @param negativeTrust
2775 * The negative trust to validate
2776 * @return {@code true} if the negative trust was valid, {@code false}
2779 public boolean validateNegativeTrust(Integer negativeTrust) {
2780 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2784 * Sets the negative trust.
2786 * @param negativeTrust
2787 * The negative trust, or {@code null} to restore it to the
2789 * @return The preferences
2791 public Preferences setNegativeTrust(Integer negativeTrust) {
2792 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2797 * Returns the trust comment. This is the comment that is set in the web
2798 * of trust when a trust value is assigned to an identity.
2800 * @return The trust comment
2802 public String getTrustComment() {
2803 return options.getStringOption("TrustComment").get();
2807 * Sets the trust comment.
2809 * @param trustComment
2810 * The trust comment, or {@code null} to restore it to the
2812 * @return This preferences
2814 public Preferences setTrustComment(String trustComment) {
2815 options.getStringOption("TrustComment").set(trustComment);
2820 * Returns whether the {@link FcpInterface FCP interface} is currently
2823 * @see FcpInterface#setActive(boolean)
2824 * @return {@code true} if the FCP interface is currently active,
2825 * {@code false} otherwise
2827 public boolean isFcpInterfaceActive() {
2828 return options.getBooleanOption("ActivateFcpInterface").get();
2832 * Sets whether the {@link FcpInterface FCP interface} is currently
2835 * @see FcpInterface#setActive(boolean)
2836 * @param fcpInterfaceActive
2837 * {@code true} to activate the FCP interface, {@code false}
2838 * to deactivate the FCP interface
2839 * @return This preferences object
2841 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2842 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2847 * Returns the action level for which full access to the FCP interface
2850 * @return The action level for which full access to the FCP interface
2853 public FullAccessRequired getFcpFullAccessRequired() {
2854 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2858 * Sets the action level for which full access to the FCP interface is
2861 * @param fcpFullAccessRequired
2863 * @return This preferences
2865 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2866 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);