2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
41 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
42 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
43 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
44 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
45 import net.pterodactylus.sone.data.Album;
46 import net.pterodactylus.sone.data.Client;
47 import net.pterodactylus.sone.data.Image;
48 import net.pterodactylus.sone.data.Post;
49 import net.pterodactylus.sone.data.PostReply;
50 import net.pterodactylus.sone.data.Profile;
51 import net.pterodactylus.sone.data.Profile.Field;
52 import net.pterodactylus.sone.data.Reply;
53 import net.pterodactylus.sone.data.Sone;
54 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
55 import net.pterodactylus.sone.data.Sone.SoneStatus;
56 import net.pterodactylus.sone.data.TemporaryImage;
57 import net.pterodactylus.sone.data.impl.PostImpl;
58 import net.pterodactylus.sone.fcp.FcpInterface;
59 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
60 import net.pterodactylus.sone.freenet.wot.Identity;
61 import net.pterodactylus.sone.freenet.wot.IdentityListener;
62 import net.pterodactylus.sone.freenet.wot.IdentityManager;
63 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
64 import net.pterodactylus.sone.main.SonePlugin;
65 import net.pterodactylus.util.config.Configuration;
66 import net.pterodactylus.util.config.ConfigurationException;
67 import net.pterodactylus.util.logging.Logging;
68 import net.pterodactylus.util.number.Numbers;
69 import net.pterodactylus.util.service.AbstractService;
70 import net.pterodactylus.util.thread.NamedThreadFactory;
71 import net.pterodactylus.util.thread.Ticker;
72 import net.pterodactylus.util.validation.EqualityValidator;
73 import net.pterodactylus.util.validation.IntegerRangeValidator;
74 import net.pterodactylus.util.validation.OrValidator;
75 import net.pterodactylus.util.validation.Validation;
76 import net.pterodactylus.util.version.Version;
78 import com.google.common.base.Predicate;
79 import com.google.common.collect.Collections2;
80 import com.google.common.eventbus.EventBus;
81 import com.google.inject.Inject;
83 import freenet.keys.FreenetURI;
88 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
90 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
93 private static final Logger logger = Logging.getLogger(Core.class);
95 /** The start time. */
96 private final long startupTime = System.currentTimeMillis();
99 private final Options options = new Options();
101 /** The preferences. */
102 private final Preferences preferences = new Preferences(options);
104 /** The core listener manager. */
105 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
107 /** The event bus. */
108 private final EventBus eventBus;
110 /** The configuration. */
111 private Configuration configuration;
113 /** Whether we’re currently saving the configuration. */
114 private boolean storingConfiguration = false;
116 /** The identity manager. */
117 private final IdentityManager identityManager;
119 /** Interface to freenet. */
120 private final FreenetInterface freenetInterface;
122 /** The Sone downloader. */
123 private final SoneDownloader soneDownloader;
125 /** The image inserter. */
126 private final ImageInserter imageInserter;
128 /** Sone downloader thread-pool. */
129 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
131 /** The update checker. */
132 private final UpdateChecker updateChecker;
134 /** The trust updater. */
135 private final WebOfTrustUpdater webOfTrustUpdater;
137 /** The FCP interface. */
138 private volatile FcpInterface fcpInterface;
140 /** The times Sones were followed. */
141 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
143 /** Locked local Sones. */
144 /* synchronize on itself. */
145 private final Set<Sone> lockedSones = new HashSet<Sone>();
147 /** Sone inserters. */
148 /* synchronize access on this on sones. */
149 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
151 /** Sone rescuers. */
152 /* synchronize access on this on sones. */
153 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
156 /* synchronize access on this on itself. */
157 private final Map<String, Sone> sones = new HashMap<String, Sone>();
159 /** All known Sones. */
160 private final Set<String> knownSones = new HashSet<String>();
163 private final Map<String, Post> posts = new HashMap<String, Post>();
165 /** All known posts. */
166 private final Set<String> knownPosts = new HashSet<String>();
169 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
171 /** All known replies. */
172 private final Set<String> knownReplies = new HashSet<String>();
174 /** All bookmarked posts. */
175 /* synchronize access on itself. */
176 private final Set<String> bookmarkedPosts = new HashSet<String>();
178 /** Trusted identities, sorted by own identities. */
179 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
181 /** All known albums. */
182 private final Map<String, Album> albums = new HashMap<String, Album>();
184 /** All known images. */
185 private final Map<String, Image> images = new HashMap<String, Image>();
187 /** All temporary images. */
188 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
190 /** Ticker for threads that mark own elements as known. */
191 private final Ticker localElementTicker = new Ticker();
193 /** The time the configuration was last touched. */
194 private volatile long lastConfigurationUpdate;
197 * Creates a new core.
199 * @param configuration
200 * The configuration of the core
201 * @param freenetInterface
202 * The freenet interface
203 * @param identityManager
204 * The identity manager
205 * @param webOfTrustUpdater
206 * The WebOfTrust updater
211 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
213 this.configuration = configuration;
214 this.freenetInterface = freenetInterface;
215 this.identityManager = identityManager;
216 this.soneDownloader = new SoneDownloader(this, freenetInterface);
217 this.imageInserter = new ImageInserter(this, freenetInterface);
218 this.updateChecker = new UpdateChecker(freenetInterface);
219 this.webOfTrustUpdater = webOfTrustUpdater;
220 this.eventBus = eventBus;
224 // LISTENER MANAGEMENT
228 * Adds a new core listener.
230 * @param coreListener
231 * The listener to add
233 public void addCoreListener(CoreListener coreListener) {
234 coreListenerManager.addListener(coreListener);
238 * Removes a core listener.
240 * @param coreListener
241 * The listener to remove
243 public void removeCoreListener(CoreListener coreListener) {
244 coreListenerManager.removeListener(coreListener);
252 * Returns the time Sone was started.
254 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
256 public long getStartupTime() {
261 * Sets the configuration to use. This will automatically save the current
262 * configuration to the given configuration.
264 * @param configuration
265 * The new configuration to use
267 public void setConfiguration(Configuration configuration) {
268 this.configuration = configuration;
269 touchConfiguration();
273 * Returns the options used by the core.
275 * @return The options of the core
277 public Preferences getPreferences() {
282 * Returns the identity manager used by the core.
284 * @return The identity manager
286 public IdentityManager getIdentityManager() {
287 return identityManager;
291 * Returns the update checker.
293 * @return The update checker
295 public UpdateChecker getUpdateChecker() {
296 return updateChecker;
300 * Sets the FCP interface to use.
302 * @param fcpInterface
303 * The FCP interface to use
305 public void setFcpInterface(FcpInterface fcpInterface) {
306 this.fcpInterface = fcpInterface;
310 * Returns the Sone rescuer for the given local Sone.
313 * The local Sone to get the rescuer for
314 * @return The Sone rescuer for the given Sone
316 public SoneRescuer getSoneRescuer(Sone sone) {
317 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
318 synchronized (sones) {
319 SoneRescuer soneRescuer = soneRescuers.get(sone);
320 if (soneRescuer == null) {
321 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
322 soneRescuers.put(sone, soneRescuer);
330 * Returns whether the given Sone is currently locked.
334 * @return {@code true} if the Sone is locked, {@code false} if it is not
336 public boolean isLocked(Sone sone) {
337 synchronized (lockedSones) {
338 return lockedSones.contains(sone);
343 * Returns all Sones, remote and local.
347 public Set<Sone> getSones() {
348 return new HashSet<Sone>(sones.values());
352 * Returns the Sone with the given ID, regardless whether it’s local or
356 * The ID of the Sone to get
357 * @return The Sone with the given ID, or {@code null} if there is no such
360 public Sone getSone(String id) {
361 return getSone(id, true);
365 * Returns the Sone with the given ID, regardless whether it’s local or
369 * The ID of the Sone to get
371 * {@code true} to create a new Sone if none exists,
372 * {@code false} to return {@code null} if a Sone with the given
374 * @return The Sone with the given ID, or {@code null} if there is no such
378 public Sone getSone(String id, boolean create) {
379 synchronized (sones) {
380 if (!sones.containsKey(id)) {
381 Sone sone = new Sone(id, false);
384 return sones.get(id);
389 * Checks whether the core knows a Sone with the given ID.
393 * @return {@code true} if there is a Sone with the given ID, {@code false}
396 public boolean hasSone(String id) {
397 synchronized (sones) {
398 return sones.containsKey(id);
403 * Returns all local Sones.
405 * @return All local Sones
407 public Collection<Sone> getLocalSones() {
408 synchronized (sones) {
409 return Collections2.filter(sones.values(), new Predicate<Sone>() {
412 public boolean apply(Sone sone) {
413 return sone.isLocal();
420 * Returns the local Sone with the given ID, optionally creating a new Sone.
425 * {@code true} to create a new Sone if none exists,
426 * {@code false} to return null if none exists
427 * @return The Sone with the given ID, or {@code null}
429 public Sone getLocalSone(String id, boolean create) {
430 synchronized (sones) {
431 Sone sone = sones.get(id);
432 if ((sone == null) && create) {
433 sone = new Sone(id, true);
436 if ((sone != null) && !sone.isLocal()) {
437 sone = new Sone(id, true);
445 * Returns all remote Sones.
447 * @return All remote Sones
449 public Collection<Sone> getRemoteSones() {
450 synchronized (sones) {
451 return Collections2.filter(sones.values(), new Predicate<Sone>() {
454 public boolean apply(Sone sone) {
455 return !sone.isLocal();
462 * Returns the remote Sone with the given ID.
465 * The ID of the remote Sone to get
467 * {@code true} to always create a Sone, {@code false} to return
468 * {@code null} if no Sone with the given ID exists
469 * @return The Sone with the given ID
471 public Sone getRemoteSone(String id, boolean create) {
472 synchronized (sones) {
473 Sone sone = sones.get(id);
474 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
475 sone = new Sone(id, false);
483 * Returns whether the given Sone has been modified.
486 * The Sone to check for modifications
487 * @return {@code true} if a modification has been detected in the Sone,
488 * {@code false} otherwise
490 public boolean isModifiedSone(Sone sone) {
491 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
495 * Returns the time when the given was first followed by any local Sone.
498 * The Sone to get the time for
499 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
500 * been followed, or {@link Long#MAX_VALUE}
502 public long getSoneFollowingTime(Sone sone) {
503 synchronized (soneFollowingTimes) {
504 if (soneFollowingTimes.containsKey(sone)) {
505 return soneFollowingTimes.get(sone);
507 return Long.MAX_VALUE;
512 * Returns whether the target Sone is trusted by the origin Sone.
518 * @return {@code true} if the target Sone is trusted by the origin Sone
520 public boolean isSoneTrusted(Sone origin, Sone target) {
521 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
522 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
526 * Returns the post with the given ID.
529 * The ID of the post to get
530 * @return The post with the given ID, or a new post with the given ID
532 public Post getPost(String postId) {
533 return getPost(postId, true);
537 * Returns the post with the given ID, optionally creating a new post.
540 * The ID of the post to get
542 * {@code true} it create a new post if no post with the given ID
543 * exists, {@code false} to return {@code null}
544 * @return The post, or {@code null} if there is no such post
547 public Post getPost(String postId, boolean create) {
548 synchronized (posts) {
549 Post post = posts.get(postId);
550 if ((post == null) && create) {
551 post = new PostImpl(postId);
552 posts.put(postId, post);
559 * Returns all posts that have the given Sone as recipient.
561 * @see Post#getRecipient()
563 * The recipient of the posts
564 * @return All posts that have the given Sone as recipient
566 public Set<Post> getDirectedPosts(Sone recipient) {
567 Validation.begin().isNotNull("Recipient", recipient).check();
568 Set<Post> directedPosts = new HashSet<Post>();
569 synchronized (posts) {
570 for (Post post : posts.values()) {
571 if (recipient.equals(post.getRecipient())) {
572 directedPosts.add(post);
576 return directedPosts;
580 * Returns the reply with the given ID. If there is no reply with the given
581 * ID yet, a new one is created, unless {@code create} is false in which
582 * case {@code null} is returned.
585 * The ID of the reply to get
587 * {@code true} to always return a {@link Reply}, {@code false}
588 * to return {@code null} if no reply can be found
589 * @return The reply, or {@code null} if there is no such reply
591 public PostReply getPostReply(String replyId, boolean create) {
592 synchronized (replies) {
593 PostReply reply = replies.get(replyId);
594 if (create && (reply == null)) {
595 reply = new PostReply(replyId);
596 replies.put(replyId, reply);
603 * Returns all replies for the given post, order ascending by time.
606 * The post to get all replies for
607 * @return All replies for the given post
609 public List<PostReply> getReplies(Post post) {
610 Set<Sone> sones = getSones();
611 List<PostReply> replies = new ArrayList<PostReply>();
612 for (Sone sone : sones) {
613 for (PostReply reply : sone.getReplies()) {
614 if (reply.getPost().equals(post)) {
619 Collections.sort(replies, Reply.TIME_COMPARATOR);
624 * Returns all Sones that have liked the given post.
627 * The post to get the liking Sones for
628 * @return The Sones that like the given post
630 public Set<Sone> getLikes(Post post) {
631 Set<Sone> sones = new HashSet<Sone>();
632 for (Sone sone : getSones()) {
633 if (sone.getLikedPostIds().contains(post.getId())) {
641 * Returns all Sones that have liked the given reply.
644 * The reply to get the liking Sones for
645 * @return The Sones that like the given reply
647 public Set<Sone> getLikes(PostReply reply) {
648 Set<Sone> sones = new HashSet<Sone>();
649 for (Sone sone : getSones()) {
650 if (sone.getLikedReplyIds().contains(reply.getId())) {
658 * Returns whether the given post is bookmarked.
662 * @return {@code true} if the given post is bookmarked, {@code false}
665 public boolean isBookmarked(Post post) {
666 return isPostBookmarked(post.getId());
670 * Returns whether the post with the given ID is bookmarked.
673 * The ID of the post to check
674 * @return {@code true} if the post with the given ID is bookmarked,
675 * {@code false} otherwise
677 public boolean isPostBookmarked(String id) {
678 synchronized (bookmarkedPosts) {
679 return bookmarkedPosts.contains(id);
684 * Returns all currently known bookmarked posts.
686 * @return All bookmarked posts
688 public Set<Post> getBookmarkedPosts() {
689 Set<Post> posts = new HashSet<Post>();
690 synchronized (bookmarkedPosts) {
691 for (String bookmarkedPostId : bookmarkedPosts) {
692 Post post = getPost(bookmarkedPostId, false);
702 * Returns the album with the given ID, creating a new album if no album
703 * with the given ID can be found.
706 * The ID of the album
707 * @return The album with the given ID
709 public Album getAlbum(String albumId) {
710 return getAlbum(albumId, true);
714 * Returns the album with the given ID, optionally creating a new album if
715 * an album with the given ID can not be found.
718 * The ID of the album
720 * {@code true} to create a new album if none exists for the
722 * @return The album with the given ID, or {@code null} if no album with the
723 * given ID exists and {@code create} is {@code false}
725 public Album getAlbum(String albumId, boolean create) {
726 synchronized (albums) {
727 Album album = albums.get(albumId);
728 if (create && (album == null)) {
729 album = new Album(albumId);
730 albums.put(albumId, album);
737 * Returns the image with the given ID, creating it if necessary.
740 * The ID of the image
741 * @return The image with the given ID
743 public Image getImage(String imageId) {
744 return getImage(imageId, true);
748 * Returns the image with the given ID, optionally creating it if it does
752 * The ID of the image
754 * {@code true} to create an image if none exists with the given
756 * @return The image with the given ID, or {@code null} if none exists and
759 public Image getImage(String imageId, boolean create) {
760 synchronized (images) {
761 Image image = images.get(imageId);
762 if (create && (image == null)) {
763 image = new Image(imageId);
764 images.put(imageId, image);
771 * Returns the temporary image with the given ID.
774 * The ID of the temporary image
775 * @return The temporary image, or {@code null} if there is no temporary
776 * image with the given ID
778 public TemporaryImage getTemporaryImage(String imageId) {
779 synchronized (temporaryImages) {
780 return temporaryImages.get(imageId);
789 * Locks the given Sone. A locked Sone will not be inserted by
790 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
796 public void lockSone(Sone sone) {
797 synchronized (lockedSones) {
798 if (lockedSones.add(sone)) {
799 coreListenerManager.fireSoneLocked(sone);
805 * Unlocks the given Sone.
807 * @see #lockSone(Sone)
811 public void unlockSone(Sone sone) {
812 synchronized (lockedSones) {
813 if (lockedSones.remove(sone)) {
814 coreListenerManager.fireSoneUnlocked(sone);
820 * Adds a local Sone from the given own identity.
823 * The own identity to create a Sone from
824 * @return The added (or already existing) Sone
826 public Sone addLocalSone(OwnIdentity ownIdentity) {
827 if (ownIdentity == null) {
828 logger.log(Level.WARNING, "Given OwnIdentity is null!");
831 synchronized (sones) {
834 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
835 } catch (MalformedURLException mue1) {
836 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
839 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
840 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
842 /* TODO - load posts ’n stuff */
843 sones.put(ownIdentity.getId(), sone);
844 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
845 soneInserter.addSoneInsertListener(this);
846 soneInserters.put(sone, soneInserter);
847 sone.setStatus(SoneStatus.idle);
849 soneInserter.start();
855 * Creates a new Sone for the given own identity.
858 * The own identity to create a Sone for
859 * @return The created Sone
861 public Sone createSone(OwnIdentity ownIdentity) {
862 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
863 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
866 Sone sone = addLocalSone(ownIdentity);
867 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
868 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
869 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
870 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
871 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
872 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
874 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
875 touchConfiguration();
880 * Adds the Sone of the given identity.
883 * The identity whose Sone to add
884 * @return The added or already existing Sone
886 public Sone addRemoteSone(Identity identity) {
887 if (identity == null) {
888 logger.log(Level.WARNING, "Given Identity is null!");
891 synchronized (sones) {
892 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
893 boolean newSone = sone.getRequestUri() == null;
894 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
895 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
897 synchronized (knownSones) {
898 newSone = !knownSones.contains(sone.getId());
900 sone.setKnown(!newSone);
902 eventBus.post(new NewSoneFoundEvent(sone));
903 for (Sone localSone : getLocalSones()) {
904 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
905 followSone(localSone, sone);
910 soneDownloader.addSone(sone);
911 soneDownloaders.execute(new Runnable() {
914 @SuppressWarnings("synthetic-access")
916 soneDownloader.fetchSone(sone, sone.getRequestUri());
925 * Lets the given local Sone follow the Sone with the given ID.
928 * The local Sone that should follow another Sone
930 * The ID of the Sone to follow
932 public void followSone(Sone sone, String soneId) {
933 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
934 Sone followedSone = getSone(soneId, true);
935 if (followedSone == null) {
936 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
939 followSone(sone, getSone(soneId));
943 * Lets the given local Sone follow the other given Sone. If the given Sone
944 * was not followed by any local Sone before, this will mark all elements of
945 * the followed Sone as read that have been created before the current
949 * The local Sone that should follow the other Sone
950 * @param followedSone
951 * The Sone that should be followed
953 public void followSone(Sone sone, Sone followedSone) {
954 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
955 sone.addFriend(followedSone.getId());
956 synchronized (soneFollowingTimes) {
957 if (!soneFollowingTimes.containsKey(followedSone)) {
958 long now = System.currentTimeMillis();
959 soneFollowingTimes.put(followedSone, now);
960 for (Post post : followedSone.getPosts()) {
961 if (post.getTime() < now) {
965 for (PostReply reply : followedSone.getReplies()) {
966 if (reply.getTime() < now) {
967 markReplyKnown(reply);
972 touchConfiguration();
976 * Lets the given local Sone unfollow the Sone with the given ID.
979 * The local Sone that should unfollow another Sone
981 * The ID of the Sone being unfollowed
983 public void unfollowSone(Sone sone, String soneId) {
984 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
985 unfollowSone(sone, getSone(soneId, false));
989 * Lets the given local Sone unfollow the other given Sone. If the given
990 * local Sone is the last local Sone that followed the given Sone, its
991 * following time will be removed.
994 * The local Sone that should unfollow another Sone
995 * @param unfollowedSone
996 * The Sone being unfollowed
998 public void unfollowSone(Sone sone, Sone unfollowedSone) {
999 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1000 sone.removeFriend(unfollowedSone.getId());
1001 boolean unfollowedSoneStillFollowed = false;
1002 for (Sone localSone : getLocalSones()) {
1003 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1005 if (!unfollowedSoneStillFollowed) {
1006 synchronized (soneFollowingTimes) {
1007 soneFollowingTimes.remove(unfollowedSone);
1010 touchConfiguration();
1014 * Sets the trust value of the given origin Sone for the target Sone.
1021 * The trust value (from {@code -100} to {@code 100})
1023 public void setTrust(Sone origin, Sone target, int trustValue) {
1024 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();
1025 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1029 * Removes any trust assignment for the given target Sone.
1036 public void removeTrust(Sone origin, Sone target) {
1037 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1038 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1042 * Assigns the configured positive trust value for the given target.
1049 public void trustSone(Sone origin, Sone target) {
1050 setTrust(origin, target, preferences.getPositiveTrust());
1054 * Assigns the configured negative trust value for the given target.
1061 public void distrustSone(Sone origin, Sone target) {
1062 setTrust(origin, target, preferences.getNegativeTrust());
1066 * Removes the trust assignment for the given target.
1073 public void untrustSone(Sone origin, Sone target) {
1074 removeTrust(origin, target);
1078 * Updates the stored Sone with the given Sone.
1083 public void updateSone(Sone sone) {
1084 updateSone(sone, false);
1088 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1089 * {@code true}, an older Sone than the current Sone can be given to restore
1093 * The Sone to update
1094 * @param soneRescueMode
1095 * {@code true} if the stored Sone should be updated regardless
1096 * of the age of the given Sone
1098 public void updateSone(Sone sone, boolean soneRescueMode) {
1099 if (hasSone(sone.getId())) {
1100 Sone storedSone = getSone(sone.getId());
1101 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1102 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1105 synchronized (posts) {
1106 if (!soneRescueMode) {
1107 for (Post post : storedSone.getPosts()) {
1108 posts.remove(post.getId());
1109 if (!sone.getPosts().contains(post)) {
1110 coreListenerManager.firePostRemoved(post);
1114 List<Post> storedPosts = storedSone.getPosts();
1115 synchronized (knownPosts) {
1116 for (Post post : sone.getPosts()) {
1117 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1118 if (!storedPosts.contains(post)) {
1119 if (post.getTime() < getSoneFollowingTime(sone)) {
1120 knownPosts.add(post.getId());
1121 post.setKnown(true);
1122 } else if (!knownPosts.contains(post.getId())) {
1123 eventBus.post(new NewPostFoundEvent(post));
1126 posts.put(post.getId(), post);
1130 synchronized (replies) {
1131 if (!soneRescueMode) {
1132 for (PostReply reply : storedSone.getReplies()) {
1133 replies.remove(reply.getId());
1134 if (!sone.getReplies().contains(reply)) {
1135 coreListenerManager.fireReplyRemoved(reply);
1139 Set<PostReply> storedReplies = storedSone.getReplies();
1140 synchronized (knownReplies) {
1141 for (PostReply reply : sone.getReplies()) {
1142 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1143 if (!storedReplies.contains(reply)) {
1144 if (reply.getTime() < getSoneFollowingTime(sone)) {
1145 knownReplies.add(reply.getId());
1146 reply.setKnown(true);
1147 } else if (!knownReplies.contains(reply.getId())) {
1148 eventBus.post(new NewPostReplyFoundEvent(reply));
1151 replies.put(reply.getId(), reply);
1155 synchronized (albums) {
1156 synchronized (images) {
1157 for (Album album : storedSone.getAlbums()) {
1158 albums.remove(album.getId());
1159 for (Image image : album.getImages()) {
1160 images.remove(image.getId());
1163 for (Album album : sone.getAlbums()) {
1164 albums.put(album.getId(), album);
1165 for (Image image : album.getImages()) {
1166 images.put(image.getId(), image);
1171 synchronized (storedSone) {
1172 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1173 storedSone.setTime(sone.getTime());
1175 storedSone.setClient(sone.getClient());
1176 storedSone.setProfile(sone.getProfile());
1177 if (soneRescueMode) {
1178 for (Post post : sone.getPosts()) {
1179 storedSone.addPost(post);
1181 for (PostReply reply : sone.getReplies()) {
1182 storedSone.addReply(reply);
1184 for (String likedPostId : sone.getLikedPostIds()) {
1185 storedSone.addLikedPostId(likedPostId);
1187 for (String likedReplyId : sone.getLikedReplyIds()) {
1188 storedSone.addLikedReplyId(likedReplyId);
1190 for (Album album : sone.getAlbums()) {
1191 storedSone.addAlbum(album);
1194 storedSone.setPosts(sone.getPosts());
1195 storedSone.setReplies(sone.getReplies());
1196 storedSone.setLikePostIds(sone.getLikedPostIds());
1197 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1198 storedSone.setAlbums(sone.getAlbums());
1200 storedSone.setLatestEdition(sone.getLatestEdition());
1206 * Deletes the given Sone. This will remove the Sone from the
1207 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1208 * remove the context from its identity.
1211 * The Sone to delete
1213 public void deleteSone(Sone sone) {
1214 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1215 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1218 synchronized (sones) {
1219 if (!getLocalSones().contains(sone)) {
1220 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1223 sones.remove(sone.getId());
1224 SoneInserter soneInserter = soneInserters.remove(sone);
1225 soneInserter.removeSoneInsertListener(this);
1226 soneInserter.stop();
1228 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1229 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1231 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1232 } catch (ConfigurationException ce1) {
1233 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1238 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1239 * known} before, a {@link MarkSoneKnownEvent} is fired.
1242 * The Sone to mark as known
1244 public void markSoneKnown(Sone sone) {
1245 if (!sone.isKnown()) {
1246 sone.setKnown(true);
1247 synchronized (knownSones) {
1248 knownSones.add(sone.getId());
1250 eventBus.post(new MarkSoneKnownEvent(sone));
1251 touchConfiguration();
1256 * Loads and updates the given Sone from the configuration. If any error is
1257 * encountered, loading is aborted and the given Sone is not changed.
1260 * The Sone to load and update
1262 public void loadSone(Sone sone) {
1263 if (!sone.isLocal()) {
1264 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1268 /* initialize options. */
1269 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1270 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1271 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1272 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1273 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1274 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1277 String sonePrefix = "Sone/" + sone.getId();
1278 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1279 if (soneTime == null) {
1280 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1283 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1286 Profile profile = new Profile(sone);
1287 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1288 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1289 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1290 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1291 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1292 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1294 /* load profile fields. */
1296 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1297 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1298 if (fieldName == null) {
1301 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1302 profile.addField(fieldName).setValue(fieldValue);
1306 Set<Post> posts = new HashSet<Post>();
1308 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1309 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1310 if (postId == null) {
1313 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1314 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1315 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1316 if ((postTime == 0) || (postText == null)) {
1317 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1320 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1321 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1322 post.setRecipient(getSone(postRecipientId));
1328 Set<PostReply> replies = new HashSet<PostReply>();
1330 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1331 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1332 if (replyId == null) {
1335 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1336 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1337 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1338 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1339 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1342 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1345 /* load post likes. */
1346 Set<String> likedPostIds = new HashSet<String>();
1348 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1349 if (likedPostId == null) {
1352 likedPostIds.add(likedPostId);
1355 /* load reply likes. */
1356 Set<String> likedReplyIds = new HashSet<String>();
1358 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1359 if (likedReplyId == null) {
1362 likedReplyIds.add(likedReplyId);
1366 Set<String> friends = new HashSet<String>();
1368 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1369 if (friendId == null) {
1372 friends.add(friendId);
1376 List<Album> topLevelAlbums = new ArrayList<Album>();
1377 int albumCounter = 0;
1379 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1380 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1381 if (albumId == null) {
1384 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1385 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1386 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1387 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1388 if ((albumTitle == null) || (albumDescription == null)) {
1389 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1392 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1393 if (albumParentId != null) {
1394 Album parentAlbum = getAlbum(albumParentId, false);
1395 if (parentAlbum == null) {
1396 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1399 parentAlbum.addAlbum(album);
1401 if (!topLevelAlbums.contains(album)) {
1402 topLevelAlbums.add(album);
1408 int imageCounter = 0;
1410 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1411 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1412 if (imageId == null) {
1415 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1416 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1417 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1418 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1419 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1420 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1421 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1422 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1423 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1426 Album album = getAlbum(albumId, false);
1427 if (album == null) {
1428 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1431 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1432 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1433 album.addImage(image);
1437 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1438 if (avatarId != null) {
1439 profile.setAvatar(getImage(avatarId, false));
1443 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1444 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1445 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1446 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1447 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1448 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1450 /* if we’re still here, Sone was loaded successfully. */
1451 synchronized (sone) {
1452 sone.setTime(soneTime);
1453 sone.setProfile(profile);
1454 sone.setPosts(posts);
1455 sone.setReplies(replies);
1456 sone.setLikePostIds(likedPostIds);
1457 sone.setLikeReplyIds(likedReplyIds);
1458 for (String friendId : friends) {
1459 followSone(sone, friendId);
1461 sone.setAlbums(topLevelAlbums);
1462 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1464 synchronized (knownSones) {
1465 for (String friend : friends) {
1466 knownSones.add(friend);
1469 synchronized (knownPosts) {
1470 for (Post post : posts) {
1471 knownPosts.add(post.getId());
1474 synchronized (knownReplies) {
1475 for (PostReply reply : replies) {
1476 knownReplies.add(reply.getId());
1482 * Creates a new post.
1485 * The Sone that creates the post
1487 * The text of the post
1488 * @return The created post
1490 public Post createPost(Sone sone, String text) {
1491 return createPost(sone, System.currentTimeMillis(), text);
1495 * Creates a new post.
1498 * The Sone that creates the post
1500 * The time of the post
1502 * The text of the post
1503 * @return The created post
1505 public Post createPost(Sone sone, long time, String text) {
1506 return createPost(sone, null, time, text);
1510 * Creates a new post.
1513 * The Sone that creates the post
1515 * The recipient Sone, or {@code null} if this post does not have
1518 * The text of the post
1519 * @return The created post
1521 public Post createPost(Sone sone, Sone recipient, String text) {
1522 return createPost(sone, recipient, System.currentTimeMillis(), text);
1526 * Creates a new post.
1529 * The Sone that creates the post
1531 * The recipient Sone, or {@code null} if this post does not have
1534 * The time of the post
1536 * The text of the post
1537 * @return The created post
1539 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1540 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1541 if (!sone.isLocal()) {
1542 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1545 final Post post = new PostImpl(sone, time, text);
1546 if (recipient != null) {
1547 post.setRecipient(recipient);
1549 synchronized (posts) {
1550 posts.put(post.getId(), post);
1552 eventBus.post(new NewPostFoundEvent(post));
1554 touchConfiguration();
1555 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1562 markPostKnown(post);
1564 }, "Mark " + post + " read.");
1569 * Deletes the given post.
1572 * The post to delete
1574 public void deletePost(Post post) {
1575 if (!post.getSone().isLocal()) {
1576 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1579 post.getSone().removePost(post);
1580 synchronized (posts) {
1581 posts.remove(post.getId());
1583 coreListenerManager.firePostRemoved(post);
1584 markPostKnown(post);
1585 touchConfiguration();
1589 * Marks the given post as known, if it is currently not a known post
1590 * (according to {@link Post#isKnown()}).
1593 * The post to mark as known
1595 public void markPostKnown(Post post) {
1596 post.setKnown(true);
1597 synchronized (knownPosts) {
1598 eventBus.post(new MarkPostKnownEvent(post));
1599 if (knownPosts.add(post.getId())) {
1600 touchConfiguration();
1603 for (PostReply reply : getReplies(post)) {
1604 markReplyKnown(reply);
1609 * Bookmarks the given post.
1612 * The post to bookmark
1614 public void bookmark(Post post) {
1615 bookmarkPost(post.getId());
1619 * Bookmarks the post with the given ID.
1622 * The ID of the post to bookmark
1624 public void bookmarkPost(String id) {
1625 synchronized (bookmarkedPosts) {
1626 bookmarkedPosts.add(id);
1631 * Removes the given post from the bookmarks.
1634 * The post to unbookmark
1636 public void unbookmark(Post post) {
1637 unbookmarkPost(post.getId());
1641 * Removes the post with the given ID from the bookmarks.
1644 * The ID of the post to unbookmark
1646 public void unbookmarkPost(String id) {
1647 synchronized (bookmarkedPosts) {
1648 bookmarkedPosts.remove(id);
1653 * Creates a new reply.
1656 * The Sone that creates the reply
1658 * The post that this reply refers to
1660 * The text of the reply
1661 * @return The created reply
1663 public PostReply createReply(Sone sone, Post post, String text) {
1664 return createReply(sone, post, System.currentTimeMillis(), text);
1668 * Creates a new reply.
1671 * The Sone that creates the reply
1673 * The post that this reply refers to
1675 * The time of the reply
1677 * The text of the reply
1678 * @return The created reply
1680 public PostReply createReply(Sone sone, Post post, long time, String text) {
1681 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1682 if (!sone.isLocal()) {
1683 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1686 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1687 synchronized (replies) {
1688 replies.put(reply.getId(), reply);
1690 synchronized (knownReplies) {
1691 eventBus.post(new NewPostReplyFoundEvent(reply));
1693 sone.addReply(reply);
1694 touchConfiguration();
1695 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1702 markReplyKnown(reply);
1704 }, "Mark " + reply + " read.");
1709 * Deletes the given reply.
1712 * The reply to delete
1714 public void deleteReply(PostReply reply) {
1715 Sone sone = reply.getSone();
1716 if (!sone.isLocal()) {
1717 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1720 synchronized (replies) {
1721 replies.remove(reply.getId());
1723 synchronized (knownReplies) {
1724 markReplyKnown(reply);
1725 knownReplies.remove(reply.getId());
1727 sone.removeReply(reply);
1728 touchConfiguration();
1732 * Marks the given reply as known, if it is currently not a known reply
1733 * (according to {@link Reply#isKnown()}).
1736 * The reply to mark as known
1738 public void markReplyKnown(PostReply reply) {
1739 reply.setKnown(true);
1740 synchronized (knownReplies) {
1741 eventBus.post(new MarkPostReplyKnownEvent(reply));
1742 if (knownReplies.add(reply.getId())) {
1743 touchConfiguration();
1749 * Creates a new top-level album for the given Sone.
1752 * The Sone to create the album for
1753 * @return The new album
1755 public Album createAlbum(Sone sone) {
1756 return createAlbum(sone, null);
1760 * Creates a new album for the given Sone.
1763 * The Sone to create the album for
1765 * The parent of the album (may be {@code null} to create a
1767 * @return The new album
1769 public Album createAlbum(Sone sone, Album parent) {
1770 Album album = new Album();
1771 synchronized (albums) {
1772 albums.put(album.getId(), album);
1774 album.setSone(sone);
1775 if (parent != null) {
1776 parent.addAlbum(album);
1778 sone.addAlbum(album);
1784 * Deletes the given album. The owner of the album has to be a local Sone,
1785 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1788 * The album to remove
1790 public void deleteAlbum(Album album) {
1791 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1792 if (!album.isEmpty()) {
1795 if (album.getParent() == null) {
1796 album.getSone().removeAlbum(album);
1798 album.getParent().removeAlbum(album);
1800 synchronized (albums) {
1801 albums.remove(album.getId());
1803 touchConfiguration();
1807 * Creates a new image.
1810 * The Sone creating the image
1812 * The album the image will be inserted into
1813 * @param temporaryImage
1814 * The temporary image to create the image from
1815 * @return The newly created image
1817 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1818 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();
1819 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1820 album.addImage(image);
1821 synchronized (images) {
1822 images.put(image.getId(), image);
1824 imageInserter.insertImage(temporaryImage, image);
1829 * Deletes the given image. This method will also delete a matching
1832 * @see #deleteTemporaryImage(TemporaryImage)
1834 * The image to delete
1836 public void deleteImage(Image image) {
1837 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1838 deleteTemporaryImage(image.getId());
1839 image.getAlbum().removeImage(image);
1840 synchronized (images) {
1841 images.remove(image.getId());
1843 touchConfiguration();
1847 * Creates a new temporary image.
1850 * The MIME type of the temporary image
1852 * The encoded data of the image
1853 * @return The temporary image
1855 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1856 TemporaryImage temporaryImage = new TemporaryImage();
1857 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1858 synchronized (temporaryImages) {
1859 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1861 return temporaryImage;
1865 * Deletes the given temporary image.
1867 * @param temporaryImage
1868 * The temporary image to delete
1870 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1871 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1872 deleteTemporaryImage(temporaryImage.getId());
1876 * Deletes the temporary image with the given ID.
1879 * The ID of the temporary image to delete
1881 public void deleteTemporaryImage(String imageId) {
1882 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1883 synchronized (temporaryImages) {
1884 temporaryImages.remove(imageId);
1886 Image image = getImage(imageId, false);
1887 if (image != null) {
1888 imageInserter.cancelImageInsert(image);
1893 * Notifies the core that the configuration, either of the core or of a
1894 * single local Sone, has changed, and that the configuration should be
1897 public void touchConfiguration() {
1898 lastConfigurationUpdate = System.currentTimeMillis();
1909 public void serviceStart() {
1910 loadConfiguration();
1911 updateChecker.addUpdateListener(this);
1912 updateChecker.start();
1913 identityManager.addIdentityListener(this);
1914 identityManager.start();
1915 webOfTrustUpdater.init();
1916 webOfTrustUpdater.start();
1923 public void serviceRun() {
1924 long lastSaved = System.currentTimeMillis();
1925 while (!shouldStop()) {
1927 long now = System.currentTimeMillis();
1928 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1929 for (Sone localSone : getLocalSones()) {
1930 saveSone(localSone);
1932 saveConfiguration();
1942 public void serviceStop() {
1943 synchronized (sones) {
1944 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1945 soneInserter.getValue().removeSoneInsertListener(this);
1946 soneInserter.getValue().stop();
1947 saveSone(soneInserter.getKey());
1950 saveConfiguration();
1951 webOfTrustUpdater.stop();
1952 updateChecker.stop();
1953 updateChecker.removeUpdateListener(this);
1954 soneDownloader.stop();
1955 identityManager.removeIdentityListener(this);
1956 identityManager.stop();
1964 * Saves the given Sone. This will persist all local settings for the given
1965 * Sone, such as the friends list and similar, private options.
1970 private synchronized void saveSone(Sone sone) {
1971 if (!sone.isLocal()) {
1972 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1975 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1976 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1980 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1982 /* save Sone into configuration. */
1983 String sonePrefix = "Sone/" + sone.getId();
1984 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1985 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1988 Profile profile = sone.getProfile();
1989 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1990 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1991 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1992 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1993 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1994 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1995 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1997 /* save profile fields. */
1998 int fieldCounter = 0;
1999 for (Field profileField : profile.getFields()) {
2000 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2001 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2002 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2004 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2007 int postCounter = 0;
2008 for (Post post : sone.getPosts()) {
2009 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2010 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2011 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2012 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2013 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2015 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2018 int replyCounter = 0;
2019 for (PostReply reply : sone.getReplies()) {
2020 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2021 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2022 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2023 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2024 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2026 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2028 /* save post likes. */
2029 int postLikeCounter = 0;
2030 for (String postId : sone.getLikedPostIds()) {
2031 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2033 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2035 /* save reply likes. */
2036 int replyLikeCounter = 0;
2037 for (String replyId : sone.getLikedReplyIds()) {
2038 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2040 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2043 int friendCounter = 0;
2044 for (String friendId : sone.getFriends()) {
2045 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2047 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2049 /* save albums. first, collect in a flat structure, top-level first. */
2050 List<Album> albums = sone.getAllAlbums();
2052 int albumCounter = 0;
2053 for (Album album : albums) {
2054 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2055 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2056 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2057 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2058 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2059 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2061 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2064 int imageCounter = 0;
2065 for (Album album : albums) {
2066 for (Image image : album.getImages()) {
2067 if (!image.isInserted()) {
2070 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2071 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2072 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2073 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2074 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2075 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2076 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2077 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2078 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2081 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2084 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2085 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2086 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2087 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2088 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2089 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2091 configuration.save();
2093 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2095 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2096 } catch (ConfigurationException ce1) {
2097 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2102 * Saves the current options.
2104 private void saveConfiguration() {
2105 synchronized (configuration) {
2106 if (storingConfiguration) {
2107 logger.log(Level.FINE, "Already storing configuration…");
2110 storingConfiguration = true;
2113 /* store the options first. */
2115 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2116 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2117 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2118 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2119 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2120 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2121 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2122 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2123 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2124 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2125 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2126 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2128 /* save known Sones. */
2129 int soneCounter = 0;
2130 synchronized (knownSones) {
2131 for (String knownSoneId : knownSones) {
2132 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2134 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2137 /* save Sone following times. */
2139 synchronized (soneFollowingTimes) {
2140 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2141 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2142 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2145 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2148 /* save known posts. */
2149 int postCounter = 0;
2150 synchronized (knownPosts) {
2151 for (String knownPostId : knownPosts) {
2152 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2154 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2157 /* save known replies. */
2158 int replyCounter = 0;
2159 synchronized (knownReplies) {
2160 for (String knownReplyId : knownReplies) {
2161 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2163 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2166 /* save bookmarked posts. */
2167 int bookmarkedPostCounter = 0;
2168 synchronized (bookmarkedPosts) {
2169 for (String bookmarkedPostId : bookmarkedPosts) {
2170 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2173 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2176 configuration.save();
2178 } catch (ConfigurationException ce1) {
2179 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2181 synchronized (configuration) {
2182 storingConfiguration = false;
2188 * Loads the configuration.
2190 @SuppressWarnings("unchecked")
2191 private void loadConfiguration() {
2192 /* create options. */
2193 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2196 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2197 SoneInserter.setInsertionDelay(newValue);
2201 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2202 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2203 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2204 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2205 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2206 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2207 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2208 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2209 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2212 @SuppressWarnings("synthetic-access")
2213 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2214 fcpInterface.setActive(newValue);
2217 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2220 @SuppressWarnings("synthetic-access")
2221 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2222 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2227 loadConfigurationValue("InsertionDelay");
2228 loadConfigurationValue("PostsPerPage");
2229 loadConfigurationValue("ImagesPerPage");
2230 loadConfigurationValue("CharactersPerPost");
2231 loadConfigurationValue("PostCutOffLength");
2232 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2233 loadConfigurationValue("PositiveTrust");
2234 loadConfigurationValue("NegativeTrust");
2235 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2236 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2237 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2239 /* load known Sones. */
2240 int soneCounter = 0;
2242 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2243 if (knownSoneId == null) {
2246 synchronized (knownSones) {
2247 knownSones.add(knownSoneId);
2251 /* load Sone following times. */
2254 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2255 if (soneId == null) {
2258 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2259 Sone followedSone = getSone(soneId);
2260 if (followedSone == null) {
2261 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2263 synchronized (soneFollowingTimes) {
2264 soneFollowingTimes.put(getSone(soneId), time);
2270 /* load known posts. */
2271 int postCounter = 0;
2273 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2274 if (knownPostId == null) {
2277 synchronized (knownPosts) {
2278 knownPosts.add(knownPostId);
2282 /* load known replies. */
2283 int replyCounter = 0;
2285 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2286 if (knownReplyId == null) {
2289 synchronized (knownReplies) {
2290 knownReplies.add(knownReplyId);
2294 /* load bookmarked posts. */
2295 int bookmarkedPostCounter = 0;
2297 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2298 if (bookmarkedPostId == null) {
2301 synchronized (bookmarkedPosts) {
2302 bookmarkedPosts.add(bookmarkedPostId);
2309 * Loads an {@link Integer} configuration value for the option with the
2310 * given name, logging validation failures.
2313 * The name of the option to load
2315 private void loadConfigurationValue(String optionName) {
2317 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2318 } catch (IllegalArgumentException iae1) {
2319 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2324 * Generate a Sone URI from the given URI and latest edition.
2327 * The URI to derive the Sone URI from
2328 * @return The derived URI
2330 private static FreenetURI getSoneUri(String uriString) {
2332 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2334 } catch (MalformedURLException mue1) {
2335 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2341 // INTERFACE IdentityListener
2348 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2349 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2350 if (ownIdentity.hasContext("Sone")) {
2351 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2352 addLocalSone(ownIdentity);
2360 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2361 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2362 trustedIdentities.remove(ownIdentity);
2369 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2370 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2371 trustedIdentities.get(ownIdentity).add(identity);
2372 addRemoteSone(identity);
2379 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2380 soneDownloaders.execute(new Runnable() {
2383 @SuppressWarnings("synthetic-access")
2385 Sone sone = getRemoteSone(identity.getId(), false);
2386 sone.setIdentity(identity);
2387 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2388 soneDownloader.addSone(sone);
2389 soneDownloader.fetchSone(sone);
2398 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2399 trustedIdentities.get(ownIdentity).remove(identity);
2400 boolean foundIdentity = false;
2401 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2402 if (trustedIdentity.getKey().equals(ownIdentity)) {
2405 if (trustedIdentity.getValue().contains(identity)) {
2406 foundIdentity = true;
2409 if (foundIdentity) {
2410 /* some local identity still trusts this identity, don’t remove. */
2413 Sone sone = getSone(identity.getId(), false);
2415 /* TODO - we don’t have the Sone anymore. should this happen? */
2418 synchronized (posts) {
2419 synchronized (knownPosts) {
2420 for (Post post : sone.getPosts()) {
2421 posts.remove(post.getId());
2422 coreListenerManager.firePostRemoved(post);
2426 synchronized (replies) {
2427 synchronized (knownReplies) {
2428 for (PostReply reply : sone.getReplies()) {
2429 replies.remove(reply.getId());
2430 coreListenerManager.fireReplyRemoved(reply);
2434 synchronized (sones) {
2435 sones.remove(identity.getId());
2437 eventBus.post(new SoneRemovedEvent(sone));
2441 // INTERFACE UpdateListener
2448 public void updateFound(Version version, long releaseTime, long latestEdition) {
2449 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2453 // INTERFACE ImageInsertListener
2460 public void insertStarted(Sone sone) {
2461 coreListenerManager.fireSoneInserting(sone);
2468 public void insertFinished(Sone sone, long insertDuration) {
2469 coreListenerManager.fireSoneInserted(sone, insertDuration);
2476 public void insertAborted(Sone sone, Throwable cause) {
2477 coreListenerManager.fireSoneInsertAborted(sone, cause);
2481 // SONEINSERTLISTENER METHODS
2488 public void imageInsertStarted(Image image) {
2489 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2490 coreListenerManager.fireImageInsertStarted(image);
2497 public void imageInsertAborted(Image image) {
2498 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2499 coreListenerManager.fireImageInsertAborted(image);
2506 public void imageInsertFinished(Image image, FreenetURI key) {
2507 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2508 image.setKey(key.toString());
2509 deleteTemporaryImage(image.getId());
2510 touchConfiguration();
2511 coreListenerManager.fireImageInsertFinished(image);
2518 public void imageInsertFailed(Image image, Throwable cause) {
2519 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2520 coreListenerManager.fireImageInsertFailed(image, cause);
2524 * Convenience interface for external classes that want to access the core’s
2527 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2529 public static class Preferences {
2531 /** The wrapped options. */
2532 private final Options options;
2535 * Creates a new preferences object wrapped around the given options.
2538 * The options to wrap
2540 public Preferences(Options options) {
2541 this.options = options;
2545 * Returns the insertion delay.
2547 * @return The insertion delay
2549 public int getInsertionDelay() {
2550 return options.getIntegerOption("InsertionDelay").get();
2554 * Validates the given insertion delay.
2556 * @param insertionDelay
2557 * The insertion delay to validate
2558 * @return {@code true} if the given insertion delay was valid,
2559 * {@code false} otherwise
2561 public boolean validateInsertionDelay(Integer insertionDelay) {
2562 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2566 * Sets the insertion delay
2568 * @param insertionDelay
2569 * The new insertion delay, or {@code null} to restore it to
2571 * @return This preferences
2573 public Preferences setInsertionDelay(Integer insertionDelay) {
2574 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2579 * Returns the number of posts to show per page.
2581 * @return The number of posts to show per page
2583 public int getPostsPerPage() {
2584 return options.getIntegerOption("PostsPerPage").get();
2588 * Validates the number of posts per page.
2590 * @param postsPerPage
2591 * The number of posts per page
2592 * @return {@code true} if the number of posts per page was valid,
2593 * {@code false} otherwise
2595 public boolean validatePostsPerPage(Integer postsPerPage) {
2596 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2600 * Sets the number of posts to show per page.
2602 * @param postsPerPage
2603 * The number of posts to show per page
2604 * @return This preferences object
2606 public Preferences setPostsPerPage(Integer postsPerPage) {
2607 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2612 * Returns the number of images to show per page.
2614 * @return The number of images to show per page
2616 public int getImagesPerPage() {
2617 return options.getIntegerOption("ImagesPerPage").get();
2621 * Validates the number of images per page.
2623 * @param imagesPerPage
2624 * The number of images per page
2625 * @return {@code true} if the number of images per page was valid,
2626 * {@code false} otherwise
2628 public boolean validateImagesPerPage(Integer imagesPerPage) {
2629 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2633 * Sets the number of images per page.
2635 * @param imagesPerPage
2636 * The number of images per page
2637 * @return This preferences object
2639 public Preferences setImagesPerPage(Integer imagesPerPage) {
2640 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2645 * Returns the number of characters per post, or <code>-1</code> if the
2646 * posts should not be cut off.
2648 * @return The numbers of characters per post
2650 public int getCharactersPerPost() {
2651 return options.getIntegerOption("CharactersPerPost").get();
2655 * Validates the number of characters per post.
2657 * @param charactersPerPost
2658 * The number of characters per post
2659 * @return {@code true} if the number of characters per post was valid,
2660 * {@code false} otherwise
2662 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2663 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2667 * Sets the number of characters per post.
2669 * @param charactersPerPost
2670 * The number of characters per post, or <code>-1</code> to
2671 * not cut off the posts
2672 * @return This preferences objects
2674 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2675 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2680 * Returns the number of characters the shortened post should have.
2682 * @return The number of characters of the snippet
2684 public int getPostCutOffLength() {
2685 return options.getIntegerOption("PostCutOffLength").get();
2689 * Validates the number of characters after which to cut off the post.
2691 * @param postCutOffLength
2692 * The number of characters of the snippet
2693 * @return {@code true} if the number of characters of the snippet is
2694 * valid, {@code false} otherwise
2696 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2697 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2701 * Sets the number of characters the shortened post should have.
2703 * @param postCutOffLength
2704 * The number of characters of the snippet
2705 * @return This preferences
2707 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2708 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2713 * Returns whether Sone requires full access to be even visible.
2715 * @return {@code true} if Sone requires full access, {@code false}
2718 public boolean isRequireFullAccess() {
2719 return options.getBooleanOption("RequireFullAccess").get();
2723 * Sets whether Sone requires full access to be even visible.
2725 * @param requireFullAccess
2726 * {@code true} if Sone requires full access, {@code false}
2729 public void setRequireFullAccess(Boolean requireFullAccess) {
2730 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2734 * Returns the positive trust.
2736 * @return The positive trust
2738 public int getPositiveTrust() {
2739 return options.getIntegerOption("PositiveTrust").get();
2743 * Validates the positive trust.
2745 * @param positiveTrust
2746 * The positive trust to validate
2747 * @return {@code true} if the positive trust was valid, {@code false}
2750 public boolean validatePositiveTrust(Integer positiveTrust) {
2751 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2755 * Sets the positive trust.
2757 * @param positiveTrust
2758 * The new positive trust, or {@code null} to restore it to
2760 * @return This preferences
2762 public Preferences setPositiveTrust(Integer positiveTrust) {
2763 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2768 * Returns the negative trust.
2770 * @return The negative trust
2772 public int getNegativeTrust() {
2773 return options.getIntegerOption("NegativeTrust").get();
2777 * Validates the negative trust.
2779 * @param negativeTrust
2780 * The negative trust to validate
2781 * @return {@code true} if the negative trust was valid, {@code false}
2784 public boolean validateNegativeTrust(Integer negativeTrust) {
2785 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2789 * Sets the negative trust.
2791 * @param negativeTrust
2792 * The negative trust, or {@code null} to restore it to the
2794 * @return The preferences
2796 public Preferences setNegativeTrust(Integer negativeTrust) {
2797 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2802 * Returns the trust comment. This is the comment that is set in the web
2803 * of trust when a trust value is assigned to an identity.
2805 * @return The trust comment
2807 public String getTrustComment() {
2808 return options.getStringOption("TrustComment").get();
2812 * Sets the trust comment.
2814 * @param trustComment
2815 * The trust comment, or {@code null} to restore it to the
2817 * @return This preferences
2819 public Preferences setTrustComment(String trustComment) {
2820 options.getStringOption("TrustComment").set(trustComment);
2825 * Returns whether the {@link FcpInterface FCP interface} is currently
2828 * @see FcpInterface#setActive(boolean)
2829 * @return {@code true} if the FCP interface is currently active,
2830 * {@code false} otherwise
2832 public boolean isFcpInterfaceActive() {
2833 return options.getBooleanOption("ActivateFcpInterface").get();
2837 * Sets whether the {@link FcpInterface FCP interface} is currently
2840 * @see FcpInterface#setActive(boolean)
2841 * @param fcpInterfaceActive
2842 * {@code true} to activate the FCP interface, {@code false}
2843 * to deactivate the FCP interface
2844 * @return This preferences object
2846 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2847 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2852 * Returns the action level for which full access to the FCP interface
2855 * @return The action level for which full access to the FCP interface
2858 public FullAccessRequired getFcpFullAccessRequired() {
2859 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2863 * Sets the action level for which full access to the FCP interface is
2866 * @param fcpFullAccessRequired
2868 * @return This preferences
2870 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2871 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);