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.PostRemovedEvent;
45 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
46 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
47 import net.pterodactylus.sone.data.Album;
48 import net.pterodactylus.sone.data.Client;
49 import net.pterodactylus.sone.data.Image;
50 import net.pterodactylus.sone.data.Post;
51 import net.pterodactylus.sone.data.PostReply;
52 import net.pterodactylus.sone.data.Profile;
53 import net.pterodactylus.sone.data.Profile.Field;
54 import net.pterodactylus.sone.data.Reply;
55 import net.pterodactylus.sone.data.Sone;
56 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
57 import net.pterodactylus.sone.data.Sone.SoneStatus;
58 import net.pterodactylus.sone.data.TemporaryImage;
59 import net.pterodactylus.sone.data.impl.PostImpl;
60 import net.pterodactylus.sone.fcp.FcpInterface;
61 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
62 import net.pterodactylus.sone.freenet.wot.Identity;
63 import net.pterodactylus.sone.freenet.wot.IdentityListener;
64 import net.pterodactylus.sone.freenet.wot.IdentityManager;
65 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
66 import net.pterodactylus.sone.main.SonePlugin;
67 import net.pterodactylus.util.config.Configuration;
68 import net.pterodactylus.util.config.ConfigurationException;
69 import net.pterodactylus.util.logging.Logging;
70 import net.pterodactylus.util.number.Numbers;
71 import net.pterodactylus.util.service.AbstractService;
72 import net.pterodactylus.util.thread.NamedThreadFactory;
73 import net.pterodactylus.util.thread.Ticker;
74 import net.pterodactylus.util.validation.EqualityValidator;
75 import net.pterodactylus.util.validation.IntegerRangeValidator;
76 import net.pterodactylus.util.validation.OrValidator;
77 import net.pterodactylus.util.validation.Validation;
78 import net.pterodactylus.util.version.Version;
80 import com.google.common.base.Predicate;
81 import com.google.common.collect.Collections2;
82 import com.google.common.eventbus.EventBus;
83 import com.google.inject.Inject;
85 import freenet.keys.FreenetURI;
90 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
92 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
95 private static final Logger logger = Logging.getLogger(Core.class);
97 /** The start time. */
98 private final long startupTime = System.currentTimeMillis();
101 private final Options options = new Options();
103 /** The preferences. */
104 private final Preferences preferences = new Preferences(options);
106 /** The core listener manager. */
107 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
109 /** The event bus. */
110 private final EventBus eventBus;
112 /** The configuration. */
113 private Configuration configuration;
115 /** Whether we’re currently saving the configuration. */
116 private boolean storingConfiguration = false;
118 /** The identity manager. */
119 private final IdentityManager identityManager;
121 /** Interface to freenet. */
122 private final FreenetInterface freenetInterface;
124 /** The Sone downloader. */
125 private final SoneDownloader soneDownloader;
127 /** The image inserter. */
128 private final ImageInserter imageInserter;
130 /** Sone downloader thread-pool. */
131 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
133 /** The update checker. */
134 private final UpdateChecker updateChecker;
136 /** The trust updater. */
137 private final WebOfTrustUpdater webOfTrustUpdater;
139 /** The FCP interface. */
140 private volatile FcpInterface fcpInterface;
142 /** The times Sones were followed. */
143 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
145 /** Locked local Sones. */
146 /* synchronize on itself. */
147 private final Set<Sone> lockedSones = new HashSet<Sone>();
149 /** Sone inserters. */
150 /* synchronize access on this on sones. */
151 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
153 /** Sone rescuers. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
158 /* synchronize access on this on itself. */
159 private final Map<String, Sone> sones = new HashMap<String, Sone>();
161 /** All known Sones. */
162 private final Set<String> knownSones = new HashSet<String>();
165 private final Map<String, Post> posts = new HashMap<String, Post>();
167 /** All known posts. */
168 private final Set<String> knownPosts = new HashSet<String>();
171 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
173 /** All known replies. */
174 private final Set<String> knownReplies = new HashSet<String>();
176 /** All bookmarked posts. */
177 /* synchronize access on itself. */
178 private final Set<String> bookmarkedPosts = new HashSet<String>();
180 /** Trusted identities, sorted by own identities. */
181 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
183 /** All known albums. */
184 private final Map<String, Album> albums = new HashMap<String, Album>();
186 /** All known images. */
187 private final Map<String, Image> images = new HashMap<String, Image>();
189 /** All temporary images. */
190 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
192 /** Ticker for threads that mark own elements as known. */
193 private final Ticker localElementTicker = new Ticker();
195 /** The time the configuration was last touched. */
196 private volatile long lastConfigurationUpdate;
199 * Creates a new core.
201 * @param configuration
202 * The configuration of the core
203 * @param freenetInterface
204 * The freenet interface
205 * @param identityManager
206 * The identity manager
207 * @param webOfTrustUpdater
208 * The WebOfTrust updater
213 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
215 this.configuration = configuration;
216 this.freenetInterface = freenetInterface;
217 this.identityManager = identityManager;
218 this.soneDownloader = new SoneDownloader(this, freenetInterface);
219 this.imageInserter = new ImageInserter(this, freenetInterface);
220 this.updateChecker = new UpdateChecker(freenetInterface);
221 this.webOfTrustUpdater = webOfTrustUpdater;
222 this.eventBus = eventBus;
226 // LISTENER MANAGEMENT
230 * Adds a new core listener.
232 * @param coreListener
233 * The listener to add
235 public void addCoreListener(CoreListener coreListener) {
236 coreListenerManager.addListener(coreListener);
240 * Removes a core listener.
242 * @param coreListener
243 * The listener to remove
245 public void removeCoreListener(CoreListener coreListener) {
246 coreListenerManager.removeListener(coreListener);
254 * Returns the time Sone was started.
256 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
258 public long getStartupTime() {
263 * Sets the configuration to use. This will automatically save the current
264 * configuration to the given configuration.
266 * @param configuration
267 * The new configuration to use
269 public void setConfiguration(Configuration configuration) {
270 this.configuration = configuration;
271 touchConfiguration();
275 * Returns the options used by the core.
277 * @return The options of the core
279 public Preferences getPreferences() {
284 * Returns the identity manager used by the core.
286 * @return The identity manager
288 public IdentityManager getIdentityManager() {
289 return identityManager;
293 * Returns the update checker.
295 * @return The update checker
297 public UpdateChecker getUpdateChecker() {
298 return updateChecker;
302 * Sets the FCP interface to use.
304 * @param fcpInterface
305 * The FCP interface to use
307 public void setFcpInterface(FcpInterface fcpInterface) {
308 this.fcpInterface = fcpInterface;
312 * Returns the Sone rescuer for the given local Sone.
315 * The local Sone to get the rescuer for
316 * @return The Sone rescuer for the given Sone
318 public SoneRescuer getSoneRescuer(Sone sone) {
319 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
320 synchronized (sones) {
321 SoneRescuer soneRescuer = soneRescuers.get(sone);
322 if (soneRescuer == null) {
323 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
324 soneRescuers.put(sone, soneRescuer);
332 * Returns whether the given Sone is currently locked.
336 * @return {@code true} if the Sone is locked, {@code false} if it is not
338 public boolean isLocked(Sone sone) {
339 synchronized (lockedSones) {
340 return lockedSones.contains(sone);
345 * Returns all Sones, remote and local.
349 public Set<Sone> getSones() {
350 return new HashSet<Sone>(sones.values());
354 * Returns the Sone with the given ID, regardless whether it’s local or
358 * The ID of the Sone to get
359 * @return The Sone with the given ID, or {@code null} if there is no such
362 public Sone getSone(String id) {
363 return getSone(id, true);
367 * Returns the Sone with the given ID, regardless whether it’s local or
371 * The ID of the Sone to get
373 * {@code true} to create a new Sone if none exists,
374 * {@code false} to return {@code null} if a Sone with the given
376 * @return The Sone with the given ID, or {@code null} if there is no such
380 public Sone getSone(String id, boolean create) {
381 synchronized (sones) {
382 if (!sones.containsKey(id)) {
383 Sone sone = new Sone(id, false);
386 return sones.get(id);
391 * Checks whether the core knows a Sone with the given ID.
395 * @return {@code true} if there is a Sone with the given ID, {@code false}
398 public boolean hasSone(String id) {
399 synchronized (sones) {
400 return sones.containsKey(id);
405 * Returns all local Sones.
407 * @return All local Sones
409 public Collection<Sone> getLocalSones() {
410 synchronized (sones) {
411 return Collections2.filter(sones.values(), new Predicate<Sone>() {
414 public boolean apply(Sone sone) {
415 return sone.isLocal();
422 * Returns the local Sone with the given ID, optionally creating a new Sone.
427 * {@code true} to create a new Sone if none exists,
428 * {@code false} to return null if none exists
429 * @return The Sone with the given ID, or {@code null}
431 public Sone getLocalSone(String id, boolean create) {
432 synchronized (sones) {
433 Sone sone = sones.get(id);
434 if ((sone == null) && create) {
435 sone = new Sone(id, true);
438 if ((sone != null) && !sone.isLocal()) {
439 sone = new Sone(id, true);
447 * Returns all remote Sones.
449 * @return All remote Sones
451 public Collection<Sone> getRemoteSones() {
452 synchronized (sones) {
453 return Collections2.filter(sones.values(), new Predicate<Sone>() {
456 public boolean apply(Sone sone) {
457 return !sone.isLocal();
464 * Returns the remote Sone with the given ID.
467 * The ID of the remote Sone to get
469 * {@code true} to always create a Sone, {@code false} to return
470 * {@code null} if no Sone with the given ID exists
471 * @return The Sone with the given ID
473 public Sone getRemoteSone(String id, boolean create) {
474 synchronized (sones) {
475 Sone sone = sones.get(id);
476 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
477 sone = new Sone(id, false);
485 * Returns whether the given Sone has been modified.
488 * The Sone to check for modifications
489 * @return {@code true} if a modification has been detected in the Sone,
490 * {@code false} otherwise
492 public boolean isModifiedSone(Sone sone) {
493 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
497 * Returns the time when the given was first followed by any local Sone.
500 * The Sone to get the time for
501 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
502 * been followed, or {@link Long#MAX_VALUE}
504 public long getSoneFollowingTime(Sone sone) {
505 synchronized (soneFollowingTimes) {
506 if (soneFollowingTimes.containsKey(sone)) {
507 return soneFollowingTimes.get(sone);
509 return Long.MAX_VALUE;
514 * Returns whether the target Sone is trusted by the origin Sone.
520 * @return {@code true} if the target Sone is trusted by the origin Sone
522 public boolean isSoneTrusted(Sone origin, Sone target) {
523 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
524 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
528 * Returns the post with the given ID.
531 * The ID of the post to get
532 * @return The post with the given ID, or a new post with the given ID
534 public Post getPost(String postId) {
535 return getPost(postId, true);
539 * Returns the post with the given ID, optionally creating a new post.
542 * The ID of the post to get
544 * {@code true} it create a new post if no post with the given ID
545 * exists, {@code false} to return {@code null}
546 * @return The post, or {@code null} if there is no such post
549 public Post getPost(String postId, boolean create) {
550 synchronized (posts) {
551 Post post = posts.get(postId);
552 if ((post == null) && create) {
553 post = new PostImpl(postId);
554 posts.put(postId, post);
561 * Returns all posts that have the given Sone as recipient.
563 * @see Post#getRecipient()
565 * The recipient of the posts
566 * @return All posts that have the given Sone as recipient
568 public Set<Post> getDirectedPosts(Sone recipient) {
569 Validation.begin().isNotNull("Recipient", recipient).check();
570 Set<Post> directedPosts = new HashSet<Post>();
571 synchronized (posts) {
572 for (Post post : posts.values()) {
573 if (recipient.equals(post.getRecipient())) {
574 directedPosts.add(post);
578 return directedPosts;
582 * Returns the reply with the given ID. If there is no reply with the given
583 * ID yet, a new one is created, unless {@code create} is false in which
584 * case {@code null} is returned.
587 * The ID of the reply to get
589 * {@code true} to always return a {@link Reply}, {@code false}
590 * to return {@code null} if no reply can be found
591 * @return The reply, or {@code null} if there is no such reply
593 public PostReply getPostReply(String replyId, boolean create) {
594 synchronized (replies) {
595 PostReply reply = replies.get(replyId);
596 if (create && (reply == null)) {
597 reply = new PostReply(replyId);
598 replies.put(replyId, reply);
605 * Returns all replies for the given post, order ascending by time.
608 * The post to get all replies for
609 * @return All replies for the given post
611 public List<PostReply> getReplies(Post post) {
612 Set<Sone> sones = getSones();
613 List<PostReply> replies = new ArrayList<PostReply>();
614 for (Sone sone : sones) {
615 for (PostReply reply : sone.getReplies()) {
616 if (reply.getPost().equals(post)) {
621 Collections.sort(replies, Reply.TIME_COMPARATOR);
626 * Returns all Sones that have liked the given post.
629 * The post to get the liking Sones for
630 * @return The Sones that like the given post
632 public Set<Sone> getLikes(Post post) {
633 Set<Sone> sones = new HashSet<Sone>();
634 for (Sone sone : getSones()) {
635 if (sone.getLikedPostIds().contains(post.getId())) {
643 * Returns all Sones that have liked the given reply.
646 * The reply to get the liking Sones for
647 * @return The Sones that like the given reply
649 public Set<Sone> getLikes(PostReply reply) {
650 Set<Sone> sones = new HashSet<Sone>();
651 for (Sone sone : getSones()) {
652 if (sone.getLikedReplyIds().contains(reply.getId())) {
660 * Returns whether the given post is bookmarked.
664 * @return {@code true} if the given post is bookmarked, {@code false}
667 public boolean isBookmarked(Post post) {
668 return isPostBookmarked(post.getId());
672 * Returns whether the post with the given ID is bookmarked.
675 * The ID of the post to check
676 * @return {@code true} if the post with the given ID is bookmarked,
677 * {@code false} otherwise
679 public boolean isPostBookmarked(String id) {
680 synchronized (bookmarkedPosts) {
681 return bookmarkedPosts.contains(id);
686 * Returns all currently known bookmarked posts.
688 * @return All bookmarked posts
690 public Set<Post> getBookmarkedPosts() {
691 Set<Post> posts = new HashSet<Post>();
692 synchronized (bookmarkedPosts) {
693 for (String bookmarkedPostId : bookmarkedPosts) {
694 Post post = getPost(bookmarkedPostId, false);
704 * Returns the album with the given ID, creating a new album if no album
705 * with the given ID can be found.
708 * The ID of the album
709 * @return The album with the given ID
711 public Album getAlbum(String albumId) {
712 return getAlbum(albumId, true);
716 * Returns the album with the given ID, optionally creating a new album if
717 * an album with the given ID can not be found.
720 * The ID of the album
722 * {@code true} to create a new album if none exists for the
724 * @return The album with the given ID, or {@code null} if no album with the
725 * given ID exists and {@code create} is {@code false}
727 public Album getAlbum(String albumId, boolean create) {
728 synchronized (albums) {
729 Album album = albums.get(albumId);
730 if (create && (album == null)) {
731 album = new Album(albumId);
732 albums.put(albumId, album);
739 * Returns the image with the given ID, creating it if necessary.
742 * The ID of the image
743 * @return The image with the given ID
745 public Image getImage(String imageId) {
746 return getImage(imageId, true);
750 * Returns the image with the given ID, optionally creating it if it does
754 * The ID of the image
756 * {@code true} to create an image if none exists with the given
758 * @return The image with the given ID, or {@code null} if none exists and
761 public Image getImage(String imageId, boolean create) {
762 synchronized (images) {
763 Image image = images.get(imageId);
764 if (create && (image == null)) {
765 image = new Image(imageId);
766 images.put(imageId, image);
773 * Returns the temporary image with the given ID.
776 * The ID of the temporary image
777 * @return The temporary image, or {@code null} if there is no temporary
778 * image with the given ID
780 public TemporaryImage getTemporaryImage(String imageId) {
781 synchronized (temporaryImages) {
782 return temporaryImages.get(imageId);
791 * Locks the given Sone. A locked Sone will not be inserted by
792 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
798 public void lockSone(Sone sone) {
799 synchronized (lockedSones) {
800 if (lockedSones.add(sone)) {
801 coreListenerManager.fireSoneLocked(sone);
807 * Unlocks the given Sone.
809 * @see #lockSone(Sone)
813 public void unlockSone(Sone sone) {
814 synchronized (lockedSones) {
815 if (lockedSones.remove(sone)) {
816 coreListenerManager.fireSoneUnlocked(sone);
822 * Adds a local Sone from the given own identity.
825 * The own identity to create a Sone from
826 * @return The added (or already existing) Sone
828 public Sone addLocalSone(OwnIdentity ownIdentity) {
829 if (ownIdentity == null) {
830 logger.log(Level.WARNING, "Given OwnIdentity is null!");
833 synchronized (sones) {
836 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
837 } catch (MalformedURLException mue1) {
838 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
841 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
842 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
844 /* TODO - load posts ’n stuff */
845 sones.put(ownIdentity.getId(), sone);
846 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
847 soneInserter.addSoneInsertListener(this);
848 soneInserters.put(sone, soneInserter);
849 sone.setStatus(SoneStatus.idle);
851 soneInserter.start();
857 * Creates a new Sone for the given own identity.
860 * The own identity to create a Sone for
861 * @return The created Sone
863 public Sone createSone(OwnIdentity ownIdentity) {
864 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
865 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
868 Sone sone = addLocalSone(ownIdentity);
869 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
870 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
871 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
872 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
873 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
874 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
876 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
877 touchConfiguration();
882 * Adds the Sone of the given identity.
885 * The identity whose Sone to add
886 * @return The added or already existing Sone
888 public Sone addRemoteSone(Identity identity) {
889 if (identity == null) {
890 logger.log(Level.WARNING, "Given Identity is null!");
893 synchronized (sones) {
894 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
895 boolean newSone = sone.getRequestUri() == null;
896 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
897 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
899 synchronized (knownSones) {
900 newSone = !knownSones.contains(sone.getId());
902 sone.setKnown(!newSone);
904 eventBus.post(new NewSoneFoundEvent(sone));
905 for (Sone localSone : getLocalSones()) {
906 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
907 followSone(localSone, sone);
912 soneDownloader.addSone(sone);
913 soneDownloaders.execute(new Runnable() {
916 @SuppressWarnings("synthetic-access")
918 soneDownloader.fetchSone(sone, sone.getRequestUri());
927 * Lets the given local Sone follow the Sone with the given ID.
930 * The local Sone that should follow another Sone
932 * The ID of the Sone to follow
934 public void followSone(Sone sone, String soneId) {
935 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
936 Sone followedSone = getSone(soneId, true);
937 if (followedSone == null) {
938 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
941 followSone(sone, getSone(soneId));
945 * Lets the given local Sone follow the other given Sone. If the given Sone
946 * was not followed by any local Sone before, this will mark all elements of
947 * the followed Sone as read that have been created before the current
951 * The local Sone that should follow the other Sone
952 * @param followedSone
953 * The Sone that should be followed
955 public void followSone(Sone sone, Sone followedSone) {
956 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
957 sone.addFriend(followedSone.getId());
958 synchronized (soneFollowingTimes) {
959 if (!soneFollowingTimes.containsKey(followedSone)) {
960 long now = System.currentTimeMillis();
961 soneFollowingTimes.put(followedSone, now);
962 for (Post post : followedSone.getPosts()) {
963 if (post.getTime() < now) {
967 for (PostReply reply : followedSone.getReplies()) {
968 if (reply.getTime() < now) {
969 markReplyKnown(reply);
974 touchConfiguration();
978 * Lets the given local Sone unfollow the Sone with the given ID.
981 * The local Sone that should unfollow another Sone
983 * The ID of the Sone being unfollowed
985 public void unfollowSone(Sone sone, String soneId) {
986 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
987 unfollowSone(sone, getSone(soneId, false));
991 * Lets the given local Sone unfollow the other given Sone. If the given
992 * local Sone is the last local Sone that followed the given Sone, its
993 * following time will be removed.
996 * The local Sone that should unfollow another Sone
997 * @param unfollowedSone
998 * The Sone being unfollowed
1000 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1001 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1002 sone.removeFriend(unfollowedSone.getId());
1003 boolean unfollowedSoneStillFollowed = false;
1004 for (Sone localSone : getLocalSones()) {
1005 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1007 if (!unfollowedSoneStillFollowed) {
1008 synchronized (soneFollowingTimes) {
1009 soneFollowingTimes.remove(unfollowedSone);
1012 touchConfiguration();
1016 * Sets the trust value of the given origin Sone for the target Sone.
1023 * The trust value (from {@code -100} to {@code 100})
1025 public void setTrust(Sone origin, Sone target, int trustValue) {
1026 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();
1027 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1031 * Removes any trust assignment for the given target Sone.
1038 public void removeTrust(Sone origin, Sone target) {
1039 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1040 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1044 * Assigns the configured positive trust value for the given target.
1051 public void trustSone(Sone origin, Sone target) {
1052 setTrust(origin, target, preferences.getPositiveTrust());
1056 * Assigns the configured negative trust value for the given target.
1063 public void distrustSone(Sone origin, Sone target) {
1064 setTrust(origin, target, preferences.getNegativeTrust());
1068 * Removes the trust assignment for the given target.
1075 public void untrustSone(Sone origin, Sone target) {
1076 removeTrust(origin, target);
1080 * Updates the stored Sone with the given Sone.
1085 public void updateSone(Sone sone) {
1086 updateSone(sone, false);
1090 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1091 * {@code true}, an older Sone than the current Sone can be given to restore
1095 * The Sone to update
1096 * @param soneRescueMode
1097 * {@code true} if the stored Sone should be updated regardless
1098 * of the age of the given Sone
1100 public void updateSone(Sone sone, boolean soneRescueMode) {
1101 if (hasSone(sone.getId())) {
1102 Sone storedSone = getSone(sone.getId());
1103 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1104 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1107 synchronized (posts) {
1108 if (!soneRescueMode) {
1109 for (Post post : storedSone.getPosts()) {
1110 posts.remove(post.getId());
1111 if (!sone.getPosts().contains(post)) {
1112 eventBus.post(new PostRemovedEvent(post));
1116 List<Post> storedPosts = storedSone.getPosts();
1117 synchronized (knownPosts) {
1118 for (Post post : sone.getPosts()) {
1119 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1120 if (!storedPosts.contains(post)) {
1121 if (post.getTime() < getSoneFollowingTime(sone)) {
1122 knownPosts.add(post.getId());
1123 post.setKnown(true);
1124 } else if (!knownPosts.contains(post.getId())) {
1125 eventBus.post(new NewPostFoundEvent(post));
1128 posts.put(post.getId(), post);
1132 synchronized (replies) {
1133 if (!soneRescueMode) {
1134 for (PostReply reply : storedSone.getReplies()) {
1135 replies.remove(reply.getId());
1136 if (!sone.getReplies().contains(reply)) {
1137 eventBus.post(new PostReplyRemovedEvent(reply));
1141 Set<PostReply> storedReplies = storedSone.getReplies();
1142 synchronized (knownReplies) {
1143 for (PostReply reply : sone.getReplies()) {
1144 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1145 if (!storedReplies.contains(reply)) {
1146 if (reply.getTime() < getSoneFollowingTime(sone)) {
1147 knownReplies.add(reply.getId());
1148 reply.setKnown(true);
1149 } else if (!knownReplies.contains(reply.getId())) {
1150 eventBus.post(new NewPostReplyFoundEvent(reply));
1153 replies.put(reply.getId(), reply);
1157 synchronized (albums) {
1158 synchronized (images) {
1159 for (Album album : storedSone.getAlbums()) {
1160 albums.remove(album.getId());
1161 for (Image image : album.getImages()) {
1162 images.remove(image.getId());
1165 for (Album album : sone.getAlbums()) {
1166 albums.put(album.getId(), album);
1167 for (Image image : album.getImages()) {
1168 images.put(image.getId(), image);
1173 synchronized (storedSone) {
1174 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1175 storedSone.setTime(sone.getTime());
1177 storedSone.setClient(sone.getClient());
1178 storedSone.setProfile(sone.getProfile());
1179 if (soneRescueMode) {
1180 for (Post post : sone.getPosts()) {
1181 storedSone.addPost(post);
1183 for (PostReply reply : sone.getReplies()) {
1184 storedSone.addReply(reply);
1186 for (String likedPostId : sone.getLikedPostIds()) {
1187 storedSone.addLikedPostId(likedPostId);
1189 for (String likedReplyId : sone.getLikedReplyIds()) {
1190 storedSone.addLikedReplyId(likedReplyId);
1192 for (Album album : sone.getAlbums()) {
1193 storedSone.addAlbum(album);
1196 storedSone.setPosts(sone.getPosts());
1197 storedSone.setReplies(sone.getReplies());
1198 storedSone.setLikePostIds(sone.getLikedPostIds());
1199 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1200 storedSone.setAlbums(sone.getAlbums());
1202 storedSone.setLatestEdition(sone.getLatestEdition());
1208 * Deletes the given Sone. This will remove the Sone from the
1209 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1210 * remove the context from its identity.
1213 * The Sone to delete
1215 public void deleteSone(Sone sone) {
1216 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1217 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1220 synchronized (sones) {
1221 if (!getLocalSones().contains(sone)) {
1222 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1225 sones.remove(sone.getId());
1226 SoneInserter soneInserter = soneInserters.remove(sone);
1227 soneInserter.removeSoneInsertListener(this);
1228 soneInserter.stop();
1230 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1231 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1233 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1234 } catch (ConfigurationException ce1) {
1235 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1240 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1241 * known} before, a {@link MarkSoneKnownEvent} is fired.
1244 * The Sone to mark as known
1246 public void markSoneKnown(Sone sone) {
1247 if (!sone.isKnown()) {
1248 sone.setKnown(true);
1249 synchronized (knownSones) {
1250 knownSones.add(sone.getId());
1252 eventBus.post(new MarkSoneKnownEvent(sone));
1253 touchConfiguration();
1258 * Loads and updates the given Sone from the configuration. If any error is
1259 * encountered, loading is aborted and the given Sone is not changed.
1262 * The Sone to load and update
1264 public void loadSone(Sone sone) {
1265 if (!sone.isLocal()) {
1266 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1270 /* initialize options. */
1271 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1272 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1273 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1274 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1275 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1276 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1279 String sonePrefix = "Sone/" + sone.getId();
1280 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1281 if (soneTime == null) {
1282 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1285 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1288 Profile profile = new Profile(sone);
1289 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1290 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1291 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1292 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1293 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1294 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1296 /* load profile fields. */
1298 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1299 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1300 if (fieldName == null) {
1303 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1304 profile.addField(fieldName).setValue(fieldValue);
1308 Set<Post> posts = new HashSet<Post>();
1310 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1311 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1312 if (postId == null) {
1315 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1316 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1317 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1318 if ((postTime == 0) || (postText == null)) {
1319 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1322 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1323 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1324 post.setRecipient(getSone(postRecipientId));
1330 Set<PostReply> replies = new HashSet<PostReply>();
1332 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1333 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1334 if (replyId == null) {
1337 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1338 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1339 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1340 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1341 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1344 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1347 /* load post likes. */
1348 Set<String> likedPostIds = new HashSet<String>();
1350 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1351 if (likedPostId == null) {
1354 likedPostIds.add(likedPostId);
1357 /* load reply likes. */
1358 Set<String> likedReplyIds = new HashSet<String>();
1360 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1361 if (likedReplyId == null) {
1364 likedReplyIds.add(likedReplyId);
1368 Set<String> friends = new HashSet<String>();
1370 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1371 if (friendId == null) {
1374 friends.add(friendId);
1378 List<Album> topLevelAlbums = new ArrayList<Album>();
1379 int albumCounter = 0;
1381 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1382 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1383 if (albumId == null) {
1386 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1387 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1388 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1389 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1390 if ((albumTitle == null) || (albumDescription == null)) {
1391 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1394 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1395 if (albumParentId != null) {
1396 Album parentAlbum = getAlbum(albumParentId, false);
1397 if (parentAlbum == null) {
1398 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1401 parentAlbum.addAlbum(album);
1403 if (!topLevelAlbums.contains(album)) {
1404 topLevelAlbums.add(album);
1410 int imageCounter = 0;
1412 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1413 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1414 if (imageId == null) {
1417 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1418 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1419 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1420 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1421 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1422 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1423 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1424 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1425 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1428 Album album = getAlbum(albumId, false);
1429 if (album == null) {
1430 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1433 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1434 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1435 album.addImage(image);
1439 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1440 if (avatarId != null) {
1441 profile.setAvatar(getImage(avatarId, false));
1445 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1446 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1447 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1448 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1449 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1450 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1452 /* if we’re still here, Sone was loaded successfully. */
1453 synchronized (sone) {
1454 sone.setTime(soneTime);
1455 sone.setProfile(profile);
1456 sone.setPosts(posts);
1457 sone.setReplies(replies);
1458 sone.setLikePostIds(likedPostIds);
1459 sone.setLikeReplyIds(likedReplyIds);
1460 for (String friendId : friends) {
1461 followSone(sone, friendId);
1463 sone.setAlbums(topLevelAlbums);
1464 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1466 synchronized (knownSones) {
1467 for (String friend : friends) {
1468 knownSones.add(friend);
1471 synchronized (knownPosts) {
1472 for (Post post : posts) {
1473 knownPosts.add(post.getId());
1476 synchronized (knownReplies) {
1477 for (PostReply reply : replies) {
1478 knownReplies.add(reply.getId());
1484 * Creates a new post.
1487 * The Sone that creates the post
1489 * The text of the post
1490 * @return The created post
1492 public Post createPost(Sone sone, String text) {
1493 return createPost(sone, System.currentTimeMillis(), text);
1497 * Creates a new post.
1500 * The Sone that creates the post
1502 * The time of the post
1504 * The text of the post
1505 * @return The created post
1507 public Post createPost(Sone sone, long time, String text) {
1508 return createPost(sone, null, time, text);
1512 * Creates a new post.
1515 * The Sone that creates the post
1517 * The recipient Sone, or {@code null} if this post does not have
1520 * The text of the post
1521 * @return The created post
1523 public Post createPost(Sone sone, Sone recipient, String text) {
1524 return createPost(sone, recipient, System.currentTimeMillis(), text);
1528 * Creates a new post.
1531 * The Sone that creates the post
1533 * The recipient Sone, or {@code null} if this post does not have
1536 * The time of the post
1538 * The text of the post
1539 * @return The created post
1541 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1542 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1543 if (!sone.isLocal()) {
1544 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1547 final Post post = new PostImpl(sone, time, text);
1548 if (recipient != null) {
1549 post.setRecipient(recipient);
1551 synchronized (posts) {
1552 posts.put(post.getId(), post);
1554 eventBus.post(new NewPostFoundEvent(post));
1556 touchConfiguration();
1557 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1564 markPostKnown(post);
1566 }, "Mark " + post + " read.");
1571 * Deletes the given post.
1574 * The post to delete
1576 public void deletePost(Post post) {
1577 if (!post.getSone().isLocal()) {
1578 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1581 post.getSone().removePost(post);
1582 synchronized (posts) {
1583 posts.remove(post.getId());
1585 eventBus.post(new PostRemovedEvent(post));
1586 markPostKnown(post);
1587 touchConfiguration();
1591 * Marks the given post as known, if it is currently not a known post
1592 * (according to {@link Post#isKnown()}).
1595 * The post to mark as known
1597 public void markPostKnown(Post post) {
1598 post.setKnown(true);
1599 synchronized (knownPosts) {
1600 eventBus.post(new MarkPostKnownEvent(post));
1601 if (knownPosts.add(post.getId())) {
1602 touchConfiguration();
1605 for (PostReply reply : getReplies(post)) {
1606 markReplyKnown(reply);
1611 * Bookmarks the given post.
1614 * The post to bookmark
1616 public void bookmark(Post post) {
1617 bookmarkPost(post.getId());
1621 * Bookmarks the post with the given ID.
1624 * The ID of the post to bookmark
1626 public void bookmarkPost(String id) {
1627 synchronized (bookmarkedPosts) {
1628 bookmarkedPosts.add(id);
1633 * Removes the given post from the bookmarks.
1636 * The post to unbookmark
1638 public void unbookmark(Post post) {
1639 unbookmarkPost(post.getId());
1643 * Removes the post with the given ID from the bookmarks.
1646 * The ID of the post to unbookmark
1648 public void unbookmarkPost(String id) {
1649 synchronized (bookmarkedPosts) {
1650 bookmarkedPosts.remove(id);
1655 * Creates a new reply.
1658 * The Sone that creates the reply
1660 * The post that this reply refers to
1662 * The text of the reply
1663 * @return The created reply
1665 public PostReply createReply(Sone sone, Post post, String text) {
1666 return createReply(sone, post, System.currentTimeMillis(), text);
1670 * Creates a new reply.
1673 * The Sone that creates the reply
1675 * The post that this reply refers to
1677 * The time of the reply
1679 * The text of the reply
1680 * @return The created reply
1682 public PostReply createReply(Sone sone, Post post, long time, String text) {
1683 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1684 if (!sone.isLocal()) {
1685 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1688 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1689 synchronized (replies) {
1690 replies.put(reply.getId(), reply);
1692 synchronized (knownReplies) {
1693 eventBus.post(new NewPostReplyFoundEvent(reply));
1695 sone.addReply(reply);
1696 touchConfiguration();
1697 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1704 markReplyKnown(reply);
1706 }, "Mark " + reply + " read.");
1711 * Deletes the given reply.
1714 * The reply to delete
1716 public void deleteReply(PostReply reply) {
1717 Sone sone = reply.getSone();
1718 if (!sone.isLocal()) {
1719 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1722 synchronized (replies) {
1723 replies.remove(reply.getId());
1725 synchronized (knownReplies) {
1726 markReplyKnown(reply);
1727 knownReplies.remove(reply.getId());
1729 sone.removeReply(reply);
1730 touchConfiguration();
1734 * Marks the given reply as known, if it is currently not a known reply
1735 * (according to {@link Reply#isKnown()}).
1738 * The reply to mark as known
1740 public void markReplyKnown(PostReply reply) {
1741 reply.setKnown(true);
1742 synchronized (knownReplies) {
1743 eventBus.post(new MarkPostReplyKnownEvent(reply));
1744 if (knownReplies.add(reply.getId())) {
1745 touchConfiguration();
1751 * Creates a new top-level album for the given Sone.
1754 * The Sone to create the album for
1755 * @return The new album
1757 public Album createAlbum(Sone sone) {
1758 return createAlbum(sone, null);
1762 * Creates a new album for the given Sone.
1765 * The Sone to create the album for
1767 * The parent of the album (may be {@code null} to create a
1769 * @return The new album
1771 public Album createAlbum(Sone sone, Album parent) {
1772 Album album = new Album();
1773 synchronized (albums) {
1774 albums.put(album.getId(), album);
1776 album.setSone(sone);
1777 if (parent != null) {
1778 parent.addAlbum(album);
1780 sone.addAlbum(album);
1786 * Deletes the given album. The owner of the album has to be a local Sone,
1787 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1790 * The album to remove
1792 public void deleteAlbum(Album album) {
1793 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1794 if (!album.isEmpty()) {
1797 if (album.getParent() == null) {
1798 album.getSone().removeAlbum(album);
1800 album.getParent().removeAlbum(album);
1802 synchronized (albums) {
1803 albums.remove(album.getId());
1805 touchConfiguration();
1809 * Creates a new image.
1812 * The Sone creating the image
1814 * The album the image will be inserted into
1815 * @param temporaryImage
1816 * The temporary image to create the image from
1817 * @return The newly created image
1819 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1820 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();
1821 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1822 album.addImage(image);
1823 synchronized (images) {
1824 images.put(image.getId(), image);
1826 imageInserter.insertImage(temporaryImage, image);
1831 * Deletes the given image. This method will also delete a matching
1834 * @see #deleteTemporaryImage(TemporaryImage)
1836 * The image to delete
1838 public void deleteImage(Image image) {
1839 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1840 deleteTemporaryImage(image.getId());
1841 image.getAlbum().removeImage(image);
1842 synchronized (images) {
1843 images.remove(image.getId());
1845 touchConfiguration();
1849 * Creates a new temporary image.
1852 * The MIME type of the temporary image
1854 * The encoded data of the image
1855 * @return The temporary image
1857 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1858 TemporaryImage temporaryImage = new TemporaryImage();
1859 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1860 synchronized (temporaryImages) {
1861 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1863 return temporaryImage;
1867 * Deletes the given temporary image.
1869 * @param temporaryImage
1870 * The temporary image to delete
1872 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1873 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1874 deleteTemporaryImage(temporaryImage.getId());
1878 * Deletes the temporary image with the given ID.
1881 * The ID of the temporary image to delete
1883 public void deleteTemporaryImage(String imageId) {
1884 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1885 synchronized (temporaryImages) {
1886 temporaryImages.remove(imageId);
1888 Image image = getImage(imageId, false);
1889 if (image != null) {
1890 imageInserter.cancelImageInsert(image);
1895 * Notifies the core that the configuration, either of the core or of a
1896 * single local Sone, has changed, and that the configuration should be
1899 public void touchConfiguration() {
1900 lastConfigurationUpdate = System.currentTimeMillis();
1911 public void serviceStart() {
1912 loadConfiguration();
1913 updateChecker.addUpdateListener(this);
1914 updateChecker.start();
1915 identityManager.addIdentityListener(this);
1916 identityManager.start();
1917 webOfTrustUpdater.init();
1918 webOfTrustUpdater.start();
1925 public void serviceRun() {
1926 long lastSaved = System.currentTimeMillis();
1927 while (!shouldStop()) {
1929 long now = System.currentTimeMillis();
1930 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1931 for (Sone localSone : getLocalSones()) {
1932 saveSone(localSone);
1934 saveConfiguration();
1944 public void serviceStop() {
1945 synchronized (sones) {
1946 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1947 soneInserter.getValue().removeSoneInsertListener(this);
1948 soneInserter.getValue().stop();
1949 saveSone(soneInserter.getKey());
1952 saveConfiguration();
1953 webOfTrustUpdater.stop();
1954 updateChecker.stop();
1955 updateChecker.removeUpdateListener(this);
1956 soneDownloader.stop();
1957 identityManager.removeIdentityListener(this);
1958 identityManager.stop();
1966 * Saves the given Sone. This will persist all local settings for the given
1967 * Sone, such as the friends list and similar, private options.
1972 private synchronized void saveSone(Sone sone) {
1973 if (!sone.isLocal()) {
1974 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1977 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1978 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1982 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1984 /* save Sone into configuration. */
1985 String sonePrefix = "Sone/" + sone.getId();
1986 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1987 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1990 Profile profile = sone.getProfile();
1991 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1992 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1993 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1994 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1995 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1996 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1997 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1999 /* save profile fields. */
2000 int fieldCounter = 0;
2001 for (Field profileField : profile.getFields()) {
2002 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2003 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2004 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2006 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2009 int postCounter = 0;
2010 for (Post post : sone.getPosts()) {
2011 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2012 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2013 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2014 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2015 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2017 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2020 int replyCounter = 0;
2021 for (PostReply reply : sone.getReplies()) {
2022 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2023 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2024 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2025 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2026 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2028 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2030 /* save post likes. */
2031 int postLikeCounter = 0;
2032 for (String postId : sone.getLikedPostIds()) {
2033 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2035 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2037 /* save reply likes. */
2038 int replyLikeCounter = 0;
2039 for (String replyId : sone.getLikedReplyIds()) {
2040 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2042 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2045 int friendCounter = 0;
2046 for (String friendId : sone.getFriends()) {
2047 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2049 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2051 /* save albums. first, collect in a flat structure, top-level first. */
2052 List<Album> albums = sone.getAllAlbums();
2054 int albumCounter = 0;
2055 for (Album album : albums) {
2056 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2057 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2058 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2059 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2060 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2061 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2063 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2066 int imageCounter = 0;
2067 for (Album album : albums) {
2068 for (Image image : album.getImages()) {
2069 if (!image.isInserted()) {
2072 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2073 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2074 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2075 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2076 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2077 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2078 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2079 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2080 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2083 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2086 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2087 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2088 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2089 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2090 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2091 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2093 configuration.save();
2095 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2097 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2098 } catch (ConfigurationException ce1) {
2099 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2104 * Saves the current options.
2106 private void saveConfiguration() {
2107 synchronized (configuration) {
2108 if (storingConfiguration) {
2109 logger.log(Level.FINE, "Already storing configuration…");
2112 storingConfiguration = true;
2115 /* store the options first. */
2117 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2118 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2119 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2120 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2121 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2122 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2123 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2124 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2125 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2126 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2127 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2128 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2130 /* save known Sones. */
2131 int soneCounter = 0;
2132 synchronized (knownSones) {
2133 for (String knownSoneId : knownSones) {
2134 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2136 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2139 /* save Sone following times. */
2141 synchronized (soneFollowingTimes) {
2142 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2143 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2144 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2147 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2150 /* save known posts. */
2151 int postCounter = 0;
2152 synchronized (knownPosts) {
2153 for (String knownPostId : knownPosts) {
2154 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2156 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2159 /* save known replies. */
2160 int replyCounter = 0;
2161 synchronized (knownReplies) {
2162 for (String knownReplyId : knownReplies) {
2163 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2165 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2168 /* save bookmarked posts. */
2169 int bookmarkedPostCounter = 0;
2170 synchronized (bookmarkedPosts) {
2171 for (String bookmarkedPostId : bookmarkedPosts) {
2172 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2175 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2178 configuration.save();
2180 } catch (ConfigurationException ce1) {
2181 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2183 synchronized (configuration) {
2184 storingConfiguration = false;
2190 * Loads the configuration.
2192 @SuppressWarnings("unchecked")
2193 private void loadConfiguration() {
2194 /* create options. */
2195 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2198 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2199 SoneInserter.setInsertionDelay(newValue);
2203 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2204 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2205 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2206 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2207 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2208 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2209 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2210 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2211 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2214 @SuppressWarnings("synthetic-access")
2215 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2216 fcpInterface.setActive(newValue);
2219 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2222 @SuppressWarnings("synthetic-access")
2223 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2224 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2229 loadConfigurationValue("InsertionDelay");
2230 loadConfigurationValue("PostsPerPage");
2231 loadConfigurationValue("ImagesPerPage");
2232 loadConfigurationValue("CharactersPerPost");
2233 loadConfigurationValue("PostCutOffLength");
2234 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2235 loadConfigurationValue("PositiveTrust");
2236 loadConfigurationValue("NegativeTrust");
2237 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2238 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2239 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2241 /* load known Sones. */
2242 int soneCounter = 0;
2244 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2245 if (knownSoneId == null) {
2248 synchronized (knownSones) {
2249 knownSones.add(knownSoneId);
2253 /* load Sone following times. */
2256 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2257 if (soneId == null) {
2260 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2261 Sone followedSone = getSone(soneId);
2262 if (followedSone == null) {
2263 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2265 synchronized (soneFollowingTimes) {
2266 soneFollowingTimes.put(getSone(soneId), time);
2272 /* load known posts. */
2273 int postCounter = 0;
2275 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2276 if (knownPostId == null) {
2279 synchronized (knownPosts) {
2280 knownPosts.add(knownPostId);
2284 /* load known replies. */
2285 int replyCounter = 0;
2287 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2288 if (knownReplyId == null) {
2291 synchronized (knownReplies) {
2292 knownReplies.add(knownReplyId);
2296 /* load bookmarked posts. */
2297 int bookmarkedPostCounter = 0;
2299 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2300 if (bookmarkedPostId == null) {
2303 synchronized (bookmarkedPosts) {
2304 bookmarkedPosts.add(bookmarkedPostId);
2311 * Loads an {@link Integer} configuration value for the option with the
2312 * given name, logging validation failures.
2315 * The name of the option to load
2317 private void loadConfigurationValue(String optionName) {
2319 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2320 } catch (IllegalArgumentException iae1) {
2321 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2326 * Generate a Sone URI from the given URI and latest edition.
2329 * The URI to derive the Sone URI from
2330 * @return The derived URI
2332 private static FreenetURI getSoneUri(String uriString) {
2334 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2336 } catch (MalformedURLException mue1) {
2337 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2343 // INTERFACE IdentityListener
2350 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2351 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2352 if (ownIdentity.hasContext("Sone")) {
2353 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2354 addLocalSone(ownIdentity);
2362 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2363 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2364 trustedIdentities.remove(ownIdentity);
2371 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2372 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2373 trustedIdentities.get(ownIdentity).add(identity);
2374 addRemoteSone(identity);
2381 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2382 soneDownloaders.execute(new Runnable() {
2385 @SuppressWarnings("synthetic-access")
2387 Sone sone = getRemoteSone(identity.getId(), false);
2388 sone.setIdentity(identity);
2389 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2390 soneDownloader.addSone(sone);
2391 soneDownloader.fetchSone(sone);
2400 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2401 trustedIdentities.get(ownIdentity).remove(identity);
2402 boolean foundIdentity = false;
2403 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2404 if (trustedIdentity.getKey().equals(ownIdentity)) {
2407 if (trustedIdentity.getValue().contains(identity)) {
2408 foundIdentity = true;
2411 if (foundIdentity) {
2412 /* some local identity still trusts this identity, don’t remove. */
2415 Sone sone = getSone(identity.getId(), false);
2417 /* TODO - we don’t have the Sone anymore. should this happen? */
2420 synchronized (posts) {
2421 synchronized (knownPosts) {
2422 for (Post post : sone.getPosts()) {
2423 posts.remove(post.getId());
2424 eventBus.post(new PostRemovedEvent(post));
2428 synchronized (replies) {
2429 synchronized (knownReplies) {
2430 for (PostReply reply : sone.getReplies()) {
2431 replies.remove(reply.getId());
2432 eventBus.post(new PostReplyRemovedEvent(reply));
2436 synchronized (sones) {
2437 sones.remove(identity.getId());
2439 eventBus.post(new SoneRemovedEvent(sone));
2443 // INTERFACE UpdateListener
2450 public void updateFound(Version version, long releaseTime, long latestEdition) {
2451 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2455 // INTERFACE ImageInsertListener
2462 public void insertStarted(Sone sone) {
2463 coreListenerManager.fireSoneInserting(sone);
2470 public void insertFinished(Sone sone, long insertDuration) {
2471 coreListenerManager.fireSoneInserted(sone, insertDuration);
2478 public void insertAborted(Sone sone, Throwable cause) {
2479 coreListenerManager.fireSoneInsertAborted(sone, cause);
2483 // SONEINSERTLISTENER METHODS
2490 public void imageInsertStarted(Image image) {
2491 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2492 coreListenerManager.fireImageInsertStarted(image);
2499 public void imageInsertAborted(Image image) {
2500 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2501 coreListenerManager.fireImageInsertAborted(image);
2508 public void imageInsertFinished(Image image, FreenetURI key) {
2509 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2510 image.setKey(key.toString());
2511 deleteTemporaryImage(image.getId());
2512 touchConfiguration();
2513 coreListenerManager.fireImageInsertFinished(image);
2520 public void imageInsertFailed(Image image, Throwable cause) {
2521 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2522 coreListenerManager.fireImageInsertFailed(image, cause);
2526 * Convenience interface for external classes that want to access the core’s
2529 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2531 public static class Preferences {
2533 /** The wrapped options. */
2534 private final Options options;
2537 * Creates a new preferences object wrapped around the given options.
2540 * The options to wrap
2542 public Preferences(Options options) {
2543 this.options = options;
2547 * Returns the insertion delay.
2549 * @return The insertion delay
2551 public int getInsertionDelay() {
2552 return options.getIntegerOption("InsertionDelay").get();
2556 * Validates the given insertion delay.
2558 * @param insertionDelay
2559 * The insertion delay to validate
2560 * @return {@code true} if the given insertion delay was valid,
2561 * {@code false} otherwise
2563 public boolean validateInsertionDelay(Integer insertionDelay) {
2564 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2568 * Sets the insertion delay
2570 * @param insertionDelay
2571 * The new insertion delay, or {@code null} to restore it to
2573 * @return This preferences
2575 public Preferences setInsertionDelay(Integer insertionDelay) {
2576 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2581 * Returns the number of posts to show per page.
2583 * @return The number of posts to show per page
2585 public int getPostsPerPage() {
2586 return options.getIntegerOption("PostsPerPage").get();
2590 * Validates the number of posts per page.
2592 * @param postsPerPage
2593 * The number of posts per page
2594 * @return {@code true} if the number of posts per page was valid,
2595 * {@code false} otherwise
2597 public boolean validatePostsPerPage(Integer postsPerPage) {
2598 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2602 * Sets the number of posts to show per page.
2604 * @param postsPerPage
2605 * The number of posts to show per page
2606 * @return This preferences object
2608 public Preferences setPostsPerPage(Integer postsPerPage) {
2609 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2614 * Returns the number of images to show per page.
2616 * @return The number of images to show per page
2618 public int getImagesPerPage() {
2619 return options.getIntegerOption("ImagesPerPage").get();
2623 * Validates the number of images per page.
2625 * @param imagesPerPage
2626 * The number of images per page
2627 * @return {@code true} if the number of images per page was valid,
2628 * {@code false} otherwise
2630 public boolean validateImagesPerPage(Integer imagesPerPage) {
2631 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2635 * Sets the number of images per page.
2637 * @param imagesPerPage
2638 * The number of images per page
2639 * @return This preferences object
2641 public Preferences setImagesPerPage(Integer imagesPerPage) {
2642 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2647 * Returns the number of characters per post, or <code>-1</code> if the
2648 * posts should not be cut off.
2650 * @return The numbers of characters per post
2652 public int getCharactersPerPost() {
2653 return options.getIntegerOption("CharactersPerPost").get();
2657 * Validates the number of characters per post.
2659 * @param charactersPerPost
2660 * The number of characters per post
2661 * @return {@code true} if the number of characters per post was valid,
2662 * {@code false} otherwise
2664 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2665 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2669 * Sets the number of characters per post.
2671 * @param charactersPerPost
2672 * The number of characters per post, or <code>-1</code> to
2673 * not cut off the posts
2674 * @return This preferences objects
2676 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2677 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2682 * Returns the number of characters the shortened post should have.
2684 * @return The number of characters of the snippet
2686 public int getPostCutOffLength() {
2687 return options.getIntegerOption("PostCutOffLength").get();
2691 * Validates the number of characters after which to cut off the post.
2693 * @param postCutOffLength
2694 * The number of characters of the snippet
2695 * @return {@code true} if the number of characters of the snippet is
2696 * valid, {@code false} otherwise
2698 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2699 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2703 * Sets the number of characters the shortened post should have.
2705 * @param postCutOffLength
2706 * The number of characters of the snippet
2707 * @return This preferences
2709 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2710 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2715 * Returns whether Sone requires full access to be even visible.
2717 * @return {@code true} if Sone requires full access, {@code false}
2720 public boolean isRequireFullAccess() {
2721 return options.getBooleanOption("RequireFullAccess").get();
2725 * Sets whether Sone requires full access to be even visible.
2727 * @param requireFullAccess
2728 * {@code true} if Sone requires full access, {@code false}
2731 public void setRequireFullAccess(Boolean requireFullAccess) {
2732 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2736 * Returns the positive trust.
2738 * @return The positive trust
2740 public int getPositiveTrust() {
2741 return options.getIntegerOption("PositiveTrust").get();
2745 * Validates the positive trust.
2747 * @param positiveTrust
2748 * The positive trust to validate
2749 * @return {@code true} if the positive trust was valid, {@code false}
2752 public boolean validatePositiveTrust(Integer positiveTrust) {
2753 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2757 * Sets the positive trust.
2759 * @param positiveTrust
2760 * The new positive trust, or {@code null} to restore it to
2762 * @return This preferences
2764 public Preferences setPositiveTrust(Integer positiveTrust) {
2765 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2770 * Returns the negative trust.
2772 * @return The negative trust
2774 public int getNegativeTrust() {
2775 return options.getIntegerOption("NegativeTrust").get();
2779 * Validates the negative trust.
2781 * @param negativeTrust
2782 * The negative trust to validate
2783 * @return {@code true} if the negative trust was valid, {@code false}
2786 public boolean validateNegativeTrust(Integer negativeTrust) {
2787 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2791 * Sets the negative trust.
2793 * @param negativeTrust
2794 * The negative trust, or {@code null} to restore it to the
2796 * @return The preferences
2798 public Preferences setNegativeTrust(Integer negativeTrust) {
2799 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2804 * Returns the trust comment. This is the comment that is set in the web
2805 * of trust when a trust value is assigned to an identity.
2807 * @return The trust comment
2809 public String getTrustComment() {
2810 return options.getStringOption("TrustComment").get();
2814 * Sets the trust comment.
2816 * @param trustComment
2817 * The trust comment, or {@code null} to restore it to the
2819 * @return This preferences
2821 public Preferences setTrustComment(String trustComment) {
2822 options.getStringOption("TrustComment").set(trustComment);
2827 * Returns whether the {@link FcpInterface FCP interface} is currently
2830 * @see FcpInterface#setActive(boolean)
2831 * @return {@code true} if the FCP interface is currently active,
2832 * {@code false} otherwise
2834 public boolean isFcpInterfaceActive() {
2835 return options.getBooleanOption("ActivateFcpInterface").get();
2839 * Sets whether the {@link FcpInterface FCP interface} is currently
2842 * @see FcpInterface#setActive(boolean)
2843 * @param fcpInterfaceActive
2844 * {@code true} to activate the FCP interface, {@code false}
2845 * to deactivate the FCP interface
2846 * @return This preferences object
2848 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2849 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2854 * Returns the action level for which full access to the FCP interface
2857 * @return The action level for which full access to the FCP interface
2860 public FullAccessRequired getFcpFullAccessRequired() {
2861 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2865 * Sets the action level for which full access to the FCP interface is
2868 * @param fcpFullAccessRequired
2870 * @return This preferences
2872 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2873 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);