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.NewPostReplyFoundEvent;
40 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
41 import net.pterodactylus.sone.data.Album;
42 import net.pterodactylus.sone.data.Client;
43 import net.pterodactylus.sone.data.Image;
44 import net.pterodactylus.sone.data.Post;
45 import net.pterodactylus.sone.data.PostReply;
46 import net.pterodactylus.sone.data.Profile;
47 import net.pterodactylus.sone.data.Profile.Field;
48 import net.pterodactylus.sone.data.Reply;
49 import net.pterodactylus.sone.data.Sone;
50 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
51 import net.pterodactylus.sone.data.Sone.SoneStatus;
52 import net.pterodactylus.sone.data.TemporaryImage;
53 import net.pterodactylus.sone.data.impl.PostImpl;
54 import net.pterodactylus.sone.fcp.FcpInterface;
55 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
56 import net.pterodactylus.sone.freenet.wot.Identity;
57 import net.pterodactylus.sone.freenet.wot.IdentityListener;
58 import net.pterodactylus.sone.freenet.wot.IdentityManager;
59 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
60 import net.pterodactylus.sone.main.SonePlugin;
61 import net.pterodactylus.util.config.Configuration;
62 import net.pterodactylus.util.config.ConfigurationException;
63 import net.pterodactylus.util.logging.Logging;
64 import net.pterodactylus.util.number.Numbers;
65 import net.pterodactylus.util.service.AbstractService;
66 import net.pterodactylus.util.thread.NamedThreadFactory;
67 import net.pterodactylus.util.thread.Ticker;
68 import net.pterodactylus.util.validation.EqualityValidator;
69 import net.pterodactylus.util.validation.IntegerRangeValidator;
70 import net.pterodactylus.util.validation.OrValidator;
71 import net.pterodactylus.util.validation.Validation;
72 import net.pterodactylus.util.version.Version;
74 import com.google.common.base.Predicate;
75 import com.google.common.collect.Collections2;
76 import com.google.common.eventbus.EventBus;
77 import com.google.inject.Inject;
79 import freenet.keys.FreenetURI;
84 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
86 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
89 private static final Logger logger = Logging.getLogger(Core.class);
91 /** The start time. */
92 private final long startupTime = System.currentTimeMillis();
95 private final Options options = new Options();
97 /** The preferences. */
98 private final Preferences preferences = new Preferences(options);
100 /** The core listener manager. */
101 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
103 /** The event bus. */
104 private final EventBus eventBus;
106 /** The configuration. */
107 private Configuration configuration;
109 /** Whether we’re currently saving the configuration. */
110 private boolean storingConfiguration = false;
112 /** The identity manager. */
113 private final IdentityManager identityManager;
115 /** Interface to freenet. */
116 private final FreenetInterface freenetInterface;
118 /** The Sone downloader. */
119 private final SoneDownloader soneDownloader;
121 /** The image inserter. */
122 private final ImageInserter imageInserter;
124 /** Sone downloader thread-pool. */
125 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
127 /** The update checker. */
128 private final UpdateChecker updateChecker;
130 /** The trust updater. */
131 private final WebOfTrustUpdater webOfTrustUpdater;
133 /** The FCP interface. */
134 private volatile FcpInterface fcpInterface;
136 /** The times Sones were followed. */
137 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
139 /** Locked local Sones. */
140 /* synchronize on itself. */
141 private final Set<Sone> lockedSones = new HashSet<Sone>();
143 /** Sone inserters. */
144 /* synchronize access on this on sones. */
145 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
147 /** Sone rescuers. */
148 /* synchronize access on this on sones. */
149 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
152 /* synchronize access on this on itself. */
153 private final Map<String, Sone> sones = new HashMap<String, Sone>();
155 /** All known Sones. */
156 private final Set<String> knownSones = new HashSet<String>();
159 private final Map<String, Post> posts = new HashMap<String, Post>();
161 /** All known posts. */
162 private final Set<String> knownPosts = new HashSet<String>();
165 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
167 /** All known replies. */
168 private final Set<String> knownReplies = new HashSet<String>();
170 /** All bookmarked posts. */
171 /* synchronize access on itself. */
172 private final Set<String> bookmarkedPosts = new HashSet<String>();
174 /** Trusted identities, sorted by own identities. */
175 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
177 /** All known albums. */
178 private final Map<String, Album> albums = new HashMap<String, Album>();
180 /** All known images. */
181 private final Map<String, Image> images = new HashMap<String, Image>();
183 /** All temporary images. */
184 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
186 /** Ticker for threads that mark own elements as known. */
187 private final Ticker localElementTicker = new Ticker();
189 /** The time the configuration was last touched. */
190 private volatile long lastConfigurationUpdate;
193 * Creates a new core.
195 * @param configuration
196 * The configuration of the core
197 * @param freenetInterface
198 * The freenet interface
199 * @param identityManager
200 * The identity manager
201 * @param webOfTrustUpdater
202 * The WebOfTrust updater
207 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
209 this.configuration = configuration;
210 this.freenetInterface = freenetInterface;
211 this.identityManager = identityManager;
212 this.soneDownloader = new SoneDownloader(this, freenetInterface);
213 this.imageInserter = new ImageInserter(this, freenetInterface);
214 this.updateChecker = new UpdateChecker(freenetInterface);
215 this.webOfTrustUpdater = webOfTrustUpdater;
216 this.eventBus = eventBus;
220 // LISTENER MANAGEMENT
224 * Adds a new core listener.
226 * @param coreListener
227 * The listener to add
229 public void addCoreListener(CoreListener coreListener) {
230 coreListenerManager.addListener(coreListener);
234 * Removes a core listener.
236 * @param coreListener
237 * The listener to remove
239 public void removeCoreListener(CoreListener coreListener) {
240 coreListenerManager.removeListener(coreListener);
248 * Returns the time Sone was started.
250 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
252 public long getStartupTime() {
257 * Sets the configuration to use. This will automatically save the current
258 * configuration to the given configuration.
260 * @param configuration
261 * The new configuration to use
263 public void setConfiguration(Configuration configuration) {
264 this.configuration = configuration;
265 touchConfiguration();
269 * Returns the options used by the core.
271 * @return The options of the core
273 public Preferences getPreferences() {
278 * Returns the identity manager used by the core.
280 * @return The identity manager
282 public IdentityManager getIdentityManager() {
283 return identityManager;
287 * Returns the update checker.
289 * @return The update checker
291 public UpdateChecker getUpdateChecker() {
292 return updateChecker;
296 * Sets the FCP interface to use.
298 * @param fcpInterface
299 * The FCP interface to use
301 public void setFcpInterface(FcpInterface fcpInterface) {
302 this.fcpInterface = fcpInterface;
306 * Returns the Sone rescuer for the given local Sone.
309 * The local Sone to get the rescuer for
310 * @return The Sone rescuer for the given Sone
312 public SoneRescuer getSoneRescuer(Sone sone) {
313 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
314 synchronized (sones) {
315 SoneRescuer soneRescuer = soneRescuers.get(sone);
316 if (soneRescuer == null) {
317 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
318 soneRescuers.put(sone, soneRescuer);
326 * Returns whether the given Sone is currently locked.
330 * @return {@code true} if the Sone is locked, {@code false} if it is not
332 public boolean isLocked(Sone sone) {
333 synchronized (lockedSones) {
334 return lockedSones.contains(sone);
339 * Returns all Sones, remote and local.
343 public Set<Sone> getSones() {
344 return new HashSet<Sone>(sones.values());
348 * Returns the Sone with the given ID, regardless whether it’s local or
352 * The ID of the Sone to get
353 * @return The Sone with the given ID, or {@code null} if there is no such
356 public Sone getSone(String id) {
357 return getSone(id, true);
361 * Returns the Sone with the given ID, regardless whether it’s local or
365 * The ID of the Sone to get
367 * {@code true} to create a new Sone if none exists,
368 * {@code false} to return {@code null} if a Sone with the given
370 * @return The Sone with the given ID, or {@code null} if there is no such
374 public Sone getSone(String id, boolean create) {
375 synchronized (sones) {
376 if (!sones.containsKey(id)) {
377 Sone sone = new Sone(id, false);
380 return sones.get(id);
385 * Checks whether the core knows a Sone with the given ID.
389 * @return {@code true} if there is a Sone with the given ID, {@code false}
392 public boolean hasSone(String id) {
393 synchronized (sones) {
394 return sones.containsKey(id);
399 * Returns all local Sones.
401 * @return All local Sones
403 public Collection<Sone> getLocalSones() {
404 synchronized (sones) {
405 return Collections2.filter(sones.values(), new Predicate<Sone>() {
408 public boolean apply(Sone sone) {
409 return sone.isLocal();
416 * Returns the local Sone with the given ID, optionally creating a new Sone.
421 * {@code true} to create a new Sone if none exists,
422 * {@code false} to return null if none exists
423 * @return The Sone with the given ID, or {@code null}
425 public Sone getLocalSone(String id, boolean create) {
426 synchronized (sones) {
427 Sone sone = sones.get(id);
428 if ((sone == null) && create) {
429 sone = new Sone(id, true);
432 if ((sone != null) && !sone.isLocal()) {
433 sone = new Sone(id, true);
441 * Returns all remote Sones.
443 * @return All remote Sones
445 public Collection<Sone> getRemoteSones() {
446 synchronized (sones) {
447 return Collections2.filter(sones.values(), new Predicate<Sone>() {
450 public boolean apply(Sone sone) {
451 return !sone.isLocal();
458 * Returns the remote Sone with the given ID.
461 * The ID of the remote Sone to get
463 * {@code true} to always create a Sone, {@code false} to return
464 * {@code null} if no Sone with the given ID exists
465 * @return The Sone with the given ID
467 public Sone getRemoteSone(String id, boolean create) {
468 synchronized (sones) {
469 Sone sone = sones.get(id);
470 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
471 sone = new Sone(id, false);
479 * Returns whether the given Sone has been modified.
482 * The Sone to check for modifications
483 * @return {@code true} if a modification has been detected in the Sone,
484 * {@code false} otherwise
486 public boolean isModifiedSone(Sone sone) {
487 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
491 * Returns the time when the given was first followed by any local Sone.
494 * The Sone to get the time for
495 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
496 * been followed, or {@link Long#MAX_VALUE}
498 public long getSoneFollowingTime(Sone sone) {
499 synchronized (soneFollowingTimes) {
500 if (soneFollowingTimes.containsKey(sone)) {
501 return soneFollowingTimes.get(sone);
503 return Long.MAX_VALUE;
508 * Returns whether the target Sone is trusted by the origin Sone.
514 * @return {@code true} if the target Sone is trusted by the origin Sone
516 public boolean isSoneTrusted(Sone origin, Sone target) {
517 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
518 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
522 * Returns the post with the given ID.
525 * The ID of the post to get
526 * @return The post with the given ID, or a new post with the given ID
528 public Post getPost(String postId) {
529 return getPost(postId, true);
533 * Returns the post with the given ID, optionally creating a new post.
536 * The ID of the post to get
538 * {@code true} it create a new post if no post with the given ID
539 * exists, {@code false} to return {@code null}
540 * @return The post, or {@code null} if there is no such post
543 public Post getPost(String postId, boolean create) {
544 synchronized (posts) {
545 Post post = posts.get(postId);
546 if ((post == null) && create) {
547 post = new PostImpl(postId);
548 posts.put(postId, post);
555 * Returns all posts that have the given Sone as recipient.
557 * @see Post#getRecipient()
559 * The recipient of the posts
560 * @return All posts that have the given Sone as recipient
562 public Set<Post> getDirectedPosts(Sone recipient) {
563 Validation.begin().isNotNull("Recipient", recipient).check();
564 Set<Post> directedPosts = new HashSet<Post>();
565 synchronized (posts) {
566 for (Post post : posts.values()) {
567 if (recipient.equals(post.getRecipient())) {
568 directedPosts.add(post);
572 return directedPosts;
576 * Returns the reply with the given ID. If there is no reply with the given
577 * ID yet, a new one is created, unless {@code create} is false in which
578 * case {@code null} is returned.
581 * The ID of the reply to get
583 * {@code true} to always return a {@link Reply}, {@code false}
584 * to return {@code null} if no reply can be found
585 * @return The reply, or {@code null} if there is no such reply
587 public PostReply getPostReply(String replyId, boolean create) {
588 synchronized (replies) {
589 PostReply reply = replies.get(replyId);
590 if (create && (reply == null)) {
591 reply = new PostReply(replyId);
592 replies.put(replyId, reply);
599 * Returns all replies for the given post, order ascending by time.
602 * The post to get all replies for
603 * @return All replies for the given post
605 public List<PostReply> getReplies(Post post) {
606 Set<Sone> sones = getSones();
607 List<PostReply> replies = new ArrayList<PostReply>();
608 for (Sone sone : sones) {
609 for (PostReply reply : sone.getReplies()) {
610 if (reply.getPost().equals(post)) {
615 Collections.sort(replies, Reply.TIME_COMPARATOR);
620 * Returns all Sones that have liked the given post.
623 * The post to get the liking Sones for
624 * @return The Sones that like the given post
626 public Set<Sone> getLikes(Post post) {
627 Set<Sone> sones = new HashSet<Sone>();
628 for (Sone sone : getSones()) {
629 if (sone.getLikedPostIds().contains(post.getId())) {
637 * Returns all Sones that have liked the given reply.
640 * The reply to get the liking Sones for
641 * @return The Sones that like the given reply
643 public Set<Sone> getLikes(PostReply reply) {
644 Set<Sone> sones = new HashSet<Sone>();
645 for (Sone sone : getSones()) {
646 if (sone.getLikedReplyIds().contains(reply.getId())) {
654 * Returns whether the given post is bookmarked.
658 * @return {@code true} if the given post is bookmarked, {@code false}
661 public boolean isBookmarked(Post post) {
662 return isPostBookmarked(post.getId());
666 * Returns whether the post with the given ID is bookmarked.
669 * The ID of the post to check
670 * @return {@code true} if the post with the given ID is bookmarked,
671 * {@code false} otherwise
673 public boolean isPostBookmarked(String id) {
674 synchronized (bookmarkedPosts) {
675 return bookmarkedPosts.contains(id);
680 * Returns all currently known bookmarked posts.
682 * @return All bookmarked posts
684 public Set<Post> getBookmarkedPosts() {
685 Set<Post> posts = new HashSet<Post>();
686 synchronized (bookmarkedPosts) {
687 for (String bookmarkedPostId : bookmarkedPosts) {
688 Post post = getPost(bookmarkedPostId, false);
698 * Returns the album with the given ID, creating a new album if no album
699 * with the given ID can be found.
702 * The ID of the album
703 * @return The album with the given ID
705 public Album getAlbum(String albumId) {
706 return getAlbum(albumId, true);
710 * Returns the album with the given ID, optionally creating a new album if
711 * an album with the given ID can not be found.
714 * The ID of the album
716 * {@code true} to create a new album if none exists for the
718 * @return The album with the given ID, or {@code null} if no album with the
719 * given ID exists and {@code create} is {@code false}
721 public Album getAlbum(String albumId, boolean create) {
722 synchronized (albums) {
723 Album album = albums.get(albumId);
724 if (create && (album == null)) {
725 album = new Album(albumId);
726 albums.put(albumId, album);
733 * Returns the image with the given ID, creating it if necessary.
736 * The ID of the image
737 * @return The image with the given ID
739 public Image getImage(String imageId) {
740 return getImage(imageId, true);
744 * Returns the image with the given ID, optionally creating it if it does
748 * The ID of the image
750 * {@code true} to create an image if none exists with the given
752 * @return The image with the given ID, or {@code null} if none exists and
755 public Image getImage(String imageId, boolean create) {
756 synchronized (images) {
757 Image image = images.get(imageId);
758 if (create && (image == null)) {
759 image = new Image(imageId);
760 images.put(imageId, image);
767 * Returns the temporary image with the given ID.
770 * The ID of the temporary image
771 * @return The temporary image, or {@code null} if there is no temporary
772 * image with the given ID
774 public TemporaryImage getTemporaryImage(String imageId) {
775 synchronized (temporaryImages) {
776 return temporaryImages.get(imageId);
785 * Locks the given Sone. A locked Sone will not be inserted by
786 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
792 public void lockSone(Sone sone) {
793 synchronized (lockedSones) {
794 if (lockedSones.add(sone)) {
795 coreListenerManager.fireSoneLocked(sone);
801 * Unlocks the given Sone.
803 * @see #lockSone(Sone)
807 public void unlockSone(Sone sone) {
808 synchronized (lockedSones) {
809 if (lockedSones.remove(sone)) {
810 coreListenerManager.fireSoneUnlocked(sone);
816 * Adds a local Sone from the given own identity.
819 * The own identity to create a Sone from
820 * @return The added (or already existing) Sone
822 public Sone addLocalSone(OwnIdentity ownIdentity) {
823 if (ownIdentity == null) {
824 logger.log(Level.WARNING, "Given OwnIdentity is null!");
827 synchronized (sones) {
830 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
831 } catch (MalformedURLException mue1) {
832 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
835 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
836 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
838 /* TODO - load posts ’n stuff */
839 sones.put(ownIdentity.getId(), sone);
840 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
841 soneInserter.addSoneInsertListener(this);
842 soneInserters.put(sone, soneInserter);
843 sone.setStatus(SoneStatus.idle);
845 soneInserter.start();
851 * Creates a new Sone for the given own identity.
854 * The own identity to create a Sone for
855 * @return The created Sone
857 public Sone createSone(OwnIdentity ownIdentity) {
858 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
859 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
862 Sone sone = addLocalSone(ownIdentity);
863 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
864 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
865 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
866 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
867 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
868 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
870 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
871 touchConfiguration();
876 * Adds the Sone of the given identity.
879 * The identity whose Sone to add
880 * @return The added or already existing Sone
882 public Sone addRemoteSone(Identity identity) {
883 if (identity == null) {
884 logger.log(Level.WARNING, "Given Identity is null!");
887 synchronized (sones) {
888 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
889 boolean newSone = sone.getRequestUri() == null;
890 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
891 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
893 synchronized (knownSones) {
894 newSone = !knownSones.contains(sone.getId());
896 sone.setKnown(!newSone);
898 eventBus.post(new NewSoneFoundEvent(sone));
899 for (Sone localSone : getLocalSones()) {
900 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
901 followSone(localSone, sone);
906 soneDownloader.addSone(sone);
907 soneDownloaders.execute(new Runnable() {
910 @SuppressWarnings("synthetic-access")
912 soneDownloader.fetchSone(sone, sone.getRequestUri());
921 * Lets the given local Sone follow the Sone with the given ID.
924 * The local Sone that should follow another Sone
926 * The ID of the Sone to follow
928 public void followSone(Sone sone, String soneId) {
929 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
930 Sone followedSone = getSone(soneId, true);
931 if (followedSone == null) {
932 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
935 followSone(sone, getSone(soneId));
939 * Lets the given local Sone follow the other given Sone. If the given Sone
940 * was not followed by any local Sone before, this will mark all elements of
941 * the followed Sone as read that have been created before the current
945 * The local Sone that should follow the other Sone
946 * @param followedSone
947 * The Sone that should be followed
949 public void followSone(Sone sone, Sone followedSone) {
950 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
951 sone.addFriend(followedSone.getId());
952 synchronized (soneFollowingTimes) {
953 if (!soneFollowingTimes.containsKey(followedSone)) {
954 long now = System.currentTimeMillis();
955 soneFollowingTimes.put(followedSone, now);
956 for (Post post : followedSone.getPosts()) {
957 if (post.getTime() < now) {
961 for (PostReply reply : followedSone.getReplies()) {
962 if (reply.getTime() < now) {
963 markReplyKnown(reply);
968 touchConfiguration();
972 * Lets the given local Sone unfollow the Sone with the given ID.
975 * The local Sone that should unfollow another Sone
977 * The ID of the Sone being unfollowed
979 public void unfollowSone(Sone sone, String soneId) {
980 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
981 unfollowSone(sone, getSone(soneId, false));
985 * Lets the given local Sone unfollow the other given Sone. If the given
986 * local Sone is the last local Sone that followed the given Sone, its
987 * following time will be removed.
990 * The local Sone that should unfollow another Sone
991 * @param unfollowedSone
992 * The Sone being unfollowed
994 public void unfollowSone(Sone sone, Sone unfollowedSone) {
995 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
996 sone.removeFriend(unfollowedSone.getId());
997 boolean unfollowedSoneStillFollowed = false;
998 for (Sone localSone : getLocalSones()) {
999 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1001 if (!unfollowedSoneStillFollowed) {
1002 synchronized (soneFollowingTimes) {
1003 soneFollowingTimes.remove(unfollowedSone);
1006 touchConfiguration();
1010 * Sets the trust value of the given origin Sone for the target Sone.
1017 * The trust value (from {@code -100} to {@code 100})
1019 public void setTrust(Sone origin, Sone target, int trustValue) {
1020 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();
1021 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1025 * Removes any trust assignment for the given target Sone.
1032 public void removeTrust(Sone origin, Sone target) {
1033 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1034 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1038 * Assigns the configured positive trust value for the given target.
1045 public void trustSone(Sone origin, Sone target) {
1046 setTrust(origin, target, preferences.getPositiveTrust());
1050 * Assigns the configured negative trust value for the given target.
1057 public void distrustSone(Sone origin, Sone target) {
1058 setTrust(origin, target, preferences.getNegativeTrust());
1062 * Removes the trust assignment for the given target.
1069 public void untrustSone(Sone origin, Sone target) {
1070 removeTrust(origin, target);
1074 * Updates the stored Sone with the given Sone.
1079 public void updateSone(Sone sone) {
1080 updateSone(sone, false);
1084 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1085 * {@code true}, an older Sone than the current Sone can be given to restore
1089 * The Sone to update
1090 * @param soneRescueMode
1091 * {@code true} if the stored Sone should be updated regardless
1092 * of the age of the given Sone
1094 public void updateSone(Sone sone, boolean soneRescueMode) {
1095 if (hasSone(sone.getId())) {
1096 Sone storedSone = getSone(sone.getId());
1097 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1098 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1101 synchronized (posts) {
1102 if (!soneRescueMode) {
1103 for (Post post : storedSone.getPosts()) {
1104 posts.remove(post.getId());
1105 if (!sone.getPosts().contains(post)) {
1106 coreListenerManager.firePostRemoved(post);
1110 List<Post> storedPosts = storedSone.getPosts();
1111 synchronized (knownPosts) {
1112 for (Post post : sone.getPosts()) {
1113 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1114 if (!storedPosts.contains(post)) {
1115 if (post.getTime() < getSoneFollowingTime(sone)) {
1116 knownPosts.add(post.getId());
1117 post.setKnown(true);
1118 } else if (!knownPosts.contains(post.getId())) {
1119 eventBus.post(new NewPostFoundEvent(post));
1122 posts.put(post.getId(), post);
1126 synchronized (replies) {
1127 if (!soneRescueMode) {
1128 for (PostReply reply : storedSone.getReplies()) {
1129 replies.remove(reply.getId());
1130 if (!sone.getReplies().contains(reply)) {
1131 coreListenerManager.fireReplyRemoved(reply);
1135 Set<PostReply> storedReplies = storedSone.getReplies();
1136 synchronized (knownReplies) {
1137 for (PostReply reply : sone.getReplies()) {
1138 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1139 if (!storedReplies.contains(reply)) {
1140 if (reply.getTime() < getSoneFollowingTime(sone)) {
1141 knownReplies.add(reply.getId());
1142 reply.setKnown(true);
1143 } else if (!knownReplies.contains(reply.getId())) {
1144 eventBus.post(new NewPostReplyFoundEvent(reply));
1147 replies.put(reply.getId(), reply);
1151 synchronized (albums) {
1152 synchronized (images) {
1153 for (Album album : storedSone.getAlbums()) {
1154 albums.remove(album.getId());
1155 for (Image image : album.getImages()) {
1156 images.remove(image.getId());
1159 for (Album album : sone.getAlbums()) {
1160 albums.put(album.getId(), album);
1161 for (Image image : album.getImages()) {
1162 images.put(image.getId(), image);
1167 synchronized (storedSone) {
1168 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1169 storedSone.setTime(sone.getTime());
1171 storedSone.setClient(sone.getClient());
1172 storedSone.setProfile(sone.getProfile());
1173 if (soneRescueMode) {
1174 for (Post post : sone.getPosts()) {
1175 storedSone.addPost(post);
1177 for (PostReply reply : sone.getReplies()) {
1178 storedSone.addReply(reply);
1180 for (String likedPostId : sone.getLikedPostIds()) {
1181 storedSone.addLikedPostId(likedPostId);
1183 for (String likedReplyId : sone.getLikedReplyIds()) {
1184 storedSone.addLikedReplyId(likedReplyId);
1186 for (Album album : sone.getAlbums()) {
1187 storedSone.addAlbum(album);
1190 storedSone.setPosts(sone.getPosts());
1191 storedSone.setReplies(sone.getReplies());
1192 storedSone.setLikePostIds(sone.getLikedPostIds());
1193 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1194 storedSone.setAlbums(sone.getAlbums());
1196 storedSone.setLatestEdition(sone.getLatestEdition());
1202 * Deletes the given Sone. This will remove the Sone from the
1203 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1204 * remove the context from its identity.
1207 * The Sone to delete
1209 public void deleteSone(Sone sone) {
1210 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1211 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1214 synchronized (sones) {
1215 if (!getLocalSones().contains(sone)) {
1216 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1219 sones.remove(sone.getId());
1220 SoneInserter soneInserter = soneInserters.remove(sone);
1221 soneInserter.removeSoneInsertListener(this);
1222 soneInserter.stop();
1224 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1225 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1227 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1228 } catch (ConfigurationException ce1) {
1229 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1234 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1235 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1238 * The Sone to mark as known
1240 public void markSoneKnown(Sone sone) {
1241 if (!sone.isKnown()) {
1242 sone.setKnown(true);
1243 synchronized (knownSones) {
1244 knownSones.add(sone.getId());
1246 coreListenerManager.fireMarkSoneKnown(sone);
1247 touchConfiguration();
1252 * Loads and updates the given Sone from the configuration. If any error is
1253 * encountered, loading is aborted and the given Sone is not changed.
1256 * The Sone to load and update
1258 public void loadSone(Sone sone) {
1259 if (!sone.isLocal()) {
1260 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1264 /* initialize options. */
1265 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1266 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1267 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1268 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1269 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1270 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1273 String sonePrefix = "Sone/" + sone.getId();
1274 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1275 if (soneTime == null) {
1276 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1279 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1282 Profile profile = new Profile(sone);
1283 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1284 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1285 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1286 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1287 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1288 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1290 /* load profile fields. */
1292 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1293 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1294 if (fieldName == null) {
1297 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1298 profile.addField(fieldName).setValue(fieldValue);
1302 Set<Post> posts = new HashSet<Post>();
1304 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1305 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1306 if (postId == null) {
1309 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1310 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1311 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1312 if ((postTime == 0) || (postText == null)) {
1313 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1316 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1317 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1318 post.setRecipient(getSone(postRecipientId));
1324 Set<PostReply> replies = new HashSet<PostReply>();
1326 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1327 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1328 if (replyId == null) {
1331 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1332 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1333 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1334 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1335 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1338 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1341 /* load post likes. */
1342 Set<String> likedPostIds = new HashSet<String>();
1344 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1345 if (likedPostId == null) {
1348 likedPostIds.add(likedPostId);
1351 /* load reply likes. */
1352 Set<String> likedReplyIds = new HashSet<String>();
1354 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1355 if (likedReplyId == null) {
1358 likedReplyIds.add(likedReplyId);
1362 Set<String> friends = new HashSet<String>();
1364 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1365 if (friendId == null) {
1368 friends.add(friendId);
1372 List<Album> topLevelAlbums = new ArrayList<Album>();
1373 int albumCounter = 0;
1375 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1376 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1377 if (albumId == null) {
1380 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1381 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1382 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1383 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1384 if ((albumTitle == null) || (albumDescription == null)) {
1385 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1388 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1389 if (albumParentId != null) {
1390 Album parentAlbum = getAlbum(albumParentId, false);
1391 if (parentAlbum == null) {
1392 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1395 parentAlbum.addAlbum(album);
1397 if (!topLevelAlbums.contains(album)) {
1398 topLevelAlbums.add(album);
1404 int imageCounter = 0;
1406 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1407 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1408 if (imageId == null) {
1411 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1412 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1413 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1414 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1415 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1416 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1417 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1418 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1419 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1422 Album album = getAlbum(albumId, false);
1423 if (album == null) {
1424 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1427 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1428 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1429 album.addImage(image);
1433 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1434 if (avatarId != null) {
1435 profile.setAvatar(getImage(avatarId, false));
1439 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1440 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1441 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1442 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1443 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1444 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1446 /* if we’re still here, Sone was loaded successfully. */
1447 synchronized (sone) {
1448 sone.setTime(soneTime);
1449 sone.setProfile(profile);
1450 sone.setPosts(posts);
1451 sone.setReplies(replies);
1452 sone.setLikePostIds(likedPostIds);
1453 sone.setLikeReplyIds(likedReplyIds);
1454 for (String friendId : friends) {
1455 followSone(sone, friendId);
1457 sone.setAlbums(topLevelAlbums);
1458 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1460 synchronized (knownSones) {
1461 for (String friend : friends) {
1462 knownSones.add(friend);
1465 synchronized (knownPosts) {
1466 for (Post post : posts) {
1467 knownPosts.add(post.getId());
1470 synchronized (knownReplies) {
1471 for (PostReply reply : replies) {
1472 knownReplies.add(reply.getId());
1478 * Creates a new post.
1481 * The Sone that creates the post
1483 * The text of the post
1484 * @return The created post
1486 public Post createPost(Sone sone, String text) {
1487 return createPost(sone, System.currentTimeMillis(), text);
1491 * Creates a new post.
1494 * The Sone that creates the post
1496 * The time of the post
1498 * The text of the post
1499 * @return The created post
1501 public Post createPost(Sone sone, long time, String text) {
1502 return createPost(sone, null, time, text);
1506 * Creates a new post.
1509 * The Sone that creates the post
1511 * The recipient Sone, or {@code null} if this post does not have
1514 * The text of the post
1515 * @return The created post
1517 public Post createPost(Sone sone, Sone recipient, String text) {
1518 return createPost(sone, recipient, System.currentTimeMillis(), text);
1522 * Creates a new post.
1525 * The Sone that creates the post
1527 * The recipient Sone, or {@code null} if this post does not have
1530 * The time of the post
1532 * The text of the post
1533 * @return The created post
1535 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1536 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1537 if (!sone.isLocal()) {
1538 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1541 final Post post = new PostImpl(sone, time, text);
1542 if (recipient != null) {
1543 post.setRecipient(recipient);
1545 synchronized (posts) {
1546 posts.put(post.getId(), post);
1548 eventBus.post(new NewPostFoundEvent(post));
1550 touchConfiguration();
1551 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1558 markPostKnown(post);
1560 }, "Mark " + post + " read.");
1565 * Deletes the given post.
1568 * The post to delete
1570 public void deletePost(Post post) {
1571 if (!post.getSone().isLocal()) {
1572 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1575 post.getSone().removePost(post);
1576 synchronized (posts) {
1577 posts.remove(post.getId());
1579 coreListenerManager.firePostRemoved(post);
1580 markPostKnown(post);
1581 touchConfiguration();
1585 * Marks the given post as known, if it is currently not a known post
1586 * (according to {@link Post#isKnown()}).
1589 * The post to mark as known
1591 public void markPostKnown(Post post) {
1592 post.setKnown(true);
1593 synchronized (knownPosts) {
1594 coreListenerManager.fireMarkPostKnown(post);
1595 if (knownPosts.add(post.getId())) {
1596 touchConfiguration();
1599 for (PostReply reply : getReplies(post)) {
1600 markReplyKnown(reply);
1605 * Bookmarks the given post.
1608 * The post to bookmark
1610 public void bookmark(Post post) {
1611 bookmarkPost(post.getId());
1615 * Bookmarks the post with the given ID.
1618 * The ID of the post to bookmark
1620 public void bookmarkPost(String id) {
1621 synchronized (bookmarkedPosts) {
1622 bookmarkedPosts.add(id);
1627 * Removes the given post from the bookmarks.
1630 * The post to unbookmark
1632 public void unbookmark(Post post) {
1633 unbookmarkPost(post.getId());
1637 * Removes the post with the given ID from the bookmarks.
1640 * The ID of the post to unbookmark
1642 public void unbookmarkPost(String id) {
1643 synchronized (bookmarkedPosts) {
1644 bookmarkedPosts.remove(id);
1649 * Creates a new reply.
1652 * The Sone that creates the reply
1654 * The post that this reply refers to
1656 * The text of the reply
1657 * @return The created reply
1659 public PostReply createReply(Sone sone, Post post, String text) {
1660 return createReply(sone, post, System.currentTimeMillis(), text);
1664 * Creates a new reply.
1667 * The Sone that creates the reply
1669 * The post that this reply refers to
1671 * The time of the reply
1673 * The text of the reply
1674 * @return The created reply
1676 public PostReply createReply(Sone sone, Post post, long time, String text) {
1677 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1678 if (!sone.isLocal()) {
1679 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1682 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1683 synchronized (replies) {
1684 replies.put(reply.getId(), reply);
1686 synchronized (knownReplies) {
1687 eventBus.post(new NewPostReplyFoundEvent(reply));
1689 sone.addReply(reply);
1690 touchConfiguration();
1691 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1698 markReplyKnown(reply);
1700 }, "Mark " + reply + " read.");
1705 * Deletes the given reply.
1708 * The reply to delete
1710 public void deleteReply(PostReply reply) {
1711 Sone sone = reply.getSone();
1712 if (!sone.isLocal()) {
1713 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1716 synchronized (replies) {
1717 replies.remove(reply.getId());
1719 synchronized (knownReplies) {
1720 markReplyKnown(reply);
1721 knownReplies.remove(reply.getId());
1723 sone.removeReply(reply);
1724 touchConfiguration();
1728 * Marks the given reply as known, if it is currently not a known reply
1729 * (according to {@link Reply#isKnown()}).
1732 * The reply to mark as known
1734 public void markReplyKnown(PostReply reply) {
1735 reply.setKnown(true);
1736 synchronized (knownReplies) {
1737 coreListenerManager.fireMarkReplyKnown(reply);
1738 if (knownReplies.add(reply.getId())) {
1739 touchConfiguration();
1745 * Creates a new top-level album for the given Sone.
1748 * The Sone to create the album for
1749 * @return The new album
1751 public Album createAlbum(Sone sone) {
1752 return createAlbum(sone, null);
1756 * Creates a new album for the given Sone.
1759 * The Sone to create the album for
1761 * The parent of the album (may be {@code null} to create a
1763 * @return The new album
1765 public Album createAlbum(Sone sone, Album parent) {
1766 Album album = new Album();
1767 synchronized (albums) {
1768 albums.put(album.getId(), album);
1770 album.setSone(sone);
1771 if (parent != null) {
1772 parent.addAlbum(album);
1774 sone.addAlbum(album);
1780 * Deletes the given album. The owner of the album has to be a local Sone,
1781 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1784 * The album to remove
1786 public void deleteAlbum(Album album) {
1787 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1788 if (!album.isEmpty()) {
1791 if (album.getParent() == null) {
1792 album.getSone().removeAlbum(album);
1794 album.getParent().removeAlbum(album);
1796 synchronized (albums) {
1797 albums.remove(album.getId());
1799 touchConfiguration();
1803 * Creates a new image.
1806 * The Sone creating the image
1808 * The album the image will be inserted into
1809 * @param temporaryImage
1810 * The temporary image to create the image from
1811 * @return The newly created image
1813 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1814 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();
1815 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1816 album.addImage(image);
1817 synchronized (images) {
1818 images.put(image.getId(), image);
1820 imageInserter.insertImage(temporaryImage, image);
1825 * Deletes the given image. This method will also delete a matching
1828 * @see #deleteTemporaryImage(TemporaryImage)
1830 * The image to delete
1832 public void deleteImage(Image image) {
1833 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1834 deleteTemporaryImage(image.getId());
1835 image.getAlbum().removeImage(image);
1836 synchronized (images) {
1837 images.remove(image.getId());
1839 touchConfiguration();
1843 * Creates a new temporary image.
1846 * The MIME type of the temporary image
1848 * The encoded data of the image
1849 * @return The temporary image
1851 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1852 TemporaryImage temporaryImage = new TemporaryImage();
1853 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1854 synchronized (temporaryImages) {
1855 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1857 return temporaryImage;
1861 * Deletes the given temporary image.
1863 * @param temporaryImage
1864 * The temporary image to delete
1866 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1867 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1868 deleteTemporaryImage(temporaryImage.getId());
1872 * Deletes the temporary image with the given ID.
1875 * The ID of the temporary image to delete
1877 public void deleteTemporaryImage(String imageId) {
1878 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1879 synchronized (temporaryImages) {
1880 temporaryImages.remove(imageId);
1882 Image image = getImage(imageId, false);
1883 if (image != null) {
1884 imageInserter.cancelImageInsert(image);
1889 * Notifies the core that the configuration, either of the core or of a
1890 * single local Sone, has changed, and that the configuration should be
1893 public void touchConfiguration() {
1894 lastConfigurationUpdate = System.currentTimeMillis();
1905 public void serviceStart() {
1906 loadConfiguration();
1907 updateChecker.addUpdateListener(this);
1908 updateChecker.start();
1909 identityManager.addIdentityListener(this);
1910 identityManager.start();
1911 webOfTrustUpdater.init();
1912 webOfTrustUpdater.start();
1919 public void serviceRun() {
1920 long lastSaved = System.currentTimeMillis();
1921 while (!shouldStop()) {
1923 long now = System.currentTimeMillis();
1924 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1925 for (Sone localSone : getLocalSones()) {
1926 saveSone(localSone);
1928 saveConfiguration();
1938 public void serviceStop() {
1939 synchronized (sones) {
1940 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1941 soneInserter.getValue().removeSoneInsertListener(this);
1942 soneInserter.getValue().stop();
1943 saveSone(soneInserter.getKey());
1946 saveConfiguration();
1947 webOfTrustUpdater.stop();
1948 updateChecker.stop();
1949 updateChecker.removeUpdateListener(this);
1950 soneDownloader.stop();
1951 identityManager.removeIdentityListener(this);
1952 identityManager.stop();
1960 * Saves the given Sone. This will persist all local settings for the given
1961 * Sone, such as the friends list and similar, private options.
1966 private synchronized void saveSone(Sone sone) {
1967 if (!sone.isLocal()) {
1968 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1971 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1972 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1976 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1978 /* save Sone into configuration. */
1979 String sonePrefix = "Sone/" + sone.getId();
1980 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1981 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1984 Profile profile = sone.getProfile();
1985 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1986 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1987 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1988 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1989 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1990 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1991 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1993 /* save profile fields. */
1994 int fieldCounter = 0;
1995 for (Field profileField : profile.getFields()) {
1996 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1997 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1998 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2000 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2003 int postCounter = 0;
2004 for (Post post : sone.getPosts()) {
2005 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2006 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2007 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2008 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2009 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2011 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2014 int replyCounter = 0;
2015 for (PostReply reply : sone.getReplies()) {
2016 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2017 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2018 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2019 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2020 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2022 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2024 /* save post likes. */
2025 int postLikeCounter = 0;
2026 for (String postId : sone.getLikedPostIds()) {
2027 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2029 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2031 /* save reply likes. */
2032 int replyLikeCounter = 0;
2033 for (String replyId : sone.getLikedReplyIds()) {
2034 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2036 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2039 int friendCounter = 0;
2040 for (String friendId : sone.getFriends()) {
2041 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2043 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2045 /* save albums. first, collect in a flat structure, top-level first. */
2046 List<Album> albums = sone.getAllAlbums();
2048 int albumCounter = 0;
2049 for (Album album : albums) {
2050 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2051 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2052 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2053 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2054 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2055 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2057 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2060 int imageCounter = 0;
2061 for (Album album : albums) {
2062 for (Image image : album.getImages()) {
2063 if (!image.isInserted()) {
2066 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2067 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2068 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2069 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2070 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2071 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2072 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2073 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2074 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2077 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2080 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2081 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2082 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2083 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2084 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2085 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2087 configuration.save();
2089 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2091 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2092 } catch (ConfigurationException ce1) {
2093 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2098 * Saves the current options.
2100 private void saveConfiguration() {
2101 synchronized (configuration) {
2102 if (storingConfiguration) {
2103 logger.log(Level.FINE, "Already storing configuration…");
2106 storingConfiguration = true;
2109 /* store the options first. */
2111 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2112 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2113 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2114 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2115 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2116 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2117 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2118 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2119 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2120 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2121 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2122 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2124 /* save known Sones. */
2125 int soneCounter = 0;
2126 synchronized (knownSones) {
2127 for (String knownSoneId : knownSones) {
2128 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2130 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2133 /* save Sone following times. */
2135 synchronized (soneFollowingTimes) {
2136 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2137 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2138 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2141 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2144 /* save known posts. */
2145 int postCounter = 0;
2146 synchronized (knownPosts) {
2147 for (String knownPostId : knownPosts) {
2148 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2150 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2153 /* save known replies. */
2154 int replyCounter = 0;
2155 synchronized (knownReplies) {
2156 for (String knownReplyId : knownReplies) {
2157 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2159 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2162 /* save bookmarked posts. */
2163 int bookmarkedPostCounter = 0;
2164 synchronized (bookmarkedPosts) {
2165 for (String bookmarkedPostId : bookmarkedPosts) {
2166 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2169 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2172 configuration.save();
2174 } catch (ConfigurationException ce1) {
2175 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2177 synchronized (configuration) {
2178 storingConfiguration = false;
2184 * Loads the configuration.
2186 @SuppressWarnings("unchecked")
2187 private void loadConfiguration() {
2188 /* create options. */
2189 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2192 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2193 SoneInserter.setInsertionDelay(newValue);
2197 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2198 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2199 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2200 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2201 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2202 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2203 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2204 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2205 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2208 @SuppressWarnings("synthetic-access")
2209 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2210 fcpInterface.setActive(newValue);
2213 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2216 @SuppressWarnings("synthetic-access")
2217 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2218 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2223 loadConfigurationValue("InsertionDelay");
2224 loadConfigurationValue("PostsPerPage");
2225 loadConfigurationValue("ImagesPerPage");
2226 loadConfigurationValue("CharactersPerPost");
2227 loadConfigurationValue("PostCutOffLength");
2228 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2229 loadConfigurationValue("PositiveTrust");
2230 loadConfigurationValue("NegativeTrust");
2231 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2232 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2233 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2235 /* load known Sones. */
2236 int soneCounter = 0;
2238 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2239 if (knownSoneId == null) {
2242 synchronized (knownSones) {
2243 knownSones.add(knownSoneId);
2247 /* load Sone following times. */
2250 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2251 if (soneId == null) {
2254 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2255 Sone followedSone = getSone(soneId);
2256 if (followedSone == null) {
2257 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2259 synchronized (soneFollowingTimes) {
2260 soneFollowingTimes.put(getSone(soneId), time);
2266 /* load known posts. */
2267 int postCounter = 0;
2269 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2270 if (knownPostId == null) {
2273 synchronized (knownPosts) {
2274 knownPosts.add(knownPostId);
2278 /* load known replies. */
2279 int replyCounter = 0;
2281 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2282 if (knownReplyId == null) {
2285 synchronized (knownReplies) {
2286 knownReplies.add(knownReplyId);
2290 /* load bookmarked posts. */
2291 int bookmarkedPostCounter = 0;
2293 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2294 if (bookmarkedPostId == null) {
2297 synchronized (bookmarkedPosts) {
2298 bookmarkedPosts.add(bookmarkedPostId);
2305 * Loads an {@link Integer} configuration value for the option with the
2306 * given name, logging validation failures.
2309 * The name of the option to load
2311 private void loadConfigurationValue(String optionName) {
2313 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2314 } catch (IllegalArgumentException iae1) {
2315 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2320 * Generate a Sone URI from the given URI and latest edition.
2323 * The URI to derive the Sone URI from
2324 * @return The derived URI
2326 private static FreenetURI getSoneUri(String uriString) {
2328 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2330 } catch (MalformedURLException mue1) {
2331 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2337 // INTERFACE IdentityListener
2344 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2345 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2346 if (ownIdentity.hasContext("Sone")) {
2347 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2348 addLocalSone(ownIdentity);
2356 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2357 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2358 trustedIdentities.remove(ownIdentity);
2365 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2366 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2367 trustedIdentities.get(ownIdentity).add(identity);
2368 addRemoteSone(identity);
2375 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2376 soneDownloaders.execute(new Runnable() {
2379 @SuppressWarnings("synthetic-access")
2381 Sone sone = getRemoteSone(identity.getId(), false);
2382 sone.setIdentity(identity);
2383 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2384 soneDownloader.addSone(sone);
2385 soneDownloader.fetchSone(sone);
2394 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2395 trustedIdentities.get(ownIdentity).remove(identity);
2396 boolean foundIdentity = false;
2397 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2398 if (trustedIdentity.getKey().equals(ownIdentity)) {
2401 if (trustedIdentity.getValue().contains(identity)) {
2402 foundIdentity = true;
2405 if (foundIdentity) {
2406 /* some local identity still trusts this identity, don’t remove. */
2409 Sone sone = getSone(identity.getId(), false);
2411 /* TODO - we don’t have the Sone anymore. should this happen? */
2414 synchronized (posts) {
2415 synchronized (knownPosts) {
2416 for (Post post : sone.getPosts()) {
2417 posts.remove(post.getId());
2418 coreListenerManager.firePostRemoved(post);
2422 synchronized (replies) {
2423 synchronized (knownReplies) {
2424 for (PostReply reply : sone.getReplies()) {
2425 replies.remove(reply.getId());
2426 coreListenerManager.fireReplyRemoved(reply);
2430 synchronized (sones) {
2431 sones.remove(identity.getId());
2433 coreListenerManager.fireSoneRemoved(sone);
2437 // INTERFACE UpdateListener
2444 public void updateFound(Version version, long releaseTime, long latestEdition) {
2445 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2449 // INTERFACE ImageInsertListener
2456 public void insertStarted(Sone sone) {
2457 coreListenerManager.fireSoneInserting(sone);
2464 public void insertFinished(Sone sone, long insertDuration) {
2465 coreListenerManager.fireSoneInserted(sone, insertDuration);
2472 public void insertAborted(Sone sone, Throwable cause) {
2473 coreListenerManager.fireSoneInsertAborted(sone, cause);
2477 // SONEINSERTLISTENER METHODS
2484 public void imageInsertStarted(Image image) {
2485 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2486 coreListenerManager.fireImageInsertStarted(image);
2493 public void imageInsertAborted(Image image) {
2494 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2495 coreListenerManager.fireImageInsertAborted(image);
2502 public void imageInsertFinished(Image image, FreenetURI key) {
2503 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2504 image.setKey(key.toString());
2505 deleteTemporaryImage(image.getId());
2506 touchConfiguration();
2507 coreListenerManager.fireImageInsertFinished(image);
2514 public void imageInsertFailed(Image image, Throwable cause) {
2515 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2516 coreListenerManager.fireImageInsertFailed(image, cause);
2520 * Convenience interface for external classes that want to access the core’s
2523 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2525 public static class Preferences {
2527 /** The wrapped options. */
2528 private final Options options;
2531 * Creates a new preferences object wrapped around the given options.
2534 * The options to wrap
2536 public Preferences(Options options) {
2537 this.options = options;
2541 * Returns the insertion delay.
2543 * @return The insertion delay
2545 public int getInsertionDelay() {
2546 return options.getIntegerOption("InsertionDelay").get();
2550 * Validates the given insertion delay.
2552 * @param insertionDelay
2553 * The insertion delay to validate
2554 * @return {@code true} if the given insertion delay was valid,
2555 * {@code false} otherwise
2557 public boolean validateInsertionDelay(Integer insertionDelay) {
2558 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2562 * Sets the insertion delay
2564 * @param insertionDelay
2565 * The new insertion delay, or {@code null} to restore it to
2567 * @return This preferences
2569 public Preferences setInsertionDelay(Integer insertionDelay) {
2570 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2575 * Returns the number of posts to show per page.
2577 * @return The number of posts to show per page
2579 public int getPostsPerPage() {
2580 return options.getIntegerOption("PostsPerPage").get();
2584 * Validates the number of posts per page.
2586 * @param postsPerPage
2587 * The number of posts per page
2588 * @return {@code true} if the number of posts per page was valid,
2589 * {@code false} otherwise
2591 public boolean validatePostsPerPage(Integer postsPerPage) {
2592 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2596 * Sets the number of posts to show per page.
2598 * @param postsPerPage
2599 * The number of posts to show per page
2600 * @return This preferences object
2602 public Preferences setPostsPerPage(Integer postsPerPage) {
2603 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2608 * Returns the number of images to show per page.
2610 * @return The number of images to show per page
2612 public int getImagesPerPage() {
2613 return options.getIntegerOption("ImagesPerPage").get();
2617 * Validates the number of images per page.
2619 * @param imagesPerPage
2620 * The number of images per page
2621 * @return {@code true} if the number of images per page was valid,
2622 * {@code false} otherwise
2624 public boolean validateImagesPerPage(Integer imagesPerPage) {
2625 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2629 * Sets the number of images per page.
2631 * @param imagesPerPage
2632 * The number of images per page
2633 * @return This preferences object
2635 public Preferences setImagesPerPage(Integer imagesPerPage) {
2636 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2641 * Returns the number of characters per post, or <code>-1</code> if the
2642 * posts should not be cut off.
2644 * @return The numbers of characters per post
2646 public int getCharactersPerPost() {
2647 return options.getIntegerOption("CharactersPerPost").get();
2651 * Validates the number of characters per post.
2653 * @param charactersPerPost
2654 * The number of characters per post
2655 * @return {@code true} if the number of characters per post was valid,
2656 * {@code false} otherwise
2658 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2659 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2663 * Sets the number of characters per post.
2665 * @param charactersPerPost
2666 * The number of characters per post, or <code>-1</code> to
2667 * not cut off the posts
2668 * @return This preferences objects
2670 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2671 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2676 * Returns the number of characters the shortened post should have.
2678 * @return The number of characters of the snippet
2680 public int getPostCutOffLength() {
2681 return options.getIntegerOption("PostCutOffLength").get();
2685 * Validates the number of characters after which to cut off the post.
2687 * @param postCutOffLength
2688 * The number of characters of the snippet
2689 * @return {@code true} if the number of characters of the snippet is
2690 * valid, {@code false} otherwise
2692 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2693 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2697 * Sets the number of characters the shortened post should have.
2699 * @param postCutOffLength
2700 * The number of characters of the snippet
2701 * @return This preferences
2703 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2704 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2709 * Returns whether Sone requires full access to be even visible.
2711 * @return {@code true} if Sone requires full access, {@code false}
2714 public boolean isRequireFullAccess() {
2715 return options.getBooleanOption("RequireFullAccess").get();
2719 * Sets whether Sone requires full access to be even visible.
2721 * @param requireFullAccess
2722 * {@code true} if Sone requires full access, {@code false}
2725 public void setRequireFullAccess(Boolean requireFullAccess) {
2726 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2730 * Returns the positive trust.
2732 * @return The positive trust
2734 public int getPositiveTrust() {
2735 return options.getIntegerOption("PositiveTrust").get();
2739 * Validates the positive trust.
2741 * @param positiveTrust
2742 * The positive trust to validate
2743 * @return {@code true} if the positive trust was valid, {@code false}
2746 public boolean validatePositiveTrust(Integer positiveTrust) {
2747 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2751 * Sets the positive trust.
2753 * @param positiveTrust
2754 * The new positive trust, or {@code null} to restore it to
2756 * @return This preferences
2758 public Preferences setPositiveTrust(Integer positiveTrust) {
2759 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2764 * Returns the negative trust.
2766 * @return The negative trust
2768 public int getNegativeTrust() {
2769 return options.getIntegerOption("NegativeTrust").get();
2773 * Validates the negative trust.
2775 * @param negativeTrust
2776 * The negative trust to validate
2777 * @return {@code true} if the negative trust was valid, {@code false}
2780 public boolean validateNegativeTrust(Integer negativeTrust) {
2781 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2785 * Sets the negative trust.
2787 * @param negativeTrust
2788 * The negative trust, or {@code null} to restore it to the
2790 * @return The preferences
2792 public Preferences setNegativeTrust(Integer negativeTrust) {
2793 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2798 * Returns the trust comment. This is the comment that is set in the web
2799 * of trust when a trust value is assigned to an identity.
2801 * @return The trust comment
2803 public String getTrustComment() {
2804 return options.getStringOption("TrustComment").get();
2808 * Sets the trust comment.
2810 * @param trustComment
2811 * The trust comment, or {@code null} to restore it to the
2813 * @return This preferences
2815 public Preferences setTrustComment(String trustComment) {
2816 options.getStringOption("TrustComment").set(trustComment);
2821 * Returns whether the {@link FcpInterface FCP interface} is currently
2824 * @see FcpInterface#setActive(boolean)
2825 * @return {@code true} if the FCP interface is currently active,
2826 * {@code false} otherwise
2828 public boolean isFcpInterfaceActive() {
2829 return options.getBooleanOption("ActivateFcpInterface").get();
2833 * Sets whether the {@link FcpInterface FCP interface} is currently
2836 * @see FcpInterface#setActive(boolean)
2837 * @param fcpInterfaceActive
2838 * {@code true} to activate the FCP interface, {@code false}
2839 * to deactivate the FCP interface
2840 * @return This preferences object
2842 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2843 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2848 * Returns the action level for which full access to the FCP interface
2851 * @return The action level for which full access to the FCP interface
2854 public FullAccessRequired getFcpFullAccessRequired() {
2855 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2859 * Sets the action level for which full access to the FCP interface is
2862 * @param fcpFullAccessRequired
2864 * @return This preferences
2866 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2867 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);