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.data.Album;
39 import net.pterodactylus.sone.data.Client;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Profile;
44 import net.pterodactylus.sone.data.Profile.Field;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.data.TemporaryImage;
50 import net.pterodactylus.sone.data.impl.PostImpl;
51 import net.pterodactylus.sone.fcp.FcpInterface;
52 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
53 import net.pterodactylus.sone.freenet.wot.Identity;
54 import net.pterodactylus.sone.freenet.wot.IdentityListener;
55 import net.pterodactylus.sone.freenet.wot.IdentityManager;
56 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
57 import net.pterodactylus.sone.main.SonePlugin;
58 import net.pterodactylus.util.config.Configuration;
59 import net.pterodactylus.util.config.ConfigurationException;
60 import net.pterodactylus.util.logging.Logging;
61 import net.pterodactylus.util.number.Numbers;
62 import net.pterodactylus.util.service.AbstractService;
63 import net.pterodactylus.util.thread.NamedThreadFactory;
64 import net.pterodactylus.util.thread.Ticker;
65 import net.pterodactylus.util.validation.EqualityValidator;
66 import net.pterodactylus.util.validation.IntegerRangeValidator;
67 import net.pterodactylus.util.validation.OrValidator;
68 import net.pterodactylus.util.validation.Validation;
69 import net.pterodactylus.util.version.Version;
71 import com.google.common.base.Predicate;
72 import com.google.common.collect.Collections2;
73 import com.google.common.eventbus.EventBus;
74 import com.google.inject.Inject;
76 import freenet.keys.FreenetURI;
81 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
83 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
86 private static final Logger logger = Logging.getLogger(Core.class);
88 /** The start time. */
89 private final long startupTime = System.currentTimeMillis();
92 private final Options options = new Options();
94 /** The preferences. */
95 private final Preferences preferences = new Preferences(options);
97 /** The core listener manager. */
98 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
100 /** The event bus. */
101 private final EventBus eventBus;
103 /** The configuration. */
104 private Configuration configuration;
106 /** Whether we’re currently saving the configuration. */
107 private boolean storingConfiguration = false;
109 /** The identity manager. */
110 private final IdentityManager identityManager;
112 /** Interface to freenet. */
113 private final FreenetInterface freenetInterface;
115 /** The Sone downloader. */
116 private final SoneDownloader soneDownloader;
118 /** The image inserter. */
119 private final ImageInserter imageInserter;
121 /** Sone downloader thread-pool. */
122 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
124 /** The update checker. */
125 private final UpdateChecker updateChecker;
127 /** The trust updater. */
128 private final WebOfTrustUpdater webOfTrustUpdater;
130 /** The FCP interface. */
131 private volatile FcpInterface fcpInterface;
133 /** The times Sones were followed. */
134 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
136 /** Locked local Sones. */
137 /* synchronize on itself. */
138 private final Set<Sone> lockedSones = new HashSet<Sone>();
140 /** Sone inserters. */
141 /* synchronize access on this on sones. */
142 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
144 /** Sone rescuers. */
145 /* synchronize access on this on sones. */
146 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
149 /* synchronize access on this on itself. */
150 private final Map<String, Sone> sones = new HashMap<String, Sone>();
152 /** All known Sones. */
153 private final Set<String> knownSones = new HashSet<String>();
156 private final Map<String, Post> posts = new HashMap<String, Post>();
158 /** All known posts. */
159 private final Set<String> knownPosts = new HashSet<String>();
162 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
164 /** All known replies. */
165 private final Set<String> knownReplies = new HashSet<String>();
167 /** All bookmarked posts. */
168 /* synchronize access on itself. */
169 private final Set<String> bookmarkedPosts = new HashSet<String>();
171 /** Trusted identities, sorted by own identities. */
172 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
174 /** All known albums. */
175 private final Map<String, Album> albums = new HashMap<String, Album>();
177 /** All known images. */
178 private final Map<String, Image> images = new HashMap<String, Image>();
180 /** All temporary images. */
181 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
183 /** Ticker for threads that mark own elements as known. */
184 private final Ticker localElementTicker = new Ticker();
186 /** The time the configuration was last touched. */
187 private volatile long lastConfigurationUpdate;
190 * Creates a new core.
192 * @param configuration
193 * The configuration of the core
194 * @param freenetInterface
195 * The freenet interface
196 * @param identityManager
197 * The identity manager
198 * @param webOfTrustUpdater
199 * The WebOfTrust updater
204 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
206 this.configuration = configuration;
207 this.freenetInterface = freenetInterface;
208 this.identityManager = identityManager;
209 this.soneDownloader = new SoneDownloader(this, freenetInterface);
210 this.imageInserter = new ImageInserter(this, freenetInterface);
211 this.updateChecker = new UpdateChecker(freenetInterface);
212 this.webOfTrustUpdater = webOfTrustUpdater;
213 this.eventBus = eventBus;
217 // LISTENER MANAGEMENT
221 * Adds a new core listener.
223 * @param coreListener
224 * The listener to add
226 public void addCoreListener(CoreListener coreListener) {
227 coreListenerManager.addListener(coreListener);
231 * Removes a core listener.
233 * @param coreListener
234 * The listener to remove
236 public void removeCoreListener(CoreListener coreListener) {
237 coreListenerManager.removeListener(coreListener);
245 * Returns the time Sone was started.
247 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
249 public long getStartupTime() {
254 * Sets the configuration to use. This will automatically save the current
255 * configuration to the given configuration.
257 * @param configuration
258 * The new configuration to use
260 public void setConfiguration(Configuration configuration) {
261 this.configuration = configuration;
262 touchConfiguration();
266 * Returns the options used by the core.
268 * @return The options of the core
270 public Preferences getPreferences() {
275 * Returns the identity manager used by the core.
277 * @return The identity manager
279 public IdentityManager getIdentityManager() {
280 return identityManager;
284 * Returns the update checker.
286 * @return The update checker
288 public UpdateChecker getUpdateChecker() {
289 return updateChecker;
293 * Sets the FCP interface to use.
295 * @param fcpInterface
296 * The FCP interface to use
298 public void setFcpInterface(FcpInterface fcpInterface) {
299 this.fcpInterface = fcpInterface;
303 * Returns the Sone rescuer for the given local Sone.
306 * The local Sone to get the rescuer for
307 * @return The Sone rescuer for the given Sone
309 public SoneRescuer getSoneRescuer(Sone sone) {
310 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
311 synchronized (sones) {
312 SoneRescuer soneRescuer = soneRescuers.get(sone);
313 if (soneRescuer == null) {
314 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
315 soneRescuers.put(sone, soneRescuer);
323 * Returns whether the given Sone is currently locked.
327 * @return {@code true} if the Sone is locked, {@code false} if it is not
329 public boolean isLocked(Sone sone) {
330 synchronized (lockedSones) {
331 return lockedSones.contains(sone);
336 * Returns all Sones, remote and local.
340 public Set<Sone> getSones() {
341 return new HashSet<Sone>(sones.values());
345 * Returns the Sone with the given ID, regardless whether it’s local or
349 * The ID of the Sone to get
350 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Sone getSone(String id) {
354 return getSone(id, true);
358 * Returns the Sone with the given ID, regardless whether it’s local or
362 * The ID of the Sone to get
364 * {@code true} to create a new Sone if none exists,
365 * {@code false} to return {@code null} if a Sone with the given
367 * @return The Sone with the given ID, or {@code null} if there is no such
371 public Sone getSone(String id, boolean create) {
372 synchronized (sones) {
373 if (!sones.containsKey(id)) {
374 Sone sone = new Sone(id, false);
377 return sones.get(id);
382 * Checks whether the core knows a Sone with the given ID.
386 * @return {@code true} if there is a Sone with the given ID, {@code false}
389 public boolean hasSone(String id) {
390 synchronized (sones) {
391 return sones.containsKey(id);
396 * Returns all local Sones.
398 * @return All local Sones
400 public Collection<Sone> getLocalSones() {
401 synchronized (sones) {
402 return Collections2.filter(sones.values(), new Predicate<Sone>() {
405 public boolean apply(Sone sone) {
406 return sone.isLocal();
413 * Returns the local Sone with the given ID, optionally creating a new Sone.
418 * {@code true} to create a new Sone if none exists,
419 * {@code false} to return null if none exists
420 * @return The Sone with the given ID, or {@code null}
422 public Sone getLocalSone(String id, boolean create) {
423 synchronized (sones) {
424 Sone sone = sones.get(id);
425 if ((sone == null) && create) {
426 sone = new Sone(id, true);
429 if ((sone != null) && !sone.isLocal()) {
430 sone = new Sone(id, true);
438 * Returns all remote Sones.
440 * @return All remote Sones
442 public Collection<Sone> getRemoteSones() {
443 synchronized (sones) {
444 return Collections2.filter(sones.values(), new Predicate<Sone>() {
447 public boolean apply(Sone sone) {
448 return !sone.isLocal();
455 * Returns the remote Sone with the given ID.
458 * The ID of the remote Sone to get
460 * {@code true} to always create a Sone, {@code false} to return
461 * {@code null} if no Sone with the given ID exists
462 * @return The Sone with the given ID
464 public Sone getRemoteSone(String id, boolean create) {
465 synchronized (sones) {
466 Sone sone = sones.get(id);
467 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
468 sone = new Sone(id, false);
476 * Returns whether the given Sone has been modified.
479 * The Sone to check for modifications
480 * @return {@code true} if a modification has been detected in the Sone,
481 * {@code false} otherwise
483 public boolean isModifiedSone(Sone sone) {
484 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
488 * Returns the time when the given was first followed by any local Sone.
491 * The Sone to get the time for
492 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
493 * been followed, or {@link Long#MAX_VALUE}
495 public long getSoneFollowingTime(Sone sone) {
496 synchronized (soneFollowingTimes) {
497 if (soneFollowingTimes.containsKey(sone)) {
498 return soneFollowingTimes.get(sone);
500 return Long.MAX_VALUE;
505 * Returns whether the target Sone is trusted by the origin Sone.
511 * @return {@code true} if the target Sone is trusted by the origin Sone
513 public boolean isSoneTrusted(Sone origin, Sone target) {
514 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
515 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
519 * Returns the post with the given ID.
522 * The ID of the post to get
523 * @return The post with the given ID, or a new post with the given ID
525 public Post getPost(String postId) {
526 return getPost(postId, true);
530 * Returns the post with the given ID, optionally creating a new post.
533 * The ID of the post to get
535 * {@code true} it create a new post if no post with the given ID
536 * exists, {@code false} to return {@code null}
537 * @return The post, or {@code null} if there is no such post
540 public Post getPost(String postId, boolean create) {
541 synchronized (posts) {
542 Post post = posts.get(postId);
543 if ((post == null) && create) {
544 post = new PostImpl(postId);
545 posts.put(postId, post);
552 * Returns all posts that have the given Sone as recipient.
554 * @see Post#getRecipient()
556 * The recipient of the posts
557 * @return All posts that have the given Sone as recipient
559 public Set<Post> getDirectedPosts(Sone recipient) {
560 Validation.begin().isNotNull("Recipient", recipient).check();
561 Set<Post> directedPosts = new HashSet<Post>();
562 synchronized (posts) {
563 for (Post post : posts.values()) {
564 if (recipient.equals(post.getRecipient())) {
565 directedPosts.add(post);
569 return directedPosts;
573 * Returns the reply with the given ID. If there is no reply with the given
574 * ID yet, a new one is created, unless {@code create} is false in which
575 * case {@code null} is returned.
578 * The ID of the reply to get
580 * {@code true} to always return a {@link Reply}, {@code false}
581 * to return {@code null} if no reply can be found
582 * @return The reply, or {@code null} if there is no such reply
584 public PostReply getPostReply(String replyId, boolean create) {
585 synchronized (replies) {
586 PostReply reply = replies.get(replyId);
587 if (create && (reply == null)) {
588 reply = new PostReply(replyId);
589 replies.put(replyId, reply);
596 * Returns all replies for the given post, order ascending by time.
599 * The post to get all replies for
600 * @return All replies for the given post
602 public List<PostReply> getReplies(Post post) {
603 Set<Sone> sones = getSones();
604 List<PostReply> replies = new ArrayList<PostReply>();
605 for (Sone sone : sones) {
606 for (PostReply reply : sone.getReplies()) {
607 if (reply.getPost().equals(post)) {
612 Collections.sort(replies, Reply.TIME_COMPARATOR);
617 * Returns all Sones that have liked the given post.
620 * The post to get the liking Sones for
621 * @return The Sones that like the given post
623 public Set<Sone> getLikes(Post post) {
624 Set<Sone> sones = new HashSet<Sone>();
625 for (Sone sone : getSones()) {
626 if (sone.getLikedPostIds().contains(post.getId())) {
634 * Returns all Sones that have liked the given reply.
637 * The reply to get the liking Sones for
638 * @return The Sones that like the given reply
640 public Set<Sone> getLikes(PostReply reply) {
641 Set<Sone> sones = new HashSet<Sone>();
642 for (Sone sone : getSones()) {
643 if (sone.getLikedReplyIds().contains(reply.getId())) {
651 * Returns whether the given post is bookmarked.
655 * @return {@code true} if the given post is bookmarked, {@code false}
658 public boolean isBookmarked(Post post) {
659 return isPostBookmarked(post.getId());
663 * Returns whether the post with the given ID is bookmarked.
666 * The ID of the post to check
667 * @return {@code true} if the post with the given ID is bookmarked,
668 * {@code false} otherwise
670 public boolean isPostBookmarked(String id) {
671 synchronized (bookmarkedPosts) {
672 return bookmarkedPosts.contains(id);
677 * Returns all currently known bookmarked posts.
679 * @return All bookmarked posts
681 public Set<Post> getBookmarkedPosts() {
682 Set<Post> posts = new HashSet<Post>();
683 synchronized (bookmarkedPosts) {
684 for (String bookmarkedPostId : bookmarkedPosts) {
685 Post post = getPost(bookmarkedPostId, false);
695 * Returns the album with the given ID, creating a new album if no album
696 * with the given ID can be found.
699 * The ID of the album
700 * @return The album with the given ID
702 public Album getAlbum(String albumId) {
703 return getAlbum(albumId, true);
707 * Returns the album with the given ID, optionally creating a new album if
708 * an album with the given ID can not be found.
711 * The ID of the album
713 * {@code true} to create a new album if none exists for the
715 * @return The album with the given ID, or {@code null} if no album with the
716 * given ID exists and {@code create} is {@code false}
718 public Album getAlbum(String albumId, boolean create) {
719 synchronized (albums) {
720 Album album = albums.get(albumId);
721 if (create && (album == null)) {
722 album = new Album(albumId);
723 albums.put(albumId, album);
730 * Returns the image with the given ID, creating it if necessary.
733 * The ID of the image
734 * @return The image with the given ID
736 public Image getImage(String imageId) {
737 return getImage(imageId, true);
741 * Returns the image with the given ID, optionally creating it if it does
745 * The ID of the image
747 * {@code true} to create an image if none exists with the given
749 * @return The image with the given ID, or {@code null} if none exists and
752 public Image getImage(String imageId, boolean create) {
753 synchronized (images) {
754 Image image = images.get(imageId);
755 if (create && (image == null)) {
756 image = new Image(imageId);
757 images.put(imageId, image);
764 * Returns the temporary image with the given ID.
767 * The ID of the temporary image
768 * @return The temporary image, or {@code null} if there is no temporary
769 * image with the given ID
771 public TemporaryImage getTemporaryImage(String imageId) {
772 synchronized (temporaryImages) {
773 return temporaryImages.get(imageId);
782 * Locks the given Sone. A locked Sone will not be inserted by
783 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
789 public void lockSone(Sone sone) {
790 synchronized (lockedSones) {
791 if (lockedSones.add(sone)) {
792 coreListenerManager.fireSoneLocked(sone);
798 * Unlocks the given Sone.
800 * @see #lockSone(Sone)
804 public void unlockSone(Sone sone) {
805 synchronized (lockedSones) {
806 if (lockedSones.remove(sone)) {
807 coreListenerManager.fireSoneUnlocked(sone);
813 * Adds a local Sone from the given own identity.
816 * The own identity to create a Sone from
817 * @return The added (or already existing) Sone
819 public Sone addLocalSone(OwnIdentity ownIdentity) {
820 if (ownIdentity == null) {
821 logger.log(Level.WARNING, "Given OwnIdentity is null!");
824 synchronized (sones) {
827 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
828 } catch (MalformedURLException mue1) {
829 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
832 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
833 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
835 /* TODO - load posts ’n stuff */
836 sones.put(ownIdentity.getId(), sone);
837 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
838 soneInserter.addSoneInsertListener(this);
839 soneInserters.put(sone, soneInserter);
840 sone.setStatus(SoneStatus.idle);
842 soneInserter.start();
848 * Creates a new Sone for the given own identity.
851 * The own identity to create a Sone for
852 * @return The created Sone
854 public Sone createSone(OwnIdentity ownIdentity) {
855 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
856 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
859 Sone sone = addLocalSone(ownIdentity);
860 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
861 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
862 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
863 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
864 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
865 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
867 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
868 touchConfiguration();
873 * Adds the Sone of the given identity.
876 * The identity whose Sone to add
877 * @return The added or already existing Sone
879 public Sone addRemoteSone(Identity identity) {
880 if (identity == null) {
881 logger.log(Level.WARNING, "Given Identity is null!");
884 synchronized (sones) {
885 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
886 boolean newSone = sone.getRequestUri() == null;
887 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
888 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
890 synchronized (knownSones) {
891 newSone = !knownSones.contains(sone.getId());
893 sone.setKnown(!newSone);
895 coreListenerManager.fireNewSoneFound(sone);
896 for (Sone localSone : getLocalSones()) {
897 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
898 followSone(localSone, sone);
903 soneDownloader.addSone(sone);
904 soneDownloaders.execute(new Runnable() {
907 @SuppressWarnings("synthetic-access")
909 soneDownloader.fetchSone(sone, sone.getRequestUri());
918 * Lets the given local Sone follow the Sone with the given ID.
921 * The local Sone that should follow another Sone
923 * The ID of the Sone to follow
925 public void followSone(Sone sone, String soneId) {
926 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
927 Sone followedSone = getSone(soneId, true);
928 if (followedSone == null) {
929 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
932 followSone(sone, getSone(soneId));
936 * Lets the given local Sone follow the other given Sone. If the given Sone
937 * was not followed by any local Sone before, this will mark all elements of
938 * the followed Sone as read that have been created before the current
942 * The local Sone that should follow the other Sone
943 * @param followedSone
944 * The Sone that should be followed
946 public void followSone(Sone sone, Sone followedSone) {
947 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
948 sone.addFriend(followedSone.getId());
949 synchronized (soneFollowingTimes) {
950 if (!soneFollowingTimes.containsKey(followedSone)) {
951 long now = System.currentTimeMillis();
952 soneFollowingTimes.put(followedSone, now);
953 for (Post post : followedSone.getPosts()) {
954 if (post.getTime() < now) {
958 for (PostReply reply : followedSone.getReplies()) {
959 if (reply.getTime() < now) {
960 markReplyKnown(reply);
965 touchConfiguration();
969 * Lets the given local Sone unfollow the Sone with the given ID.
972 * The local Sone that should unfollow another Sone
974 * The ID of the Sone being unfollowed
976 public void unfollowSone(Sone sone, String soneId) {
977 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
978 unfollowSone(sone, getSone(soneId, false));
982 * Lets the given local Sone unfollow the other given Sone. If the given
983 * local Sone is the last local Sone that followed the given Sone, its
984 * following time will be removed.
987 * The local Sone that should unfollow another Sone
988 * @param unfollowedSone
989 * The Sone being unfollowed
991 public void unfollowSone(Sone sone, Sone unfollowedSone) {
992 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
993 sone.removeFriend(unfollowedSone.getId());
994 boolean unfollowedSoneStillFollowed = false;
995 for (Sone localSone : getLocalSones()) {
996 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
998 if (!unfollowedSoneStillFollowed) {
999 synchronized (soneFollowingTimes) {
1000 soneFollowingTimes.remove(unfollowedSone);
1003 touchConfiguration();
1007 * Sets the trust value of the given origin Sone for the target Sone.
1014 * The trust value (from {@code -100} to {@code 100})
1016 public void setTrust(Sone origin, Sone target, int trustValue) {
1017 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();
1018 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1022 * Removes any trust assignment for the given target Sone.
1029 public void removeTrust(Sone origin, Sone target) {
1030 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1031 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1035 * Assigns the configured positive trust value for the given target.
1042 public void trustSone(Sone origin, Sone target) {
1043 setTrust(origin, target, preferences.getPositiveTrust());
1047 * Assigns the configured negative trust value for the given target.
1054 public void distrustSone(Sone origin, Sone target) {
1055 setTrust(origin, target, preferences.getNegativeTrust());
1059 * Removes the trust assignment for the given target.
1066 public void untrustSone(Sone origin, Sone target) {
1067 removeTrust(origin, target);
1071 * Updates the stored Sone with the given Sone.
1076 public void updateSone(Sone sone) {
1077 updateSone(sone, false);
1081 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1082 * {@code true}, an older Sone than the current Sone can be given to restore
1086 * The Sone to update
1087 * @param soneRescueMode
1088 * {@code true} if the stored Sone should be updated regardless
1089 * of the age of the given Sone
1091 public void updateSone(Sone sone, boolean soneRescueMode) {
1092 if (hasSone(sone.getId())) {
1093 Sone storedSone = getSone(sone.getId());
1094 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1095 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1098 synchronized (posts) {
1099 if (!soneRescueMode) {
1100 for (Post post : storedSone.getPosts()) {
1101 posts.remove(post.getId());
1102 if (!sone.getPosts().contains(post)) {
1103 coreListenerManager.firePostRemoved(post);
1107 List<Post> storedPosts = storedSone.getPosts();
1108 synchronized (knownPosts) {
1109 for (Post post : sone.getPosts()) {
1110 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1111 if (!storedPosts.contains(post)) {
1112 if (post.getTime() < getSoneFollowingTime(sone)) {
1113 knownPosts.add(post.getId());
1114 post.setKnown(true);
1115 } else if (!knownPosts.contains(post.getId())) {
1116 coreListenerManager.fireNewPostFound(post);
1119 posts.put(post.getId(), post);
1123 synchronized (replies) {
1124 if (!soneRescueMode) {
1125 for (PostReply reply : storedSone.getReplies()) {
1126 replies.remove(reply.getId());
1127 if (!sone.getReplies().contains(reply)) {
1128 coreListenerManager.fireReplyRemoved(reply);
1132 Set<PostReply> storedReplies = storedSone.getReplies();
1133 synchronized (knownReplies) {
1134 for (PostReply reply : sone.getReplies()) {
1135 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1136 if (!storedReplies.contains(reply)) {
1137 if (reply.getTime() < getSoneFollowingTime(sone)) {
1138 knownReplies.add(reply.getId());
1139 reply.setKnown(true);
1140 } else if (!knownReplies.contains(reply.getId())) {
1141 coreListenerManager.fireNewReplyFound(reply);
1144 replies.put(reply.getId(), reply);
1148 synchronized (albums) {
1149 synchronized (images) {
1150 for (Album album : storedSone.getAlbums()) {
1151 albums.remove(album.getId());
1152 for (Image image : album.getImages()) {
1153 images.remove(image.getId());
1156 for (Album album : sone.getAlbums()) {
1157 albums.put(album.getId(), album);
1158 for (Image image : album.getImages()) {
1159 images.put(image.getId(), image);
1164 synchronized (storedSone) {
1165 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1166 storedSone.setTime(sone.getTime());
1168 storedSone.setClient(sone.getClient());
1169 storedSone.setProfile(sone.getProfile());
1170 if (soneRescueMode) {
1171 for (Post post : sone.getPosts()) {
1172 storedSone.addPost(post);
1174 for (PostReply reply : sone.getReplies()) {
1175 storedSone.addReply(reply);
1177 for (String likedPostId : sone.getLikedPostIds()) {
1178 storedSone.addLikedPostId(likedPostId);
1180 for (String likedReplyId : sone.getLikedReplyIds()) {
1181 storedSone.addLikedReplyId(likedReplyId);
1183 for (Album album : sone.getAlbums()) {
1184 storedSone.addAlbum(album);
1187 storedSone.setPosts(sone.getPosts());
1188 storedSone.setReplies(sone.getReplies());
1189 storedSone.setLikePostIds(sone.getLikedPostIds());
1190 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1191 storedSone.setAlbums(sone.getAlbums());
1193 storedSone.setLatestEdition(sone.getLatestEdition());
1199 * Deletes the given Sone. This will remove the Sone from the
1200 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1201 * remove the context from its identity.
1204 * The Sone to delete
1206 public void deleteSone(Sone sone) {
1207 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1208 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1211 synchronized (sones) {
1212 if (!getLocalSones().contains(sone)) {
1213 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1216 sones.remove(sone.getId());
1217 SoneInserter soneInserter = soneInserters.remove(sone);
1218 soneInserter.removeSoneInsertListener(this);
1219 soneInserter.stop();
1221 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1222 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1224 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1225 } catch (ConfigurationException ce1) {
1226 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1231 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1232 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1235 * The Sone to mark as known
1237 public void markSoneKnown(Sone sone) {
1238 if (!sone.isKnown()) {
1239 sone.setKnown(true);
1240 synchronized (knownSones) {
1241 knownSones.add(sone.getId());
1243 coreListenerManager.fireMarkSoneKnown(sone);
1244 touchConfiguration();
1249 * Loads and updates the given Sone from the configuration. If any error is
1250 * encountered, loading is aborted and the given Sone is not changed.
1253 * The Sone to load and update
1255 public void loadSone(Sone sone) {
1256 if (!sone.isLocal()) {
1257 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1261 /* initialize options. */
1262 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1263 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1264 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1265 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1266 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1267 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1270 String sonePrefix = "Sone/" + sone.getId();
1271 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1272 if (soneTime == null) {
1273 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1276 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1279 Profile profile = new Profile(sone);
1280 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1281 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1282 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1283 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1284 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1285 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1287 /* load profile fields. */
1289 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1290 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1291 if (fieldName == null) {
1294 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1295 profile.addField(fieldName).setValue(fieldValue);
1299 Set<Post> posts = new HashSet<Post>();
1301 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1302 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1303 if (postId == null) {
1306 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1307 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1308 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1309 if ((postTime == 0) || (postText == null)) {
1310 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1313 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1314 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1315 post.setRecipient(getSone(postRecipientId));
1321 Set<PostReply> replies = new HashSet<PostReply>();
1323 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1324 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1325 if (replyId == null) {
1328 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1329 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1330 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1331 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1332 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1335 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1338 /* load post likes. */
1339 Set<String> likedPostIds = new HashSet<String>();
1341 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1342 if (likedPostId == null) {
1345 likedPostIds.add(likedPostId);
1348 /* load reply likes. */
1349 Set<String> likedReplyIds = new HashSet<String>();
1351 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1352 if (likedReplyId == null) {
1355 likedReplyIds.add(likedReplyId);
1359 Set<String> friends = new HashSet<String>();
1361 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1362 if (friendId == null) {
1365 friends.add(friendId);
1369 List<Album> topLevelAlbums = new ArrayList<Album>();
1370 int albumCounter = 0;
1372 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1373 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1374 if (albumId == null) {
1377 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1378 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1379 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1380 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1381 if ((albumTitle == null) || (albumDescription == null)) {
1382 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1385 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1386 if (albumParentId != null) {
1387 Album parentAlbum = getAlbum(albumParentId, false);
1388 if (parentAlbum == null) {
1389 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1392 parentAlbum.addAlbum(album);
1394 if (!topLevelAlbums.contains(album)) {
1395 topLevelAlbums.add(album);
1401 int imageCounter = 0;
1403 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1404 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1405 if (imageId == null) {
1408 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1409 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1410 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1411 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1412 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1413 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1414 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1415 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1416 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1419 Album album = getAlbum(albumId, false);
1420 if (album == null) {
1421 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1424 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1425 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1426 album.addImage(image);
1430 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1431 if (avatarId != null) {
1432 profile.setAvatar(getImage(avatarId, false));
1436 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1437 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1438 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1439 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1440 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1441 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1443 /* if we’re still here, Sone was loaded successfully. */
1444 synchronized (sone) {
1445 sone.setTime(soneTime);
1446 sone.setProfile(profile);
1447 sone.setPosts(posts);
1448 sone.setReplies(replies);
1449 sone.setLikePostIds(likedPostIds);
1450 sone.setLikeReplyIds(likedReplyIds);
1451 for (String friendId : friends) {
1452 followSone(sone, friendId);
1454 sone.setAlbums(topLevelAlbums);
1455 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1457 synchronized (knownSones) {
1458 for (String friend : friends) {
1459 knownSones.add(friend);
1462 synchronized (knownPosts) {
1463 for (Post post : posts) {
1464 knownPosts.add(post.getId());
1467 synchronized (knownReplies) {
1468 for (PostReply reply : replies) {
1469 knownReplies.add(reply.getId());
1475 * Creates a new post.
1478 * The Sone that creates the post
1480 * The text of the post
1481 * @return The created post
1483 public Post createPost(Sone sone, String text) {
1484 return createPost(sone, System.currentTimeMillis(), text);
1488 * Creates a new post.
1491 * The Sone that creates the post
1493 * The time of the post
1495 * The text of the post
1496 * @return The created post
1498 public Post createPost(Sone sone, long time, String text) {
1499 return createPost(sone, null, time, text);
1503 * Creates a new post.
1506 * The Sone that creates the post
1508 * The recipient Sone, or {@code null} if this post does not have
1511 * The text of the post
1512 * @return The created post
1514 public Post createPost(Sone sone, Sone recipient, String text) {
1515 return createPost(sone, recipient, System.currentTimeMillis(), text);
1519 * Creates a new post.
1522 * The Sone that creates the post
1524 * The recipient Sone, or {@code null} if this post does not have
1527 * The time of the post
1529 * The text of the post
1530 * @return The created post
1532 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1533 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1534 if (!sone.isLocal()) {
1535 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1538 final Post post = new PostImpl(sone, time, text);
1539 if (recipient != null) {
1540 post.setRecipient(recipient);
1542 synchronized (posts) {
1543 posts.put(post.getId(), post);
1545 coreListenerManager.fireNewPostFound(post);
1547 touchConfiguration();
1548 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1555 markPostKnown(post);
1557 }, "Mark " + post + " read.");
1562 * Deletes the given post.
1565 * The post to delete
1567 public void deletePost(Post post) {
1568 if (!post.getSone().isLocal()) {
1569 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1572 post.getSone().removePost(post);
1573 synchronized (posts) {
1574 posts.remove(post.getId());
1576 coreListenerManager.firePostRemoved(post);
1577 markPostKnown(post);
1578 touchConfiguration();
1582 * Marks the given post as known, if it is currently not a known post
1583 * (according to {@link Post#isKnown()}).
1586 * The post to mark as known
1588 public void markPostKnown(Post post) {
1589 post.setKnown(true);
1590 synchronized (knownPosts) {
1591 coreListenerManager.fireMarkPostKnown(post);
1592 if (knownPosts.add(post.getId())) {
1593 touchConfiguration();
1596 for (PostReply reply : getReplies(post)) {
1597 markReplyKnown(reply);
1602 * Bookmarks the given post.
1605 * The post to bookmark
1607 public void bookmark(Post post) {
1608 bookmarkPost(post.getId());
1612 * Bookmarks the post with the given ID.
1615 * The ID of the post to bookmark
1617 public void bookmarkPost(String id) {
1618 synchronized (bookmarkedPosts) {
1619 bookmarkedPosts.add(id);
1624 * Removes the given post from the bookmarks.
1627 * The post to unbookmark
1629 public void unbookmark(Post post) {
1630 unbookmarkPost(post.getId());
1634 * Removes the post with the given ID from the bookmarks.
1637 * The ID of the post to unbookmark
1639 public void unbookmarkPost(String id) {
1640 synchronized (bookmarkedPosts) {
1641 bookmarkedPosts.remove(id);
1646 * Creates a new reply.
1649 * The Sone that creates the reply
1651 * The post that this reply refers to
1653 * The text of the reply
1654 * @return The created reply
1656 public PostReply createReply(Sone sone, Post post, String text) {
1657 return createReply(sone, post, System.currentTimeMillis(), text);
1661 * Creates a new reply.
1664 * The Sone that creates the reply
1666 * The post that this reply refers to
1668 * The time of the reply
1670 * The text of the reply
1671 * @return The created reply
1673 public PostReply createReply(Sone sone, Post post, long time, String text) {
1674 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1675 if (!sone.isLocal()) {
1676 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1679 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1680 synchronized (replies) {
1681 replies.put(reply.getId(), reply);
1683 synchronized (knownReplies) {
1684 coreListenerManager.fireNewReplyFound(reply);
1686 sone.addReply(reply);
1687 touchConfiguration();
1688 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1695 markReplyKnown(reply);
1697 }, "Mark " + reply + " read.");
1702 * Deletes the given reply.
1705 * The reply to delete
1707 public void deleteReply(PostReply reply) {
1708 Sone sone = reply.getSone();
1709 if (!sone.isLocal()) {
1710 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1713 synchronized (replies) {
1714 replies.remove(reply.getId());
1716 synchronized (knownReplies) {
1717 markReplyKnown(reply);
1718 knownReplies.remove(reply.getId());
1720 sone.removeReply(reply);
1721 touchConfiguration();
1725 * Marks the given reply as known, if it is currently not a known reply
1726 * (according to {@link Reply#isKnown()}).
1729 * The reply to mark as known
1731 public void markReplyKnown(PostReply reply) {
1732 reply.setKnown(true);
1733 synchronized (knownReplies) {
1734 coreListenerManager.fireMarkReplyKnown(reply);
1735 if (knownReplies.add(reply.getId())) {
1736 touchConfiguration();
1742 * Creates a new top-level album for the given Sone.
1745 * The Sone to create the album for
1746 * @return The new album
1748 public Album createAlbum(Sone sone) {
1749 return createAlbum(sone, null);
1753 * Creates a new album for the given Sone.
1756 * The Sone to create the album for
1758 * The parent of the album (may be {@code null} to create a
1760 * @return The new album
1762 public Album createAlbum(Sone sone, Album parent) {
1763 Album album = new Album();
1764 synchronized (albums) {
1765 albums.put(album.getId(), album);
1767 album.setSone(sone);
1768 if (parent != null) {
1769 parent.addAlbum(album);
1771 sone.addAlbum(album);
1777 * Deletes the given album. The owner of the album has to be a local Sone,
1778 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1781 * The album to remove
1783 public void deleteAlbum(Album album) {
1784 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1785 if (!album.isEmpty()) {
1788 if (album.getParent() == null) {
1789 album.getSone().removeAlbum(album);
1791 album.getParent().removeAlbum(album);
1793 synchronized (albums) {
1794 albums.remove(album.getId());
1796 touchConfiguration();
1800 * Creates a new image.
1803 * The Sone creating the image
1805 * The album the image will be inserted into
1806 * @param temporaryImage
1807 * The temporary image to create the image from
1808 * @return The newly created image
1810 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1811 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();
1812 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1813 album.addImage(image);
1814 synchronized (images) {
1815 images.put(image.getId(), image);
1817 imageInserter.insertImage(temporaryImage, image);
1822 * Deletes the given image. This method will also delete a matching
1825 * @see #deleteTemporaryImage(TemporaryImage)
1827 * The image to delete
1829 public void deleteImage(Image image) {
1830 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1831 deleteTemporaryImage(image.getId());
1832 image.getAlbum().removeImage(image);
1833 synchronized (images) {
1834 images.remove(image.getId());
1836 touchConfiguration();
1840 * Creates a new temporary image.
1843 * The MIME type of the temporary image
1845 * The encoded data of the image
1846 * @return The temporary image
1848 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1849 TemporaryImage temporaryImage = new TemporaryImage();
1850 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1851 synchronized (temporaryImages) {
1852 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1854 return temporaryImage;
1858 * Deletes the given temporary image.
1860 * @param temporaryImage
1861 * The temporary image to delete
1863 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1864 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1865 deleteTemporaryImage(temporaryImage.getId());
1869 * Deletes the temporary image with the given ID.
1872 * The ID of the temporary image to delete
1874 public void deleteTemporaryImage(String imageId) {
1875 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1876 synchronized (temporaryImages) {
1877 temporaryImages.remove(imageId);
1879 Image image = getImage(imageId, false);
1880 if (image != null) {
1881 imageInserter.cancelImageInsert(image);
1886 * Notifies the core that the configuration, either of the core or of a
1887 * single local Sone, has changed, and that the configuration should be
1890 public void touchConfiguration() {
1891 lastConfigurationUpdate = System.currentTimeMillis();
1902 public void serviceStart() {
1903 loadConfiguration();
1904 updateChecker.addUpdateListener(this);
1905 updateChecker.start();
1906 identityManager.addIdentityListener(this);
1907 identityManager.start();
1908 webOfTrustUpdater.init();
1909 webOfTrustUpdater.start();
1916 public void serviceRun() {
1917 long lastSaved = System.currentTimeMillis();
1918 while (!shouldStop()) {
1920 long now = System.currentTimeMillis();
1921 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1922 for (Sone localSone : getLocalSones()) {
1923 saveSone(localSone);
1925 saveConfiguration();
1935 public void serviceStop() {
1936 synchronized (sones) {
1937 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1938 soneInserter.getValue().removeSoneInsertListener(this);
1939 soneInserter.getValue().stop();
1940 saveSone(soneInserter.getKey());
1943 saveConfiguration();
1944 webOfTrustUpdater.stop();
1945 updateChecker.stop();
1946 updateChecker.removeUpdateListener(this);
1947 soneDownloader.stop();
1948 identityManager.removeIdentityListener(this);
1949 identityManager.stop();
1957 * Saves the given Sone. This will persist all local settings for the given
1958 * Sone, such as the friends list and similar, private options.
1963 private synchronized void saveSone(Sone sone) {
1964 if (!sone.isLocal()) {
1965 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1968 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1969 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1973 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1975 /* save Sone into configuration. */
1976 String sonePrefix = "Sone/" + sone.getId();
1977 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1978 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1981 Profile profile = sone.getProfile();
1982 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1983 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1984 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1985 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1986 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1987 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1988 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1990 /* save profile fields. */
1991 int fieldCounter = 0;
1992 for (Field profileField : profile.getFields()) {
1993 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1994 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1995 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1997 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2000 int postCounter = 0;
2001 for (Post post : sone.getPosts()) {
2002 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2003 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2004 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2005 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2006 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2008 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2011 int replyCounter = 0;
2012 for (PostReply reply : sone.getReplies()) {
2013 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2014 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2015 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2016 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2017 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2019 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2021 /* save post likes. */
2022 int postLikeCounter = 0;
2023 for (String postId : sone.getLikedPostIds()) {
2024 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2026 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2028 /* save reply likes. */
2029 int replyLikeCounter = 0;
2030 for (String replyId : sone.getLikedReplyIds()) {
2031 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2033 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2036 int friendCounter = 0;
2037 for (String friendId : sone.getFriends()) {
2038 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2040 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2042 /* save albums. first, collect in a flat structure, top-level first. */
2043 List<Album> albums = sone.getAllAlbums();
2045 int albumCounter = 0;
2046 for (Album album : albums) {
2047 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2048 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2049 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2050 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2051 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2052 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2054 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2057 int imageCounter = 0;
2058 for (Album album : albums) {
2059 for (Image image : album.getImages()) {
2060 if (!image.isInserted()) {
2063 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2064 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2065 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2066 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2067 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2068 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2069 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2070 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2071 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2074 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2077 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2078 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2079 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2080 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2081 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2082 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2084 configuration.save();
2086 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2088 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2089 } catch (ConfigurationException ce1) {
2090 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2095 * Saves the current options.
2097 private void saveConfiguration() {
2098 synchronized (configuration) {
2099 if (storingConfiguration) {
2100 logger.log(Level.FINE, "Already storing configuration…");
2103 storingConfiguration = true;
2106 /* store the options first. */
2108 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2109 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2110 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2111 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2112 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2113 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2114 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2115 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2116 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2117 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2118 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2119 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2121 /* save known Sones. */
2122 int soneCounter = 0;
2123 synchronized (knownSones) {
2124 for (String knownSoneId : knownSones) {
2125 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2127 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2130 /* save Sone following times. */
2132 synchronized (soneFollowingTimes) {
2133 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2134 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2135 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2138 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2141 /* save known posts. */
2142 int postCounter = 0;
2143 synchronized (knownPosts) {
2144 for (String knownPostId : knownPosts) {
2145 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2147 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2150 /* save known replies. */
2151 int replyCounter = 0;
2152 synchronized (knownReplies) {
2153 for (String knownReplyId : knownReplies) {
2154 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2156 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2159 /* save bookmarked posts. */
2160 int bookmarkedPostCounter = 0;
2161 synchronized (bookmarkedPosts) {
2162 for (String bookmarkedPostId : bookmarkedPosts) {
2163 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2166 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2169 configuration.save();
2171 } catch (ConfigurationException ce1) {
2172 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2174 synchronized (configuration) {
2175 storingConfiguration = false;
2181 * Loads the configuration.
2183 @SuppressWarnings("unchecked")
2184 private void loadConfiguration() {
2185 /* create options. */
2186 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2189 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2190 SoneInserter.setInsertionDelay(newValue);
2194 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2195 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2196 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2197 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2198 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2199 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2200 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2201 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2202 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2205 @SuppressWarnings("synthetic-access")
2206 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2207 fcpInterface.setActive(newValue);
2210 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2213 @SuppressWarnings("synthetic-access")
2214 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2215 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2220 loadConfigurationValue("InsertionDelay");
2221 loadConfigurationValue("PostsPerPage");
2222 loadConfigurationValue("ImagesPerPage");
2223 loadConfigurationValue("CharactersPerPost");
2224 loadConfigurationValue("PostCutOffLength");
2225 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2226 loadConfigurationValue("PositiveTrust");
2227 loadConfigurationValue("NegativeTrust");
2228 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2229 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2230 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2232 /* load known Sones. */
2233 int soneCounter = 0;
2235 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2236 if (knownSoneId == null) {
2239 synchronized (knownSones) {
2240 knownSones.add(knownSoneId);
2244 /* load Sone following times. */
2247 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2248 if (soneId == null) {
2251 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2252 Sone followedSone = getSone(soneId);
2253 if (followedSone == null) {
2254 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2256 synchronized (soneFollowingTimes) {
2257 soneFollowingTimes.put(getSone(soneId), time);
2263 /* load known posts. */
2264 int postCounter = 0;
2266 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2267 if (knownPostId == null) {
2270 synchronized (knownPosts) {
2271 knownPosts.add(knownPostId);
2275 /* load known replies. */
2276 int replyCounter = 0;
2278 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2279 if (knownReplyId == null) {
2282 synchronized (knownReplies) {
2283 knownReplies.add(knownReplyId);
2287 /* load bookmarked posts. */
2288 int bookmarkedPostCounter = 0;
2290 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2291 if (bookmarkedPostId == null) {
2294 synchronized (bookmarkedPosts) {
2295 bookmarkedPosts.add(bookmarkedPostId);
2302 * Loads an {@link Integer} configuration value for the option with the
2303 * given name, logging validation failures.
2306 * The name of the option to load
2308 private void loadConfigurationValue(String optionName) {
2310 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2311 } catch (IllegalArgumentException iae1) {
2312 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2317 * Generate a Sone URI from the given URI and latest edition.
2320 * The URI to derive the Sone URI from
2321 * @return The derived URI
2323 private static FreenetURI getSoneUri(String uriString) {
2325 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2327 } catch (MalformedURLException mue1) {
2328 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2334 // INTERFACE IdentityListener
2341 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2342 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2343 if (ownIdentity.hasContext("Sone")) {
2344 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2345 addLocalSone(ownIdentity);
2353 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2354 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2355 trustedIdentities.remove(ownIdentity);
2362 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2363 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2364 trustedIdentities.get(ownIdentity).add(identity);
2365 addRemoteSone(identity);
2372 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2373 soneDownloaders.execute(new Runnable() {
2376 @SuppressWarnings("synthetic-access")
2378 Sone sone = getRemoteSone(identity.getId(), false);
2379 sone.setIdentity(identity);
2380 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2381 soneDownloader.addSone(sone);
2382 soneDownloader.fetchSone(sone);
2391 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2392 trustedIdentities.get(ownIdentity).remove(identity);
2393 boolean foundIdentity = false;
2394 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2395 if (trustedIdentity.getKey().equals(ownIdentity)) {
2398 if (trustedIdentity.getValue().contains(identity)) {
2399 foundIdentity = true;
2402 if (foundIdentity) {
2403 /* some local identity still trusts this identity, don’t remove. */
2406 Sone sone = getSone(identity.getId(), false);
2408 /* TODO - we don’t have the Sone anymore. should this happen? */
2411 synchronized (posts) {
2412 synchronized (knownPosts) {
2413 for (Post post : sone.getPosts()) {
2414 posts.remove(post.getId());
2415 coreListenerManager.firePostRemoved(post);
2419 synchronized (replies) {
2420 synchronized (knownReplies) {
2421 for (PostReply reply : sone.getReplies()) {
2422 replies.remove(reply.getId());
2423 coreListenerManager.fireReplyRemoved(reply);
2427 synchronized (sones) {
2428 sones.remove(identity.getId());
2430 coreListenerManager.fireSoneRemoved(sone);
2434 // INTERFACE UpdateListener
2441 public void updateFound(Version version, long releaseTime, long latestEdition) {
2442 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2446 // INTERFACE ImageInsertListener
2453 public void insertStarted(Sone sone) {
2454 coreListenerManager.fireSoneInserting(sone);
2461 public void insertFinished(Sone sone, long insertDuration) {
2462 coreListenerManager.fireSoneInserted(sone, insertDuration);
2469 public void insertAborted(Sone sone, Throwable cause) {
2470 coreListenerManager.fireSoneInsertAborted(sone, cause);
2474 // SONEINSERTLISTENER METHODS
2481 public void imageInsertStarted(Image image) {
2482 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2483 coreListenerManager.fireImageInsertStarted(image);
2490 public void imageInsertAborted(Image image) {
2491 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2492 coreListenerManager.fireImageInsertAborted(image);
2499 public void imageInsertFinished(Image image, FreenetURI key) {
2500 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2501 image.setKey(key.toString());
2502 deleteTemporaryImage(image.getId());
2503 touchConfiguration();
2504 coreListenerManager.fireImageInsertFinished(image);
2511 public void imageInsertFailed(Image image, Throwable cause) {
2512 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2513 coreListenerManager.fireImageInsertFailed(image, cause);
2517 * Convenience interface for external classes that want to access the core’s
2520 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2522 public static class Preferences {
2524 /** The wrapped options. */
2525 private final Options options;
2528 * Creates a new preferences object wrapped around the given options.
2531 * The options to wrap
2533 public Preferences(Options options) {
2534 this.options = options;
2538 * Returns the insertion delay.
2540 * @return The insertion delay
2542 public int getInsertionDelay() {
2543 return options.getIntegerOption("InsertionDelay").get();
2547 * Validates the given insertion delay.
2549 * @param insertionDelay
2550 * The insertion delay to validate
2551 * @return {@code true} if the given insertion delay was valid,
2552 * {@code false} otherwise
2554 public boolean validateInsertionDelay(Integer insertionDelay) {
2555 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2559 * Sets the insertion delay
2561 * @param insertionDelay
2562 * The new insertion delay, or {@code null} to restore it to
2564 * @return This preferences
2566 public Preferences setInsertionDelay(Integer insertionDelay) {
2567 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2572 * Returns the number of posts to show per page.
2574 * @return The number of posts to show per page
2576 public int getPostsPerPage() {
2577 return options.getIntegerOption("PostsPerPage").get();
2581 * Validates the number of posts per page.
2583 * @param postsPerPage
2584 * The number of posts per page
2585 * @return {@code true} if the number of posts per page was valid,
2586 * {@code false} otherwise
2588 public boolean validatePostsPerPage(Integer postsPerPage) {
2589 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2593 * Sets the number of posts to show per page.
2595 * @param postsPerPage
2596 * The number of posts to show per page
2597 * @return This preferences object
2599 public Preferences setPostsPerPage(Integer postsPerPage) {
2600 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2605 * Returns the number of images to show per page.
2607 * @return The number of images to show per page
2609 public int getImagesPerPage() {
2610 return options.getIntegerOption("ImagesPerPage").get();
2614 * Validates the number of images per page.
2616 * @param imagesPerPage
2617 * The number of images per page
2618 * @return {@code true} if the number of images per page was valid,
2619 * {@code false} otherwise
2621 public boolean validateImagesPerPage(Integer imagesPerPage) {
2622 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2626 * Sets the number of images per page.
2628 * @param imagesPerPage
2629 * The number of images per page
2630 * @return This preferences object
2632 public Preferences setImagesPerPage(Integer imagesPerPage) {
2633 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2638 * Returns the number of characters per post, or <code>-1</code> if the
2639 * posts should not be cut off.
2641 * @return The numbers of characters per post
2643 public int getCharactersPerPost() {
2644 return options.getIntegerOption("CharactersPerPost").get();
2648 * Validates the number of characters per post.
2650 * @param charactersPerPost
2651 * The number of characters per post
2652 * @return {@code true} if the number of characters per post was valid,
2653 * {@code false} otherwise
2655 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2656 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2660 * Sets the number of characters per post.
2662 * @param charactersPerPost
2663 * The number of characters per post, or <code>-1</code> to
2664 * not cut off the posts
2665 * @return This preferences objects
2667 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2668 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2673 * Returns the number of characters the shortened post should have.
2675 * @return The number of characters of the snippet
2677 public int getPostCutOffLength() {
2678 return options.getIntegerOption("PostCutOffLength").get();
2682 * Validates the number of characters after which to cut off the post.
2684 * @param postCutOffLength
2685 * The number of characters of the snippet
2686 * @return {@code true} if the number of characters of the snippet is
2687 * valid, {@code false} otherwise
2689 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2690 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2694 * Sets the number of characters the shortened post should have.
2696 * @param postCutOffLength
2697 * The number of characters of the snippet
2698 * @return This preferences
2700 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2701 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2706 * Returns whether Sone requires full access to be even visible.
2708 * @return {@code true} if Sone requires full access, {@code false}
2711 public boolean isRequireFullAccess() {
2712 return options.getBooleanOption("RequireFullAccess").get();
2716 * Sets whether Sone requires full access to be even visible.
2718 * @param requireFullAccess
2719 * {@code true} if Sone requires full access, {@code false}
2722 public void setRequireFullAccess(Boolean requireFullAccess) {
2723 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2727 * Returns the positive trust.
2729 * @return The positive trust
2731 public int getPositiveTrust() {
2732 return options.getIntegerOption("PositiveTrust").get();
2736 * Validates the positive trust.
2738 * @param positiveTrust
2739 * The positive trust to validate
2740 * @return {@code true} if the positive trust was valid, {@code false}
2743 public boolean validatePositiveTrust(Integer positiveTrust) {
2744 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2748 * Sets the positive trust.
2750 * @param positiveTrust
2751 * The new positive trust, or {@code null} to restore it to
2753 * @return This preferences
2755 public Preferences setPositiveTrust(Integer positiveTrust) {
2756 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2761 * Returns the negative trust.
2763 * @return The negative trust
2765 public int getNegativeTrust() {
2766 return options.getIntegerOption("NegativeTrust").get();
2770 * Validates the negative trust.
2772 * @param negativeTrust
2773 * The negative trust to validate
2774 * @return {@code true} if the negative trust was valid, {@code false}
2777 public boolean validateNegativeTrust(Integer negativeTrust) {
2778 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2782 * Sets the negative trust.
2784 * @param negativeTrust
2785 * The negative trust, or {@code null} to restore it to the
2787 * @return The preferences
2789 public Preferences setNegativeTrust(Integer negativeTrust) {
2790 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2795 * Returns the trust comment. This is the comment that is set in the web
2796 * of trust when a trust value is assigned to an identity.
2798 * @return The trust comment
2800 public String getTrustComment() {
2801 return options.getStringOption("TrustComment").get();
2805 * Sets the trust comment.
2807 * @param trustComment
2808 * The trust comment, or {@code null} to restore it to the
2810 * @return This preferences
2812 public Preferences setTrustComment(String trustComment) {
2813 options.getStringOption("TrustComment").set(trustComment);
2818 * Returns whether the {@link FcpInterface FCP interface} is currently
2821 * @see FcpInterface#setActive(boolean)
2822 * @return {@code true} if the FCP interface is currently active,
2823 * {@code false} otherwise
2825 public boolean isFcpInterfaceActive() {
2826 return options.getBooleanOption("ActivateFcpInterface").get();
2830 * Sets whether the {@link FcpInterface FCP interface} is currently
2833 * @see FcpInterface#setActive(boolean)
2834 * @param fcpInterfaceActive
2835 * {@code true} to activate the FCP interface, {@code false}
2836 * to deactivate the FCP interface
2837 * @return This preferences object
2839 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2840 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2845 * Returns the action level for which full access to the FCP interface
2848 * @return The action level for which full access to the FCP interface
2851 public FullAccessRequired getFcpFullAccessRequired() {
2852 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2856 * Sets the action level for which full access to the FCP interface is
2859 * @param fcpFullAccessRequired
2861 * @return This preferences
2863 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2864 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);