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.data.Album;
45 import net.pterodactylus.sone.data.Client;
46 import net.pterodactylus.sone.data.Image;
47 import net.pterodactylus.sone.data.Post;
48 import net.pterodactylus.sone.data.PostReply;
49 import net.pterodactylus.sone.data.Profile;
50 import net.pterodactylus.sone.data.Profile.Field;
51 import net.pterodactylus.sone.data.Reply;
52 import net.pterodactylus.sone.data.Sone;
53 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
54 import net.pterodactylus.sone.data.Sone.SoneStatus;
55 import net.pterodactylus.sone.data.TemporaryImage;
56 import net.pterodactylus.sone.data.impl.PostImpl;
57 import net.pterodactylus.sone.fcp.FcpInterface;
58 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
59 import net.pterodactylus.sone.freenet.wot.Identity;
60 import net.pterodactylus.sone.freenet.wot.IdentityListener;
61 import net.pterodactylus.sone.freenet.wot.IdentityManager;
62 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
63 import net.pterodactylus.sone.main.SonePlugin;
64 import net.pterodactylus.util.config.Configuration;
65 import net.pterodactylus.util.config.ConfigurationException;
66 import net.pterodactylus.util.logging.Logging;
67 import net.pterodactylus.util.number.Numbers;
68 import net.pterodactylus.util.service.AbstractService;
69 import net.pterodactylus.util.thread.NamedThreadFactory;
70 import net.pterodactylus.util.thread.Ticker;
71 import net.pterodactylus.util.validation.EqualityValidator;
72 import net.pterodactylus.util.validation.IntegerRangeValidator;
73 import net.pterodactylus.util.validation.OrValidator;
74 import net.pterodactylus.util.validation.Validation;
75 import net.pterodactylus.util.version.Version;
77 import com.google.common.base.Predicate;
78 import com.google.common.collect.Collections2;
79 import com.google.common.eventbus.EventBus;
80 import com.google.inject.Inject;
82 import freenet.keys.FreenetURI;
87 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
89 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
92 private static final Logger logger = Logging.getLogger(Core.class);
94 /** The start time. */
95 private final long startupTime = System.currentTimeMillis();
98 private final Options options = new Options();
100 /** The preferences. */
101 private final Preferences preferences = new Preferences(options);
103 /** The core listener manager. */
104 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
106 /** The event bus. */
107 private final EventBus eventBus;
109 /** The configuration. */
110 private Configuration configuration;
112 /** Whether we’re currently saving the configuration. */
113 private boolean storingConfiguration = false;
115 /** The identity manager. */
116 private final IdentityManager identityManager;
118 /** Interface to freenet. */
119 private final FreenetInterface freenetInterface;
121 /** The Sone downloader. */
122 private final SoneDownloader soneDownloader;
124 /** The image inserter. */
125 private final ImageInserter imageInserter;
127 /** Sone downloader thread-pool. */
128 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
130 /** The update checker. */
131 private final UpdateChecker updateChecker;
133 /** The trust updater. */
134 private final WebOfTrustUpdater webOfTrustUpdater;
136 /** The FCP interface. */
137 private volatile FcpInterface fcpInterface;
139 /** The times Sones were followed. */
140 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
142 /** Locked local Sones. */
143 /* synchronize on itself. */
144 private final Set<Sone> lockedSones = new HashSet<Sone>();
146 /** Sone inserters. */
147 /* synchronize access on this on sones. */
148 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
150 /** Sone rescuers. */
151 /* synchronize access on this on sones. */
152 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
155 /* synchronize access on this on itself. */
156 private final Map<String, Sone> sones = new HashMap<String, Sone>();
158 /** All known Sones. */
159 private final Set<String> knownSones = new HashSet<String>();
162 private final Map<String, Post> posts = new HashMap<String, Post>();
164 /** All known posts. */
165 private final Set<String> knownPosts = new HashSet<String>();
168 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
170 /** All known replies. */
171 private final Set<String> knownReplies = new HashSet<String>();
173 /** All bookmarked posts. */
174 /* synchronize access on itself. */
175 private final Set<String> bookmarkedPosts = new HashSet<String>();
177 /** Trusted identities, sorted by own identities. */
178 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
180 /** All known albums. */
181 private final Map<String, Album> albums = new HashMap<String, Album>();
183 /** All known images. */
184 private final Map<String, Image> images = new HashMap<String, Image>();
186 /** All temporary images. */
187 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
189 /** Ticker for threads that mark own elements as known. */
190 private final Ticker localElementTicker = new Ticker();
192 /** The time the configuration was last touched. */
193 private volatile long lastConfigurationUpdate;
196 * Creates a new core.
198 * @param configuration
199 * The configuration of the core
200 * @param freenetInterface
201 * The freenet interface
202 * @param identityManager
203 * The identity manager
204 * @param webOfTrustUpdater
205 * The WebOfTrust updater
210 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
212 this.configuration = configuration;
213 this.freenetInterface = freenetInterface;
214 this.identityManager = identityManager;
215 this.soneDownloader = new SoneDownloader(this, freenetInterface);
216 this.imageInserter = new ImageInserter(this, freenetInterface);
217 this.updateChecker = new UpdateChecker(freenetInterface);
218 this.webOfTrustUpdater = webOfTrustUpdater;
219 this.eventBus = eventBus;
223 // LISTENER MANAGEMENT
227 * Adds a new core listener.
229 * @param coreListener
230 * The listener to add
232 public void addCoreListener(CoreListener coreListener) {
233 coreListenerManager.addListener(coreListener);
237 * Removes a core listener.
239 * @param coreListener
240 * The listener to remove
242 public void removeCoreListener(CoreListener coreListener) {
243 coreListenerManager.removeListener(coreListener);
251 * Returns the time Sone was started.
253 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
255 public long getStartupTime() {
260 * Sets the configuration to use. This will automatically save the current
261 * configuration to the given configuration.
263 * @param configuration
264 * The new configuration to use
266 public void setConfiguration(Configuration configuration) {
267 this.configuration = configuration;
268 touchConfiguration();
272 * Returns the options used by the core.
274 * @return The options of the core
276 public Preferences getPreferences() {
281 * Returns the identity manager used by the core.
283 * @return The identity manager
285 public IdentityManager getIdentityManager() {
286 return identityManager;
290 * Returns the update checker.
292 * @return The update checker
294 public UpdateChecker getUpdateChecker() {
295 return updateChecker;
299 * Sets the FCP interface to use.
301 * @param fcpInterface
302 * The FCP interface to use
304 public void setFcpInterface(FcpInterface fcpInterface) {
305 this.fcpInterface = fcpInterface;
309 * Returns the Sone rescuer for the given local Sone.
312 * The local Sone to get the rescuer for
313 * @return The Sone rescuer for the given Sone
315 public SoneRescuer getSoneRescuer(Sone sone) {
316 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
317 synchronized (sones) {
318 SoneRescuer soneRescuer = soneRescuers.get(sone);
319 if (soneRescuer == null) {
320 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
321 soneRescuers.put(sone, soneRescuer);
329 * Returns whether the given Sone is currently locked.
333 * @return {@code true} if the Sone is locked, {@code false} if it is not
335 public boolean isLocked(Sone sone) {
336 synchronized (lockedSones) {
337 return lockedSones.contains(sone);
342 * Returns all Sones, remote and local.
346 public Set<Sone> getSones() {
347 return new HashSet<Sone>(sones.values());
351 * Returns the Sone with the given ID, regardless whether it’s local or
355 * The ID of the Sone to get
356 * @return The Sone with the given ID, or {@code null} if there is no such
359 public Sone getSone(String id) {
360 return getSone(id, true);
364 * Returns the Sone with the given ID, regardless whether it’s local or
368 * The ID of the Sone to get
370 * {@code true} to create a new Sone if none exists,
371 * {@code false} to return {@code null} if a Sone with the given
373 * @return The Sone with the given ID, or {@code null} if there is no such
377 public Sone getSone(String id, boolean create) {
378 synchronized (sones) {
379 if (!sones.containsKey(id)) {
380 Sone sone = new Sone(id, false);
383 return sones.get(id);
388 * Checks whether the core knows a Sone with the given ID.
392 * @return {@code true} if there is a Sone with the given ID, {@code false}
395 public boolean hasSone(String id) {
396 synchronized (sones) {
397 return sones.containsKey(id);
402 * Returns all local Sones.
404 * @return All local Sones
406 public Collection<Sone> getLocalSones() {
407 synchronized (sones) {
408 return Collections2.filter(sones.values(), new Predicate<Sone>() {
411 public boolean apply(Sone sone) {
412 return sone.isLocal();
419 * Returns the local Sone with the given ID, optionally creating a new Sone.
424 * {@code true} to create a new Sone if none exists,
425 * {@code false} to return null if none exists
426 * @return The Sone with the given ID, or {@code null}
428 public Sone getLocalSone(String id, boolean create) {
429 synchronized (sones) {
430 Sone sone = sones.get(id);
431 if ((sone == null) && create) {
432 sone = new Sone(id, true);
435 if ((sone != null) && !sone.isLocal()) {
436 sone = new Sone(id, true);
444 * Returns all remote Sones.
446 * @return All remote Sones
448 public Collection<Sone> getRemoteSones() {
449 synchronized (sones) {
450 return Collections2.filter(sones.values(), new Predicate<Sone>() {
453 public boolean apply(Sone sone) {
454 return !sone.isLocal();
461 * Returns the remote Sone with the given ID.
464 * The ID of the remote Sone to get
466 * {@code true} to always create a Sone, {@code false} to return
467 * {@code null} if no Sone with the given ID exists
468 * @return The Sone with the given ID
470 public Sone getRemoteSone(String id, boolean create) {
471 synchronized (sones) {
472 Sone sone = sones.get(id);
473 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
474 sone = new Sone(id, false);
482 * Returns whether the given Sone has been modified.
485 * The Sone to check for modifications
486 * @return {@code true} if a modification has been detected in the Sone,
487 * {@code false} otherwise
489 public boolean isModifiedSone(Sone sone) {
490 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
494 * Returns the time when the given was first followed by any local Sone.
497 * The Sone to get the time for
498 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
499 * been followed, or {@link Long#MAX_VALUE}
501 public long getSoneFollowingTime(Sone sone) {
502 synchronized (soneFollowingTimes) {
503 if (soneFollowingTimes.containsKey(sone)) {
504 return soneFollowingTimes.get(sone);
506 return Long.MAX_VALUE;
511 * Returns whether the target Sone is trusted by the origin Sone.
517 * @return {@code true} if the target Sone is trusted by the origin Sone
519 public boolean isSoneTrusted(Sone origin, Sone target) {
520 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
521 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
525 * Returns the post with the given ID.
528 * The ID of the post to get
529 * @return The post with the given ID, or a new post with the given ID
531 public Post getPost(String postId) {
532 return getPost(postId, true);
536 * Returns the post with the given ID, optionally creating a new post.
539 * The ID of the post to get
541 * {@code true} it create a new post if no post with the given ID
542 * exists, {@code false} to return {@code null}
543 * @return The post, or {@code null} if there is no such post
546 public Post getPost(String postId, boolean create) {
547 synchronized (posts) {
548 Post post = posts.get(postId);
549 if ((post == null) && create) {
550 post = new PostImpl(postId);
551 posts.put(postId, post);
558 * Returns all posts that have the given Sone as recipient.
560 * @see Post#getRecipient()
562 * The recipient of the posts
563 * @return All posts that have the given Sone as recipient
565 public Set<Post> getDirectedPosts(Sone recipient) {
566 Validation.begin().isNotNull("Recipient", recipient).check();
567 Set<Post> directedPosts = new HashSet<Post>();
568 synchronized (posts) {
569 for (Post post : posts.values()) {
570 if (recipient.equals(post.getRecipient())) {
571 directedPosts.add(post);
575 return directedPosts;
579 * Returns the reply with the given ID. If there is no reply with the given
580 * ID yet, a new one is created, unless {@code create} is false in which
581 * case {@code null} is returned.
584 * The ID of the reply to get
586 * {@code true} to always return a {@link Reply}, {@code false}
587 * to return {@code null} if no reply can be found
588 * @return The reply, or {@code null} if there is no such reply
590 public PostReply getPostReply(String replyId, boolean create) {
591 synchronized (replies) {
592 PostReply reply = replies.get(replyId);
593 if (create && (reply == null)) {
594 reply = new PostReply(replyId);
595 replies.put(replyId, reply);
602 * Returns all replies for the given post, order ascending by time.
605 * The post to get all replies for
606 * @return All replies for the given post
608 public List<PostReply> getReplies(Post post) {
609 Set<Sone> sones = getSones();
610 List<PostReply> replies = new ArrayList<PostReply>();
611 for (Sone sone : sones) {
612 for (PostReply reply : sone.getReplies()) {
613 if (reply.getPost().equals(post)) {
618 Collections.sort(replies, Reply.TIME_COMPARATOR);
623 * Returns all Sones that have liked the given post.
626 * The post to get the liking Sones for
627 * @return The Sones that like the given post
629 public Set<Sone> getLikes(Post post) {
630 Set<Sone> sones = new HashSet<Sone>();
631 for (Sone sone : getSones()) {
632 if (sone.getLikedPostIds().contains(post.getId())) {
640 * Returns all Sones that have liked the given reply.
643 * The reply to get the liking Sones for
644 * @return The Sones that like the given reply
646 public Set<Sone> getLikes(PostReply reply) {
647 Set<Sone> sones = new HashSet<Sone>();
648 for (Sone sone : getSones()) {
649 if (sone.getLikedReplyIds().contains(reply.getId())) {
657 * Returns whether the given post is bookmarked.
661 * @return {@code true} if the given post is bookmarked, {@code false}
664 public boolean isBookmarked(Post post) {
665 return isPostBookmarked(post.getId());
669 * Returns whether the post with the given ID is bookmarked.
672 * The ID of the post to check
673 * @return {@code true} if the post with the given ID is bookmarked,
674 * {@code false} otherwise
676 public boolean isPostBookmarked(String id) {
677 synchronized (bookmarkedPosts) {
678 return bookmarkedPosts.contains(id);
683 * Returns all currently known bookmarked posts.
685 * @return All bookmarked posts
687 public Set<Post> getBookmarkedPosts() {
688 Set<Post> posts = new HashSet<Post>();
689 synchronized (bookmarkedPosts) {
690 for (String bookmarkedPostId : bookmarkedPosts) {
691 Post post = getPost(bookmarkedPostId, false);
701 * Returns the album with the given ID, creating a new album if no album
702 * with the given ID can be found.
705 * The ID of the album
706 * @return The album with the given ID
708 public Album getAlbum(String albumId) {
709 return getAlbum(albumId, true);
713 * Returns the album with the given ID, optionally creating a new album if
714 * an album with the given ID can not be found.
717 * The ID of the album
719 * {@code true} to create a new album if none exists for the
721 * @return The album with the given ID, or {@code null} if no album with the
722 * given ID exists and {@code create} is {@code false}
724 public Album getAlbum(String albumId, boolean create) {
725 synchronized (albums) {
726 Album album = albums.get(albumId);
727 if (create && (album == null)) {
728 album = new Album(albumId);
729 albums.put(albumId, album);
736 * Returns the image with the given ID, creating it if necessary.
739 * The ID of the image
740 * @return The image with the given ID
742 public Image getImage(String imageId) {
743 return getImage(imageId, true);
747 * Returns the image with the given ID, optionally creating it if it does
751 * The ID of the image
753 * {@code true} to create an image if none exists with the given
755 * @return The image with the given ID, or {@code null} if none exists and
758 public Image getImage(String imageId, boolean create) {
759 synchronized (images) {
760 Image image = images.get(imageId);
761 if (create && (image == null)) {
762 image = new Image(imageId);
763 images.put(imageId, image);
770 * Returns the temporary image with the given ID.
773 * The ID of the temporary image
774 * @return The temporary image, or {@code null} if there is no temporary
775 * image with the given ID
777 public TemporaryImage getTemporaryImage(String imageId) {
778 synchronized (temporaryImages) {
779 return temporaryImages.get(imageId);
788 * Locks the given Sone. A locked Sone will not be inserted by
789 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
795 public void lockSone(Sone sone) {
796 synchronized (lockedSones) {
797 if (lockedSones.add(sone)) {
798 coreListenerManager.fireSoneLocked(sone);
804 * Unlocks the given Sone.
806 * @see #lockSone(Sone)
810 public void unlockSone(Sone sone) {
811 synchronized (lockedSones) {
812 if (lockedSones.remove(sone)) {
813 coreListenerManager.fireSoneUnlocked(sone);
819 * Adds a local Sone from the given own identity.
822 * The own identity to create a Sone from
823 * @return The added (or already existing) Sone
825 public Sone addLocalSone(OwnIdentity ownIdentity) {
826 if (ownIdentity == null) {
827 logger.log(Level.WARNING, "Given OwnIdentity is null!");
830 synchronized (sones) {
833 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
834 } catch (MalformedURLException mue1) {
835 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
838 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
839 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
841 /* TODO - load posts ’n stuff */
842 sones.put(ownIdentity.getId(), sone);
843 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
844 soneInserter.addSoneInsertListener(this);
845 soneInserters.put(sone, soneInserter);
846 sone.setStatus(SoneStatus.idle);
848 soneInserter.start();
854 * Creates a new Sone for the given own identity.
857 * The own identity to create a Sone for
858 * @return The created Sone
860 public Sone createSone(OwnIdentity ownIdentity) {
861 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
862 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
865 Sone sone = addLocalSone(ownIdentity);
866 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
867 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
868 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
869 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
870 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
871 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
873 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
874 touchConfiguration();
879 * Adds the Sone of the given identity.
882 * The identity whose Sone to add
883 * @return The added or already existing Sone
885 public Sone addRemoteSone(Identity identity) {
886 if (identity == null) {
887 logger.log(Level.WARNING, "Given Identity is null!");
890 synchronized (sones) {
891 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
892 boolean newSone = sone.getRequestUri() == null;
893 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
894 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
896 synchronized (knownSones) {
897 newSone = !knownSones.contains(sone.getId());
899 sone.setKnown(!newSone);
901 eventBus.post(new NewSoneFoundEvent(sone));
902 for (Sone localSone : getLocalSones()) {
903 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
904 followSone(localSone, sone);
909 soneDownloader.addSone(sone);
910 soneDownloaders.execute(new Runnable() {
913 @SuppressWarnings("synthetic-access")
915 soneDownloader.fetchSone(sone, sone.getRequestUri());
924 * Lets the given local Sone follow the Sone with the given ID.
927 * The local Sone that should follow another Sone
929 * The ID of the Sone to follow
931 public void followSone(Sone sone, String soneId) {
932 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
933 Sone followedSone = getSone(soneId, true);
934 if (followedSone == null) {
935 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
938 followSone(sone, getSone(soneId));
942 * Lets the given local Sone follow the other given Sone. If the given Sone
943 * was not followed by any local Sone before, this will mark all elements of
944 * the followed Sone as read that have been created before the current
948 * The local Sone that should follow the other Sone
949 * @param followedSone
950 * The Sone that should be followed
952 public void followSone(Sone sone, Sone followedSone) {
953 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
954 sone.addFriend(followedSone.getId());
955 synchronized (soneFollowingTimes) {
956 if (!soneFollowingTimes.containsKey(followedSone)) {
957 long now = System.currentTimeMillis();
958 soneFollowingTimes.put(followedSone, now);
959 for (Post post : followedSone.getPosts()) {
960 if (post.getTime() < now) {
964 for (PostReply reply : followedSone.getReplies()) {
965 if (reply.getTime() < now) {
966 markReplyKnown(reply);
971 touchConfiguration();
975 * Lets the given local Sone unfollow the Sone with the given ID.
978 * The local Sone that should unfollow another Sone
980 * The ID of the Sone being unfollowed
982 public void unfollowSone(Sone sone, String soneId) {
983 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
984 unfollowSone(sone, getSone(soneId, false));
988 * Lets the given local Sone unfollow the other given Sone. If the given
989 * local Sone is the last local Sone that followed the given Sone, its
990 * following time will be removed.
993 * The local Sone that should unfollow another Sone
994 * @param unfollowedSone
995 * The Sone being unfollowed
997 public void unfollowSone(Sone sone, Sone unfollowedSone) {
998 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
999 sone.removeFriend(unfollowedSone.getId());
1000 boolean unfollowedSoneStillFollowed = false;
1001 for (Sone localSone : getLocalSones()) {
1002 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1004 if (!unfollowedSoneStillFollowed) {
1005 synchronized (soneFollowingTimes) {
1006 soneFollowingTimes.remove(unfollowedSone);
1009 touchConfiguration();
1013 * Sets the trust value of the given origin Sone for the target Sone.
1020 * The trust value (from {@code -100} to {@code 100})
1022 public void setTrust(Sone origin, Sone target, int trustValue) {
1023 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();
1024 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1028 * Removes any trust assignment for the given target Sone.
1035 public void removeTrust(Sone origin, Sone target) {
1036 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1037 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1041 * Assigns the configured positive trust value for the given target.
1048 public void trustSone(Sone origin, Sone target) {
1049 setTrust(origin, target, preferences.getPositiveTrust());
1053 * Assigns the configured negative trust value for the given target.
1060 public void distrustSone(Sone origin, Sone target) {
1061 setTrust(origin, target, preferences.getNegativeTrust());
1065 * Removes the trust assignment for the given target.
1072 public void untrustSone(Sone origin, Sone target) {
1073 removeTrust(origin, target);
1077 * Updates the stored Sone with the given Sone.
1082 public void updateSone(Sone sone) {
1083 updateSone(sone, false);
1087 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1088 * {@code true}, an older Sone than the current Sone can be given to restore
1092 * The Sone to update
1093 * @param soneRescueMode
1094 * {@code true} if the stored Sone should be updated regardless
1095 * of the age of the given Sone
1097 public void updateSone(Sone sone, boolean soneRescueMode) {
1098 if (hasSone(sone.getId())) {
1099 Sone storedSone = getSone(sone.getId());
1100 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1101 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1104 synchronized (posts) {
1105 if (!soneRescueMode) {
1106 for (Post post : storedSone.getPosts()) {
1107 posts.remove(post.getId());
1108 if (!sone.getPosts().contains(post)) {
1109 coreListenerManager.firePostRemoved(post);
1113 List<Post> storedPosts = storedSone.getPosts();
1114 synchronized (knownPosts) {
1115 for (Post post : sone.getPosts()) {
1116 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1117 if (!storedPosts.contains(post)) {
1118 if (post.getTime() < getSoneFollowingTime(sone)) {
1119 knownPosts.add(post.getId());
1120 post.setKnown(true);
1121 } else if (!knownPosts.contains(post.getId())) {
1122 eventBus.post(new NewPostFoundEvent(post));
1125 posts.put(post.getId(), post);
1129 synchronized (replies) {
1130 if (!soneRescueMode) {
1131 for (PostReply reply : storedSone.getReplies()) {
1132 replies.remove(reply.getId());
1133 if (!sone.getReplies().contains(reply)) {
1134 coreListenerManager.fireReplyRemoved(reply);
1138 Set<PostReply> storedReplies = storedSone.getReplies();
1139 synchronized (knownReplies) {
1140 for (PostReply reply : sone.getReplies()) {
1141 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1142 if (!storedReplies.contains(reply)) {
1143 if (reply.getTime() < getSoneFollowingTime(sone)) {
1144 knownReplies.add(reply.getId());
1145 reply.setKnown(true);
1146 } else if (!knownReplies.contains(reply.getId())) {
1147 eventBus.post(new NewPostReplyFoundEvent(reply));
1150 replies.put(reply.getId(), reply);
1154 synchronized (albums) {
1155 synchronized (images) {
1156 for (Album album : storedSone.getAlbums()) {
1157 albums.remove(album.getId());
1158 for (Image image : album.getImages()) {
1159 images.remove(image.getId());
1162 for (Album album : sone.getAlbums()) {
1163 albums.put(album.getId(), album);
1164 for (Image image : album.getImages()) {
1165 images.put(image.getId(), image);
1170 synchronized (storedSone) {
1171 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1172 storedSone.setTime(sone.getTime());
1174 storedSone.setClient(sone.getClient());
1175 storedSone.setProfile(sone.getProfile());
1176 if (soneRescueMode) {
1177 for (Post post : sone.getPosts()) {
1178 storedSone.addPost(post);
1180 for (PostReply reply : sone.getReplies()) {
1181 storedSone.addReply(reply);
1183 for (String likedPostId : sone.getLikedPostIds()) {
1184 storedSone.addLikedPostId(likedPostId);
1186 for (String likedReplyId : sone.getLikedReplyIds()) {
1187 storedSone.addLikedReplyId(likedReplyId);
1189 for (Album album : sone.getAlbums()) {
1190 storedSone.addAlbum(album);
1193 storedSone.setPosts(sone.getPosts());
1194 storedSone.setReplies(sone.getReplies());
1195 storedSone.setLikePostIds(sone.getLikedPostIds());
1196 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1197 storedSone.setAlbums(sone.getAlbums());
1199 storedSone.setLatestEdition(sone.getLatestEdition());
1205 * Deletes the given Sone. This will remove the Sone from the
1206 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1207 * remove the context from its identity.
1210 * The Sone to delete
1212 public void deleteSone(Sone sone) {
1213 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1214 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1217 synchronized (sones) {
1218 if (!getLocalSones().contains(sone)) {
1219 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1222 sones.remove(sone.getId());
1223 SoneInserter soneInserter = soneInserters.remove(sone);
1224 soneInserter.removeSoneInsertListener(this);
1225 soneInserter.stop();
1227 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1228 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1230 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1231 } catch (ConfigurationException ce1) {
1232 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1237 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1238 * known} before, a {@link MarkSoneKnownEvent} is fired.
1241 * The Sone to mark as known
1243 public void markSoneKnown(Sone sone) {
1244 if (!sone.isKnown()) {
1245 sone.setKnown(true);
1246 synchronized (knownSones) {
1247 knownSones.add(sone.getId());
1249 eventBus.post(new MarkSoneKnownEvent(sone));
1250 touchConfiguration();
1255 * Loads and updates the given Sone from the configuration. If any error is
1256 * encountered, loading is aborted and the given Sone is not changed.
1259 * The Sone to load and update
1261 public void loadSone(Sone sone) {
1262 if (!sone.isLocal()) {
1263 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1267 /* initialize options. */
1268 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1269 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1270 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1271 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1272 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1273 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1276 String sonePrefix = "Sone/" + sone.getId();
1277 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1278 if (soneTime == null) {
1279 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1282 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1285 Profile profile = new Profile(sone);
1286 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1287 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1288 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1289 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1290 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1291 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1293 /* load profile fields. */
1295 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1296 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1297 if (fieldName == null) {
1300 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1301 profile.addField(fieldName).setValue(fieldValue);
1305 Set<Post> posts = new HashSet<Post>();
1307 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1308 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1309 if (postId == null) {
1312 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1313 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1314 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1315 if ((postTime == 0) || (postText == null)) {
1316 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1319 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1320 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1321 post.setRecipient(getSone(postRecipientId));
1327 Set<PostReply> replies = new HashSet<PostReply>();
1329 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1330 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1331 if (replyId == null) {
1334 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1335 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1336 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1337 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1338 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1341 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1344 /* load post likes. */
1345 Set<String> likedPostIds = new HashSet<String>();
1347 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1348 if (likedPostId == null) {
1351 likedPostIds.add(likedPostId);
1354 /* load reply likes. */
1355 Set<String> likedReplyIds = new HashSet<String>();
1357 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1358 if (likedReplyId == null) {
1361 likedReplyIds.add(likedReplyId);
1365 Set<String> friends = new HashSet<String>();
1367 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1368 if (friendId == null) {
1371 friends.add(friendId);
1375 List<Album> topLevelAlbums = new ArrayList<Album>();
1376 int albumCounter = 0;
1378 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1379 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1380 if (albumId == null) {
1383 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1384 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1385 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1386 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1387 if ((albumTitle == null) || (albumDescription == null)) {
1388 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1391 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1392 if (albumParentId != null) {
1393 Album parentAlbum = getAlbum(albumParentId, false);
1394 if (parentAlbum == null) {
1395 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1398 parentAlbum.addAlbum(album);
1400 if (!topLevelAlbums.contains(album)) {
1401 topLevelAlbums.add(album);
1407 int imageCounter = 0;
1409 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1410 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1411 if (imageId == null) {
1414 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1415 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1416 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1417 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1418 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1419 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1420 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1421 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1422 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1425 Album album = getAlbum(albumId, false);
1426 if (album == null) {
1427 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1430 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1431 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1432 album.addImage(image);
1436 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1437 if (avatarId != null) {
1438 profile.setAvatar(getImage(avatarId, false));
1442 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1443 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1444 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1445 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1446 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1447 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1449 /* if we’re still here, Sone was loaded successfully. */
1450 synchronized (sone) {
1451 sone.setTime(soneTime);
1452 sone.setProfile(profile);
1453 sone.setPosts(posts);
1454 sone.setReplies(replies);
1455 sone.setLikePostIds(likedPostIds);
1456 sone.setLikeReplyIds(likedReplyIds);
1457 for (String friendId : friends) {
1458 followSone(sone, friendId);
1460 sone.setAlbums(topLevelAlbums);
1461 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1463 synchronized (knownSones) {
1464 for (String friend : friends) {
1465 knownSones.add(friend);
1468 synchronized (knownPosts) {
1469 for (Post post : posts) {
1470 knownPosts.add(post.getId());
1473 synchronized (knownReplies) {
1474 for (PostReply reply : replies) {
1475 knownReplies.add(reply.getId());
1481 * Creates a new post.
1484 * The Sone that creates the post
1486 * The text of the post
1487 * @return The created post
1489 public Post createPost(Sone sone, String text) {
1490 return createPost(sone, System.currentTimeMillis(), text);
1494 * Creates a new post.
1497 * The Sone that creates the post
1499 * The time of the post
1501 * The text of the post
1502 * @return The created post
1504 public Post createPost(Sone sone, long time, String text) {
1505 return createPost(sone, null, time, text);
1509 * Creates a new post.
1512 * The Sone that creates the post
1514 * The recipient Sone, or {@code null} if this post does not have
1517 * The text of the post
1518 * @return The created post
1520 public Post createPost(Sone sone, Sone recipient, String text) {
1521 return createPost(sone, recipient, System.currentTimeMillis(), text);
1525 * Creates a new post.
1528 * The Sone that creates the post
1530 * The recipient Sone, or {@code null} if this post does not have
1533 * The time of the post
1535 * The text of the post
1536 * @return The created post
1538 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1539 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1540 if (!sone.isLocal()) {
1541 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1544 final Post post = new PostImpl(sone, time, text);
1545 if (recipient != null) {
1546 post.setRecipient(recipient);
1548 synchronized (posts) {
1549 posts.put(post.getId(), post);
1551 eventBus.post(new NewPostFoundEvent(post));
1553 touchConfiguration();
1554 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1561 markPostKnown(post);
1563 }, "Mark " + post + " read.");
1568 * Deletes the given post.
1571 * The post to delete
1573 public void deletePost(Post post) {
1574 if (!post.getSone().isLocal()) {
1575 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1578 post.getSone().removePost(post);
1579 synchronized (posts) {
1580 posts.remove(post.getId());
1582 coreListenerManager.firePostRemoved(post);
1583 markPostKnown(post);
1584 touchConfiguration();
1588 * Marks the given post as known, if it is currently not a known post
1589 * (according to {@link Post#isKnown()}).
1592 * The post to mark as known
1594 public void markPostKnown(Post post) {
1595 post.setKnown(true);
1596 synchronized (knownPosts) {
1597 eventBus.post(new MarkPostKnownEvent(post));
1598 if (knownPosts.add(post.getId())) {
1599 touchConfiguration();
1602 for (PostReply reply : getReplies(post)) {
1603 markReplyKnown(reply);
1608 * Bookmarks the given post.
1611 * The post to bookmark
1613 public void bookmark(Post post) {
1614 bookmarkPost(post.getId());
1618 * Bookmarks the post with the given ID.
1621 * The ID of the post to bookmark
1623 public void bookmarkPost(String id) {
1624 synchronized (bookmarkedPosts) {
1625 bookmarkedPosts.add(id);
1630 * Removes the given post from the bookmarks.
1633 * The post to unbookmark
1635 public void unbookmark(Post post) {
1636 unbookmarkPost(post.getId());
1640 * Removes the post with the given ID from the bookmarks.
1643 * The ID of the post to unbookmark
1645 public void unbookmarkPost(String id) {
1646 synchronized (bookmarkedPosts) {
1647 bookmarkedPosts.remove(id);
1652 * Creates a new reply.
1655 * The Sone that creates the reply
1657 * The post that this reply refers to
1659 * The text of the reply
1660 * @return The created reply
1662 public PostReply createReply(Sone sone, Post post, String text) {
1663 return createReply(sone, post, System.currentTimeMillis(), text);
1667 * Creates a new reply.
1670 * The Sone that creates the reply
1672 * The post that this reply refers to
1674 * The time of the reply
1676 * The text of the reply
1677 * @return The created reply
1679 public PostReply createReply(Sone sone, Post post, long time, String text) {
1680 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1681 if (!sone.isLocal()) {
1682 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1685 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1686 synchronized (replies) {
1687 replies.put(reply.getId(), reply);
1689 synchronized (knownReplies) {
1690 eventBus.post(new NewPostReplyFoundEvent(reply));
1692 sone.addReply(reply);
1693 touchConfiguration();
1694 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1701 markReplyKnown(reply);
1703 }, "Mark " + reply + " read.");
1708 * Deletes the given reply.
1711 * The reply to delete
1713 public void deleteReply(PostReply reply) {
1714 Sone sone = reply.getSone();
1715 if (!sone.isLocal()) {
1716 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1719 synchronized (replies) {
1720 replies.remove(reply.getId());
1722 synchronized (knownReplies) {
1723 markReplyKnown(reply);
1724 knownReplies.remove(reply.getId());
1726 sone.removeReply(reply);
1727 touchConfiguration();
1731 * Marks the given reply as known, if it is currently not a known reply
1732 * (according to {@link Reply#isKnown()}).
1735 * The reply to mark as known
1737 public void markReplyKnown(PostReply reply) {
1738 reply.setKnown(true);
1739 synchronized (knownReplies) {
1740 eventBus.post(new MarkPostReplyKnownEvent(reply));
1741 if (knownReplies.add(reply.getId())) {
1742 touchConfiguration();
1748 * Creates a new top-level album for the given Sone.
1751 * The Sone to create the album for
1752 * @return The new album
1754 public Album createAlbum(Sone sone) {
1755 return createAlbum(sone, null);
1759 * Creates a new album for the given Sone.
1762 * The Sone to create the album for
1764 * The parent of the album (may be {@code null} to create a
1766 * @return The new album
1768 public Album createAlbum(Sone sone, Album parent) {
1769 Album album = new Album();
1770 synchronized (albums) {
1771 albums.put(album.getId(), album);
1773 album.setSone(sone);
1774 if (parent != null) {
1775 parent.addAlbum(album);
1777 sone.addAlbum(album);
1783 * Deletes the given album. The owner of the album has to be a local Sone,
1784 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1787 * The album to remove
1789 public void deleteAlbum(Album album) {
1790 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1791 if (!album.isEmpty()) {
1794 if (album.getParent() == null) {
1795 album.getSone().removeAlbum(album);
1797 album.getParent().removeAlbum(album);
1799 synchronized (albums) {
1800 albums.remove(album.getId());
1802 touchConfiguration();
1806 * Creates a new image.
1809 * The Sone creating the image
1811 * The album the image will be inserted into
1812 * @param temporaryImage
1813 * The temporary image to create the image from
1814 * @return The newly created image
1816 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1817 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();
1818 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1819 album.addImage(image);
1820 synchronized (images) {
1821 images.put(image.getId(), image);
1823 imageInserter.insertImage(temporaryImage, image);
1828 * Deletes the given image. This method will also delete a matching
1831 * @see #deleteTemporaryImage(TemporaryImage)
1833 * The image to delete
1835 public void deleteImage(Image image) {
1836 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1837 deleteTemporaryImage(image.getId());
1838 image.getAlbum().removeImage(image);
1839 synchronized (images) {
1840 images.remove(image.getId());
1842 touchConfiguration();
1846 * Creates a new temporary image.
1849 * The MIME type of the temporary image
1851 * The encoded data of the image
1852 * @return The temporary image
1854 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1855 TemporaryImage temporaryImage = new TemporaryImage();
1856 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1857 synchronized (temporaryImages) {
1858 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1860 return temporaryImage;
1864 * Deletes the given temporary image.
1866 * @param temporaryImage
1867 * The temporary image to delete
1869 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1870 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1871 deleteTemporaryImage(temporaryImage.getId());
1875 * Deletes the temporary image with the given ID.
1878 * The ID of the temporary image to delete
1880 public void deleteTemporaryImage(String imageId) {
1881 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1882 synchronized (temporaryImages) {
1883 temporaryImages.remove(imageId);
1885 Image image = getImage(imageId, false);
1886 if (image != null) {
1887 imageInserter.cancelImageInsert(image);
1892 * Notifies the core that the configuration, either of the core or of a
1893 * single local Sone, has changed, and that the configuration should be
1896 public void touchConfiguration() {
1897 lastConfigurationUpdate = System.currentTimeMillis();
1908 public void serviceStart() {
1909 loadConfiguration();
1910 updateChecker.addUpdateListener(this);
1911 updateChecker.start();
1912 identityManager.addIdentityListener(this);
1913 identityManager.start();
1914 webOfTrustUpdater.init();
1915 webOfTrustUpdater.start();
1922 public void serviceRun() {
1923 long lastSaved = System.currentTimeMillis();
1924 while (!shouldStop()) {
1926 long now = System.currentTimeMillis();
1927 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1928 for (Sone localSone : getLocalSones()) {
1929 saveSone(localSone);
1931 saveConfiguration();
1941 public void serviceStop() {
1942 synchronized (sones) {
1943 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1944 soneInserter.getValue().removeSoneInsertListener(this);
1945 soneInserter.getValue().stop();
1946 saveSone(soneInserter.getKey());
1949 saveConfiguration();
1950 webOfTrustUpdater.stop();
1951 updateChecker.stop();
1952 updateChecker.removeUpdateListener(this);
1953 soneDownloader.stop();
1954 identityManager.removeIdentityListener(this);
1955 identityManager.stop();
1963 * Saves the given Sone. This will persist all local settings for the given
1964 * Sone, such as the friends list and similar, private options.
1969 private synchronized void saveSone(Sone sone) {
1970 if (!sone.isLocal()) {
1971 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1974 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1975 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1979 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1981 /* save Sone into configuration. */
1982 String sonePrefix = "Sone/" + sone.getId();
1983 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1984 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1987 Profile profile = sone.getProfile();
1988 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1989 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1990 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1991 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1992 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1993 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1994 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1996 /* save profile fields. */
1997 int fieldCounter = 0;
1998 for (Field profileField : profile.getFields()) {
1999 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2000 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2001 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2003 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2006 int postCounter = 0;
2007 for (Post post : sone.getPosts()) {
2008 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2009 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2010 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2011 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2012 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2014 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2017 int replyCounter = 0;
2018 for (PostReply reply : sone.getReplies()) {
2019 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2020 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2021 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2022 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2023 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2025 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2027 /* save post likes. */
2028 int postLikeCounter = 0;
2029 for (String postId : sone.getLikedPostIds()) {
2030 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2032 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2034 /* save reply likes. */
2035 int replyLikeCounter = 0;
2036 for (String replyId : sone.getLikedReplyIds()) {
2037 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2039 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2042 int friendCounter = 0;
2043 for (String friendId : sone.getFriends()) {
2044 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2046 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2048 /* save albums. first, collect in a flat structure, top-level first. */
2049 List<Album> albums = sone.getAllAlbums();
2051 int albumCounter = 0;
2052 for (Album album : albums) {
2053 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2054 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2055 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2056 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2057 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2058 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2060 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2063 int imageCounter = 0;
2064 for (Album album : albums) {
2065 for (Image image : album.getImages()) {
2066 if (!image.isInserted()) {
2069 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2070 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2071 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2072 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2073 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2074 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2075 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2076 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2077 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2080 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2083 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2084 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2085 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2086 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2087 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2088 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2090 configuration.save();
2092 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2094 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2095 } catch (ConfigurationException ce1) {
2096 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2101 * Saves the current options.
2103 private void saveConfiguration() {
2104 synchronized (configuration) {
2105 if (storingConfiguration) {
2106 logger.log(Level.FINE, "Already storing configuration…");
2109 storingConfiguration = true;
2112 /* store the options first. */
2114 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2115 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2116 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2117 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2118 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2119 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2120 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2121 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2122 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2123 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2124 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2125 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2127 /* save known Sones. */
2128 int soneCounter = 0;
2129 synchronized (knownSones) {
2130 for (String knownSoneId : knownSones) {
2131 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2133 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2136 /* save Sone following times. */
2138 synchronized (soneFollowingTimes) {
2139 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2140 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2141 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2144 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2147 /* save known posts. */
2148 int postCounter = 0;
2149 synchronized (knownPosts) {
2150 for (String knownPostId : knownPosts) {
2151 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2153 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2156 /* save known replies. */
2157 int replyCounter = 0;
2158 synchronized (knownReplies) {
2159 for (String knownReplyId : knownReplies) {
2160 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2162 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2165 /* save bookmarked posts. */
2166 int bookmarkedPostCounter = 0;
2167 synchronized (bookmarkedPosts) {
2168 for (String bookmarkedPostId : bookmarkedPosts) {
2169 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2172 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2175 configuration.save();
2177 } catch (ConfigurationException ce1) {
2178 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2180 synchronized (configuration) {
2181 storingConfiguration = false;
2187 * Loads the configuration.
2189 @SuppressWarnings("unchecked")
2190 private void loadConfiguration() {
2191 /* create options. */
2192 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2195 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2196 SoneInserter.setInsertionDelay(newValue);
2200 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2201 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2202 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2203 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2204 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2205 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2206 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2207 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2208 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2211 @SuppressWarnings("synthetic-access")
2212 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2213 fcpInterface.setActive(newValue);
2216 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2219 @SuppressWarnings("synthetic-access")
2220 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2221 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2226 loadConfigurationValue("InsertionDelay");
2227 loadConfigurationValue("PostsPerPage");
2228 loadConfigurationValue("ImagesPerPage");
2229 loadConfigurationValue("CharactersPerPost");
2230 loadConfigurationValue("PostCutOffLength");
2231 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2232 loadConfigurationValue("PositiveTrust");
2233 loadConfigurationValue("NegativeTrust");
2234 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2235 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2236 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2238 /* load known Sones. */
2239 int soneCounter = 0;
2241 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2242 if (knownSoneId == null) {
2245 synchronized (knownSones) {
2246 knownSones.add(knownSoneId);
2250 /* load Sone following times. */
2253 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2254 if (soneId == null) {
2257 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2258 Sone followedSone = getSone(soneId);
2259 if (followedSone == null) {
2260 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2262 synchronized (soneFollowingTimes) {
2263 soneFollowingTimes.put(getSone(soneId), time);
2269 /* load known posts. */
2270 int postCounter = 0;
2272 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2273 if (knownPostId == null) {
2276 synchronized (knownPosts) {
2277 knownPosts.add(knownPostId);
2281 /* load known replies. */
2282 int replyCounter = 0;
2284 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2285 if (knownReplyId == null) {
2288 synchronized (knownReplies) {
2289 knownReplies.add(knownReplyId);
2293 /* load bookmarked posts. */
2294 int bookmarkedPostCounter = 0;
2296 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2297 if (bookmarkedPostId == null) {
2300 synchronized (bookmarkedPosts) {
2301 bookmarkedPosts.add(bookmarkedPostId);
2308 * Loads an {@link Integer} configuration value for the option with the
2309 * given name, logging validation failures.
2312 * The name of the option to load
2314 private void loadConfigurationValue(String optionName) {
2316 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2317 } catch (IllegalArgumentException iae1) {
2318 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2323 * Generate a Sone URI from the given URI and latest edition.
2326 * The URI to derive the Sone URI from
2327 * @return The derived URI
2329 private static FreenetURI getSoneUri(String uriString) {
2331 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2333 } catch (MalformedURLException mue1) {
2334 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2340 // INTERFACE IdentityListener
2347 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2348 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2349 if (ownIdentity.hasContext("Sone")) {
2350 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2351 addLocalSone(ownIdentity);
2359 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2360 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2361 trustedIdentities.remove(ownIdentity);
2368 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2369 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2370 trustedIdentities.get(ownIdentity).add(identity);
2371 addRemoteSone(identity);
2378 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2379 soneDownloaders.execute(new Runnable() {
2382 @SuppressWarnings("synthetic-access")
2384 Sone sone = getRemoteSone(identity.getId(), false);
2385 sone.setIdentity(identity);
2386 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2387 soneDownloader.addSone(sone);
2388 soneDownloader.fetchSone(sone);
2397 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2398 trustedIdentities.get(ownIdentity).remove(identity);
2399 boolean foundIdentity = false;
2400 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2401 if (trustedIdentity.getKey().equals(ownIdentity)) {
2404 if (trustedIdentity.getValue().contains(identity)) {
2405 foundIdentity = true;
2408 if (foundIdentity) {
2409 /* some local identity still trusts this identity, don’t remove. */
2412 Sone sone = getSone(identity.getId(), false);
2414 /* TODO - we don’t have the Sone anymore. should this happen? */
2417 synchronized (posts) {
2418 synchronized (knownPosts) {
2419 for (Post post : sone.getPosts()) {
2420 posts.remove(post.getId());
2421 coreListenerManager.firePostRemoved(post);
2425 synchronized (replies) {
2426 synchronized (knownReplies) {
2427 for (PostReply reply : sone.getReplies()) {
2428 replies.remove(reply.getId());
2429 coreListenerManager.fireReplyRemoved(reply);
2433 synchronized (sones) {
2434 sones.remove(identity.getId());
2436 coreListenerManager.fireSoneRemoved(sone);
2440 // INTERFACE UpdateListener
2447 public void updateFound(Version version, long releaseTime, long latestEdition) {
2448 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2452 // INTERFACE ImageInsertListener
2459 public void insertStarted(Sone sone) {
2460 coreListenerManager.fireSoneInserting(sone);
2467 public void insertFinished(Sone sone, long insertDuration) {
2468 coreListenerManager.fireSoneInserted(sone, insertDuration);
2475 public void insertAborted(Sone sone, Throwable cause) {
2476 coreListenerManager.fireSoneInsertAborted(sone, cause);
2480 // SONEINSERTLISTENER METHODS
2487 public void imageInsertStarted(Image image) {
2488 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2489 coreListenerManager.fireImageInsertStarted(image);
2496 public void imageInsertAborted(Image image) {
2497 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2498 coreListenerManager.fireImageInsertAborted(image);
2505 public void imageInsertFinished(Image image, FreenetURI key) {
2506 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2507 image.setKey(key.toString());
2508 deleteTemporaryImage(image.getId());
2509 touchConfiguration();
2510 coreListenerManager.fireImageInsertFinished(image);
2517 public void imageInsertFailed(Image image, Throwable cause) {
2518 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2519 coreListenerManager.fireImageInsertFailed(image, cause);
2523 * Convenience interface for external classes that want to access the core’s
2526 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2528 public static class Preferences {
2530 /** The wrapped options. */
2531 private final Options options;
2534 * Creates a new preferences object wrapped around the given options.
2537 * The options to wrap
2539 public Preferences(Options options) {
2540 this.options = options;
2544 * Returns the insertion delay.
2546 * @return The insertion delay
2548 public int getInsertionDelay() {
2549 return options.getIntegerOption("InsertionDelay").get();
2553 * Validates the given insertion delay.
2555 * @param insertionDelay
2556 * The insertion delay to validate
2557 * @return {@code true} if the given insertion delay was valid,
2558 * {@code false} otherwise
2560 public boolean validateInsertionDelay(Integer insertionDelay) {
2561 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2565 * Sets the insertion delay
2567 * @param insertionDelay
2568 * The new insertion delay, or {@code null} to restore it to
2570 * @return This preferences
2572 public Preferences setInsertionDelay(Integer insertionDelay) {
2573 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2578 * Returns the number of posts to show per page.
2580 * @return The number of posts to show per page
2582 public int getPostsPerPage() {
2583 return options.getIntegerOption("PostsPerPage").get();
2587 * Validates the number of posts per page.
2589 * @param postsPerPage
2590 * The number of posts per page
2591 * @return {@code true} if the number of posts per page was valid,
2592 * {@code false} otherwise
2594 public boolean validatePostsPerPage(Integer postsPerPage) {
2595 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2599 * Sets the number of posts to show per page.
2601 * @param postsPerPage
2602 * The number of posts to show per page
2603 * @return This preferences object
2605 public Preferences setPostsPerPage(Integer postsPerPage) {
2606 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2611 * Returns the number of images to show per page.
2613 * @return The number of images to show per page
2615 public int getImagesPerPage() {
2616 return options.getIntegerOption("ImagesPerPage").get();
2620 * Validates the number of images per page.
2622 * @param imagesPerPage
2623 * The number of images per page
2624 * @return {@code true} if the number of images per page was valid,
2625 * {@code false} otherwise
2627 public boolean validateImagesPerPage(Integer imagesPerPage) {
2628 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2632 * Sets the number of images per page.
2634 * @param imagesPerPage
2635 * The number of images per page
2636 * @return This preferences object
2638 public Preferences setImagesPerPage(Integer imagesPerPage) {
2639 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2644 * Returns the number of characters per post, or <code>-1</code> if the
2645 * posts should not be cut off.
2647 * @return The numbers of characters per post
2649 public int getCharactersPerPost() {
2650 return options.getIntegerOption("CharactersPerPost").get();
2654 * Validates the number of characters per post.
2656 * @param charactersPerPost
2657 * The number of characters per post
2658 * @return {@code true} if the number of characters per post was valid,
2659 * {@code false} otherwise
2661 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2662 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2666 * Sets the number of characters per post.
2668 * @param charactersPerPost
2669 * The number of characters per post, or <code>-1</code> to
2670 * not cut off the posts
2671 * @return This preferences objects
2673 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2674 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2679 * Returns the number of characters the shortened post should have.
2681 * @return The number of characters of the snippet
2683 public int getPostCutOffLength() {
2684 return options.getIntegerOption("PostCutOffLength").get();
2688 * Validates the number of characters after which to cut off the post.
2690 * @param postCutOffLength
2691 * The number of characters of the snippet
2692 * @return {@code true} if the number of characters of the snippet is
2693 * valid, {@code false} otherwise
2695 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2696 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2700 * Sets the number of characters the shortened post should have.
2702 * @param postCutOffLength
2703 * The number of characters of the snippet
2704 * @return This preferences
2706 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2707 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2712 * Returns whether Sone requires full access to be even visible.
2714 * @return {@code true} if Sone requires full access, {@code false}
2717 public boolean isRequireFullAccess() {
2718 return options.getBooleanOption("RequireFullAccess").get();
2722 * Sets whether Sone requires full access to be even visible.
2724 * @param requireFullAccess
2725 * {@code true} if Sone requires full access, {@code false}
2728 public void setRequireFullAccess(Boolean requireFullAccess) {
2729 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2733 * Returns the positive trust.
2735 * @return The positive trust
2737 public int getPositiveTrust() {
2738 return options.getIntegerOption("PositiveTrust").get();
2742 * Validates the positive trust.
2744 * @param positiveTrust
2745 * The positive trust to validate
2746 * @return {@code true} if the positive trust was valid, {@code false}
2749 public boolean validatePositiveTrust(Integer positiveTrust) {
2750 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2754 * Sets the positive trust.
2756 * @param positiveTrust
2757 * The new positive trust, or {@code null} to restore it to
2759 * @return This preferences
2761 public Preferences setPositiveTrust(Integer positiveTrust) {
2762 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2767 * Returns the negative trust.
2769 * @return The negative trust
2771 public int getNegativeTrust() {
2772 return options.getIntegerOption("NegativeTrust").get();
2776 * Validates the negative trust.
2778 * @param negativeTrust
2779 * The negative trust to validate
2780 * @return {@code true} if the negative trust was valid, {@code false}
2783 public boolean validateNegativeTrust(Integer negativeTrust) {
2784 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2788 * Sets the negative trust.
2790 * @param negativeTrust
2791 * The negative trust, or {@code null} to restore it to the
2793 * @return The preferences
2795 public Preferences setNegativeTrust(Integer negativeTrust) {
2796 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2801 * Returns the trust comment. This is the comment that is set in the web
2802 * of trust when a trust value is assigned to an identity.
2804 * @return The trust comment
2806 public String getTrustComment() {
2807 return options.getStringOption("TrustComment").get();
2811 * Sets the trust comment.
2813 * @param trustComment
2814 * The trust comment, or {@code null} to restore it to the
2816 * @return This preferences
2818 public Preferences setTrustComment(String trustComment) {
2819 options.getStringOption("TrustComment").set(trustComment);
2824 * Returns whether the {@link FcpInterface FCP interface} is currently
2827 * @see FcpInterface#setActive(boolean)
2828 * @return {@code true} if the FCP interface is currently active,
2829 * {@code false} otherwise
2831 public boolean isFcpInterfaceActive() {
2832 return options.getBooleanOption("ActivateFcpInterface").get();
2836 * Sets whether the {@link FcpInterface FCP interface} is currently
2839 * @see FcpInterface#setActive(boolean)
2840 * @param fcpInterfaceActive
2841 * {@code true} to activate the FCP interface, {@code false}
2842 * to deactivate the FCP interface
2843 * @return This preferences object
2845 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2846 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2851 * Returns the action level for which full access to the FCP interface
2854 * @return The action level for which full access to the FCP interface
2857 public FullAccessRequired getFcpFullAccessRequired() {
2858 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2862 * Sets the action level for which full access to the FCP interface is
2865 * @param fcpFullAccessRequired
2867 * @return This preferences
2869 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2870 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);