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.ImageInsertFinishedEvent;
39 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
41 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
42 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
43 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
44 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
45 import net.pterodactylus.sone.core.event.PostRemovedEvent;
46 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
47 import net.pterodactylus.sone.core.event.SoneLockedEvent;
48 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
49 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
50 import net.pterodactylus.sone.data.Album;
51 import net.pterodactylus.sone.data.Client;
52 import net.pterodactylus.sone.data.Image;
53 import net.pterodactylus.sone.data.Post;
54 import net.pterodactylus.sone.data.PostReply;
55 import net.pterodactylus.sone.data.Profile;
56 import net.pterodactylus.sone.data.Profile.Field;
57 import net.pterodactylus.sone.data.Reply;
58 import net.pterodactylus.sone.data.Sone;
59 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
60 import net.pterodactylus.sone.data.Sone.SoneStatus;
61 import net.pterodactylus.sone.data.TemporaryImage;
62 import net.pterodactylus.sone.data.impl.PostImpl;
63 import net.pterodactylus.sone.fcp.FcpInterface;
64 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
65 import net.pterodactylus.sone.freenet.wot.Identity;
66 import net.pterodactylus.sone.freenet.wot.IdentityManager;
67 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
68 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
69 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
70 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
71 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
72 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
73 import net.pterodactylus.sone.main.SonePlugin;
74 import net.pterodactylus.util.config.Configuration;
75 import net.pterodactylus.util.config.ConfigurationException;
76 import net.pterodactylus.util.logging.Logging;
77 import net.pterodactylus.util.number.Numbers;
78 import net.pterodactylus.util.service.AbstractService;
79 import net.pterodactylus.util.thread.NamedThreadFactory;
80 import net.pterodactylus.util.thread.Ticker;
81 import net.pterodactylus.util.validation.EqualityValidator;
82 import net.pterodactylus.util.validation.IntegerRangeValidator;
83 import net.pterodactylus.util.validation.OrValidator;
84 import net.pterodactylus.util.validation.Validation;
86 import com.google.common.base.Predicate;
87 import com.google.common.collect.Collections2;
88 import com.google.common.eventbus.EventBus;
89 import com.google.common.eventbus.Subscribe;
90 import com.google.inject.Inject;
92 import freenet.keys.FreenetURI;
97 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
99 public class Core extends AbstractService implements SoneProvider, PostProvider {
102 private static final Logger logger = Logging.getLogger(Core.class);
104 /** The start time. */
105 private final long startupTime = System.currentTimeMillis();
108 private final Options options = new Options();
110 /** The preferences. */
111 private final Preferences preferences = new Preferences(options);
113 /** The event bus. */
114 private final EventBus eventBus;
116 /** The configuration. */
117 private Configuration configuration;
119 /** Whether we’re currently saving the configuration. */
120 private boolean storingConfiguration = false;
122 /** The identity manager. */
123 private final IdentityManager identityManager;
125 /** Interface to freenet. */
126 private final FreenetInterface freenetInterface;
128 /** The Sone downloader. */
129 private final SoneDownloader soneDownloader;
131 /** The image inserter. */
132 private final ImageInserter imageInserter;
134 /** Sone downloader thread-pool. */
135 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
137 /** The update checker. */
138 private final UpdateChecker updateChecker;
140 /** The trust updater. */
141 private final WebOfTrustUpdater webOfTrustUpdater;
143 /** The FCP interface. */
144 private volatile FcpInterface fcpInterface;
146 /** The times Sones were followed. */
147 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
149 /** Locked local Sones. */
150 /* synchronize on itself. */
151 private final Set<Sone> lockedSones = new HashSet<Sone>();
153 /** Sone inserters. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
157 /** Sone rescuers. */
158 /* synchronize access on this on sones. */
159 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
162 /* synchronize access on this on itself. */
163 private final Map<String, Sone> sones = new HashMap<String, Sone>();
165 /** All known Sones. */
166 private final Set<String> knownSones = new HashSet<String>();
169 private final Map<String, Post> posts = new HashMap<String, Post>();
171 /** All known posts. */
172 private final Set<String> knownPosts = new HashSet<String>();
175 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
177 /** All known replies. */
178 private final Set<String> knownReplies = new HashSet<String>();
180 /** All bookmarked posts. */
181 /* synchronize access on itself. */
182 private final Set<String> bookmarkedPosts = new HashSet<String>();
184 /** Trusted identities, sorted by own identities. */
185 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
187 /** All known albums. */
188 private final Map<String, Album> albums = new HashMap<String, Album>();
190 /** All known images. */
191 private final Map<String, Image> images = new HashMap<String, Image>();
193 /** All temporary images. */
194 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
196 /** Ticker for threads that mark own elements as known. */
197 private final Ticker localElementTicker = new Ticker();
199 /** The time the configuration was last touched. */
200 private volatile long lastConfigurationUpdate;
203 * Creates a new core.
205 * @param configuration
206 * The configuration of the core
207 * @param freenetInterface
208 * The freenet interface
209 * @param identityManager
210 * The identity manager
211 * @param webOfTrustUpdater
212 * The WebOfTrust updater
217 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
219 this.configuration = configuration;
220 this.freenetInterface = freenetInterface;
221 this.identityManager = identityManager;
222 this.soneDownloader = new SoneDownloader(this, freenetInterface);
223 this.imageInserter = new ImageInserter(freenetInterface);
224 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
225 this.webOfTrustUpdater = webOfTrustUpdater;
226 this.eventBus = eventBus;
234 * Returns the time Sone was started.
236 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
238 public long getStartupTime() {
243 * Sets the configuration to use. This will automatically save the current
244 * configuration to the given configuration.
246 * @param configuration
247 * The new configuration to use
249 public void setConfiguration(Configuration configuration) {
250 this.configuration = configuration;
251 touchConfiguration();
255 * Returns the options used by the core.
257 * @return The options of the core
259 public Preferences getPreferences() {
264 * Returns the identity manager used by the core.
266 * @return The identity manager
268 public IdentityManager getIdentityManager() {
269 return identityManager;
273 * Returns the update checker.
275 * @return The update checker
277 public UpdateChecker getUpdateChecker() {
278 return updateChecker;
282 * Sets the FCP interface to use.
284 * @param fcpInterface
285 * The FCP interface to use
287 public void setFcpInterface(FcpInterface fcpInterface) {
288 this.fcpInterface = fcpInterface;
292 * Returns the Sone rescuer for the given local Sone.
295 * The local Sone to get the rescuer for
296 * @return The Sone rescuer for the given Sone
298 public SoneRescuer getSoneRescuer(Sone sone) {
299 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
300 synchronized (sones) {
301 SoneRescuer soneRescuer = soneRescuers.get(sone);
302 if (soneRescuer == null) {
303 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
304 soneRescuers.put(sone, soneRescuer);
312 * Returns whether the given Sone is currently locked.
316 * @return {@code true} if the Sone is locked, {@code false} if it is not
318 public boolean isLocked(Sone sone) {
319 synchronized (lockedSones) {
320 return lockedSones.contains(sone);
325 * Returns all Sones, remote and local.
329 public Set<Sone> getSones() {
330 return new HashSet<Sone>(sones.values());
334 * Returns the Sone with the given ID, regardless whether it’s local or
338 * The ID of the Sone to get
339 * @return The Sone with the given ID, or {@code null} if there is no such
342 public Sone getSone(String id) {
343 return getSone(id, true);
347 * Returns the Sone with the given ID, regardless whether it’s local or
351 * The ID of the Sone to get
353 * {@code true} to create a new Sone if none exists,
354 * {@code false} to return {@code null} if a Sone with the given
356 * @return The Sone with the given ID, or {@code null} if there is no such
360 public Sone getSone(String id, boolean create) {
361 synchronized (sones) {
362 if (!sones.containsKey(id) && create) {
363 Sone sone = new Sone(id, false);
366 return sones.get(id);
371 * Checks whether the core knows a Sone with the given ID.
375 * @return {@code true} if there is a Sone with the given ID, {@code false}
378 public boolean hasSone(String id) {
379 synchronized (sones) {
380 return sones.containsKey(id);
385 * Returns all local Sones.
387 * @return All local Sones
389 public Collection<Sone> getLocalSones() {
390 synchronized (sones) {
391 return Collections2.filter(sones.values(), new Predicate<Sone>() {
394 public boolean apply(Sone sone) {
395 return sone.isLocal();
402 * Returns the local Sone with the given ID, optionally creating a new Sone.
407 * {@code true} to create a new Sone if none exists,
408 * {@code false} to return null if none exists
409 * @return The Sone with the given ID, or {@code null}
411 public Sone getLocalSone(String id, boolean create) {
412 synchronized (sones) {
413 Sone sone = sones.get(id);
414 if ((sone == null) && create) {
415 sone = new Sone(id, true);
418 if ((sone != null) && !sone.isLocal()) {
419 sone = new Sone(id, true);
427 * Returns all remote Sones.
429 * @return All remote Sones
431 public Collection<Sone> getRemoteSones() {
432 synchronized (sones) {
433 return Collections2.filter(sones.values(), new Predicate<Sone>() {
436 public boolean apply(Sone sone) {
437 return !sone.isLocal();
444 * Returns the remote Sone with the given ID.
447 * The ID of the remote Sone to get
449 * {@code true} to always create a Sone, {@code false} to return
450 * {@code null} if no Sone with the given ID exists
451 * @return The Sone with the given ID
453 public Sone getRemoteSone(String id, boolean create) {
454 synchronized (sones) {
455 Sone sone = sones.get(id);
456 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
457 sone = new Sone(id, false);
465 * Returns whether the given Sone has been modified.
468 * The Sone to check for modifications
469 * @return {@code true} if a modification has been detected in the Sone,
470 * {@code false} otherwise
472 public boolean isModifiedSone(Sone sone) {
473 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
477 * Returns the time when the given was first followed by any local Sone.
480 * The Sone to get the time for
481 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
482 * been followed, or {@link Long#MAX_VALUE}
484 public long getSoneFollowingTime(Sone sone) {
485 synchronized (soneFollowingTimes) {
486 if (soneFollowingTimes.containsKey(sone)) {
487 return soneFollowingTimes.get(sone);
489 return Long.MAX_VALUE;
494 * Returns whether the target Sone is trusted by the origin Sone.
500 * @return {@code true} if the target Sone is trusted by the origin Sone
502 public boolean isSoneTrusted(Sone origin, Sone target) {
503 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
504 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
508 * Returns the post with the given ID.
511 * The ID of the post to get
512 * @return The post with the given ID, or a new post with the given ID
514 public Post getPost(String postId) {
515 return getPost(postId, true);
519 * Returns the post with the given ID, optionally creating a new post.
522 * The ID of the post to get
524 * {@code true} it create a new post if no post with the given ID
525 * exists, {@code false} to return {@code null}
526 * @return The post, or {@code null} if there is no such post
529 public Post getPost(String postId, boolean create) {
530 synchronized (posts) {
531 Post post = posts.get(postId);
532 if ((post == null) && create) {
533 post = new PostImpl(postId);
534 posts.put(postId, post);
541 * Returns all posts that have the given Sone as recipient.
543 * @see Post#getRecipient()
545 * The recipient of the posts
546 * @return All posts that have the given Sone as recipient
548 public Set<Post> getDirectedPosts(Sone recipient) {
549 Validation.begin().isNotNull("Recipient", recipient).check();
550 Set<Post> directedPosts = new HashSet<Post>();
551 synchronized (posts) {
552 for (Post post : posts.values()) {
553 if (recipient.equals(post.getRecipient())) {
554 directedPosts.add(post);
558 return directedPosts;
562 * Returns the reply with the given ID. If there is no reply with the given
563 * ID yet, a new one is created, unless {@code create} is false in which
564 * case {@code null} is returned.
567 * The ID of the reply to get
569 * {@code true} to always return a {@link Reply}, {@code false}
570 * to return {@code null} if no reply can be found
571 * @return The reply, or {@code null} if there is no such reply
573 public PostReply getPostReply(String replyId, boolean create) {
574 synchronized (replies) {
575 PostReply reply = replies.get(replyId);
576 if (create && (reply == null)) {
577 reply = new PostReply(replyId);
578 replies.put(replyId, reply);
585 * Returns all replies for the given post, order ascending by time.
588 * The post to get all replies for
589 * @return All replies for the given post
591 public List<PostReply> getReplies(Post post) {
592 Set<Sone> sones = getSones();
593 List<PostReply> replies = new ArrayList<PostReply>();
594 for (Sone sone : sones) {
595 for (PostReply reply : sone.getReplies()) {
596 if (reply.getPost().equals(post)) {
601 Collections.sort(replies, Reply.TIME_COMPARATOR);
606 * Returns all Sones that have liked the given post.
609 * The post to get the liking Sones for
610 * @return The Sones that like the given post
612 public Set<Sone> getLikes(Post post) {
613 Set<Sone> sones = new HashSet<Sone>();
614 for (Sone sone : getSones()) {
615 if (sone.getLikedPostIds().contains(post.getId())) {
623 * Returns all Sones that have liked the given reply.
626 * The reply to get the liking Sones for
627 * @return The Sones that like the given reply
629 public Set<Sone> getLikes(PostReply reply) {
630 Set<Sone> sones = new HashSet<Sone>();
631 for (Sone sone : getSones()) {
632 if (sone.getLikedReplyIds().contains(reply.getId())) {
640 * Returns whether the given post is bookmarked.
644 * @return {@code true} if the given post is bookmarked, {@code false}
647 public boolean isBookmarked(Post post) {
648 return isPostBookmarked(post.getId());
652 * Returns whether the post with the given ID is bookmarked.
655 * The ID of the post to check
656 * @return {@code true} if the post with the given ID is bookmarked,
657 * {@code false} otherwise
659 public boolean isPostBookmarked(String id) {
660 synchronized (bookmarkedPosts) {
661 return bookmarkedPosts.contains(id);
666 * Returns all currently known bookmarked posts.
668 * @return All bookmarked posts
670 public Set<Post> getBookmarkedPosts() {
671 Set<Post> posts = new HashSet<Post>();
672 synchronized (bookmarkedPosts) {
673 for (String bookmarkedPostId : bookmarkedPosts) {
674 Post post = getPost(bookmarkedPostId, false);
684 * Returns the album with the given ID, creating a new album if no album
685 * with the given ID can be found.
688 * The ID of the album
689 * @return The album with the given ID
691 public Album getAlbum(String albumId) {
692 return getAlbum(albumId, true);
696 * Returns the album with the given ID, optionally creating a new album if
697 * an album with the given ID can not be found.
700 * The ID of the album
702 * {@code true} to create a new album if none exists for the
704 * @return The album with the given ID, or {@code null} if no album with the
705 * given ID exists and {@code create} is {@code false}
707 public Album getAlbum(String albumId, boolean create) {
708 synchronized (albums) {
709 Album album = albums.get(albumId);
710 if (create && (album == null)) {
711 album = new Album(albumId);
712 albums.put(albumId, album);
719 * Returns the image with the given ID, creating it if necessary.
722 * The ID of the image
723 * @return The image with the given ID
725 public Image getImage(String imageId) {
726 return getImage(imageId, true);
730 * Returns the image with the given ID, optionally creating it if it does
734 * The ID of the image
736 * {@code true} to create an image if none exists with the given
738 * @return The image with the given ID, or {@code null} if none exists and
741 public Image getImage(String imageId, boolean create) {
742 synchronized (images) {
743 Image image = images.get(imageId);
744 if (create && (image == null)) {
745 image = new Image(imageId);
746 images.put(imageId, image);
753 * Returns the temporary image with the given ID.
756 * The ID of the temporary image
757 * @return The temporary image, or {@code null} if there is no temporary
758 * image with the given ID
760 public TemporaryImage getTemporaryImage(String imageId) {
761 synchronized (temporaryImages) {
762 return temporaryImages.get(imageId);
771 * Locks the given Sone. A locked Sone will not be inserted by
772 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
778 public void lockSone(Sone sone) {
779 synchronized (lockedSones) {
780 if (lockedSones.add(sone)) {
781 eventBus.post(new SoneLockedEvent(sone));
787 * Unlocks the given Sone.
789 * @see #lockSone(Sone)
793 public void unlockSone(Sone sone) {
794 synchronized (lockedSones) {
795 if (lockedSones.remove(sone)) {
796 eventBus.post(new SoneUnlockedEvent(sone));
802 * Adds a local Sone from the given own identity.
805 * The own identity to create a Sone from
806 * @return The added (or already existing) Sone
808 public Sone addLocalSone(OwnIdentity ownIdentity) {
809 if (ownIdentity == null) {
810 logger.log(Level.WARNING, "Given OwnIdentity is null!");
813 synchronized (sones) {
816 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
817 } catch (MalformedURLException mue1) {
818 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
821 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
822 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
824 /* TODO - load posts ’n stuff */
825 sones.put(ownIdentity.getId(), sone);
826 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
827 soneInserters.put(sone, soneInserter);
828 sone.setStatus(SoneStatus.idle);
830 soneInserter.start();
836 * Creates a new Sone for the given own identity.
839 * The own identity to create a Sone for
840 * @return The created Sone
842 public Sone createSone(OwnIdentity ownIdentity) {
843 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
844 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
847 Sone sone = addLocalSone(ownIdentity);
848 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
849 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
850 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
851 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
852 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
853 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
855 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
856 touchConfiguration();
861 * Adds the Sone of the given identity.
864 * The identity whose Sone to add
865 * @return The added or already existing Sone
867 public Sone addRemoteSone(Identity identity) {
868 if (identity == null) {
869 logger.log(Level.WARNING, "Given Identity is null!");
872 synchronized (sones) {
873 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
874 boolean newSone = sone.getRequestUri() == null;
875 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
876 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
878 synchronized (knownSones) {
879 newSone = !knownSones.contains(sone.getId());
881 sone.setKnown(!newSone);
883 eventBus.post(new NewSoneFoundEvent(sone));
884 for (Sone localSone : getLocalSones()) {
885 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
886 followSone(localSone, sone);
891 soneDownloader.addSone(sone);
892 soneDownloaders.execute(new Runnable() {
895 @SuppressWarnings("synthetic-access")
897 soneDownloader.fetchSone(sone, sone.getRequestUri());
906 * Lets the given local Sone follow the Sone with the given ID.
909 * The local Sone that should follow another Sone
911 * The ID of the Sone to follow
913 public void followSone(Sone sone, String soneId) {
914 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
915 Sone followedSone = getSone(soneId, true);
916 if (followedSone == null) {
917 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
920 followSone(sone, getSone(soneId));
924 * Lets the given local Sone follow the other given Sone. If the given Sone
925 * was not followed by any local Sone before, this will mark all elements of
926 * the followed Sone as read that have been created before the current
930 * The local Sone that should follow the other Sone
931 * @param followedSone
932 * The Sone that should be followed
934 public void followSone(Sone sone, Sone followedSone) {
935 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
936 sone.addFriend(followedSone.getId());
937 synchronized (soneFollowingTimes) {
938 if (!soneFollowingTimes.containsKey(followedSone)) {
939 long now = System.currentTimeMillis();
940 soneFollowingTimes.put(followedSone, now);
941 for (Post post : followedSone.getPosts()) {
942 if (post.getTime() < now) {
946 for (PostReply reply : followedSone.getReplies()) {
947 if (reply.getTime() < now) {
948 markReplyKnown(reply);
953 touchConfiguration();
957 * Lets the given local Sone unfollow the Sone with the given ID.
960 * The local Sone that should unfollow another Sone
962 * The ID of the Sone being unfollowed
964 public void unfollowSone(Sone sone, String soneId) {
965 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
966 unfollowSone(sone, getSone(soneId, false));
970 * Lets the given local Sone unfollow the other given Sone. If the given
971 * local Sone is the last local Sone that followed the given Sone, its
972 * following time will be removed.
975 * The local Sone that should unfollow another Sone
976 * @param unfollowedSone
977 * The Sone being unfollowed
979 public void unfollowSone(Sone sone, Sone unfollowedSone) {
980 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
981 sone.removeFriend(unfollowedSone.getId());
982 boolean unfollowedSoneStillFollowed = false;
983 for (Sone localSone : getLocalSones()) {
984 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
986 if (!unfollowedSoneStillFollowed) {
987 synchronized (soneFollowingTimes) {
988 soneFollowingTimes.remove(unfollowedSone);
991 touchConfiguration();
995 * Sets the trust value of the given origin Sone for the target Sone.
1002 * The trust value (from {@code -100} to {@code 100})
1004 public void setTrust(Sone origin, Sone target, int trustValue) {
1005 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();
1006 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1010 * Removes any trust assignment for the given target Sone.
1017 public void removeTrust(Sone origin, Sone target) {
1018 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1019 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1023 * Assigns the configured positive trust value for the given target.
1030 public void trustSone(Sone origin, Sone target) {
1031 setTrust(origin, target, preferences.getPositiveTrust());
1035 * Assigns the configured negative trust value for the given target.
1042 public void distrustSone(Sone origin, Sone target) {
1043 setTrust(origin, target, preferences.getNegativeTrust());
1047 * Removes the trust assignment for the given target.
1054 public void untrustSone(Sone origin, Sone target) {
1055 removeTrust(origin, target);
1059 * Updates the stored Sone with the given Sone.
1064 public void updateSone(Sone sone) {
1065 updateSone(sone, false);
1069 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1070 * {@code true}, an older Sone than the current Sone can be given to restore
1074 * The Sone to update
1075 * @param soneRescueMode
1076 * {@code true} if the stored Sone should be updated regardless
1077 * of the age of the given Sone
1079 public void updateSone(Sone sone, boolean soneRescueMode) {
1080 if (hasSone(sone.getId())) {
1081 Sone storedSone = getSone(sone.getId());
1082 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1083 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1086 synchronized (posts) {
1087 if (!soneRescueMode) {
1088 for (Post post : storedSone.getPosts()) {
1089 posts.remove(post.getId());
1090 if (!sone.getPosts().contains(post)) {
1091 eventBus.post(new PostRemovedEvent(post));
1095 List<Post> storedPosts = storedSone.getPosts();
1096 synchronized (knownPosts) {
1097 for (Post post : sone.getPosts()) {
1098 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1099 if (!storedPosts.contains(post)) {
1100 if (post.getTime() < getSoneFollowingTime(sone)) {
1101 knownPosts.add(post.getId());
1102 post.setKnown(true);
1103 } else if (!knownPosts.contains(post.getId())) {
1104 eventBus.post(new NewPostFoundEvent(post));
1107 posts.put(post.getId(), post);
1111 synchronized (replies) {
1112 if (!soneRescueMode) {
1113 for (PostReply reply : storedSone.getReplies()) {
1114 replies.remove(reply.getId());
1115 if (!sone.getReplies().contains(reply)) {
1116 eventBus.post(new PostReplyRemovedEvent(reply));
1120 Set<PostReply> storedReplies = storedSone.getReplies();
1121 synchronized (knownReplies) {
1122 for (PostReply reply : sone.getReplies()) {
1123 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1124 if (!storedReplies.contains(reply)) {
1125 if (reply.getTime() < getSoneFollowingTime(sone)) {
1126 knownReplies.add(reply.getId());
1127 reply.setKnown(true);
1128 } else if (!knownReplies.contains(reply.getId())) {
1129 eventBus.post(new NewPostReplyFoundEvent(reply));
1132 replies.put(reply.getId(), reply);
1136 synchronized (albums) {
1137 synchronized (images) {
1138 for (Album album : storedSone.getAlbums()) {
1139 albums.remove(album.getId());
1140 for (Image image : album.getImages()) {
1141 images.remove(image.getId());
1144 for (Album album : sone.getAlbums()) {
1145 albums.put(album.getId(), album);
1146 for (Image image : album.getImages()) {
1147 images.put(image.getId(), image);
1152 synchronized (storedSone) {
1153 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1154 storedSone.setTime(sone.getTime());
1156 storedSone.setClient(sone.getClient());
1157 storedSone.setProfile(sone.getProfile());
1158 if (soneRescueMode) {
1159 for (Post post : sone.getPosts()) {
1160 storedSone.addPost(post);
1162 for (PostReply reply : sone.getReplies()) {
1163 storedSone.addReply(reply);
1165 for (String likedPostId : sone.getLikedPostIds()) {
1166 storedSone.addLikedPostId(likedPostId);
1168 for (String likedReplyId : sone.getLikedReplyIds()) {
1169 storedSone.addLikedReplyId(likedReplyId);
1171 for (Album album : sone.getAlbums()) {
1172 storedSone.addAlbum(album);
1175 storedSone.setPosts(sone.getPosts());
1176 storedSone.setReplies(sone.getReplies());
1177 storedSone.setLikePostIds(sone.getLikedPostIds());
1178 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1179 storedSone.setAlbums(sone.getAlbums());
1181 storedSone.setLatestEdition(sone.getLatestEdition());
1187 * Deletes the given Sone. This will remove the Sone from the
1188 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1189 * remove the context from its identity.
1192 * The Sone to delete
1194 public void deleteSone(Sone sone) {
1195 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1196 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1199 synchronized (sones) {
1200 if (!getLocalSones().contains(sone)) {
1201 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1204 sones.remove(sone.getId());
1205 SoneInserter soneInserter = soneInserters.remove(sone);
1206 soneInserter.stop();
1208 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1209 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1211 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1212 } catch (ConfigurationException ce1) {
1213 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1218 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1219 * known} before, a {@link MarkSoneKnownEvent} is fired.
1222 * The Sone to mark as known
1224 public void markSoneKnown(Sone sone) {
1225 if (!sone.isKnown()) {
1226 sone.setKnown(true);
1227 synchronized (knownSones) {
1228 knownSones.add(sone.getId());
1230 eventBus.post(new MarkSoneKnownEvent(sone));
1231 touchConfiguration();
1236 * Loads and updates the given Sone from the configuration. If any error is
1237 * encountered, loading is aborted and the given Sone is not changed.
1240 * The Sone to load and update
1242 public void loadSone(Sone sone) {
1243 if (!sone.isLocal()) {
1244 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1248 /* initialize options. */
1249 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1250 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1251 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1252 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1253 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1254 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1257 String sonePrefix = "Sone/" + sone.getId();
1258 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1259 if (soneTime == null) {
1260 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1263 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1266 Profile profile = new Profile(sone);
1267 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1268 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1269 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1270 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1271 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1272 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1274 /* load profile fields. */
1276 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1277 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1278 if (fieldName == null) {
1281 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1282 profile.addField(fieldName).setValue(fieldValue);
1286 Set<Post> posts = new HashSet<Post>();
1288 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1289 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1290 if (postId == null) {
1293 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1294 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1295 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1296 if ((postTime == 0) || (postText == null)) {
1297 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1300 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1301 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1302 post.setRecipient(getSone(postRecipientId));
1308 Set<PostReply> replies = new HashSet<PostReply>();
1310 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1311 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1312 if (replyId == null) {
1315 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1316 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1317 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1318 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1319 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1322 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1325 /* load post likes. */
1326 Set<String> likedPostIds = new HashSet<String>();
1328 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1329 if (likedPostId == null) {
1332 likedPostIds.add(likedPostId);
1335 /* load reply likes. */
1336 Set<String> likedReplyIds = new HashSet<String>();
1338 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1339 if (likedReplyId == null) {
1342 likedReplyIds.add(likedReplyId);
1346 Set<String> friends = new HashSet<String>();
1348 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1349 if (friendId == null) {
1352 friends.add(friendId);
1356 List<Album> topLevelAlbums = new ArrayList<Album>();
1357 int albumCounter = 0;
1359 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1360 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1361 if (albumId == null) {
1364 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1365 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1366 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1367 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1368 if ((albumTitle == null) || (albumDescription == null)) {
1369 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1372 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1373 if (albumParentId != null) {
1374 Album parentAlbum = getAlbum(albumParentId, false);
1375 if (parentAlbum == null) {
1376 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1379 parentAlbum.addAlbum(album);
1381 if (!topLevelAlbums.contains(album)) {
1382 topLevelAlbums.add(album);
1388 int imageCounter = 0;
1390 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1391 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1392 if (imageId == null) {
1395 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1396 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1397 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1398 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1399 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1400 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1401 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1402 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1403 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1406 Album album = getAlbum(albumId, false);
1407 if (album == null) {
1408 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1411 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1412 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1413 album.addImage(image);
1417 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1418 if (avatarId != null) {
1419 profile.setAvatar(getImage(avatarId, false));
1423 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1424 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1425 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1426 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1427 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1428 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1430 /* if we’re still here, Sone was loaded successfully. */
1431 synchronized (sone) {
1432 sone.setTime(soneTime);
1433 sone.setProfile(profile);
1434 sone.setPosts(posts);
1435 sone.setReplies(replies);
1436 sone.setLikePostIds(likedPostIds);
1437 sone.setLikeReplyIds(likedReplyIds);
1438 for (String friendId : friends) {
1439 followSone(sone, friendId);
1441 sone.setAlbums(topLevelAlbums);
1442 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1444 synchronized (knownSones) {
1445 for (String friend : friends) {
1446 knownSones.add(friend);
1449 synchronized (knownPosts) {
1450 for (Post post : posts) {
1451 knownPosts.add(post.getId());
1454 synchronized (knownReplies) {
1455 for (PostReply reply : replies) {
1456 knownReplies.add(reply.getId());
1462 * Creates a new post.
1465 * The Sone that creates the post
1467 * The text of the post
1468 * @return The created post
1470 public Post createPost(Sone sone, String text) {
1471 return createPost(sone, System.currentTimeMillis(), text);
1475 * Creates a new post.
1478 * The Sone that creates the post
1480 * The time of the post
1482 * The text of the post
1483 * @return The created post
1485 public Post createPost(Sone sone, long time, String text) {
1486 return createPost(sone, null, time, text);
1490 * Creates a new post.
1493 * The Sone that creates the post
1495 * The recipient Sone, or {@code null} if this post does not have
1498 * The text of the post
1499 * @return The created post
1501 public Post createPost(Sone sone, Sone recipient, String text) {
1502 return createPost(sone, recipient, System.currentTimeMillis(), text);
1506 * Creates a new post.
1509 * The Sone that creates the post
1511 * The recipient Sone, or {@code null} if this post does not have
1514 * The time of the post
1516 * The text of the post
1517 * @return The created post
1519 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1520 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1521 if (!sone.isLocal()) {
1522 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1525 final Post post = new PostImpl(sone, time, text);
1526 if (recipient != null) {
1527 post.setRecipient(recipient);
1529 synchronized (posts) {
1530 posts.put(post.getId(), post);
1532 eventBus.post(new NewPostFoundEvent(post));
1534 touchConfiguration();
1535 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1542 markPostKnown(post);
1544 }, "Mark " + post + " read.");
1549 * Deletes the given post.
1552 * The post to delete
1554 public void deletePost(Post post) {
1555 if (!post.getSone().isLocal()) {
1556 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1559 post.getSone().removePost(post);
1560 synchronized (posts) {
1561 posts.remove(post.getId());
1563 eventBus.post(new PostRemovedEvent(post));
1564 markPostKnown(post);
1565 touchConfiguration();
1569 * Marks the given post as known, if it is currently not a known post
1570 * (according to {@link Post#isKnown()}).
1573 * The post to mark as known
1575 public void markPostKnown(Post post) {
1576 post.setKnown(true);
1577 synchronized (knownPosts) {
1578 eventBus.post(new MarkPostKnownEvent(post));
1579 if (knownPosts.add(post.getId())) {
1580 touchConfiguration();
1583 for (PostReply reply : getReplies(post)) {
1584 markReplyKnown(reply);
1589 * Bookmarks the given post.
1592 * The post to bookmark
1594 public void bookmark(Post post) {
1595 bookmarkPost(post.getId());
1599 * Bookmarks the post with the given ID.
1602 * The ID of the post to bookmark
1604 public void bookmarkPost(String id) {
1605 synchronized (bookmarkedPosts) {
1606 bookmarkedPosts.add(id);
1611 * Removes the given post from the bookmarks.
1614 * The post to unbookmark
1616 public void unbookmark(Post post) {
1617 unbookmarkPost(post.getId());
1621 * Removes the post with the given ID from the bookmarks.
1624 * The ID of the post to unbookmark
1626 public void unbookmarkPost(String id) {
1627 synchronized (bookmarkedPosts) {
1628 bookmarkedPosts.remove(id);
1633 * Creates a new reply.
1636 * The Sone that creates the reply
1638 * The post that this reply refers to
1640 * The text of the reply
1641 * @return The created reply
1643 public PostReply createReply(Sone sone, Post post, String text) {
1644 return createReply(sone, post, System.currentTimeMillis(), text);
1648 * Creates a new reply.
1651 * The Sone that creates the reply
1653 * The post that this reply refers to
1655 * The time of the reply
1657 * The text of the reply
1658 * @return The created reply
1660 public PostReply createReply(Sone sone, Post post, long time, String text) {
1661 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1662 if (!sone.isLocal()) {
1663 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1666 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1667 synchronized (replies) {
1668 replies.put(reply.getId(), reply);
1670 synchronized (knownReplies) {
1671 eventBus.post(new NewPostReplyFoundEvent(reply));
1673 sone.addReply(reply);
1674 touchConfiguration();
1675 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1682 markReplyKnown(reply);
1684 }, "Mark " + reply + " read.");
1689 * Deletes the given reply.
1692 * The reply to delete
1694 public void deleteReply(PostReply reply) {
1695 Sone sone = reply.getSone();
1696 if (!sone.isLocal()) {
1697 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1700 synchronized (replies) {
1701 replies.remove(reply.getId());
1703 synchronized (knownReplies) {
1704 markReplyKnown(reply);
1705 knownReplies.remove(reply.getId());
1707 sone.removeReply(reply);
1708 touchConfiguration();
1712 * Marks the given reply as known, if it is currently not a known reply
1713 * (according to {@link Reply#isKnown()}).
1716 * The reply to mark as known
1718 public void markReplyKnown(PostReply reply) {
1719 reply.setKnown(true);
1720 synchronized (knownReplies) {
1721 eventBus.post(new MarkPostReplyKnownEvent(reply));
1722 if (knownReplies.add(reply.getId())) {
1723 touchConfiguration();
1729 * Creates a new top-level album for the given Sone.
1732 * The Sone to create the album for
1733 * @return The new album
1735 public Album createAlbum(Sone sone) {
1736 return createAlbum(sone, null);
1740 * Creates a new album for the given Sone.
1743 * The Sone to create the album for
1745 * The parent of the album (may be {@code null} to create a
1747 * @return The new album
1749 public Album createAlbum(Sone sone, Album parent) {
1750 Album album = new Album();
1751 synchronized (albums) {
1752 albums.put(album.getId(), album);
1754 album.setSone(sone);
1755 if (parent != null) {
1756 parent.addAlbum(album);
1758 sone.addAlbum(album);
1764 * Deletes the given album. The owner of the album has to be a local Sone,
1765 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1768 * The album to remove
1770 public void deleteAlbum(Album album) {
1771 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1772 if (!album.isEmpty()) {
1775 if (album.getParent() == null) {
1776 album.getSone().removeAlbum(album);
1778 album.getParent().removeAlbum(album);
1780 synchronized (albums) {
1781 albums.remove(album.getId());
1783 touchConfiguration();
1787 * Creates a new image.
1790 * The Sone creating the image
1792 * The album the image will be inserted into
1793 * @param temporaryImage
1794 * The temporary image to create the image from
1795 * @return The newly created image
1797 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1798 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();
1799 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1800 album.addImage(image);
1801 synchronized (images) {
1802 images.put(image.getId(), image);
1804 imageInserter.insertImage(temporaryImage, image);
1809 * Deletes the given image. This method will also delete a matching
1812 * @see #deleteTemporaryImage(TemporaryImage)
1814 * The image to delete
1816 public void deleteImage(Image image) {
1817 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1818 deleteTemporaryImage(image.getId());
1819 image.getAlbum().removeImage(image);
1820 synchronized (images) {
1821 images.remove(image.getId());
1823 touchConfiguration();
1827 * Creates a new temporary image.
1830 * The MIME type of the temporary image
1832 * The encoded data of the image
1833 * @return The temporary image
1835 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1836 TemporaryImage temporaryImage = new TemporaryImage();
1837 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1838 synchronized (temporaryImages) {
1839 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1841 return temporaryImage;
1845 * Deletes the given temporary image.
1847 * @param temporaryImage
1848 * The temporary image to delete
1850 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1851 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1852 deleteTemporaryImage(temporaryImage.getId());
1856 * Deletes the temporary image with the given ID.
1859 * The ID of the temporary image to delete
1861 public void deleteTemporaryImage(String imageId) {
1862 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1863 synchronized (temporaryImages) {
1864 temporaryImages.remove(imageId);
1866 Image image = getImage(imageId, false);
1867 if (image != null) {
1868 imageInserter.cancelImageInsert(image);
1873 * Notifies the core that the configuration, either of the core or of a
1874 * single local Sone, has changed, and that the configuration should be
1877 public void touchConfiguration() {
1878 lastConfigurationUpdate = System.currentTimeMillis();
1889 public void serviceStart() {
1890 loadConfiguration();
1891 updateChecker.start();
1892 identityManager.start();
1893 webOfTrustUpdater.init();
1894 webOfTrustUpdater.start();
1901 public void serviceRun() {
1902 long lastSaved = System.currentTimeMillis();
1903 while (!shouldStop()) {
1905 long now = System.currentTimeMillis();
1906 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1907 for (Sone localSone : getLocalSones()) {
1908 saveSone(localSone);
1910 saveConfiguration();
1920 public void serviceStop() {
1921 synchronized (sones) {
1922 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1923 soneInserter.getValue().stop();
1924 saveSone(soneInserter.getKey());
1927 saveConfiguration();
1928 webOfTrustUpdater.stop();
1929 updateChecker.stop();
1930 soneDownloader.stop();
1931 identityManager.stop();
1939 * Saves the given Sone. This will persist all local settings for the given
1940 * Sone, such as the friends list and similar, private options.
1945 private synchronized void saveSone(Sone sone) {
1946 if (!sone.isLocal()) {
1947 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1950 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1951 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1955 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1957 /* save Sone into configuration. */
1958 String sonePrefix = "Sone/" + sone.getId();
1959 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1960 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1963 Profile profile = sone.getProfile();
1964 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1965 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1966 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1967 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1968 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1969 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1970 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1972 /* save profile fields. */
1973 int fieldCounter = 0;
1974 for (Field profileField : profile.getFields()) {
1975 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1976 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1977 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1979 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1982 int postCounter = 0;
1983 for (Post post : sone.getPosts()) {
1984 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1985 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1986 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1987 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1988 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1990 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1993 int replyCounter = 0;
1994 for (PostReply reply : sone.getReplies()) {
1995 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1996 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1997 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1998 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1999 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2001 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2003 /* save post likes. */
2004 int postLikeCounter = 0;
2005 for (String postId : sone.getLikedPostIds()) {
2006 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2008 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2010 /* save reply likes. */
2011 int replyLikeCounter = 0;
2012 for (String replyId : sone.getLikedReplyIds()) {
2013 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2015 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2018 int friendCounter = 0;
2019 for (String friendId : sone.getFriends()) {
2020 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2022 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2024 /* save albums. first, collect in a flat structure, top-level first. */
2025 List<Album> albums = sone.getAllAlbums();
2027 int albumCounter = 0;
2028 for (Album album : albums) {
2029 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2030 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2031 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2032 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2033 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2034 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2036 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2039 int imageCounter = 0;
2040 for (Album album : albums) {
2041 for (Image image : album.getImages()) {
2042 if (!image.isInserted()) {
2045 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2046 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2047 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2048 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2049 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2050 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2051 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2052 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2053 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2056 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2059 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2060 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2061 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2062 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2063 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2064 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2066 configuration.save();
2068 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2070 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2071 } catch (ConfigurationException ce1) {
2072 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2077 * Saves the current options.
2079 private void saveConfiguration() {
2080 synchronized (configuration) {
2081 if (storingConfiguration) {
2082 logger.log(Level.FINE, "Already storing configuration…");
2085 storingConfiguration = true;
2088 /* store the options first. */
2090 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2091 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2092 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2093 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2094 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2095 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2096 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2097 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2098 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2099 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2100 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2101 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2103 /* save known Sones. */
2104 int soneCounter = 0;
2105 synchronized (knownSones) {
2106 for (String knownSoneId : knownSones) {
2107 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2109 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2112 /* save Sone following times. */
2114 synchronized (soneFollowingTimes) {
2115 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2116 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2117 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2120 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2123 /* save known posts. */
2124 int postCounter = 0;
2125 synchronized (knownPosts) {
2126 for (String knownPostId : knownPosts) {
2127 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2129 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2132 /* save known replies. */
2133 int replyCounter = 0;
2134 synchronized (knownReplies) {
2135 for (String knownReplyId : knownReplies) {
2136 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2138 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2141 /* save bookmarked posts. */
2142 int bookmarkedPostCounter = 0;
2143 synchronized (bookmarkedPosts) {
2144 for (String bookmarkedPostId : bookmarkedPosts) {
2145 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2148 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2151 configuration.save();
2153 } catch (ConfigurationException ce1) {
2154 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2156 synchronized (configuration) {
2157 storingConfiguration = false;
2163 * Loads the configuration.
2165 @SuppressWarnings("unchecked")
2166 private void loadConfiguration() {
2167 /* create options. */
2168 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2171 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2172 SoneInserter.setInsertionDelay(newValue);
2176 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2177 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2178 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2179 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2180 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2181 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2182 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2183 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2184 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2187 @SuppressWarnings("synthetic-access")
2188 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2189 fcpInterface.setActive(newValue);
2192 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2195 @SuppressWarnings("synthetic-access")
2196 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2197 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2202 loadConfigurationValue("InsertionDelay");
2203 loadConfigurationValue("PostsPerPage");
2204 loadConfigurationValue("ImagesPerPage");
2205 loadConfigurationValue("CharactersPerPost");
2206 loadConfigurationValue("PostCutOffLength");
2207 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2208 loadConfigurationValue("PositiveTrust");
2209 loadConfigurationValue("NegativeTrust");
2210 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2211 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2212 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2214 /* load known Sones. */
2215 int soneCounter = 0;
2217 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2218 if (knownSoneId == null) {
2221 synchronized (knownSones) {
2222 knownSones.add(knownSoneId);
2226 /* load Sone following times. */
2229 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2230 if (soneId == null) {
2233 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2234 Sone followedSone = getSone(soneId);
2235 if (followedSone == null) {
2236 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2238 synchronized (soneFollowingTimes) {
2239 soneFollowingTimes.put(getSone(soneId), time);
2245 /* load known posts. */
2246 int postCounter = 0;
2248 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2249 if (knownPostId == null) {
2252 synchronized (knownPosts) {
2253 knownPosts.add(knownPostId);
2257 /* load known replies. */
2258 int replyCounter = 0;
2260 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2261 if (knownReplyId == null) {
2264 synchronized (knownReplies) {
2265 knownReplies.add(knownReplyId);
2269 /* load bookmarked posts. */
2270 int bookmarkedPostCounter = 0;
2272 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2273 if (bookmarkedPostId == null) {
2276 synchronized (bookmarkedPosts) {
2277 bookmarkedPosts.add(bookmarkedPostId);
2284 * Loads an {@link Integer} configuration value for the option with the
2285 * given name, logging validation failures.
2288 * The name of the option to load
2290 private void loadConfigurationValue(String optionName) {
2292 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2293 } catch (IllegalArgumentException iae1) {
2294 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2299 * Generate a Sone URI from the given URI and latest edition.
2302 * The URI to derive the Sone URI from
2303 * @return The derived URI
2305 private static FreenetURI getSoneUri(String uriString) {
2307 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2309 } catch (MalformedURLException mue1) {
2310 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2316 * Notifies the core that a new {@link OwnIdentity} was added.
2318 * @param ownIdentityAddedEvent
2322 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2323 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2324 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2325 if (ownIdentity.hasContext("Sone")) {
2326 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2327 addLocalSone(ownIdentity);
2332 * Notifies the core that an {@link OwnIdentity} was removed.
2334 * @param ownIdentityRemovedEvent
2338 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2339 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2340 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2341 trustedIdentities.remove(ownIdentity);
2345 * Notifies the core that a new {@link Identity} was added.
2347 * @param identityAddedEvent
2351 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2352 Identity identity = identityAddedEvent.identity();
2353 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2354 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2355 addRemoteSone(identity);
2359 * Notifies the core that an {@link Identity} was updated.
2361 * @param identityUpdatedEvent
2365 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2366 final Identity identity = identityUpdatedEvent.identity();
2367 soneDownloaders.execute(new Runnable() {
2370 @SuppressWarnings("synthetic-access")
2372 Sone sone = getRemoteSone(identity.getId(), false);
2373 sone.setIdentity(identity);
2374 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2375 soneDownloader.addSone(sone);
2376 soneDownloader.fetchSone(sone);
2382 * Notifies the core that an {@link Identity} was removed.
2384 * @param identityRemovedEvent
2388 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2389 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2390 Identity identity = identityRemovedEvent.identity();
2391 trustedIdentities.get(ownIdentity).remove(identity);
2392 boolean foundIdentity = false;
2393 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2394 if (trustedIdentity.getKey().equals(ownIdentity)) {
2397 if (trustedIdentity.getValue().contains(identity)) {
2398 foundIdentity = true;
2401 if (foundIdentity) {
2402 /* some local identity still trusts this identity, don’t remove. */
2405 Sone sone = getSone(identity.getId(), false);
2407 /* TODO - we don’t have the Sone anymore. should this happen? */
2410 synchronized (posts) {
2411 synchronized (knownPosts) {
2412 for (Post post : sone.getPosts()) {
2413 posts.remove(post.getId());
2414 eventBus.post(new PostRemovedEvent(post));
2418 synchronized (replies) {
2419 synchronized (knownReplies) {
2420 for (PostReply reply : sone.getReplies()) {
2421 replies.remove(reply.getId());
2422 eventBus.post(new PostReplyRemovedEvent(reply));
2426 synchronized (sones) {
2427 sones.remove(identity.getId());
2429 eventBus.post(new SoneRemovedEvent(sone));
2433 * Deletes the temporary image.
2435 * @param imageInsertFinishedEvent
2439 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2440 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2441 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2442 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2443 touchConfiguration();
2447 * Convenience interface for external classes that want to access the core’s
2450 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2452 public static class Preferences {
2454 /** The wrapped options. */
2455 private final Options options;
2458 * Creates a new preferences object wrapped around the given options.
2461 * The options to wrap
2463 public Preferences(Options options) {
2464 this.options = options;
2468 * Returns the insertion delay.
2470 * @return The insertion delay
2472 public int getInsertionDelay() {
2473 return options.getIntegerOption("InsertionDelay").get();
2477 * Validates the given insertion delay.
2479 * @param insertionDelay
2480 * The insertion delay to validate
2481 * @return {@code true} if the given insertion delay was valid,
2482 * {@code false} otherwise
2484 public boolean validateInsertionDelay(Integer insertionDelay) {
2485 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2489 * Sets the insertion delay
2491 * @param insertionDelay
2492 * The new insertion delay, or {@code null} to restore it to
2494 * @return This preferences
2496 public Preferences setInsertionDelay(Integer insertionDelay) {
2497 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2502 * Returns the number of posts to show per page.
2504 * @return The number of posts to show per page
2506 public int getPostsPerPage() {
2507 return options.getIntegerOption("PostsPerPage").get();
2511 * Validates the number of posts per page.
2513 * @param postsPerPage
2514 * The number of posts per page
2515 * @return {@code true} if the number of posts per page was valid,
2516 * {@code false} otherwise
2518 public boolean validatePostsPerPage(Integer postsPerPage) {
2519 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2523 * Sets the number of posts to show per page.
2525 * @param postsPerPage
2526 * The number of posts to show per page
2527 * @return This preferences object
2529 public Preferences setPostsPerPage(Integer postsPerPage) {
2530 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2535 * Returns the number of images to show per page.
2537 * @return The number of images to show per page
2539 public int getImagesPerPage() {
2540 return options.getIntegerOption("ImagesPerPage").get();
2544 * Validates the number of images per page.
2546 * @param imagesPerPage
2547 * The number of images per page
2548 * @return {@code true} if the number of images per page was valid,
2549 * {@code false} otherwise
2551 public boolean validateImagesPerPage(Integer imagesPerPage) {
2552 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2556 * Sets the number of images per page.
2558 * @param imagesPerPage
2559 * The number of images per page
2560 * @return This preferences object
2562 public Preferences setImagesPerPage(Integer imagesPerPage) {
2563 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2568 * Returns the number of characters per post, or <code>-1</code> if the
2569 * posts should not be cut off.
2571 * @return The numbers of characters per post
2573 public int getCharactersPerPost() {
2574 return options.getIntegerOption("CharactersPerPost").get();
2578 * Validates the number of characters per post.
2580 * @param charactersPerPost
2581 * The number of characters per post
2582 * @return {@code true} if the number of characters per post was valid,
2583 * {@code false} otherwise
2585 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2586 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2590 * Sets the number of characters per post.
2592 * @param charactersPerPost
2593 * The number of characters per post, or <code>-1</code> to
2594 * not cut off the posts
2595 * @return This preferences objects
2597 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2598 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2603 * Returns the number of characters the shortened post should have.
2605 * @return The number of characters of the snippet
2607 public int getPostCutOffLength() {
2608 return options.getIntegerOption("PostCutOffLength").get();
2612 * Validates the number of characters after which to cut off the post.
2614 * @param postCutOffLength
2615 * The number of characters of the snippet
2616 * @return {@code true} if the number of characters of the snippet is
2617 * valid, {@code false} otherwise
2619 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2620 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2624 * Sets the number of characters the shortened post should have.
2626 * @param postCutOffLength
2627 * The number of characters of the snippet
2628 * @return This preferences
2630 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2631 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2636 * Returns whether Sone requires full access to be even visible.
2638 * @return {@code true} if Sone requires full access, {@code false}
2641 public boolean isRequireFullAccess() {
2642 return options.getBooleanOption("RequireFullAccess").get();
2646 * Sets whether Sone requires full access to be even visible.
2648 * @param requireFullAccess
2649 * {@code true} if Sone requires full access, {@code false}
2652 public void setRequireFullAccess(Boolean requireFullAccess) {
2653 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2657 * Returns the positive trust.
2659 * @return The positive trust
2661 public int getPositiveTrust() {
2662 return options.getIntegerOption("PositiveTrust").get();
2666 * Validates the positive trust.
2668 * @param positiveTrust
2669 * The positive trust to validate
2670 * @return {@code true} if the positive trust was valid, {@code false}
2673 public boolean validatePositiveTrust(Integer positiveTrust) {
2674 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2678 * Sets the positive trust.
2680 * @param positiveTrust
2681 * The new positive trust, or {@code null} to restore it to
2683 * @return This preferences
2685 public Preferences setPositiveTrust(Integer positiveTrust) {
2686 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2691 * Returns the negative trust.
2693 * @return The negative trust
2695 public int getNegativeTrust() {
2696 return options.getIntegerOption("NegativeTrust").get();
2700 * Validates the negative trust.
2702 * @param negativeTrust
2703 * The negative trust to validate
2704 * @return {@code true} if the negative trust was valid, {@code false}
2707 public boolean validateNegativeTrust(Integer negativeTrust) {
2708 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2712 * Sets the negative trust.
2714 * @param negativeTrust
2715 * The negative trust, or {@code null} to restore it to the
2717 * @return The preferences
2719 public Preferences setNegativeTrust(Integer negativeTrust) {
2720 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2725 * Returns the trust comment. This is the comment that is set in the web
2726 * of trust when a trust value is assigned to an identity.
2728 * @return The trust comment
2730 public String getTrustComment() {
2731 return options.getStringOption("TrustComment").get();
2735 * Sets the trust comment.
2737 * @param trustComment
2738 * The trust comment, or {@code null} to restore it to the
2740 * @return This preferences
2742 public Preferences setTrustComment(String trustComment) {
2743 options.getStringOption("TrustComment").set(trustComment);
2748 * Returns whether the {@link FcpInterface FCP interface} is currently
2751 * @see FcpInterface#setActive(boolean)
2752 * @return {@code true} if the FCP interface is currently active,
2753 * {@code false} otherwise
2755 public boolean isFcpInterfaceActive() {
2756 return options.getBooleanOption("ActivateFcpInterface").get();
2760 * Sets whether the {@link FcpInterface FCP interface} is currently
2763 * @see FcpInterface#setActive(boolean)
2764 * @param fcpInterfaceActive
2765 * {@code true} to activate the FCP interface, {@code false}
2766 * to deactivate the FCP interface
2767 * @return This preferences object
2769 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2770 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2775 * Returns the action level for which full access to the FCP interface
2778 * @return The action level for which full access to the FCP interface
2781 public FullAccessRequired getFcpFullAccessRequired() {
2782 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2786 * Sets the action level for which full access to the FCP interface is
2789 * @param fcpFullAccessRequired
2791 * @return This preferences
2793 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2794 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);