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.inject.Inject;
75 import freenet.keys.FreenetURI;
80 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
85 private static final Logger logger = Logging.getLogger(Core.class);
87 /** The start time. */
88 private final long startupTime = System.currentTimeMillis();
91 private final Options options = new Options();
93 /** The preferences. */
94 private final Preferences preferences = new Preferences(options);
96 /** The core listener manager. */
97 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
99 /** The configuration. */
100 private Configuration configuration;
102 /** Whether we’re currently saving the configuration. */
103 private boolean storingConfiguration = false;
105 /** The identity manager. */
106 private final IdentityManager identityManager;
108 /** Interface to freenet. */
109 private final FreenetInterface freenetInterface;
111 /** The Sone downloader. */
112 private final SoneDownloader soneDownloader;
114 /** The image inserter. */
115 private final ImageInserter imageInserter;
117 /** Sone downloader thread-pool. */
118 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
120 /** The update checker. */
121 private final UpdateChecker updateChecker;
123 /** The trust updater. */
124 private final WebOfTrustUpdater webOfTrustUpdater;
126 /** The FCP interface. */
127 private volatile FcpInterface fcpInterface;
129 /** The times Sones were followed. */
130 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
132 /** Locked local Sones. */
133 /* synchronize on itself. */
134 private final Set<Sone> lockedSones = new HashSet<Sone>();
136 /** Sone inserters. */
137 /* synchronize access on this on sones. */
138 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
140 /** Sone rescuers. */
141 /* synchronize access on this on sones. */
142 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
145 /* synchronize access on this on itself. */
146 private final Map<String, Sone> sones = new HashMap<String, Sone>();
148 /** All known Sones. */
149 private final Set<String> knownSones = new HashSet<String>();
152 private final Map<String, Post> posts = new HashMap<String, Post>();
154 /** All known posts. */
155 private final Set<String> knownPosts = new HashSet<String>();
158 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
160 /** All known replies. */
161 private final Set<String> knownReplies = new HashSet<String>();
163 /** All bookmarked posts. */
164 /* synchronize access on itself. */
165 private final Set<String> bookmarkedPosts = new HashSet<String>();
167 /** Trusted identities, sorted by own identities. */
168 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
170 /** All known albums. */
171 private final Map<String, Album> albums = new HashMap<String, Album>();
173 /** All known images. */
174 private final Map<String, Image> images = new HashMap<String, Image>();
176 /** All temporary images. */
177 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
179 /** Ticker for threads that mark own elements as known. */
180 private final Ticker localElementTicker = new Ticker();
182 /** The time the configuration was last touched. */
183 private volatile long lastConfigurationUpdate;
186 * Creates a new core.
188 * @param configuration
189 * The configuration of the core
190 * @param freenetInterface
191 * The freenet interface
192 * @param identityManager
193 * The identity manager
194 * @param webOfTrustUpdater
195 * The WebOfTrust updater
198 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
200 this.configuration = configuration;
201 this.freenetInterface = freenetInterface;
202 this.identityManager = identityManager;
203 this.soneDownloader = new SoneDownloader(this, freenetInterface);
204 this.imageInserter = new ImageInserter(this, freenetInterface);
205 this.updateChecker = new UpdateChecker(freenetInterface);
206 this.webOfTrustUpdater = webOfTrustUpdater;
210 // LISTENER MANAGEMENT
214 * Adds a new core listener.
216 * @param coreListener
217 * The listener to add
219 public void addCoreListener(CoreListener coreListener) {
220 coreListenerManager.addListener(coreListener);
224 * Removes a core listener.
226 * @param coreListener
227 * The listener to remove
229 public void removeCoreListener(CoreListener coreListener) {
230 coreListenerManager.removeListener(coreListener);
238 * Returns the time Sone was started.
240 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
242 public long getStartupTime() {
247 * Sets the configuration to use. This will automatically save the current
248 * configuration to the given configuration.
250 * @param configuration
251 * The new configuration to use
253 public void setConfiguration(Configuration configuration) {
254 this.configuration = configuration;
255 touchConfiguration();
259 * Returns the options used by the core.
261 * @return The options of the core
263 public Preferences getPreferences() {
268 * Returns the identity manager used by the core.
270 * @return The identity manager
272 public IdentityManager getIdentityManager() {
273 return identityManager;
277 * Returns the update checker.
279 * @return The update checker
281 public UpdateChecker getUpdateChecker() {
282 return updateChecker;
286 * Sets the FCP interface to use.
288 * @param fcpInterface
289 * The FCP interface to use
291 public void setFcpInterface(FcpInterface fcpInterface) {
292 this.fcpInterface = fcpInterface;
296 * Returns the Sone rescuer for the given local Sone.
299 * The local Sone to get the rescuer for
300 * @return The Sone rescuer for the given Sone
302 public SoneRescuer getSoneRescuer(Sone sone) {
303 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
304 synchronized (sones) {
305 SoneRescuer soneRescuer = soneRescuers.get(sone);
306 if (soneRescuer == null) {
307 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
308 soneRescuers.put(sone, soneRescuer);
316 * Returns whether the given Sone is currently locked.
320 * @return {@code true} if the Sone is locked, {@code false} if it is not
322 public boolean isLocked(Sone sone) {
323 synchronized (lockedSones) {
324 return lockedSones.contains(sone);
329 * Returns all Sones, remote and local.
333 public Set<Sone> getSones() {
334 return new HashSet<Sone>(sones.values());
338 * Returns the Sone with the given ID, regardless whether it’s local or
342 * The ID of the Sone to get
343 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Sone getSone(String id) {
347 return getSone(id, true);
351 * Returns the Sone with the given ID, regardless whether it’s local or
355 * The ID of the Sone to get
357 * {@code true} to create a new Sone if none exists,
358 * {@code false} to return {@code null} if a Sone with the given
360 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Sone getSone(String id, boolean create) {
365 synchronized (sones) {
366 if (!sones.containsKey(id)) {
367 Sone sone = new Sone(id, false);
370 return sones.get(id);
375 * Checks whether the core knows a Sone with the given ID.
379 * @return {@code true} if there is a Sone with the given ID, {@code false}
382 public boolean hasSone(String id) {
383 synchronized (sones) {
384 return sones.containsKey(id);
389 * Returns all local Sones.
391 * @return All local Sones
393 public Collection<Sone> getLocalSones() {
394 synchronized (sones) {
395 return Collections2.filter(sones.values(), new Predicate<Sone>() {
398 public boolean apply(Sone sone) {
399 return sone.isLocal();
406 * Returns the local Sone with the given ID, optionally creating a new Sone.
411 * {@code true} to create a new Sone if none exists,
412 * {@code false} to return null if none exists
413 * @return The Sone with the given ID, or {@code null}
415 public Sone getLocalSone(String id, boolean create) {
416 synchronized (sones) {
417 Sone sone = sones.get(id);
418 if ((sone == null) && create) {
419 sone = new Sone(id, true);
422 if ((sone != null) && !sone.isLocal()) {
423 sone = new Sone(id, true);
431 * Returns all remote Sones.
433 * @return All remote Sones
435 public Collection<Sone> getRemoteSones() {
436 synchronized (sones) {
437 return Collections2.filter(sones.values(), new Predicate<Sone>() {
440 public boolean apply(Sone sone) {
441 return !sone.isLocal();
448 * Returns the remote Sone with the given ID.
451 * The ID of the remote Sone to get
453 * {@code true} to always create a Sone, {@code false} to return
454 * {@code null} if no Sone with the given ID exists
455 * @return The Sone with the given ID
457 public Sone getRemoteSone(String id, boolean create) {
458 synchronized (sones) {
459 Sone sone = sones.get(id);
460 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
461 sone = new Sone(id, false);
469 * Returns whether the given Sone has been modified.
472 * The Sone to check for modifications
473 * @return {@code true} if a modification has been detected in the Sone,
474 * {@code false} otherwise
476 public boolean isModifiedSone(Sone sone) {
477 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
481 * Returns the time when the given was first followed by any local Sone.
484 * The Sone to get the time for
485 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
486 * been followed, or {@link Long#MAX_VALUE}
488 public long getSoneFollowingTime(Sone sone) {
489 synchronized (soneFollowingTimes) {
490 if (soneFollowingTimes.containsKey(sone)) {
491 return soneFollowingTimes.get(sone);
493 return Long.MAX_VALUE;
498 * Returns whether the target Sone is trusted by the origin Sone.
504 * @return {@code true} if the target Sone is trusted by the origin Sone
506 public boolean isSoneTrusted(Sone origin, Sone target) {
507 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
508 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
512 * Returns the post with the given ID.
515 * The ID of the post to get
516 * @return The post with the given ID, or a new post with the given ID
518 public Post getPost(String postId) {
519 return getPost(postId, true);
523 * Returns the post with the given ID, optionally creating a new post.
526 * The ID of the post to get
528 * {@code true} it create a new post if no post with the given ID
529 * exists, {@code false} to return {@code null}
530 * @return The post, or {@code null} if there is no such post
533 public Post getPost(String postId, boolean create) {
534 synchronized (posts) {
535 Post post = posts.get(postId);
536 if ((post == null) && create) {
537 post = new PostImpl(postId);
538 posts.put(postId, post);
545 * Returns all posts that have the given Sone as recipient.
547 * @see Post#getRecipient()
549 * The recipient of the posts
550 * @return All posts that have the given Sone as recipient
552 public Set<Post> getDirectedPosts(Sone recipient) {
553 Validation.begin().isNotNull("Recipient", recipient).check();
554 Set<Post> directedPosts = new HashSet<Post>();
555 synchronized (posts) {
556 for (Post post : posts.values()) {
557 if (recipient.equals(post.getRecipient())) {
558 directedPosts.add(post);
562 return directedPosts;
566 * Returns the reply with the given ID. If there is no reply with the given
567 * ID yet, a new one is created, unless {@code create} is false in which
568 * case {@code null} is returned.
571 * The ID of the reply to get
573 * {@code true} to always return a {@link Reply}, {@code false}
574 * to return {@code null} if no reply can be found
575 * @return The reply, or {@code null} if there is no such reply
577 public PostReply getPostReply(String replyId, boolean create) {
578 synchronized (replies) {
579 PostReply reply = replies.get(replyId);
580 if (create && (reply == null)) {
581 reply = new PostReply(replyId);
582 replies.put(replyId, reply);
589 * Returns all replies for the given post, order ascending by time.
592 * The post to get all replies for
593 * @return All replies for the given post
595 public List<PostReply> getReplies(Post post) {
596 Set<Sone> sones = getSones();
597 List<PostReply> replies = new ArrayList<PostReply>();
598 for (Sone sone : sones) {
599 for (PostReply reply : sone.getReplies()) {
600 if (reply.getPost().equals(post)) {
605 Collections.sort(replies, Reply.TIME_COMPARATOR);
610 * Returns all Sones that have liked the given post.
613 * The post to get the liking Sones for
614 * @return The Sones that like the given post
616 public Set<Sone> getLikes(Post post) {
617 Set<Sone> sones = new HashSet<Sone>();
618 for (Sone sone : getSones()) {
619 if (sone.getLikedPostIds().contains(post.getId())) {
627 * Returns all Sones that have liked the given reply.
630 * The reply to get the liking Sones for
631 * @return The Sones that like the given reply
633 public Set<Sone> getLikes(PostReply reply) {
634 Set<Sone> sones = new HashSet<Sone>();
635 for (Sone sone : getSones()) {
636 if (sone.getLikedReplyIds().contains(reply.getId())) {
644 * Returns whether the given post is bookmarked.
648 * @return {@code true} if the given post is bookmarked, {@code false}
651 public boolean isBookmarked(Post post) {
652 return isPostBookmarked(post.getId());
656 * Returns whether the post with the given ID is bookmarked.
659 * The ID of the post to check
660 * @return {@code true} if the post with the given ID is bookmarked,
661 * {@code false} otherwise
663 public boolean isPostBookmarked(String id) {
664 synchronized (bookmarkedPosts) {
665 return bookmarkedPosts.contains(id);
670 * Returns all currently known bookmarked posts.
672 * @return All bookmarked posts
674 public Set<Post> getBookmarkedPosts() {
675 Set<Post> posts = new HashSet<Post>();
676 synchronized (bookmarkedPosts) {
677 for (String bookmarkedPostId : bookmarkedPosts) {
678 Post post = getPost(bookmarkedPostId, false);
688 * Returns the album with the given ID, creating a new album if no album
689 * with the given ID can be found.
692 * The ID of the album
693 * @return The album with the given ID
695 public Album getAlbum(String albumId) {
696 return getAlbum(albumId, true);
700 * Returns the album with the given ID, optionally creating a new album if
701 * an album with the given ID can not be found.
704 * The ID of the album
706 * {@code true} to create a new album if none exists for the
708 * @return The album with the given ID, or {@code null} if no album with the
709 * given ID exists and {@code create} is {@code false}
711 public Album getAlbum(String albumId, boolean create) {
712 synchronized (albums) {
713 Album album = albums.get(albumId);
714 if (create && (album == null)) {
715 album = new Album(albumId);
716 albums.put(albumId, album);
723 * Returns the image with the given ID, creating it if necessary.
726 * The ID of the image
727 * @return The image with the given ID
729 public Image getImage(String imageId) {
730 return getImage(imageId, true);
734 * Returns the image with the given ID, optionally creating it if it does
738 * The ID of the image
740 * {@code true} to create an image if none exists with the given
742 * @return The image with the given ID, or {@code null} if none exists and
745 public Image getImage(String imageId, boolean create) {
746 synchronized (images) {
747 Image image = images.get(imageId);
748 if (create && (image == null)) {
749 image = new Image(imageId);
750 images.put(imageId, image);
757 * Returns the temporary image with the given ID.
760 * The ID of the temporary image
761 * @return The temporary image, or {@code null} if there is no temporary
762 * image with the given ID
764 public TemporaryImage getTemporaryImage(String imageId) {
765 synchronized (temporaryImages) {
766 return temporaryImages.get(imageId);
775 * Locks the given Sone. A locked Sone will not be inserted by
776 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
782 public void lockSone(Sone sone) {
783 synchronized (lockedSones) {
784 if (lockedSones.add(sone)) {
785 coreListenerManager.fireSoneLocked(sone);
791 * Unlocks the given Sone.
793 * @see #lockSone(Sone)
797 public void unlockSone(Sone sone) {
798 synchronized (lockedSones) {
799 if (lockedSones.remove(sone)) {
800 coreListenerManager.fireSoneUnlocked(sone);
806 * Adds a local Sone from the given own identity.
809 * The own identity to create a Sone from
810 * @return The added (or already existing) Sone
812 public Sone addLocalSone(OwnIdentity ownIdentity) {
813 if (ownIdentity == null) {
814 logger.log(Level.WARNING, "Given OwnIdentity is null!");
817 synchronized (sones) {
820 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
821 } catch (MalformedURLException mue1) {
822 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
825 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
826 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
828 /* TODO - load posts ’n stuff */
829 sones.put(ownIdentity.getId(), sone);
830 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
831 soneInserter.addSoneInsertListener(this);
832 soneInserters.put(sone, soneInserter);
833 sone.setStatus(SoneStatus.idle);
835 soneInserter.start();
841 * Creates a new Sone for the given own identity.
844 * The own identity to create a Sone for
845 * @return The created Sone
847 public Sone createSone(OwnIdentity ownIdentity) {
848 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
849 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
852 Sone sone = addLocalSone(ownIdentity);
853 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
854 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
855 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
856 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
857 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
858 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
860 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
861 touchConfiguration();
866 * Adds the Sone of the given identity.
869 * The identity whose Sone to add
870 * @return The added or already existing Sone
872 public Sone addRemoteSone(Identity identity) {
873 if (identity == null) {
874 logger.log(Level.WARNING, "Given Identity is null!");
877 synchronized (sones) {
878 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
879 boolean newSone = sone.getRequestUri() == null;
880 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
881 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
883 synchronized (knownSones) {
884 newSone = !knownSones.contains(sone.getId());
886 sone.setKnown(!newSone);
888 coreListenerManager.fireNewSoneFound(sone);
889 for (Sone localSone : getLocalSones()) {
890 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
891 followSone(localSone, sone);
896 soneDownloader.addSone(sone);
897 soneDownloaders.execute(new Runnable() {
900 @SuppressWarnings("synthetic-access")
902 soneDownloader.fetchSone(sone, sone.getRequestUri());
911 * Lets the given local Sone follow the Sone with the given ID.
914 * The local Sone that should follow another Sone
916 * The ID of the Sone to follow
918 public void followSone(Sone sone, String soneId) {
919 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
920 Sone followedSone = getSone(soneId, true);
921 if (followedSone == null) {
922 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
925 followSone(sone, getSone(soneId));
929 * Lets the given local Sone follow the other given Sone. If the given Sone
930 * was not followed by any local Sone before, this will mark all elements of
931 * the followed Sone as read that have been created before the current
935 * The local Sone that should follow the other Sone
936 * @param followedSone
937 * The Sone that should be followed
939 public void followSone(Sone sone, Sone followedSone) {
940 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
941 sone.addFriend(followedSone.getId());
942 synchronized (soneFollowingTimes) {
943 if (!soneFollowingTimes.containsKey(followedSone)) {
944 long now = System.currentTimeMillis();
945 soneFollowingTimes.put(followedSone, now);
946 for (Post post : followedSone.getPosts()) {
947 if (post.getTime() < now) {
951 for (PostReply reply : followedSone.getReplies()) {
952 if (reply.getTime() < now) {
953 markReplyKnown(reply);
958 touchConfiguration();
962 * Lets the given local Sone unfollow the Sone with the given ID.
965 * The local Sone that should unfollow another Sone
967 * The ID of the Sone being unfollowed
969 public void unfollowSone(Sone sone, String soneId) {
970 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
971 unfollowSone(sone, getSone(soneId, false));
975 * Lets the given local Sone unfollow the other given Sone. If the given
976 * local Sone is the last local Sone that followed the given Sone, its
977 * following time will be removed.
980 * The local Sone that should unfollow another Sone
981 * @param unfollowedSone
982 * The Sone being unfollowed
984 public void unfollowSone(Sone sone, Sone unfollowedSone) {
985 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
986 sone.removeFriend(unfollowedSone.getId());
987 boolean unfollowedSoneStillFollowed = false;
988 for (Sone localSone : getLocalSones()) {
989 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
991 if (!unfollowedSoneStillFollowed) {
992 synchronized (soneFollowingTimes) {
993 soneFollowingTimes.remove(unfollowedSone);
996 touchConfiguration();
1000 * Sets the trust value of the given origin Sone for the target Sone.
1007 * The trust value (from {@code -100} to {@code 100})
1009 public void setTrust(Sone origin, Sone target, int trustValue) {
1010 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();
1011 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1015 * Removes any trust assignment for the given target Sone.
1022 public void removeTrust(Sone origin, Sone target) {
1023 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1024 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1028 * Assigns the configured positive trust value for the given target.
1035 public void trustSone(Sone origin, Sone target) {
1036 setTrust(origin, target, preferences.getPositiveTrust());
1040 * Assigns the configured negative trust value for the given target.
1047 public void distrustSone(Sone origin, Sone target) {
1048 setTrust(origin, target, preferences.getNegativeTrust());
1052 * Removes the trust assignment for the given target.
1059 public void untrustSone(Sone origin, Sone target) {
1060 removeTrust(origin, target);
1064 * Updates the stored Sone with the given Sone.
1069 public void updateSone(Sone sone) {
1070 updateSone(sone, false);
1074 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1075 * {@code true}, an older Sone than the current Sone can be given to restore
1079 * The Sone to update
1080 * @param soneRescueMode
1081 * {@code true} if the stored Sone should be updated regardless
1082 * of the age of the given Sone
1084 public void updateSone(Sone sone, boolean soneRescueMode) {
1085 if (hasSone(sone.getId())) {
1086 Sone storedSone = getSone(sone.getId());
1087 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1088 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1091 synchronized (posts) {
1092 if (!soneRescueMode) {
1093 for (Post post : storedSone.getPosts()) {
1094 posts.remove(post.getId());
1095 if (!sone.getPosts().contains(post)) {
1096 coreListenerManager.firePostRemoved(post);
1100 List<Post> storedPosts = storedSone.getPosts();
1101 synchronized (knownPosts) {
1102 for (Post post : sone.getPosts()) {
1103 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1104 if (!storedPosts.contains(post)) {
1105 if (post.getTime() < getSoneFollowingTime(sone)) {
1106 knownPosts.add(post.getId());
1107 post.setKnown(true);
1108 } else if (!knownPosts.contains(post.getId())) {
1109 coreListenerManager.fireNewPostFound(post);
1112 posts.put(post.getId(), post);
1116 synchronized (replies) {
1117 if (!soneRescueMode) {
1118 for (PostReply reply : storedSone.getReplies()) {
1119 replies.remove(reply.getId());
1120 if (!sone.getReplies().contains(reply)) {
1121 coreListenerManager.fireReplyRemoved(reply);
1125 Set<PostReply> storedReplies = storedSone.getReplies();
1126 synchronized (knownReplies) {
1127 for (PostReply reply : sone.getReplies()) {
1128 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1129 if (!storedReplies.contains(reply)) {
1130 if (reply.getTime() < getSoneFollowingTime(sone)) {
1131 knownReplies.add(reply.getId());
1132 reply.setKnown(true);
1133 } else if (!knownReplies.contains(reply.getId())) {
1134 coreListenerManager.fireNewReplyFound(reply);
1137 replies.put(reply.getId(), reply);
1141 synchronized (albums) {
1142 synchronized (images) {
1143 for (Album album : storedSone.getAlbums()) {
1144 albums.remove(album.getId());
1145 for (Image image : album.getImages()) {
1146 images.remove(image.getId());
1149 for (Album album : sone.getAlbums()) {
1150 albums.put(album.getId(), album);
1151 for (Image image : album.getImages()) {
1152 images.put(image.getId(), image);
1157 synchronized (storedSone) {
1158 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1159 storedSone.setTime(sone.getTime());
1161 storedSone.setClient(sone.getClient());
1162 storedSone.setProfile(sone.getProfile());
1163 if (soneRescueMode) {
1164 for (Post post : sone.getPosts()) {
1165 storedSone.addPost(post);
1167 for (PostReply reply : sone.getReplies()) {
1168 storedSone.addReply(reply);
1170 for (String likedPostId : sone.getLikedPostIds()) {
1171 storedSone.addLikedPostId(likedPostId);
1173 for (String likedReplyId : sone.getLikedReplyIds()) {
1174 storedSone.addLikedReplyId(likedReplyId);
1176 for (Album album : sone.getAlbums()) {
1177 storedSone.addAlbum(album);
1180 storedSone.setPosts(sone.getPosts());
1181 storedSone.setReplies(sone.getReplies());
1182 storedSone.setLikePostIds(sone.getLikedPostIds());
1183 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1184 storedSone.setAlbums(sone.getAlbums());
1186 storedSone.setLatestEdition(sone.getLatestEdition());
1192 * Deletes the given Sone. This will remove the Sone from the
1193 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1194 * remove the context from its identity.
1197 * The Sone to delete
1199 public void deleteSone(Sone sone) {
1200 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1201 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1204 synchronized (sones) {
1205 if (!getLocalSones().contains(sone)) {
1206 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1209 sones.remove(sone.getId());
1210 SoneInserter soneInserter = soneInserters.remove(sone);
1211 soneInserter.removeSoneInsertListener(this);
1212 soneInserter.stop();
1214 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1215 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1217 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1218 } catch (ConfigurationException ce1) {
1219 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1224 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1225 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1228 * The Sone to mark as known
1230 public void markSoneKnown(Sone sone) {
1231 if (!sone.isKnown()) {
1232 sone.setKnown(true);
1233 synchronized (knownSones) {
1234 knownSones.add(sone.getId());
1236 coreListenerManager.fireMarkSoneKnown(sone);
1237 touchConfiguration();
1242 * Loads and updates the given Sone from the configuration. If any error is
1243 * encountered, loading is aborted and the given Sone is not changed.
1246 * The Sone to load and update
1248 public void loadSone(Sone sone) {
1249 if (!sone.isLocal()) {
1250 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1254 /* initialize options. */
1255 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1256 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1257 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1258 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1259 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1260 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1263 String sonePrefix = "Sone/" + sone.getId();
1264 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1265 if (soneTime == null) {
1266 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1269 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1272 Profile profile = new Profile(sone);
1273 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1274 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1275 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1276 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1277 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1278 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1280 /* load profile fields. */
1282 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1283 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1284 if (fieldName == null) {
1287 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1288 profile.addField(fieldName).setValue(fieldValue);
1292 Set<Post> posts = new HashSet<Post>();
1294 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1295 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1296 if (postId == null) {
1299 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1300 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1301 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1302 if ((postTime == 0) || (postText == null)) {
1303 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1306 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1307 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1308 post.setRecipient(getSone(postRecipientId));
1314 Set<PostReply> replies = new HashSet<PostReply>();
1316 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1317 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1318 if (replyId == null) {
1321 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1322 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1323 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1324 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1325 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1328 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1331 /* load post likes. */
1332 Set<String> likedPostIds = new HashSet<String>();
1334 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1335 if (likedPostId == null) {
1338 likedPostIds.add(likedPostId);
1341 /* load reply likes. */
1342 Set<String> likedReplyIds = new HashSet<String>();
1344 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1345 if (likedReplyId == null) {
1348 likedReplyIds.add(likedReplyId);
1352 Set<String> friends = new HashSet<String>();
1354 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1355 if (friendId == null) {
1358 friends.add(friendId);
1362 List<Album> topLevelAlbums = new ArrayList<Album>();
1363 int albumCounter = 0;
1365 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1366 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1367 if (albumId == null) {
1370 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1371 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1372 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1373 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1374 if ((albumTitle == null) || (albumDescription == null)) {
1375 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1378 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1379 if (albumParentId != null) {
1380 Album parentAlbum = getAlbum(albumParentId, false);
1381 if (parentAlbum == null) {
1382 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1385 parentAlbum.addAlbum(album);
1387 if (!topLevelAlbums.contains(album)) {
1388 topLevelAlbums.add(album);
1394 int imageCounter = 0;
1396 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1397 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1398 if (imageId == null) {
1401 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1402 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1403 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1404 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1405 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1406 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1407 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1408 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1409 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1412 Album album = getAlbum(albumId, false);
1413 if (album == null) {
1414 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1417 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1418 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1419 album.addImage(image);
1423 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1424 if (avatarId != null) {
1425 profile.setAvatar(getImage(avatarId, false));
1429 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1430 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1431 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1432 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1433 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1434 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1436 /* if we’re still here, Sone was loaded successfully. */
1437 synchronized (sone) {
1438 sone.setTime(soneTime);
1439 sone.setProfile(profile);
1440 sone.setPosts(posts);
1441 sone.setReplies(replies);
1442 sone.setLikePostIds(likedPostIds);
1443 sone.setLikeReplyIds(likedReplyIds);
1444 for (String friendId : friends) {
1445 followSone(sone, friendId);
1447 sone.setAlbums(topLevelAlbums);
1448 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1450 synchronized (knownSones) {
1451 for (String friend : friends) {
1452 knownSones.add(friend);
1455 synchronized (knownPosts) {
1456 for (Post post : posts) {
1457 knownPosts.add(post.getId());
1460 synchronized (knownReplies) {
1461 for (PostReply reply : replies) {
1462 knownReplies.add(reply.getId());
1468 * Creates a new post.
1471 * The Sone that creates the post
1473 * The text of the post
1474 * @return The created post
1476 public Post createPost(Sone sone, String text) {
1477 return createPost(sone, System.currentTimeMillis(), text);
1481 * Creates a new post.
1484 * The Sone that creates the post
1486 * The time of the post
1488 * The text of the post
1489 * @return The created post
1491 public Post createPost(Sone sone, long time, String text) {
1492 return createPost(sone, null, time, text);
1496 * Creates a new post.
1499 * The Sone that creates the post
1501 * The recipient Sone, or {@code null} if this post does not have
1504 * The text of the post
1505 * @return The created post
1507 public Post createPost(Sone sone, Sone recipient, String text) {
1508 return createPost(sone, recipient, System.currentTimeMillis(), text);
1512 * Creates a new post.
1515 * The Sone that creates the post
1517 * The recipient Sone, or {@code null} if this post does not have
1520 * The time of the post
1522 * The text of the post
1523 * @return The created post
1525 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1526 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1527 if (!sone.isLocal()) {
1528 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1531 final Post post = new PostImpl(sone, time, text);
1532 if (recipient != null) {
1533 post.setRecipient(recipient);
1535 synchronized (posts) {
1536 posts.put(post.getId(), post);
1538 coreListenerManager.fireNewPostFound(post);
1540 touchConfiguration();
1541 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1548 markPostKnown(post);
1550 }, "Mark " + post + " read.");
1555 * Deletes the given post.
1558 * The post to delete
1560 public void deletePost(Post post) {
1561 if (!post.getSone().isLocal()) {
1562 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1565 post.getSone().removePost(post);
1566 synchronized (posts) {
1567 posts.remove(post.getId());
1569 coreListenerManager.firePostRemoved(post);
1570 markPostKnown(post);
1571 touchConfiguration();
1575 * Marks the given post as known, if it is currently not a known post
1576 * (according to {@link Post#isKnown()}).
1579 * The post to mark as known
1581 public void markPostKnown(Post post) {
1582 post.setKnown(true);
1583 synchronized (knownPosts) {
1584 coreListenerManager.fireMarkPostKnown(post);
1585 if (knownPosts.add(post.getId())) {
1586 touchConfiguration();
1589 for (PostReply reply : getReplies(post)) {
1590 markReplyKnown(reply);
1595 * Bookmarks the given post.
1598 * The post to bookmark
1600 public void bookmark(Post post) {
1601 bookmarkPost(post.getId());
1605 * Bookmarks the post with the given ID.
1608 * The ID of the post to bookmark
1610 public void bookmarkPost(String id) {
1611 synchronized (bookmarkedPosts) {
1612 bookmarkedPosts.add(id);
1617 * Removes the given post from the bookmarks.
1620 * The post to unbookmark
1622 public void unbookmark(Post post) {
1623 unbookmarkPost(post.getId());
1627 * Removes the post with the given ID from the bookmarks.
1630 * The ID of the post to unbookmark
1632 public void unbookmarkPost(String id) {
1633 synchronized (bookmarkedPosts) {
1634 bookmarkedPosts.remove(id);
1639 * Creates a new reply.
1642 * The Sone that creates the reply
1644 * The post that this reply refers to
1646 * The text of the reply
1647 * @return The created reply
1649 public PostReply createReply(Sone sone, Post post, String text) {
1650 return createReply(sone, post, System.currentTimeMillis(), text);
1654 * Creates a new reply.
1657 * The Sone that creates the reply
1659 * The post that this reply refers to
1661 * The time of the reply
1663 * The text of the reply
1664 * @return The created reply
1666 public PostReply createReply(Sone sone, Post post, long time, String text) {
1667 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1668 if (!sone.isLocal()) {
1669 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1672 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1673 synchronized (replies) {
1674 replies.put(reply.getId(), reply);
1676 synchronized (knownReplies) {
1677 coreListenerManager.fireNewReplyFound(reply);
1679 sone.addReply(reply);
1680 touchConfiguration();
1681 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1688 markReplyKnown(reply);
1690 }, "Mark " + reply + " read.");
1695 * Deletes the given reply.
1698 * The reply to delete
1700 public void deleteReply(PostReply reply) {
1701 Sone sone = reply.getSone();
1702 if (!sone.isLocal()) {
1703 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1706 synchronized (replies) {
1707 replies.remove(reply.getId());
1709 synchronized (knownReplies) {
1710 markReplyKnown(reply);
1711 knownReplies.remove(reply.getId());
1713 sone.removeReply(reply);
1714 touchConfiguration();
1718 * Marks the given reply as known, if it is currently not a known reply
1719 * (according to {@link Reply#isKnown()}).
1722 * The reply to mark as known
1724 public void markReplyKnown(PostReply reply) {
1725 reply.setKnown(true);
1726 synchronized (knownReplies) {
1727 coreListenerManager.fireMarkReplyKnown(reply);
1728 if (knownReplies.add(reply.getId())) {
1729 touchConfiguration();
1735 * Creates a new top-level album for the given Sone.
1738 * The Sone to create the album for
1739 * @return The new album
1741 public Album createAlbum(Sone sone) {
1742 return createAlbum(sone, null);
1746 * Creates a new album for the given Sone.
1749 * The Sone to create the album for
1751 * The parent of the album (may be {@code null} to create a
1753 * @return The new album
1755 public Album createAlbum(Sone sone, Album parent) {
1756 Album album = new Album();
1757 synchronized (albums) {
1758 albums.put(album.getId(), album);
1760 album.setSone(sone);
1761 if (parent != null) {
1762 parent.addAlbum(album);
1764 sone.addAlbum(album);
1770 * Deletes the given album. The owner of the album has to be a local Sone,
1771 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1774 * The album to remove
1776 public void deleteAlbum(Album album) {
1777 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1778 if (!album.isEmpty()) {
1781 if (album.getParent() == null) {
1782 album.getSone().removeAlbum(album);
1784 album.getParent().removeAlbum(album);
1786 synchronized (albums) {
1787 albums.remove(album.getId());
1789 touchConfiguration();
1793 * Creates a new image.
1796 * The Sone creating the image
1798 * The album the image will be inserted into
1799 * @param temporaryImage
1800 * The temporary image to create the image from
1801 * @return The newly created image
1803 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1804 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();
1805 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1806 album.addImage(image);
1807 synchronized (images) {
1808 images.put(image.getId(), image);
1810 imageInserter.insertImage(temporaryImage, image);
1815 * Deletes the given image. This method will also delete a matching
1818 * @see #deleteTemporaryImage(TemporaryImage)
1820 * The image to delete
1822 public void deleteImage(Image image) {
1823 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1824 deleteTemporaryImage(image.getId());
1825 image.getAlbum().removeImage(image);
1826 synchronized (images) {
1827 images.remove(image.getId());
1829 touchConfiguration();
1833 * Creates a new temporary image.
1836 * The MIME type of the temporary image
1838 * The encoded data of the image
1839 * @return The temporary image
1841 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1842 TemporaryImage temporaryImage = new TemporaryImage();
1843 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1844 synchronized (temporaryImages) {
1845 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1847 return temporaryImage;
1851 * Deletes the given temporary image.
1853 * @param temporaryImage
1854 * The temporary image to delete
1856 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1857 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1858 deleteTemporaryImage(temporaryImage.getId());
1862 * Deletes the temporary image with the given ID.
1865 * The ID of the temporary image to delete
1867 public void deleteTemporaryImage(String imageId) {
1868 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1869 synchronized (temporaryImages) {
1870 temporaryImages.remove(imageId);
1872 Image image = getImage(imageId, false);
1873 if (image != null) {
1874 imageInserter.cancelImageInsert(image);
1879 * Notifies the core that the configuration, either of the core or of a
1880 * single local Sone, has changed, and that the configuration should be
1883 public void touchConfiguration() {
1884 lastConfigurationUpdate = System.currentTimeMillis();
1895 public void serviceStart() {
1896 loadConfiguration();
1897 updateChecker.addUpdateListener(this);
1898 updateChecker.start();
1899 identityManager.addIdentityListener(this);
1900 identityManager.start();
1901 webOfTrustUpdater.init();
1902 webOfTrustUpdater.start();
1909 public void serviceRun() {
1910 long lastSaved = System.currentTimeMillis();
1911 while (!shouldStop()) {
1913 long now = System.currentTimeMillis();
1914 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1915 for (Sone localSone : getLocalSones()) {
1916 saveSone(localSone);
1918 saveConfiguration();
1928 public void serviceStop() {
1929 synchronized (sones) {
1930 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1931 soneInserter.getValue().removeSoneInsertListener(this);
1932 soneInserter.getValue().stop();
1933 saveSone(soneInserter.getKey());
1936 saveConfiguration();
1937 webOfTrustUpdater.stop();
1938 updateChecker.stop();
1939 updateChecker.removeUpdateListener(this);
1940 soneDownloader.stop();
1941 identityManager.removeIdentityListener(this);
1942 identityManager.stop();
1950 * Saves the given Sone. This will persist all local settings for the given
1951 * Sone, such as the friends list and similar, private options.
1956 private synchronized void saveSone(Sone sone) {
1957 if (!sone.isLocal()) {
1958 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1961 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1962 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1966 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1968 /* save Sone into configuration. */
1969 String sonePrefix = "Sone/" + sone.getId();
1970 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1971 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1974 Profile profile = sone.getProfile();
1975 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1976 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1977 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1978 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1979 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1980 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1981 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1983 /* save profile fields. */
1984 int fieldCounter = 0;
1985 for (Field profileField : profile.getFields()) {
1986 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1987 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1988 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1990 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1993 int postCounter = 0;
1994 for (Post post : sone.getPosts()) {
1995 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1996 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1997 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1998 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1999 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2001 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2004 int replyCounter = 0;
2005 for (PostReply reply : sone.getReplies()) {
2006 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2007 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2008 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2009 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2010 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2012 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2014 /* save post likes. */
2015 int postLikeCounter = 0;
2016 for (String postId : sone.getLikedPostIds()) {
2017 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2019 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2021 /* save reply likes. */
2022 int replyLikeCounter = 0;
2023 for (String replyId : sone.getLikedReplyIds()) {
2024 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2026 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2029 int friendCounter = 0;
2030 for (String friendId : sone.getFriends()) {
2031 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2033 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2035 /* save albums. first, collect in a flat structure, top-level first. */
2036 List<Album> albums = sone.getAllAlbums();
2038 int albumCounter = 0;
2039 for (Album album : albums) {
2040 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2041 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2042 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2043 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2044 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2045 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2047 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2050 int imageCounter = 0;
2051 for (Album album : albums) {
2052 for (Image image : album.getImages()) {
2053 if (!image.isInserted()) {
2056 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2057 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2058 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2059 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2060 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2061 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2062 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2063 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2064 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2067 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2070 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2071 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2072 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2073 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2074 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2075 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2077 configuration.save();
2079 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2081 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2082 } catch (ConfigurationException ce1) {
2083 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2088 * Saves the current options.
2090 private void saveConfiguration() {
2091 synchronized (configuration) {
2092 if (storingConfiguration) {
2093 logger.log(Level.FINE, "Already storing configuration…");
2096 storingConfiguration = true;
2099 /* store the options first. */
2101 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2102 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2103 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2104 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2105 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2106 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2107 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2108 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2109 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2110 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2111 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2112 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2114 /* save known Sones. */
2115 int soneCounter = 0;
2116 synchronized (knownSones) {
2117 for (String knownSoneId : knownSones) {
2118 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2120 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2123 /* save Sone following times. */
2125 synchronized (soneFollowingTimes) {
2126 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2127 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2128 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2131 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2134 /* save known posts. */
2135 int postCounter = 0;
2136 synchronized (knownPosts) {
2137 for (String knownPostId : knownPosts) {
2138 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2140 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2143 /* save known replies. */
2144 int replyCounter = 0;
2145 synchronized (knownReplies) {
2146 for (String knownReplyId : knownReplies) {
2147 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2149 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2152 /* save bookmarked posts. */
2153 int bookmarkedPostCounter = 0;
2154 synchronized (bookmarkedPosts) {
2155 for (String bookmarkedPostId : bookmarkedPosts) {
2156 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2159 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2162 configuration.save();
2164 } catch (ConfigurationException ce1) {
2165 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2167 synchronized (configuration) {
2168 storingConfiguration = false;
2174 * Loads the configuration.
2176 @SuppressWarnings("unchecked")
2177 private void loadConfiguration() {
2178 /* create options. */
2179 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2182 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2183 SoneInserter.setInsertionDelay(newValue);
2187 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2188 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2189 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2190 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2191 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2192 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2193 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2194 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2195 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2198 @SuppressWarnings("synthetic-access")
2199 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2200 fcpInterface.setActive(newValue);
2203 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2206 @SuppressWarnings("synthetic-access")
2207 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2208 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2213 loadConfigurationValue("InsertionDelay");
2214 loadConfigurationValue("PostsPerPage");
2215 loadConfigurationValue("ImagesPerPage");
2216 loadConfigurationValue("CharactersPerPost");
2217 loadConfigurationValue("PostCutOffLength");
2218 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2219 loadConfigurationValue("PositiveTrust");
2220 loadConfigurationValue("NegativeTrust");
2221 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2222 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2223 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2225 /* load known Sones. */
2226 int soneCounter = 0;
2228 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2229 if (knownSoneId == null) {
2232 synchronized (knownSones) {
2233 knownSones.add(knownSoneId);
2237 /* load Sone following times. */
2240 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2241 if (soneId == null) {
2244 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2245 Sone followedSone = getSone(soneId);
2246 if (followedSone == null) {
2247 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2249 synchronized (soneFollowingTimes) {
2250 soneFollowingTimes.put(getSone(soneId), time);
2256 /* load known posts. */
2257 int postCounter = 0;
2259 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2260 if (knownPostId == null) {
2263 synchronized (knownPosts) {
2264 knownPosts.add(knownPostId);
2268 /* load known replies. */
2269 int replyCounter = 0;
2271 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2272 if (knownReplyId == null) {
2275 synchronized (knownReplies) {
2276 knownReplies.add(knownReplyId);
2280 /* load bookmarked posts. */
2281 int bookmarkedPostCounter = 0;
2283 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2284 if (bookmarkedPostId == null) {
2287 synchronized (bookmarkedPosts) {
2288 bookmarkedPosts.add(bookmarkedPostId);
2295 * Loads an {@link Integer} configuration value for the option with the
2296 * given name, logging validation failures.
2299 * The name of the option to load
2301 private void loadConfigurationValue(String optionName) {
2303 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2304 } catch (IllegalArgumentException iae1) {
2305 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2310 * Generate a Sone URI from the given URI and latest edition.
2313 * The URI to derive the Sone URI from
2314 * @return The derived URI
2316 private static FreenetURI getSoneUri(String uriString) {
2318 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2320 } catch (MalformedURLException mue1) {
2321 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2327 // INTERFACE IdentityListener
2334 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2335 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2336 if (ownIdentity.hasContext("Sone")) {
2337 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2338 addLocalSone(ownIdentity);
2346 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2347 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2348 trustedIdentities.remove(ownIdentity);
2355 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2356 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2357 trustedIdentities.get(ownIdentity).add(identity);
2358 addRemoteSone(identity);
2365 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2366 soneDownloaders.execute(new Runnable() {
2369 @SuppressWarnings("synthetic-access")
2371 Sone sone = getRemoteSone(identity.getId(), false);
2372 sone.setIdentity(identity);
2373 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2374 soneDownloader.addSone(sone);
2375 soneDownloader.fetchSone(sone);
2384 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2385 trustedIdentities.get(ownIdentity).remove(identity);
2386 boolean foundIdentity = false;
2387 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2388 if (trustedIdentity.getKey().equals(ownIdentity)) {
2391 if (trustedIdentity.getValue().contains(identity)) {
2392 foundIdentity = true;
2395 if (foundIdentity) {
2396 /* some local identity still trusts this identity, don’t remove. */
2399 Sone sone = getSone(identity.getId(), false);
2401 /* TODO - we don’t have the Sone anymore. should this happen? */
2404 synchronized (posts) {
2405 synchronized (knownPosts) {
2406 for (Post post : sone.getPosts()) {
2407 posts.remove(post.getId());
2408 coreListenerManager.firePostRemoved(post);
2412 synchronized (replies) {
2413 synchronized (knownReplies) {
2414 for (PostReply reply : sone.getReplies()) {
2415 replies.remove(reply.getId());
2416 coreListenerManager.fireReplyRemoved(reply);
2420 synchronized (sones) {
2421 sones.remove(identity.getId());
2423 coreListenerManager.fireSoneRemoved(sone);
2427 // INTERFACE UpdateListener
2434 public void updateFound(Version version, long releaseTime, long latestEdition) {
2435 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2439 // INTERFACE ImageInsertListener
2446 public void insertStarted(Sone sone) {
2447 coreListenerManager.fireSoneInserting(sone);
2454 public void insertFinished(Sone sone, long insertDuration) {
2455 coreListenerManager.fireSoneInserted(sone, insertDuration);
2462 public void insertAborted(Sone sone, Throwable cause) {
2463 coreListenerManager.fireSoneInsertAborted(sone, cause);
2467 // SONEINSERTLISTENER METHODS
2474 public void imageInsertStarted(Image image) {
2475 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2476 coreListenerManager.fireImageInsertStarted(image);
2483 public void imageInsertAborted(Image image) {
2484 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2485 coreListenerManager.fireImageInsertAborted(image);
2492 public void imageInsertFinished(Image image, FreenetURI key) {
2493 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2494 image.setKey(key.toString());
2495 deleteTemporaryImage(image.getId());
2496 touchConfiguration();
2497 coreListenerManager.fireImageInsertFinished(image);
2504 public void imageInsertFailed(Image image, Throwable cause) {
2505 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2506 coreListenerManager.fireImageInsertFailed(image, cause);
2510 * Convenience interface for external classes that want to access the core’s
2513 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2515 public static class Preferences {
2517 /** The wrapped options. */
2518 private final Options options;
2521 * Creates a new preferences object wrapped around the given options.
2524 * The options to wrap
2526 public Preferences(Options options) {
2527 this.options = options;
2531 * Returns the insertion delay.
2533 * @return The insertion delay
2535 public int getInsertionDelay() {
2536 return options.getIntegerOption("InsertionDelay").get();
2540 * Validates the given insertion delay.
2542 * @param insertionDelay
2543 * The insertion delay to validate
2544 * @return {@code true} if the given insertion delay was valid,
2545 * {@code false} otherwise
2547 public boolean validateInsertionDelay(Integer insertionDelay) {
2548 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2552 * Sets the insertion delay
2554 * @param insertionDelay
2555 * The new insertion delay, or {@code null} to restore it to
2557 * @return This preferences
2559 public Preferences setInsertionDelay(Integer insertionDelay) {
2560 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2565 * Returns the number of posts to show per page.
2567 * @return The number of posts to show per page
2569 public int getPostsPerPage() {
2570 return options.getIntegerOption("PostsPerPage").get();
2574 * Validates the number of posts per page.
2576 * @param postsPerPage
2577 * The number of posts per page
2578 * @return {@code true} if the number of posts per page was valid,
2579 * {@code false} otherwise
2581 public boolean validatePostsPerPage(Integer postsPerPage) {
2582 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2586 * Sets the number of posts to show per page.
2588 * @param postsPerPage
2589 * The number of posts to show per page
2590 * @return This preferences object
2592 public Preferences setPostsPerPage(Integer postsPerPage) {
2593 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2598 * Returns the number of images to show per page.
2600 * @return The number of images to show per page
2602 public int getImagesPerPage() {
2603 return options.getIntegerOption("ImagesPerPage").get();
2607 * Validates the number of images per page.
2609 * @param imagesPerPage
2610 * The number of images per page
2611 * @return {@code true} if the number of images per page was valid,
2612 * {@code false} otherwise
2614 public boolean validateImagesPerPage(Integer imagesPerPage) {
2615 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2619 * Sets the number of images per page.
2621 * @param imagesPerPage
2622 * The number of images per page
2623 * @return This preferences object
2625 public Preferences setImagesPerPage(Integer imagesPerPage) {
2626 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2631 * Returns the number of characters per post, or <code>-1</code> if the
2632 * posts should not be cut off.
2634 * @return The numbers of characters per post
2636 public int getCharactersPerPost() {
2637 return options.getIntegerOption("CharactersPerPost").get();
2641 * Validates the number of characters per post.
2643 * @param charactersPerPost
2644 * The number of characters per post
2645 * @return {@code true} if the number of characters per post was valid,
2646 * {@code false} otherwise
2648 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2649 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2653 * Sets the number of characters per post.
2655 * @param charactersPerPost
2656 * The number of characters per post, or <code>-1</code> to
2657 * not cut off the posts
2658 * @return This preferences objects
2660 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2661 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2666 * Returns the number of characters the shortened post should have.
2668 * @return The number of characters of the snippet
2670 public int getPostCutOffLength() {
2671 return options.getIntegerOption("PostCutOffLength").get();
2675 * Validates the number of characters after which to cut off the post.
2677 * @param postCutOffLength
2678 * The number of characters of the snippet
2679 * @return {@code true} if the number of characters of the snippet is
2680 * valid, {@code false} otherwise
2682 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2683 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2687 * Sets the number of characters the shortened post should have.
2689 * @param postCutOffLength
2690 * The number of characters of the snippet
2691 * @return This preferences
2693 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2694 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2699 * Returns whether Sone requires full access to be even visible.
2701 * @return {@code true} if Sone requires full access, {@code false}
2704 public boolean isRequireFullAccess() {
2705 return options.getBooleanOption("RequireFullAccess").get();
2709 * Sets whether Sone requires full access to be even visible.
2711 * @param requireFullAccess
2712 * {@code true} if Sone requires full access, {@code false}
2715 public void setRequireFullAccess(Boolean requireFullAccess) {
2716 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2720 * Returns the positive trust.
2722 * @return The positive trust
2724 public int getPositiveTrust() {
2725 return options.getIntegerOption("PositiveTrust").get();
2729 * Validates the positive trust.
2731 * @param positiveTrust
2732 * The positive trust to validate
2733 * @return {@code true} if the positive trust was valid, {@code false}
2736 public boolean validatePositiveTrust(Integer positiveTrust) {
2737 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2741 * Sets the positive trust.
2743 * @param positiveTrust
2744 * The new positive trust, or {@code null} to restore it to
2746 * @return This preferences
2748 public Preferences setPositiveTrust(Integer positiveTrust) {
2749 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2754 * Returns the negative trust.
2756 * @return The negative trust
2758 public int getNegativeTrust() {
2759 return options.getIntegerOption("NegativeTrust").get();
2763 * Validates the negative trust.
2765 * @param negativeTrust
2766 * The negative trust to validate
2767 * @return {@code true} if the negative trust was valid, {@code false}
2770 public boolean validateNegativeTrust(Integer negativeTrust) {
2771 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2775 * Sets the negative trust.
2777 * @param negativeTrust
2778 * The negative trust, or {@code null} to restore it to the
2780 * @return The preferences
2782 public Preferences setNegativeTrust(Integer negativeTrust) {
2783 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2788 * Returns the trust comment. This is the comment that is set in the web
2789 * of trust when a trust value is assigned to an identity.
2791 * @return The trust comment
2793 public String getTrustComment() {
2794 return options.getStringOption("TrustComment").get();
2798 * Sets the trust comment.
2800 * @param trustComment
2801 * The trust comment, or {@code null} to restore it to the
2803 * @return This preferences
2805 public Preferences setTrustComment(String trustComment) {
2806 options.getStringOption("TrustComment").set(trustComment);
2811 * Returns whether the {@link FcpInterface FCP interface} is currently
2814 * @see FcpInterface#setActive(boolean)
2815 * @return {@code true} if the FCP interface is currently active,
2816 * {@code false} otherwise
2818 public boolean isFcpInterfaceActive() {
2819 return options.getBooleanOption("ActivateFcpInterface").get();
2823 * Sets whether the {@link FcpInterface FCP interface} is currently
2826 * @see FcpInterface#setActive(boolean)
2827 * @param fcpInterfaceActive
2828 * {@code true} to activate the FCP interface, {@code false}
2829 * to deactivate the FCP interface
2830 * @return This preferences object
2832 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2833 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2838 * Returns the action level for which full access to the FCP interface
2841 * @return The action level for which full access to the FCP interface
2844 public FullAccessRequired getFcpFullAccessRequired() {
2845 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2849 * Sets the action level for which full access to the FCP interface is
2852 * @param fcpFullAccessRequired
2854 * @return This preferences
2856 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2857 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);