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.ImageInsertAbortedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
40 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
41 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
42 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
43 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
44 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
45 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
46 import net.pterodactylus.sone.core.event.PostRemovedEvent;
47 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
48 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
49 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
50 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
51 import net.pterodactylus.sone.core.event.SoneLockedEvent;
52 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
54 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.data.TemporaryImage;
67 import net.pterodactylus.sone.data.impl.PostImpl;
68 import net.pterodactylus.sone.fcp.FcpInterface;
69 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
70 import net.pterodactylus.sone.freenet.wot.Identity;
71 import net.pterodactylus.sone.freenet.wot.IdentityListener;
72 import net.pterodactylus.sone.freenet.wot.IdentityManager;
73 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
74 import net.pterodactylus.sone.main.SonePlugin;
75 import net.pterodactylus.util.config.Configuration;
76 import net.pterodactylus.util.config.ConfigurationException;
77 import net.pterodactylus.util.logging.Logging;
78 import net.pterodactylus.util.number.Numbers;
79 import net.pterodactylus.util.service.AbstractService;
80 import net.pterodactylus.util.thread.NamedThreadFactory;
81 import net.pterodactylus.util.thread.Ticker;
82 import net.pterodactylus.util.validation.EqualityValidator;
83 import net.pterodactylus.util.validation.IntegerRangeValidator;
84 import net.pterodactylus.util.validation.OrValidator;
85 import net.pterodactylus.util.validation.Validation;
86 import net.pterodactylus.util.version.Version;
88 import com.google.common.base.Predicate;
89 import com.google.common.collect.Collections2;
90 import com.google.common.eventbus.EventBus;
91 import com.google.inject.Inject;
93 import freenet.keys.FreenetURI;
98 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
100 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
103 private static final Logger logger = Logging.getLogger(Core.class);
105 /** The start time. */
106 private final long startupTime = System.currentTimeMillis();
109 private final Options options = new Options();
111 /** The preferences. */
112 private final Preferences preferences = new Preferences(options);
114 /** The core listener manager. */
115 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
117 /** The event bus. */
118 private final EventBus eventBus;
120 /** The configuration. */
121 private Configuration configuration;
123 /** Whether we’re currently saving the configuration. */
124 private boolean storingConfiguration = false;
126 /** The identity manager. */
127 private final IdentityManager identityManager;
129 /** Interface to freenet. */
130 private final FreenetInterface freenetInterface;
132 /** The Sone downloader. */
133 private final SoneDownloader soneDownloader;
135 /** The image inserter. */
136 private final ImageInserter imageInserter;
138 /** Sone downloader thread-pool. */
139 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
141 /** The update checker. */
142 private final UpdateChecker updateChecker;
144 /** The trust updater. */
145 private final WebOfTrustUpdater webOfTrustUpdater;
147 /** The FCP interface. */
148 private volatile FcpInterface fcpInterface;
150 /** The times Sones were followed. */
151 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
153 /** Locked local Sones. */
154 /* synchronize on itself. */
155 private final Set<Sone> lockedSones = new HashSet<Sone>();
157 /** Sone inserters. */
158 /* synchronize access on this on sones. */
159 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
161 /** Sone rescuers. */
162 /* synchronize access on this on sones. */
163 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
166 /* synchronize access on this on itself. */
167 private final Map<String, Sone> sones = new HashMap<String, Sone>();
169 /** All known Sones. */
170 private final Set<String> knownSones = new HashSet<String>();
173 private final Map<String, Post> posts = new HashMap<String, Post>();
175 /** All known posts. */
176 private final Set<String> knownPosts = new HashSet<String>();
179 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
181 /** All known replies. */
182 private final Set<String> knownReplies = new HashSet<String>();
184 /** All bookmarked posts. */
185 /* synchronize access on itself. */
186 private final Set<String> bookmarkedPosts = new HashSet<String>();
188 /** Trusted identities, sorted by own identities. */
189 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
191 /** All known albums. */
192 private final Map<String, Album> albums = new HashMap<String, Album>();
194 /** All known images. */
195 private final Map<String, Image> images = new HashMap<String, Image>();
197 /** All temporary images. */
198 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
200 /** Ticker for threads that mark own elements as known. */
201 private final Ticker localElementTicker = new Ticker();
203 /** The time the configuration was last touched. */
204 private volatile long lastConfigurationUpdate;
207 * Creates a new core.
209 * @param configuration
210 * The configuration of the core
211 * @param freenetInterface
212 * The freenet interface
213 * @param identityManager
214 * The identity manager
215 * @param webOfTrustUpdater
216 * The WebOfTrust updater
221 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = new SoneDownloader(this, freenetInterface);
227 this.imageInserter = new ImageInserter(this, freenetInterface);
228 this.updateChecker = new UpdateChecker(freenetInterface);
229 this.webOfTrustUpdater = webOfTrustUpdater;
230 this.eventBus = eventBus;
234 // LISTENER MANAGEMENT
238 * Adds a new core listener.
240 * @param coreListener
241 * The listener to add
243 public void addCoreListener(CoreListener coreListener) {
244 coreListenerManager.addListener(coreListener);
248 * Removes a core listener.
250 * @param coreListener
251 * The listener to remove
253 public void removeCoreListener(CoreListener coreListener) {
254 coreListenerManager.removeListener(coreListener);
262 * Returns the time Sone was started.
264 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
266 public long getStartupTime() {
271 * Sets the configuration to use. This will automatically save the current
272 * configuration to the given configuration.
274 * @param configuration
275 * The new configuration to use
277 public void setConfiguration(Configuration configuration) {
278 this.configuration = configuration;
279 touchConfiguration();
283 * Returns the options used by the core.
285 * @return The options of the core
287 public Preferences getPreferences() {
292 * Returns the identity manager used by the core.
294 * @return The identity manager
296 public IdentityManager getIdentityManager() {
297 return identityManager;
301 * Returns the update checker.
303 * @return The update checker
305 public UpdateChecker getUpdateChecker() {
306 return updateChecker;
310 * Sets the FCP interface to use.
312 * @param fcpInterface
313 * The FCP interface to use
315 public void setFcpInterface(FcpInterface fcpInterface) {
316 this.fcpInterface = fcpInterface;
320 * Returns the Sone rescuer for the given local Sone.
323 * The local Sone to get the rescuer for
324 * @return The Sone rescuer for the given Sone
326 public SoneRescuer getSoneRescuer(Sone sone) {
327 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
328 synchronized (sones) {
329 SoneRescuer soneRescuer = soneRescuers.get(sone);
330 if (soneRescuer == null) {
331 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
332 soneRescuers.put(sone, soneRescuer);
340 * Returns whether the given Sone is currently locked.
344 * @return {@code true} if the Sone is locked, {@code false} if it is not
346 public boolean isLocked(Sone sone) {
347 synchronized (lockedSones) {
348 return lockedSones.contains(sone);
353 * Returns all Sones, remote and local.
357 public Set<Sone> getSones() {
358 return new HashSet<Sone>(sones.values());
362 * Returns the Sone with the given ID, regardless whether it’s local or
366 * The ID of the Sone to get
367 * @return The Sone with the given ID, or {@code null} if there is no such
370 public Sone getSone(String id) {
371 return getSone(id, true);
375 * Returns the Sone with the given ID, regardless whether it’s local or
379 * The ID of the Sone to get
381 * {@code true} to create a new Sone if none exists,
382 * {@code false} to return {@code null} if a Sone with the given
384 * @return The Sone with the given ID, or {@code null} if there is no such
388 public Sone getSone(String id, boolean create) {
389 synchronized (sones) {
390 if (!sones.containsKey(id)) {
391 Sone sone = new Sone(id, false);
394 return sones.get(id);
399 * Checks whether the core knows a Sone with the given ID.
403 * @return {@code true} if there is a Sone with the given ID, {@code false}
406 public boolean hasSone(String id) {
407 synchronized (sones) {
408 return sones.containsKey(id);
413 * Returns all local Sones.
415 * @return All local Sones
417 public Collection<Sone> getLocalSones() {
418 synchronized (sones) {
419 return Collections2.filter(sones.values(), new Predicate<Sone>() {
422 public boolean apply(Sone sone) {
423 return sone.isLocal();
430 * Returns the local Sone with the given ID, optionally creating a new Sone.
435 * {@code true} to create a new Sone if none exists,
436 * {@code false} to return null if none exists
437 * @return The Sone with the given ID, or {@code null}
439 public Sone getLocalSone(String id, boolean create) {
440 synchronized (sones) {
441 Sone sone = sones.get(id);
442 if ((sone == null) && create) {
443 sone = new Sone(id, true);
446 if ((sone != null) && !sone.isLocal()) {
447 sone = new Sone(id, true);
455 * Returns all remote Sones.
457 * @return All remote Sones
459 public Collection<Sone> getRemoteSones() {
460 synchronized (sones) {
461 return Collections2.filter(sones.values(), new Predicate<Sone>() {
464 public boolean apply(Sone sone) {
465 return !sone.isLocal();
472 * Returns the remote Sone with the given ID.
475 * The ID of the remote Sone to get
477 * {@code true} to always create a Sone, {@code false} to return
478 * {@code null} if no Sone with the given ID exists
479 * @return The Sone with the given ID
481 public Sone getRemoteSone(String id, boolean create) {
482 synchronized (sones) {
483 Sone sone = sones.get(id);
484 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
485 sone = new Sone(id, false);
493 * Returns whether the given Sone has been modified.
496 * The Sone to check for modifications
497 * @return {@code true} if a modification has been detected in the Sone,
498 * {@code false} otherwise
500 public boolean isModifiedSone(Sone sone) {
501 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
505 * Returns the time when the given was first followed by any local Sone.
508 * The Sone to get the time for
509 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
510 * been followed, or {@link Long#MAX_VALUE}
512 public long getSoneFollowingTime(Sone sone) {
513 synchronized (soneFollowingTimes) {
514 if (soneFollowingTimes.containsKey(sone)) {
515 return soneFollowingTimes.get(sone);
517 return Long.MAX_VALUE;
522 * Returns whether the target Sone is trusted by the origin Sone.
528 * @return {@code true} if the target Sone is trusted by the origin Sone
530 public boolean isSoneTrusted(Sone origin, Sone target) {
531 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
532 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
536 * Returns the post with the given ID.
539 * The ID of the post to get
540 * @return The post with the given ID, or a new post with the given ID
542 public Post getPost(String postId) {
543 return getPost(postId, true);
547 * Returns the post with the given ID, optionally creating a new post.
550 * The ID of the post to get
552 * {@code true} it create a new post if no post with the given ID
553 * exists, {@code false} to return {@code null}
554 * @return The post, or {@code null} if there is no such post
557 public Post getPost(String postId, boolean create) {
558 synchronized (posts) {
559 Post post = posts.get(postId);
560 if ((post == null) && create) {
561 post = new PostImpl(postId);
562 posts.put(postId, post);
569 * Returns all posts that have the given Sone as recipient.
571 * @see Post#getRecipient()
573 * The recipient of the posts
574 * @return All posts that have the given Sone as recipient
576 public Set<Post> getDirectedPosts(Sone recipient) {
577 Validation.begin().isNotNull("Recipient", recipient).check();
578 Set<Post> directedPosts = new HashSet<Post>();
579 synchronized (posts) {
580 for (Post post : posts.values()) {
581 if (recipient.equals(post.getRecipient())) {
582 directedPosts.add(post);
586 return directedPosts;
590 * Returns the reply with the given ID. If there is no reply with the given
591 * ID yet, a new one is created, unless {@code create} is false in which
592 * case {@code null} is returned.
595 * The ID of the reply to get
597 * {@code true} to always return a {@link Reply}, {@code false}
598 * to return {@code null} if no reply can be found
599 * @return The reply, or {@code null} if there is no such reply
601 public PostReply getPostReply(String replyId, boolean create) {
602 synchronized (replies) {
603 PostReply reply = replies.get(replyId);
604 if (create && (reply == null)) {
605 reply = new PostReply(replyId);
606 replies.put(replyId, reply);
613 * Returns all replies for the given post, order ascending by time.
616 * The post to get all replies for
617 * @return All replies for the given post
619 public List<PostReply> getReplies(Post post) {
620 Set<Sone> sones = getSones();
621 List<PostReply> replies = new ArrayList<PostReply>();
622 for (Sone sone : sones) {
623 for (PostReply reply : sone.getReplies()) {
624 if (reply.getPost().equals(post)) {
629 Collections.sort(replies, Reply.TIME_COMPARATOR);
634 * Returns all Sones that have liked the given post.
637 * The post to get the liking Sones for
638 * @return The Sones that like the given post
640 public Set<Sone> getLikes(Post post) {
641 Set<Sone> sones = new HashSet<Sone>();
642 for (Sone sone : getSones()) {
643 if (sone.getLikedPostIds().contains(post.getId())) {
651 * Returns all Sones that have liked the given reply.
654 * The reply to get the liking Sones for
655 * @return The Sones that like the given reply
657 public Set<Sone> getLikes(PostReply reply) {
658 Set<Sone> sones = new HashSet<Sone>();
659 for (Sone sone : getSones()) {
660 if (sone.getLikedReplyIds().contains(reply.getId())) {
668 * Returns whether the given post is bookmarked.
672 * @return {@code true} if the given post is bookmarked, {@code false}
675 public boolean isBookmarked(Post post) {
676 return isPostBookmarked(post.getId());
680 * Returns whether the post with the given ID is bookmarked.
683 * The ID of the post to check
684 * @return {@code true} if the post with the given ID is bookmarked,
685 * {@code false} otherwise
687 public boolean isPostBookmarked(String id) {
688 synchronized (bookmarkedPosts) {
689 return bookmarkedPosts.contains(id);
694 * Returns all currently known bookmarked posts.
696 * @return All bookmarked posts
698 public Set<Post> getBookmarkedPosts() {
699 Set<Post> posts = new HashSet<Post>();
700 synchronized (bookmarkedPosts) {
701 for (String bookmarkedPostId : bookmarkedPosts) {
702 Post post = getPost(bookmarkedPostId, false);
712 * Returns the album with the given ID, creating a new album if no album
713 * with the given ID can be found.
716 * The ID of the album
717 * @return The album with the given ID
719 public Album getAlbum(String albumId) {
720 return getAlbum(albumId, true);
724 * Returns the album with the given ID, optionally creating a new album if
725 * an album with the given ID can not be found.
728 * The ID of the album
730 * {@code true} to create a new album if none exists for the
732 * @return The album with the given ID, or {@code null} if no album with the
733 * given ID exists and {@code create} is {@code false}
735 public Album getAlbum(String albumId, boolean create) {
736 synchronized (albums) {
737 Album album = albums.get(albumId);
738 if (create && (album == null)) {
739 album = new Album(albumId);
740 albums.put(albumId, album);
747 * Returns the image with the given ID, creating it if necessary.
750 * The ID of the image
751 * @return The image with the given ID
753 public Image getImage(String imageId) {
754 return getImage(imageId, true);
758 * Returns the image with the given ID, optionally creating it if it does
762 * The ID of the image
764 * {@code true} to create an image if none exists with the given
766 * @return The image with the given ID, or {@code null} if none exists and
769 public Image getImage(String imageId, boolean create) {
770 synchronized (images) {
771 Image image = images.get(imageId);
772 if (create && (image == null)) {
773 image = new Image(imageId);
774 images.put(imageId, image);
781 * Returns the temporary image with the given ID.
784 * The ID of the temporary image
785 * @return The temporary image, or {@code null} if there is no temporary
786 * image with the given ID
788 public TemporaryImage getTemporaryImage(String imageId) {
789 synchronized (temporaryImages) {
790 return temporaryImages.get(imageId);
799 * Locks the given Sone. A locked Sone will not be inserted by
800 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
806 public void lockSone(Sone sone) {
807 synchronized (lockedSones) {
808 if (lockedSones.add(sone)) {
809 eventBus.post(new SoneLockedEvent(sone));
815 * Unlocks the given Sone.
817 * @see #lockSone(Sone)
821 public void unlockSone(Sone sone) {
822 synchronized (lockedSones) {
823 if (lockedSones.remove(sone)) {
824 eventBus.post(new SoneUnlockedEvent(sone));
830 * Adds a local Sone from the given own identity.
833 * The own identity to create a Sone from
834 * @return The added (or already existing) Sone
836 public Sone addLocalSone(OwnIdentity ownIdentity) {
837 if (ownIdentity == null) {
838 logger.log(Level.WARNING, "Given OwnIdentity is null!");
841 synchronized (sones) {
844 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
845 } catch (MalformedURLException mue1) {
846 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
849 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
850 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
852 /* TODO - load posts ’n stuff */
853 sones.put(ownIdentity.getId(), sone);
854 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
855 soneInserter.addSoneInsertListener(this);
856 soneInserters.put(sone, soneInserter);
857 sone.setStatus(SoneStatus.idle);
859 soneInserter.start();
865 * Creates a new Sone for the given own identity.
868 * The own identity to create a Sone for
869 * @return The created Sone
871 public Sone createSone(OwnIdentity ownIdentity) {
872 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
873 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
876 Sone sone = addLocalSone(ownIdentity);
877 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
878 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
879 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
880 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
881 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
882 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
884 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
885 touchConfiguration();
890 * Adds the Sone of the given identity.
893 * The identity whose Sone to add
894 * @return The added or already existing Sone
896 public Sone addRemoteSone(Identity identity) {
897 if (identity == null) {
898 logger.log(Level.WARNING, "Given Identity is null!");
901 synchronized (sones) {
902 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
903 boolean newSone = sone.getRequestUri() == null;
904 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
905 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
907 synchronized (knownSones) {
908 newSone = !knownSones.contains(sone.getId());
910 sone.setKnown(!newSone);
912 eventBus.post(new NewSoneFoundEvent(sone));
913 for (Sone localSone : getLocalSones()) {
914 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
915 followSone(localSone, sone);
920 soneDownloader.addSone(sone);
921 soneDownloaders.execute(new Runnable() {
924 @SuppressWarnings("synthetic-access")
926 soneDownloader.fetchSone(sone, sone.getRequestUri());
935 * Lets the given local Sone follow the Sone with the given ID.
938 * The local Sone that should follow another Sone
940 * The ID of the Sone to follow
942 public void followSone(Sone sone, String soneId) {
943 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
944 Sone followedSone = getSone(soneId, true);
945 if (followedSone == null) {
946 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
949 followSone(sone, getSone(soneId));
953 * Lets the given local Sone follow the other given Sone. If the given Sone
954 * was not followed by any local Sone before, this will mark all elements of
955 * the followed Sone as read that have been created before the current
959 * The local Sone that should follow the other Sone
960 * @param followedSone
961 * The Sone that should be followed
963 public void followSone(Sone sone, Sone followedSone) {
964 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
965 sone.addFriend(followedSone.getId());
966 synchronized (soneFollowingTimes) {
967 if (!soneFollowingTimes.containsKey(followedSone)) {
968 long now = System.currentTimeMillis();
969 soneFollowingTimes.put(followedSone, now);
970 for (Post post : followedSone.getPosts()) {
971 if (post.getTime() < now) {
975 for (PostReply reply : followedSone.getReplies()) {
976 if (reply.getTime() < now) {
977 markReplyKnown(reply);
982 touchConfiguration();
986 * Lets the given local Sone unfollow the Sone with the given ID.
989 * The local Sone that should unfollow another Sone
991 * The ID of the Sone being unfollowed
993 public void unfollowSone(Sone sone, String soneId) {
994 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
995 unfollowSone(sone, getSone(soneId, false));
999 * Lets the given local Sone unfollow the other given Sone. If the given
1000 * local Sone is the last local Sone that followed the given Sone, its
1001 * following time will be removed.
1004 * The local Sone that should unfollow another Sone
1005 * @param unfollowedSone
1006 * The Sone being unfollowed
1008 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1009 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1010 sone.removeFriend(unfollowedSone.getId());
1011 boolean unfollowedSoneStillFollowed = false;
1012 for (Sone localSone : getLocalSones()) {
1013 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1015 if (!unfollowedSoneStillFollowed) {
1016 synchronized (soneFollowingTimes) {
1017 soneFollowingTimes.remove(unfollowedSone);
1020 touchConfiguration();
1024 * Sets the trust value of the given origin Sone for the target Sone.
1031 * The trust value (from {@code -100} to {@code 100})
1033 public void setTrust(Sone origin, Sone target, int trustValue) {
1034 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();
1035 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1039 * Removes any trust assignment for the given target Sone.
1046 public void removeTrust(Sone origin, Sone target) {
1047 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1048 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1052 * Assigns the configured positive trust value for the given target.
1059 public void trustSone(Sone origin, Sone target) {
1060 setTrust(origin, target, preferences.getPositiveTrust());
1064 * Assigns the configured negative trust value for the given target.
1071 public void distrustSone(Sone origin, Sone target) {
1072 setTrust(origin, target, preferences.getNegativeTrust());
1076 * Removes the trust assignment for the given target.
1083 public void untrustSone(Sone origin, Sone target) {
1084 removeTrust(origin, target);
1088 * Updates the stored Sone with the given Sone.
1093 public void updateSone(Sone sone) {
1094 updateSone(sone, false);
1098 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1099 * {@code true}, an older Sone than the current Sone can be given to restore
1103 * The Sone to update
1104 * @param soneRescueMode
1105 * {@code true} if the stored Sone should be updated regardless
1106 * of the age of the given Sone
1108 public void updateSone(Sone sone, boolean soneRescueMode) {
1109 if (hasSone(sone.getId())) {
1110 Sone storedSone = getSone(sone.getId());
1111 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1112 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1115 synchronized (posts) {
1116 if (!soneRescueMode) {
1117 for (Post post : storedSone.getPosts()) {
1118 posts.remove(post.getId());
1119 if (!sone.getPosts().contains(post)) {
1120 eventBus.post(new PostRemovedEvent(post));
1124 List<Post> storedPosts = storedSone.getPosts();
1125 synchronized (knownPosts) {
1126 for (Post post : sone.getPosts()) {
1127 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1128 if (!storedPosts.contains(post)) {
1129 if (post.getTime() < getSoneFollowingTime(sone)) {
1130 knownPosts.add(post.getId());
1131 post.setKnown(true);
1132 } else if (!knownPosts.contains(post.getId())) {
1133 eventBus.post(new NewPostFoundEvent(post));
1136 posts.put(post.getId(), post);
1140 synchronized (replies) {
1141 if (!soneRescueMode) {
1142 for (PostReply reply : storedSone.getReplies()) {
1143 replies.remove(reply.getId());
1144 if (!sone.getReplies().contains(reply)) {
1145 eventBus.post(new PostReplyRemovedEvent(reply));
1149 Set<PostReply> storedReplies = storedSone.getReplies();
1150 synchronized (knownReplies) {
1151 for (PostReply reply : sone.getReplies()) {
1152 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1153 if (!storedReplies.contains(reply)) {
1154 if (reply.getTime() < getSoneFollowingTime(sone)) {
1155 knownReplies.add(reply.getId());
1156 reply.setKnown(true);
1157 } else if (!knownReplies.contains(reply.getId())) {
1158 eventBus.post(new NewPostReplyFoundEvent(reply));
1161 replies.put(reply.getId(), reply);
1165 synchronized (albums) {
1166 synchronized (images) {
1167 for (Album album : storedSone.getAlbums()) {
1168 albums.remove(album.getId());
1169 for (Image image : album.getImages()) {
1170 images.remove(image.getId());
1173 for (Album album : sone.getAlbums()) {
1174 albums.put(album.getId(), album);
1175 for (Image image : album.getImages()) {
1176 images.put(image.getId(), image);
1181 synchronized (storedSone) {
1182 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1183 storedSone.setTime(sone.getTime());
1185 storedSone.setClient(sone.getClient());
1186 storedSone.setProfile(sone.getProfile());
1187 if (soneRescueMode) {
1188 for (Post post : sone.getPosts()) {
1189 storedSone.addPost(post);
1191 for (PostReply reply : sone.getReplies()) {
1192 storedSone.addReply(reply);
1194 for (String likedPostId : sone.getLikedPostIds()) {
1195 storedSone.addLikedPostId(likedPostId);
1197 for (String likedReplyId : sone.getLikedReplyIds()) {
1198 storedSone.addLikedReplyId(likedReplyId);
1200 for (Album album : sone.getAlbums()) {
1201 storedSone.addAlbum(album);
1204 storedSone.setPosts(sone.getPosts());
1205 storedSone.setReplies(sone.getReplies());
1206 storedSone.setLikePostIds(sone.getLikedPostIds());
1207 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1208 storedSone.setAlbums(sone.getAlbums());
1210 storedSone.setLatestEdition(sone.getLatestEdition());
1216 * Deletes the given Sone. This will remove the Sone from the
1217 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1218 * remove the context from its identity.
1221 * The Sone to delete
1223 public void deleteSone(Sone sone) {
1224 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1225 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1228 synchronized (sones) {
1229 if (!getLocalSones().contains(sone)) {
1230 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1233 sones.remove(sone.getId());
1234 SoneInserter soneInserter = soneInserters.remove(sone);
1235 soneInserter.removeSoneInsertListener(this);
1236 soneInserter.stop();
1238 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1239 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1241 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1242 } catch (ConfigurationException ce1) {
1243 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1248 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1249 * known} before, a {@link MarkSoneKnownEvent} is fired.
1252 * The Sone to mark as known
1254 public void markSoneKnown(Sone sone) {
1255 if (!sone.isKnown()) {
1256 sone.setKnown(true);
1257 synchronized (knownSones) {
1258 knownSones.add(sone.getId());
1260 eventBus.post(new MarkSoneKnownEvent(sone));
1261 touchConfiguration();
1266 * Loads and updates the given Sone from the configuration. If any error is
1267 * encountered, loading is aborted and the given Sone is not changed.
1270 * The Sone to load and update
1272 public void loadSone(Sone sone) {
1273 if (!sone.isLocal()) {
1274 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1278 /* initialize options. */
1279 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1280 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1281 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1282 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1283 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1284 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1287 String sonePrefix = "Sone/" + sone.getId();
1288 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1289 if (soneTime == null) {
1290 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1293 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1296 Profile profile = new Profile(sone);
1297 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1298 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1299 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1300 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1301 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1302 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1304 /* load profile fields. */
1306 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1307 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1308 if (fieldName == null) {
1311 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1312 profile.addField(fieldName).setValue(fieldValue);
1316 Set<Post> posts = new HashSet<Post>();
1318 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1319 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1320 if (postId == null) {
1323 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1324 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1325 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1326 if ((postTime == 0) || (postText == null)) {
1327 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1330 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1331 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1332 post.setRecipient(getSone(postRecipientId));
1338 Set<PostReply> replies = new HashSet<PostReply>();
1340 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1341 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1342 if (replyId == null) {
1345 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1346 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1347 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1348 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1349 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1352 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1355 /* load post likes. */
1356 Set<String> likedPostIds = new HashSet<String>();
1358 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1359 if (likedPostId == null) {
1362 likedPostIds.add(likedPostId);
1365 /* load reply likes. */
1366 Set<String> likedReplyIds = new HashSet<String>();
1368 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1369 if (likedReplyId == null) {
1372 likedReplyIds.add(likedReplyId);
1376 Set<String> friends = new HashSet<String>();
1378 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1379 if (friendId == null) {
1382 friends.add(friendId);
1386 List<Album> topLevelAlbums = new ArrayList<Album>();
1387 int albumCounter = 0;
1389 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1390 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1391 if (albumId == null) {
1394 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1395 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1396 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1397 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1398 if ((albumTitle == null) || (albumDescription == null)) {
1399 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1402 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1403 if (albumParentId != null) {
1404 Album parentAlbum = getAlbum(albumParentId, false);
1405 if (parentAlbum == null) {
1406 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1409 parentAlbum.addAlbum(album);
1411 if (!topLevelAlbums.contains(album)) {
1412 topLevelAlbums.add(album);
1418 int imageCounter = 0;
1420 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1421 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1422 if (imageId == null) {
1425 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1426 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1427 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1428 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1429 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1430 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1431 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1432 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1433 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1436 Album album = getAlbum(albumId, false);
1437 if (album == null) {
1438 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1441 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1442 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1443 album.addImage(image);
1447 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1448 if (avatarId != null) {
1449 profile.setAvatar(getImage(avatarId, false));
1453 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1454 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1455 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1456 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1457 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1458 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1460 /* if we’re still here, Sone was loaded successfully. */
1461 synchronized (sone) {
1462 sone.setTime(soneTime);
1463 sone.setProfile(profile);
1464 sone.setPosts(posts);
1465 sone.setReplies(replies);
1466 sone.setLikePostIds(likedPostIds);
1467 sone.setLikeReplyIds(likedReplyIds);
1468 for (String friendId : friends) {
1469 followSone(sone, friendId);
1471 sone.setAlbums(topLevelAlbums);
1472 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1474 synchronized (knownSones) {
1475 for (String friend : friends) {
1476 knownSones.add(friend);
1479 synchronized (knownPosts) {
1480 for (Post post : posts) {
1481 knownPosts.add(post.getId());
1484 synchronized (knownReplies) {
1485 for (PostReply reply : replies) {
1486 knownReplies.add(reply.getId());
1492 * Creates a new post.
1495 * The Sone that creates the post
1497 * The text of the post
1498 * @return The created post
1500 public Post createPost(Sone sone, String text) {
1501 return createPost(sone, System.currentTimeMillis(), text);
1505 * Creates a new post.
1508 * The Sone that creates the post
1510 * The time of the post
1512 * The text of the post
1513 * @return The created post
1515 public Post createPost(Sone sone, long time, String text) {
1516 return createPost(sone, null, time, text);
1520 * Creates a new post.
1523 * The Sone that creates the post
1525 * The recipient Sone, or {@code null} if this post does not have
1528 * The text of the post
1529 * @return The created post
1531 public Post createPost(Sone sone, Sone recipient, String text) {
1532 return createPost(sone, recipient, System.currentTimeMillis(), text);
1536 * Creates a new post.
1539 * The Sone that creates the post
1541 * The recipient Sone, or {@code null} if this post does not have
1544 * The time of the post
1546 * The text of the post
1547 * @return The created post
1549 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1550 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1551 if (!sone.isLocal()) {
1552 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1555 final Post post = new PostImpl(sone, time, text);
1556 if (recipient != null) {
1557 post.setRecipient(recipient);
1559 synchronized (posts) {
1560 posts.put(post.getId(), post);
1562 eventBus.post(new NewPostFoundEvent(post));
1564 touchConfiguration();
1565 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1572 markPostKnown(post);
1574 }, "Mark " + post + " read.");
1579 * Deletes the given post.
1582 * The post to delete
1584 public void deletePost(Post post) {
1585 if (!post.getSone().isLocal()) {
1586 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1589 post.getSone().removePost(post);
1590 synchronized (posts) {
1591 posts.remove(post.getId());
1593 eventBus.post(new PostRemovedEvent(post));
1594 markPostKnown(post);
1595 touchConfiguration();
1599 * Marks the given post as known, if it is currently not a known post
1600 * (according to {@link Post#isKnown()}).
1603 * The post to mark as known
1605 public void markPostKnown(Post post) {
1606 post.setKnown(true);
1607 synchronized (knownPosts) {
1608 eventBus.post(new MarkPostKnownEvent(post));
1609 if (knownPosts.add(post.getId())) {
1610 touchConfiguration();
1613 for (PostReply reply : getReplies(post)) {
1614 markReplyKnown(reply);
1619 * Bookmarks the given post.
1622 * The post to bookmark
1624 public void bookmark(Post post) {
1625 bookmarkPost(post.getId());
1629 * Bookmarks the post with the given ID.
1632 * The ID of the post to bookmark
1634 public void bookmarkPost(String id) {
1635 synchronized (bookmarkedPosts) {
1636 bookmarkedPosts.add(id);
1641 * Removes the given post from the bookmarks.
1644 * The post to unbookmark
1646 public void unbookmark(Post post) {
1647 unbookmarkPost(post.getId());
1651 * Removes the post with the given ID from the bookmarks.
1654 * The ID of the post to unbookmark
1656 public void unbookmarkPost(String id) {
1657 synchronized (bookmarkedPosts) {
1658 bookmarkedPosts.remove(id);
1663 * Creates a new reply.
1666 * The Sone that creates the reply
1668 * The post that this reply refers to
1670 * The text of the reply
1671 * @return The created reply
1673 public PostReply createReply(Sone sone, Post post, String text) {
1674 return createReply(sone, post, System.currentTimeMillis(), text);
1678 * Creates a new reply.
1681 * The Sone that creates the reply
1683 * The post that this reply refers to
1685 * The time of the reply
1687 * The text of the reply
1688 * @return The created reply
1690 public PostReply createReply(Sone sone, Post post, long time, String text) {
1691 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1692 if (!sone.isLocal()) {
1693 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1696 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1697 synchronized (replies) {
1698 replies.put(reply.getId(), reply);
1700 synchronized (knownReplies) {
1701 eventBus.post(new NewPostReplyFoundEvent(reply));
1703 sone.addReply(reply);
1704 touchConfiguration();
1705 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1712 markReplyKnown(reply);
1714 }, "Mark " + reply + " read.");
1719 * Deletes the given reply.
1722 * The reply to delete
1724 public void deleteReply(PostReply reply) {
1725 Sone sone = reply.getSone();
1726 if (!sone.isLocal()) {
1727 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1730 synchronized (replies) {
1731 replies.remove(reply.getId());
1733 synchronized (knownReplies) {
1734 markReplyKnown(reply);
1735 knownReplies.remove(reply.getId());
1737 sone.removeReply(reply);
1738 touchConfiguration();
1742 * Marks the given reply as known, if it is currently not a known reply
1743 * (according to {@link Reply#isKnown()}).
1746 * The reply to mark as known
1748 public void markReplyKnown(PostReply reply) {
1749 reply.setKnown(true);
1750 synchronized (knownReplies) {
1751 eventBus.post(new MarkPostReplyKnownEvent(reply));
1752 if (knownReplies.add(reply.getId())) {
1753 touchConfiguration();
1759 * Creates a new top-level album for the given Sone.
1762 * The Sone to create the album for
1763 * @return The new album
1765 public Album createAlbum(Sone sone) {
1766 return createAlbum(sone, null);
1770 * Creates a new album for the given Sone.
1773 * The Sone to create the album for
1775 * The parent of the album (may be {@code null} to create a
1777 * @return The new album
1779 public Album createAlbum(Sone sone, Album parent) {
1780 Album album = new Album();
1781 synchronized (albums) {
1782 albums.put(album.getId(), album);
1784 album.setSone(sone);
1785 if (parent != null) {
1786 parent.addAlbum(album);
1788 sone.addAlbum(album);
1794 * Deletes the given album. The owner of the album has to be a local Sone,
1795 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1798 * The album to remove
1800 public void deleteAlbum(Album album) {
1801 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1802 if (!album.isEmpty()) {
1805 if (album.getParent() == null) {
1806 album.getSone().removeAlbum(album);
1808 album.getParent().removeAlbum(album);
1810 synchronized (albums) {
1811 albums.remove(album.getId());
1813 touchConfiguration();
1817 * Creates a new image.
1820 * The Sone creating the image
1822 * The album the image will be inserted into
1823 * @param temporaryImage
1824 * The temporary image to create the image from
1825 * @return The newly created image
1827 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1828 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();
1829 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1830 album.addImage(image);
1831 synchronized (images) {
1832 images.put(image.getId(), image);
1834 imageInserter.insertImage(temporaryImage, image);
1839 * Deletes the given image. This method will also delete a matching
1842 * @see #deleteTemporaryImage(TemporaryImage)
1844 * The image to delete
1846 public void deleteImage(Image image) {
1847 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1848 deleteTemporaryImage(image.getId());
1849 image.getAlbum().removeImage(image);
1850 synchronized (images) {
1851 images.remove(image.getId());
1853 touchConfiguration();
1857 * Creates a new temporary image.
1860 * The MIME type of the temporary image
1862 * The encoded data of the image
1863 * @return The temporary image
1865 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1866 TemporaryImage temporaryImage = new TemporaryImage();
1867 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1868 synchronized (temporaryImages) {
1869 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1871 return temporaryImage;
1875 * Deletes the given temporary image.
1877 * @param temporaryImage
1878 * The temporary image to delete
1880 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1881 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1882 deleteTemporaryImage(temporaryImage.getId());
1886 * Deletes the temporary image with the given ID.
1889 * The ID of the temporary image to delete
1891 public void deleteTemporaryImage(String imageId) {
1892 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1893 synchronized (temporaryImages) {
1894 temporaryImages.remove(imageId);
1896 Image image = getImage(imageId, false);
1897 if (image != null) {
1898 imageInserter.cancelImageInsert(image);
1903 * Notifies the core that the configuration, either of the core or of a
1904 * single local Sone, has changed, and that the configuration should be
1907 public void touchConfiguration() {
1908 lastConfigurationUpdate = System.currentTimeMillis();
1919 public void serviceStart() {
1920 loadConfiguration();
1921 updateChecker.addUpdateListener(this);
1922 updateChecker.start();
1923 identityManager.addIdentityListener(this);
1924 identityManager.start();
1925 webOfTrustUpdater.init();
1926 webOfTrustUpdater.start();
1933 public void serviceRun() {
1934 long lastSaved = System.currentTimeMillis();
1935 while (!shouldStop()) {
1937 long now = System.currentTimeMillis();
1938 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1939 for (Sone localSone : getLocalSones()) {
1940 saveSone(localSone);
1942 saveConfiguration();
1952 public void serviceStop() {
1953 synchronized (sones) {
1954 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1955 soneInserter.getValue().removeSoneInsertListener(this);
1956 soneInserter.getValue().stop();
1957 saveSone(soneInserter.getKey());
1960 saveConfiguration();
1961 webOfTrustUpdater.stop();
1962 updateChecker.stop();
1963 updateChecker.removeUpdateListener(this);
1964 soneDownloader.stop();
1965 identityManager.removeIdentityListener(this);
1966 identityManager.stop();
1974 * Saves the given Sone. This will persist all local settings for the given
1975 * Sone, such as the friends list and similar, private options.
1980 private synchronized void saveSone(Sone sone) {
1981 if (!sone.isLocal()) {
1982 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1985 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1986 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1990 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1992 /* save Sone into configuration. */
1993 String sonePrefix = "Sone/" + sone.getId();
1994 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1995 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1998 Profile profile = sone.getProfile();
1999 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2000 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2001 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2002 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2003 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2004 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2005 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2007 /* save profile fields. */
2008 int fieldCounter = 0;
2009 for (Field profileField : profile.getFields()) {
2010 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2011 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2012 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2014 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2017 int postCounter = 0;
2018 for (Post post : sone.getPosts()) {
2019 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2020 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2021 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2022 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2023 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2025 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2028 int replyCounter = 0;
2029 for (PostReply reply : sone.getReplies()) {
2030 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2031 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2032 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2033 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2034 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2036 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2038 /* save post likes. */
2039 int postLikeCounter = 0;
2040 for (String postId : sone.getLikedPostIds()) {
2041 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2043 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2045 /* save reply likes. */
2046 int replyLikeCounter = 0;
2047 for (String replyId : sone.getLikedReplyIds()) {
2048 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2050 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2053 int friendCounter = 0;
2054 for (String friendId : sone.getFriends()) {
2055 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2057 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2059 /* save albums. first, collect in a flat structure, top-level first. */
2060 List<Album> albums = sone.getAllAlbums();
2062 int albumCounter = 0;
2063 for (Album album : albums) {
2064 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2065 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2066 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2067 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2068 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2069 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2071 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2074 int imageCounter = 0;
2075 for (Album album : albums) {
2076 for (Image image : album.getImages()) {
2077 if (!image.isInserted()) {
2080 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2081 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2082 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2083 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2084 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2085 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2086 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2087 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2088 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2091 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2094 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2095 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2096 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2097 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2098 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2099 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2101 configuration.save();
2103 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2105 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2106 } catch (ConfigurationException ce1) {
2107 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2112 * Saves the current options.
2114 private void saveConfiguration() {
2115 synchronized (configuration) {
2116 if (storingConfiguration) {
2117 logger.log(Level.FINE, "Already storing configuration…");
2120 storingConfiguration = true;
2123 /* store the options first. */
2125 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2126 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2127 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2128 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2129 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2130 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2131 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2132 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2133 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2134 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2135 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2136 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2138 /* save known Sones. */
2139 int soneCounter = 0;
2140 synchronized (knownSones) {
2141 for (String knownSoneId : knownSones) {
2142 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2144 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2147 /* save Sone following times. */
2149 synchronized (soneFollowingTimes) {
2150 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2151 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2152 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2155 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2158 /* save known posts. */
2159 int postCounter = 0;
2160 synchronized (knownPosts) {
2161 for (String knownPostId : knownPosts) {
2162 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2164 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2167 /* save known replies. */
2168 int replyCounter = 0;
2169 synchronized (knownReplies) {
2170 for (String knownReplyId : knownReplies) {
2171 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2173 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2176 /* save bookmarked posts. */
2177 int bookmarkedPostCounter = 0;
2178 synchronized (bookmarkedPosts) {
2179 for (String bookmarkedPostId : bookmarkedPosts) {
2180 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2183 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2186 configuration.save();
2188 } catch (ConfigurationException ce1) {
2189 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2191 synchronized (configuration) {
2192 storingConfiguration = false;
2198 * Loads the configuration.
2200 @SuppressWarnings("unchecked")
2201 private void loadConfiguration() {
2202 /* create options. */
2203 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2206 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2207 SoneInserter.setInsertionDelay(newValue);
2211 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2212 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2213 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2214 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2215 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2216 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2217 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2218 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2219 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2222 @SuppressWarnings("synthetic-access")
2223 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2224 fcpInterface.setActive(newValue);
2227 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2230 @SuppressWarnings("synthetic-access")
2231 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2232 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2237 loadConfigurationValue("InsertionDelay");
2238 loadConfigurationValue("PostsPerPage");
2239 loadConfigurationValue("ImagesPerPage");
2240 loadConfigurationValue("CharactersPerPost");
2241 loadConfigurationValue("PostCutOffLength");
2242 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2243 loadConfigurationValue("PositiveTrust");
2244 loadConfigurationValue("NegativeTrust");
2245 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2246 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2247 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2249 /* load known Sones. */
2250 int soneCounter = 0;
2252 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2253 if (knownSoneId == null) {
2256 synchronized (knownSones) {
2257 knownSones.add(knownSoneId);
2261 /* load Sone following times. */
2264 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2265 if (soneId == null) {
2268 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2269 Sone followedSone = getSone(soneId);
2270 if (followedSone == null) {
2271 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2273 synchronized (soneFollowingTimes) {
2274 soneFollowingTimes.put(getSone(soneId), time);
2280 /* load known posts. */
2281 int postCounter = 0;
2283 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2284 if (knownPostId == null) {
2287 synchronized (knownPosts) {
2288 knownPosts.add(knownPostId);
2292 /* load known replies. */
2293 int replyCounter = 0;
2295 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2296 if (knownReplyId == null) {
2299 synchronized (knownReplies) {
2300 knownReplies.add(knownReplyId);
2304 /* load bookmarked posts. */
2305 int bookmarkedPostCounter = 0;
2307 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2308 if (bookmarkedPostId == null) {
2311 synchronized (bookmarkedPosts) {
2312 bookmarkedPosts.add(bookmarkedPostId);
2319 * Loads an {@link Integer} configuration value for the option with the
2320 * given name, logging validation failures.
2323 * The name of the option to load
2325 private void loadConfigurationValue(String optionName) {
2327 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2328 } catch (IllegalArgumentException iae1) {
2329 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2334 * Generate a Sone URI from the given URI and latest edition.
2337 * The URI to derive the Sone URI from
2338 * @return The derived URI
2340 private static FreenetURI getSoneUri(String uriString) {
2342 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2344 } catch (MalformedURLException mue1) {
2345 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2351 // INTERFACE IdentityListener
2358 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2359 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2360 if (ownIdentity.hasContext("Sone")) {
2361 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2362 addLocalSone(ownIdentity);
2370 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2371 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2372 trustedIdentities.remove(ownIdentity);
2379 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2380 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2381 trustedIdentities.get(ownIdentity).add(identity);
2382 addRemoteSone(identity);
2389 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2390 soneDownloaders.execute(new Runnable() {
2393 @SuppressWarnings("synthetic-access")
2395 Sone sone = getRemoteSone(identity.getId(), false);
2396 sone.setIdentity(identity);
2397 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2398 soneDownloader.addSone(sone);
2399 soneDownloader.fetchSone(sone);
2408 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2409 trustedIdentities.get(ownIdentity).remove(identity);
2410 boolean foundIdentity = false;
2411 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2412 if (trustedIdentity.getKey().equals(ownIdentity)) {
2415 if (trustedIdentity.getValue().contains(identity)) {
2416 foundIdentity = true;
2419 if (foundIdentity) {
2420 /* some local identity still trusts this identity, don’t remove. */
2423 Sone sone = getSone(identity.getId(), false);
2425 /* TODO - we don’t have the Sone anymore. should this happen? */
2428 synchronized (posts) {
2429 synchronized (knownPosts) {
2430 for (Post post : sone.getPosts()) {
2431 posts.remove(post.getId());
2432 eventBus.post(new PostRemovedEvent(post));
2436 synchronized (replies) {
2437 synchronized (knownReplies) {
2438 for (PostReply reply : sone.getReplies()) {
2439 replies.remove(reply.getId());
2440 eventBus.post(new PostReplyRemovedEvent(reply));
2444 synchronized (sones) {
2445 sones.remove(identity.getId());
2447 eventBus.post(new SoneRemovedEvent(sone));
2451 // INTERFACE UpdateListener
2458 public void updateFound(Version version, long releaseTime, long latestEdition) {
2459 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2463 // INTERFACE ImageInsertListener
2470 public void insertStarted(Sone sone) {
2471 eventBus.post(new SoneInsertingEvent(sone));
2478 public void insertFinished(Sone sone, long insertDuration) {
2479 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2486 public void insertAborted(Sone sone, Throwable cause) {
2487 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2491 // SONEINSERTLISTENER METHODS
2498 public void imageInsertStarted(Image image) {
2499 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2500 eventBus.post(new ImageInsertStartedEvent(image));
2507 public void imageInsertAborted(Image image) {
2508 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2509 eventBus.post(new ImageInsertAbortedEvent(image));
2516 public void imageInsertFinished(Image image, FreenetURI key) {
2517 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2518 image.setKey(key.toString());
2519 deleteTemporaryImage(image.getId());
2520 touchConfiguration();
2521 coreListenerManager.fireImageInsertFinished(image);
2528 public void imageInsertFailed(Image image, Throwable cause) {
2529 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2530 coreListenerManager.fireImageInsertFailed(image, cause);
2534 * Convenience interface for external classes that want to access the core’s
2537 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2539 public static class Preferences {
2541 /** The wrapped options. */
2542 private final Options options;
2545 * Creates a new preferences object wrapped around the given options.
2548 * The options to wrap
2550 public Preferences(Options options) {
2551 this.options = options;
2555 * Returns the insertion delay.
2557 * @return The insertion delay
2559 public int getInsertionDelay() {
2560 return options.getIntegerOption("InsertionDelay").get();
2564 * Validates the given insertion delay.
2566 * @param insertionDelay
2567 * The insertion delay to validate
2568 * @return {@code true} if the given insertion delay was valid,
2569 * {@code false} otherwise
2571 public boolean validateInsertionDelay(Integer insertionDelay) {
2572 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2576 * Sets the insertion delay
2578 * @param insertionDelay
2579 * The new insertion delay, or {@code null} to restore it to
2581 * @return This preferences
2583 public Preferences setInsertionDelay(Integer insertionDelay) {
2584 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2589 * Returns the number of posts to show per page.
2591 * @return The number of posts to show per page
2593 public int getPostsPerPage() {
2594 return options.getIntegerOption("PostsPerPage").get();
2598 * Validates the number of posts per page.
2600 * @param postsPerPage
2601 * The number of posts per page
2602 * @return {@code true} if the number of posts per page was valid,
2603 * {@code false} otherwise
2605 public boolean validatePostsPerPage(Integer postsPerPage) {
2606 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2610 * Sets the number of posts to show per page.
2612 * @param postsPerPage
2613 * The number of posts to show per page
2614 * @return This preferences object
2616 public Preferences setPostsPerPage(Integer postsPerPage) {
2617 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2622 * Returns the number of images to show per page.
2624 * @return The number of images to show per page
2626 public int getImagesPerPage() {
2627 return options.getIntegerOption("ImagesPerPage").get();
2631 * Validates the number of images per page.
2633 * @param imagesPerPage
2634 * The number of images per page
2635 * @return {@code true} if the number of images per page was valid,
2636 * {@code false} otherwise
2638 public boolean validateImagesPerPage(Integer imagesPerPage) {
2639 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2643 * Sets the number of images per page.
2645 * @param imagesPerPage
2646 * The number of images per page
2647 * @return This preferences object
2649 public Preferences setImagesPerPage(Integer imagesPerPage) {
2650 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2655 * Returns the number of characters per post, or <code>-1</code> if the
2656 * posts should not be cut off.
2658 * @return The numbers of characters per post
2660 public int getCharactersPerPost() {
2661 return options.getIntegerOption("CharactersPerPost").get();
2665 * Validates the number of characters per post.
2667 * @param charactersPerPost
2668 * The number of characters per post
2669 * @return {@code true} if the number of characters per post was valid,
2670 * {@code false} otherwise
2672 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2673 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2677 * Sets the number of characters per post.
2679 * @param charactersPerPost
2680 * The number of characters per post, or <code>-1</code> to
2681 * not cut off the posts
2682 * @return This preferences objects
2684 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2685 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2690 * Returns the number of characters the shortened post should have.
2692 * @return The number of characters of the snippet
2694 public int getPostCutOffLength() {
2695 return options.getIntegerOption("PostCutOffLength").get();
2699 * Validates the number of characters after which to cut off the post.
2701 * @param postCutOffLength
2702 * The number of characters of the snippet
2703 * @return {@code true} if the number of characters of the snippet is
2704 * valid, {@code false} otherwise
2706 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2707 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2711 * Sets the number of characters the shortened post should have.
2713 * @param postCutOffLength
2714 * The number of characters of the snippet
2715 * @return This preferences
2717 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2718 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2723 * Returns whether Sone requires full access to be even visible.
2725 * @return {@code true} if Sone requires full access, {@code false}
2728 public boolean isRequireFullAccess() {
2729 return options.getBooleanOption("RequireFullAccess").get();
2733 * Sets whether Sone requires full access to be even visible.
2735 * @param requireFullAccess
2736 * {@code true} if Sone requires full access, {@code false}
2739 public void setRequireFullAccess(Boolean requireFullAccess) {
2740 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2744 * Returns the positive trust.
2746 * @return The positive trust
2748 public int getPositiveTrust() {
2749 return options.getIntegerOption("PositiveTrust").get();
2753 * Validates the positive trust.
2755 * @param positiveTrust
2756 * The positive trust to validate
2757 * @return {@code true} if the positive trust was valid, {@code false}
2760 public boolean validatePositiveTrust(Integer positiveTrust) {
2761 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2765 * Sets the positive trust.
2767 * @param positiveTrust
2768 * The new positive trust, or {@code null} to restore it to
2770 * @return This preferences
2772 public Preferences setPositiveTrust(Integer positiveTrust) {
2773 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2778 * Returns the negative trust.
2780 * @return The negative trust
2782 public int getNegativeTrust() {
2783 return options.getIntegerOption("NegativeTrust").get();
2787 * Validates the negative trust.
2789 * @param negativeTrust
2790 * The negative trust to validate
2791 * @return {@code true} if the negative trust was valid, {@code false}
2794 public boolean validateNegativeTrust(Integer negativeTrust) {
2795 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2799 * Sets the negative trust.
2801 * @param negativeTrust
2802 * The negative trust, or {@code null} to restore it to the
2804 * @return The preferences
2806 public Preferences setNegativeTrust(Integer negativeTrust) {
2807 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2812 * Returns the trust comment. This is the comment that is set in the web
2813 * of trust when a trust value is assigned to an identity.
2815 * @return The trust comment
2817 public String getTrustComment() {
2818 return options.getStringOption("TrustComment").get();
2822 * Sets the trust comment.
2824 * @param trustComment
2825 * The trust comment, or {@code null} to restore it to the
2827 * @return This preferences
2829 public Preferences setTrustComment(String trustComment) {
2830 options.getStringOption("TrustComment").set(trustComment);
2835 * Returns whether the {@link FcpInterface FCP interface} is currently
2838 * @see FcpInterface#setActive(boolean)
2839 * @return {@code true} if the FCP interface is currently active,
2840 * {@code false} otherwise
2842 public boolean isFcpInterfaceActive() {
2843 return options.getBooleanOption("ActivateFcpInterface").get();
2847 * Sets whether the {@link FcpInterface FCP interface} is currently
2850 * @see FcpInterface#setActive(boolean)
2851 * @param fcpInterfaceActive
2852 * {@code true} to activate the FCP interface, {@code false}
2853 * to deactivate the FCP interface
2854 * @return This preferences object
2856 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2857 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2862 * Returns the action level for which full access to the FCP interface
2865 * @return The action level for which full access to the FCP interface
2868 public FullAccessRequired getFcpFullAccessRequired() {
2869 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2873 * Sets the action level for which full access to the FCP interface is
2876 * @param fcpFullAccessRequired
2878 * @return This preferences
2880 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2881 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);