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.core.event.UpdateFoundEvent;
51 import net.pterodactylus.sone.data.Album;
52 import net.pterodactylus.sone.data.Client;
53 import net.pterodactylus.sone.data.Image;
54 import net.pterodactylus.sone.data.Post;
55 import net.pterodactylus.sone.data.PostReply;
56 import net.pterodactylus.sone.data.Profile;
57 import net.pterodactylus.sone.data.Profile.Field;
58 import net.pterodactylus.sone.data.Reply;
59 import net.pterodactylus.sone.data.Sone;
60 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
61 import net.pterodactylus.sone.data.Sone.SoneStatus;
62 import net.pterodactylus.sone.data.TemporaryImage;
63 import net.pterodactylus.sone.data.impl.PostImpl;
64 import net.pterodactylus.sone.fcp.FcpInterface;
65 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
66 import net.pterodactylus.sone.freenet.wot.Identity;
67 import net.pterodactylus.sone.freenet.wot.IdentityListener;
68 import net.pterodactylus.sone.freenet.wot.IdentityManager;
69 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
70 import net.pterodactylus.sone.main.SonePlugin;
71 import net.pterodactylus.util.config.Configuration;
72 import net.pterodactylus.util.config.ConfigurationException;
73 import net.pterodactylus.util.logging.Logging;
74 import net.pterodactylus.util.number.Numbers;
75 import net.pterodactylus.util.service.AbstractService;
76 import net.pterodactylus.util.thread.NamedThreadFactory;
77 import net.pterodactylus.util.thread.Ticker;
78 import net.pterodactylus.util.validation.EqualityValidator;
79 import net.pterodactylus.util.validation.IntegerRangeValidator;
80 import net.pterodactylus.util.validation.OrValidator;
81 import net.pterodactylus.util.validation.Validation;
82 import net.pterodactylus.util.version.Version;
84 import com.google.common.base.Predicate;
85 import com.google.common.collect.Collections2;
86 import com.google.common.eventbus.EventBus;
87 import com.google.common.eventbus.Subscribe;
88 import com.google.inject.Inject;
90 import freenet.keys.FreenetURI;
95 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
97 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider {
100 private static final Logger logger = Logging.getLogger(Core.class);
102 /** The start time. */
103 private final long startupTime = System.currentTimeMillis();
106 private final Options options = new Options();
108 /** The preferences. */
109 private final Preferences preferences = new Preferences(options);
111 /** The event bus. */
112 private final EventBus eventBus;
114 /** The configuration. */
115 private Configuration configuration;
117 /** Whether we’re currently saving the configuration. */
118 private boolean storingConfiguration = false;
120 /** The identity manager. */
121 private final IdentityManager identityManager;
123 /** Interface to freenet. */
124 private final FreenetInterface freenetInterface;
126 /** The Sone downloader. */
127 private final SoneDownloader soneDownloader;
129 /** The image inserter. */
130 private final ImageInserter imageInserter;
132 /** Sone downloader thread-pool. */
133 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
135 /** The update checker. */
136 private final UpdateChecker updateChecker;
138 /** The trust updater. */
139 private final WebOfTrustUpdater webOfTrustUpdater;
141 /** The FCP interface. */
142 private volatile FcpInterface fcpInterface;
144 /** The times Sones were followed. */
145 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
147 /** Locked local Sones. */
148 /* synchronize on itself. */
149 private final Set<Sone> lockedSones = new HashSet<Sone>();
151 /** Sone inserters. */
152 /* synchronize access on this on sones. */
153 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
155 /** Sone rescuers. */
156 /* synchronize access on this on sones. */
157 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
160 /* synchronize access on this on itself. */
161 private final Map<String, Sone> sones = new HashMap<String, Sone>();
163 /** All known Sones. */
164 private final Set<String> knownSones = new HashSet<String>();
167 private final Map<String, Post> posts = new HashMap<String, Post>();
169 /** All known posts. */
170 private final Set<String> knownPosts = new HashSet<String>();
173 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
175 /** All known replies. */
176 private final Set<String> knownReplies = new HashSet<String>();
178 /** All bookmarked posts. */
179 /* synchronize access on itself. */
180 private final Set<String> bookmarkedPosts = new HashSet<String>();
182 /** Trusted identities, sorted by own identities. */
183 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
185 /** All known albums. */
186 private final Map<String, Album> albums = new HashMap<String, Album>();
188 /** All known images. */
189 private final Map<String, Image> images = new HashMap<String, Image>();
191 /** All temporary images. */
192 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
194 /** Ticker for threads that mark own elements as known. */
195 private final Ticker localElementTicker = new Ticker();
197 /** The time the configuration was last touched. */
198 private volatile long lastConfigurationUpdate;
201 * Creates a new core.
203 * @param configuration
204 * The configuration of the core
205 * @param freenetInterface
206 * The freenet interface
207 * @param identityManager
208 * The identity manager
209 * @param webOfTrustUpdater
210 * The WebOfTrust updater
215 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
217 this.configuration = configuration;
218 this.freenetInterface = freenetInterface;
219 this.identityManager = identityManager;
220 this.soneDownloader = new SoneDownloader(this, freenetInterface);
221 this.imageInserter = new ImageInserter(freenetInterface);
222 this.updateChecker = new UpdateChecker(freenetInterface);
223 this.webOfTrustUpdater = webOfTrustUpdater;
224 this.eventBus = eventBus;
232 * Returns the time Sone was started.
234 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
236 public long getStartupTime() {
241 * Sets the configuration to use. This will automatically save the current
242 * configuration to the given configuration.
244 * @param configuration
245 * The new configuration to use
247 public void setConfiguration(Configuration configuration) {
248 this.configuration = configuration;
249 touchConfiguration();
253 * Returns the options used by the core.
255 * @return The options of the core
257 public Preferences getPreferences() {
262 * Returns the identity manager used by the core.
264 * @return The identity manager
266 public IdentityManager getIdentityManager() {
267 return identityManager;
271 * Returns the update checker.
273 * @return The update checker
275 public UpdateChecker getUpdateChecker() {
276 return updateChecker;
280 * Sets the FCP interface to use.
282 * @param fcpInterface
283 * The FCP interface to use
285 public void setFcpInterface(FcpInterface fcpInterface) {
286 this.fcpInterface = fcpInterface;
290 * Returns the Sone rescuer for the given local Sone.
293 * The local Sone to get the rescuer for
294 * @return The Sone rescuer for the given Sone
296 public SoneRescuer getSoneRescuer(Sone sone) {
297 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
298 synchronized (sones) {
299 SoneRescuer soneRescuer = soneRescuers.get(sone);
300 if (soneRescuer == null) {
301 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
302 soneRescuers.put(sone, soneRescuer);
310 * Returns whether the given Sone is currently locked.
314 * @return {@code true} if the Sone is locked, {@code false} if it is not
316 public boolean isLocked(Sone sone) {
317 synchronized (lockedSones) {
318 return lockedSones.contains(sone);
323 * Returns all Sones, remote and local.
327 public Set<Sone> getSones() {
328 return new HashSet<Sone>(sones.values());
332 * Returns the Sone with the given ID, regardless whether it’s local or
336 * The ID of the Sone to get
337 * @return The Sone with the given ID, or {@code null} if there is no such
340 public Sone getSone(String id) {
341 return getSone(id, true);
345 * Returns the Sone with the given ID, regardless whether it’s local or
349 * The ID of the Sone to get
351 * {@code true} to create a new Sone if none exists,
352 * {@code false} to return {@code null} if a Sone with the given
354 * @return The Sone with the given ID, or {@code null} if there is no such
358 public Sone getSone(String id, boolean create) {
359 synchronized (sones) {
360 if (!sones.containsKey(id) && create) {
361 Sone sone = new Sone(id, false);
364 return sones.get(id);
369 * Checks whether the core knows a Sone with the given ID.
373 * @return {@code true} if there is a Sone with the given ID, {@code false}
376 public boolean hasSone(String id) {
377 synchronized (sones) {
378 return sones.containsKey(id);
383 * Returns all local Sones.
385 * @return All local Sones
387 public Collection<Sone> getLocalSones() {
388 synchronized (sones) {
389 return Collections2.filter(sones.values(), new Predicate<Sone>() {
392 public boolean apply(Sone sone) {
393 return sone.isLocal();
400 * Returns the local Sone with the given ID, optionally creating a new Sone.
405 * {@code true} to create a new Sone if none exists,
406 * {@code false} to return null if none exists
407 * @return The Sone with the given ID, or {@code null}
409 public Sone getLocalSone(String id, boolean create) {
410 synchronized (sones) {
411 Sone sone = sones.get(id);
412 if ((sone == null) && create) {
413 sone = new Sone(id, true);
416 if ((sone != null) && !sone.isLocal()) {
417 sone = new Sone(id, true);
425 * Returns all remote Sones.
427 * @return All remote Sones
429 public Collection<Sone> getRemoteSones() {
430 synchronized (sones) {
431 return Collections2.filter(sones.values(), new Predicate<Sone>() {
434 public boolean apply(Sone sone) {
435 return !sone.isLocal();
442 * Returns the remote Sone with the given ID.
445 * The ID of the remote Sone to get
447 * {@code true} to always create a Sone, {@code false} to return
448 * {@code null} if no Sone with the given ID exists
449 * @return The Sone with the given ID
451 public Sone getRemoteSone(String id, boolean create) {
452 synchronized (sones) {
453 Sone sone = sones.get(id);
454 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
455 sone = new Sone(id, false);
463 * Returns whether the given Sone has been modified.
466 * The Sone to check for modifications
467 * @return {@code true} if a modification has been detected in the Sone,
468 * {@code false} otherwise
470 public boolean isModifiedSone(Sone sone) {
471 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
475 * Returns the time when the given was first followed by any local Sone.
478 * The Sone to get the time for
479 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
480 * been followed, or {@link Long#MAX_VALUE}
482 public long getSoneFollowingTime(Sone sone) {
483 synchronized (soneFollowingTimes) {
484 if (soneFollowingTimes.containsKey(sone)) {
485 return soneFollowingTimes.get(sone);
487 return Long.MAX_VALUE;
492 * Returns whether the target Sone is trusted by the origin Sone.
498 * @return {@code true} if the target Sone is trusted by the origin Sone
500 public boolean isSoneTrusted(Sone origin, Sone target) {
501 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
502 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
506 * Returns the post with the given ID.
509 * The ID of the post to get
510 * @return The post with the given ID, or a new post with the given ID
512 public Post getPost(String postId) {
513 return getPost(postId, true);
517 * Returns the post with the given ID, optionally creating a new post.
520 * The ID of the post to get
522 * {@code true} it create a new post if no post with the given ID
523 * exists, {@code false} to return {@code null}
524 * @return The post, or {@code null} if there is no such post
527 public Post getPost(String postId, boolean create) {
528 synchronized (posts) {
529 Post post = posts.get(postId);
530 if ((post == null) && create) {
531 post = new PostImpl(postId);
532 posts.put(postId, post);
539 * Returns all posts that have the given Sone as recipient.
541 * @see Post#getRecipient()
543 * The recipient of the posts
544 * @return All posts that have the given Sone as recipient
546 public Set<Post> getDirectedPosts(Sone recipient) {
547 Validation.begin().isNotNull("Recipient", recipient).check();
548 Set<Post> directedPosts = new HashSet<Post>();
549 synchronized (posts) {
550 for (Post post : posts.values()) {
551 if (recipient.equals(post.getRecipient())) {
552 directedPosts.add(post);
556 return directedPosts;
560 * Returns the reply with the given ID. If there is no reply with the given
561 * ID yet, a new one is created, unless {@code create} is false in which
562 * case {@code null} is returned.
565 * The ID of the reply to get
567 * {@code true} to always return a {@link Reply}, {@code false}
568 * to return {@code null} if no reply can be found
569 * @return The reply, or {@code null} if there is no such reply
571 public PostReply getPostReply(String replyId, boolean create) {
572 synchronized (replies) {
573 PostReply reply = replies.get(replyId);
574 if (create && (reply == null)) {
575 reply = new PostReply(replyId);
576 replies.put(replyId, reply);
583 * Returns all replies for the given post, order ascending by time.
586 * The post to get all replies for
587 * @return All replies for the given post
589 public List<PostReply> getReplies(Post post) {
590 Set<Sone> sones = getSones();
591 List<PostReply> replies = new ArrayList<PostReply>();
592 for (Sone sone : sones) {
593 for (PostReply reply : sone.getReplies()) {
594 if (reply.getPost().equals(post)) {
599 Collections.sort(replies, Reply.TIME_COMPARATOR);
604 * Returns all Sones that have liked the given post.
607 * The post to get the liking Sones for
608 * @return The Sones that like the given post
610 public Set<Sone> getLikes(Post post) {
611 Set<Sone> sones = new HashSet<Sone>();
612 for (Sone sone : getSones()) {
613 if (sone.getLikedPostIds().contains(post.getId())) {
621 * Returns all Sones that have liked the given reply.
624 * The reply to get the liking Sones for
625 * @return The Sones that like the given reply
627 public Set<Sone> getLikes(PostReply reply) {
628 Set<Sone> sones = new HashSet<Sone>();
629 for (Sone sone : getSones()) {
630 if (sone.getLikedReplyIds().contains(reply.getId())) {
638 * Returns whether the given post is bookmarked.
642 * @return {@code true} if the given post is bookmarked, {@code false}
645 public boolean isBookmarked(Post post) {
646 return isPostBookmarked(post.getId());
650 * Returns whether the post with the given ID is bookmarked.
653 * The ID of the post to check
654 * @return {@code true} if the post with the given ID is bookmarked,
655 * {@code false} otherwise
657 public boolean isPostBookmarked(String id) {
658 synchronized (bookmarkedPosts) {
659 return bookmarkedPosts.contains(id);
664 * Returns all currently known bookmarked posts.
666 * @return All bookmarked posts
668 public Set<Post> getBookmarkedPosts() {
669 Set<Post> posts = new HashSet<Post>();
670 synchronized (bookmarkedPosts) {
671 for (String bookmarkedPostId : bookmarkedPosts) {
672 Post post = getPost(bookmarkedPostId, false);
682 * Returns the album with the given ID, creating a new album if no album
683 * with the given ID can be found.
686 * The ID of the album
687 * @return The album with the given ID
689 public Album getAlbum(String albumId) {
690 return getAlbum(albumId, true);
694 * Returns the album with the given ID, optionally creating a new album if
695 * an album with the given ID can not be found.
698 * The ID of the album
700 * {@code true} to create a new album if none exists for the
702 * @return The album with the given ID, or {@code null} if no album with the
703 * given ID exists and {@code create} is {@code false}
705 public Album getAlbum(String albumId, boolean create) {
706 synchronized (albums) {
707 Album album = albums.get(albumId);
708 if (create && (album == null)) {
709 album = new Album(albumId);
710 albums.put(albumId, album);
717 * Returns the image with the given ID, creating it if necessary.
720 * The ID of the image
721 * @return The image with the given ID
723 public Image getImage(String imageId) {
724 return getImage(imageId, true);
728 * Returns the image with the given ID, optionally creating it if it does
732 * The ID of the image
734 * {@code true} to create an image if none exists with the given
736 * @return The image with the given ID, or {@code null} if none exists and
739 public Image getImage(String imageId, boolean create) {
740 synchronized (images) {
741 Image image = images.get(imageId);
742 if (create && (image == null)) {
743 image = new Image(imageId);
744 images.put(imageId, image);
751 * Returns the temporary image with the given ID.
754 * The ID of the temporary image
755 * @return The temporary image, or {@code null} if there is no temporary
756 * image with the given ID
758 public TemporaryImage getTemporaryImage(String imageId) {
759 synchronized (temporaryImages) {
760 return temporaryImages.get(imageId);
769 * Locks the given Sone. A locked Sone will not be inserted by
770 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
776 public void lockSone(Sone sone) {
777 synchronized (lockedSones) {
778 if (lockedSones.add(sone)) {
779 eventBus.post(new SoneLockedEvent(sone));
785 * Unlocks the given Sone.
787 * @see #lockSone(Sone)
791 public void unlockSone(Sone sone) {
792 synchronized (lockedSones) {
793 if (lockedSones.remove(sone)) {
794 eventBus.post(new SoneUnlockedEvent(sone));
800 * Adds a local Sone from the given own identity.
803 * The own identity to create a Sone from
804 * @return The added (or already existing) Sone
806 public Sone addLocalSone(OwnIdentity ownIdentity) {
807 if (ownIdentity == null) {
808 logger.log(Level.WARNING, "Given OwnIdentity is null!");
811 synchronized (sones) {
814 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
815 } catch (MalformedURLException mue1) {
816 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
819 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
820 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
822 /* TODO - load posts ’n stuff */
823 sones.put(ownIdentity.getId(), sone);
824 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
825 soneInserters.put(sone, soneInserter);
826 sone.setStatus(SoneStatus.idle);
828 soneInserter.start();
834 * Creates a new Sone for the given own identity.
837 * The own identity to create a Sone for
838 * @return The created Sone
840 public Sone createSone(OwnIdentity ownIdentity) {
841 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
842 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
845 Sone sone = addLocalSone(ownIdentity);
846 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
847 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
848 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
849 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
850 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
851 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
853 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
854 touchConfiguration();
859 * Adds the Sone of the given identity.
862 * The identity whose Sone to add
863 * @return The added or already existing Sone
865 public Sone addRemoteSone(Identity identity) {
866 if (identity == null) {
867 logger.log(Level.WARNING, "Given Identity is null!");
870 synchronized (sones) {
871 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
872 boolean newSone = sone.getRequestUri() == null;
873 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
874 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
876 synchronized (knownSones) {
877 newSone = !knownSones.contains(sone.getId());
879 sone.setKnown(!newSone);
881 eventBus.post(new NewSoneFoundEvent(sone));
882 for (Sone localSone : getLocalSones()) {
883 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
884 followSone(localSone, sone);
889 soneDownloader.addSone(sone);
890 soneDownloaders.execute(new Runnable() {
893 @SuppressWarnings("synthetic-access")
895 soneDownloader.fetchSone(sone, sone.getRequestUri());
904 * Lets the given local Sone follow the Sone with the given ID.
907 * The local Sone that should follow another Sone
909 * The ID of the Sone to follow
911 public void followSone(Sone sone, String soneId) {
912 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
913 Sone followedSone = getSone(soneId, true);
914 if (followedSone == null) {
915 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
918 followSone(sone, getSone(soneId));
922 * Lets the given local Sone follow the other given Sone. If the given Sone
923 * was not followed by any local Sone before, this will mark all elements of
924 * the followed Sone as read that have been created before the current
928 * The local Sone that should follow the other Sone
929 * @param followedSone
930 * The Sone that should be followed
932 public void followSone(Sone sone, Sone followedSone) {
933 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
934 sone.addFriend(followedSone.getId());
935 synchronized (soneFollowingTimes) {
936 if (!soneFollowingTimes.containsKey(followedSone)) {
937 long now = System.currentTimeMillis();
938 soneFollowingTimes.put(followedSone, now);
939 for (Post post : followedSone.getPosts()) {
940 if (post.getTime() < now) {
944 for (PostReply reply : followedSone.getReplies()) {
945 if (reply.getTime() < now) {
946 markReplyKnown(reply);
951 touchConfiguration();
955 * Lets the given local Sone unfollow the Sone with the given ID.
958 * The local Sone that should unfollow another Sone
960 * The ID of the Sone being unfollowed
962 public void unfollowSone(Sone sone, String soneId) {
963 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
964 unfollowSone(sone, getSone(soneId, false));
968 * Lets the given local Sone unfollow the other given Sone. If the given
969 * local Sone is the last local Sone that followed the given Sone, its
970 * following time will be removed.
973 * The local Sone that should unfollow another Sone
974 * @param unfollowedSone
975 * The Sone being unfollowed
977 public void unfollowSone(Sone sone, Sone unfollowedSone) {
978 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
979 sone.removeFriend(unfollowedSone.getId());
980 boolean unfollowedSoneStillFollowed = false;
981 for (Sone localSone : getLocalSones()) {
982 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
984 if (!unfollowedSoneStillFollowed) {
985 synchronized (soneFollowingTimes) {
986 soneFollowingTimes.remove(unfollowedSone);
989 touchConfiguration();
993 * Sets the trust value of the given origin Sone for the target Sone.
1000 * The trust value (from {@code -100} to {@code 100})
1002 public void setTrust(Sone origin, Sone target, int trustValue) {
1003 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();
1004 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1008 * Removes any trust assignment for the given target Sone.
1015 public void removeTrust(Sone origin, Sone target) {
1016 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1017 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1021 * Assigns the configured positive trust value for the given target.
1028 public void trustSone(Sone origin, Sone target) {
1029 setTrust(origin, target, preferences.getPositiveTrust());
1033 * Assigns the configured negative trust value for the given target.
1040 public void distrustSone(Sone origin, Sone target) {
1041 setTrust(origin, target, preferences.getNegativeTrust());
1045 * Removes the trust assignment for the given target.
1052 public void untrustSone(Sone origin, Sone target) {
1053 removeTrust(origin, target);
1057 * Updates the stored Sone with the given Sone.
1062 public void updateSone(Sone sone) {
1063 updateSone(sone, false);
1067 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1068 * {@code true}, an older Sone than the current Sone can be given to restore
1072 * The Sone to update
1073 * @param soneRescueMode
1074 * {@code true} if the stored Sone should be updated regardless
1075 * of the age of the given Sone
1077 public void updateSone(Sone sone, boolean soneRescueMode) {
1078 if (hasSone(sone.getId())) {
1079 Sone storedSone = getSone(sone.getId());
1080 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1081 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1084 synchronized (posts) {
1085 if (!soneRescueMode) {
1086 for (Post post : storedSone.getPosts()) {
1087 posts.remove(post.getId());
1088 if (!sone.getPosts().contains(post)) {
1089 eventBus.post(new PostRemovedEvent(post));
1093 List<Post> storedPosts = storedSone.getPosts();
1094 synchronized (knownPosts) {
1095 for (Post post : sone.getPosts()) {
1096 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1097 if (!storedPosts.contains(post)) {
1098 if (post.getTime() < getSoneFollowingTime(sone)) {
1099 knownPosts.add(post.getId());
1100 post.setKnown(true);
1101 } else if (!knownPosts.contains(post.getId())) {
1102 eventBus.post(new NewPostFoundEvent(post));
1105 posts.put(post.getId(), post);
1109 synchronized (replies) {
1110 if (!soneRescueMode) {
1111 for (PostReply reply : storedSone.getReplies()) {
1112 replies.remove(reply.getId());
1113 if (!sone.getReplies().contains(reply)) {
1114 eventBus.post(new PostReplyRemovedEvent(reply));
1118 Set<PostReply> storedReplies = storedSone.getReplies();
1119 synchronized (knownReplies) {
1120 for (PostReply reply : sone.getReplies()) {
1121 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1122 if (!storedReplies.contains(reply)) {
1123 if (reply.getTime() < getSoneFollowingTime(sone)) {
1124 knownReplies.add(reply.getId());
1125 reply.setKnown(true);
1126 } else if (!knownReplies.contains(reply.getId())) {
1127 eventBus.post(new NewPostReplyFoundEvent(reply));
1130 replies.put(reply.getId(), reply);
1134 synchronized (albums) {
1135 synchronized (images) {
1136 for (Album album : storedSone.getAlbums()) {
1137 albums.remove(album.getId());
1138 for (Image image : album.getImages()) {
1139 images.remove(image.getId());
1142 for (Album album : sone.getAlbums()) {
1143 albums.put(album.getId(), album);
1144 for (Image image : album.getImages()) {
1145 images.put(image.getId(), image);
1150 synchronized (storedSone) {
1151 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1152 storedSone.setTime(sone.getTime());
1154 storedSone.setClient(sone.getClient());
1155 storedSone.setProfile(sone.getProfile());
1156 if (soneRescueMode) {
1157 for (Post post : sone.getPosts()) {
1158 storedSone.addPost(post);
1160 for (PostReply reply : sone.getReplies()) {
1161 storedSone.addReply(reply);
1163 for (String likedPostId : sone.getLikedPostIds()) {
1164 storedSone.addLikedPostId(likedPostId);
1166 for (String likedReplyId : sone.getLikedReplyIds()) {
1167 storedSone.addLikedReplyId(likedReplyId);
1169 for (Album album : sone.getAlbums()) {
1170 storedSone.addAlbum(album);
1173 storedSone.setPosts(sone.getPosts());
1174 storedSone.setReplies(sone.getReplies());
1175 storedSone.setLikePostIds(sone.getLikedPostIds());
1176 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1177 storedSone.setAlbums(sone.getAlbums());
1179 storedSone.setLatestEdition(sone.getLatestEdition());
1185 * Deletes the given Sone. This will remove the Sone from the
1186 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1187 * remove the context from its identity.
1190 * The Sone to delete
1192 public void deleteSone(Sone sone) {
1193 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1194 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1197 synchronized (sones) {
1198 if (!getLocalSones().contains(sone)) {
1199 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1202 sones.remove(sone.getId());
1203 SoneInserter soneInserter = soneInserters.remove(sone);
1204 soneInserter.stop();
1206 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1207 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1209 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1210 } catch (ConfigurationException ce1) {
1211 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1216 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1217 * known} before, a {@link MarkSoneKnownEvent} is fired.
1220 * The Sone to mark as known
1222 public void markSoneKnown(Sone sone) {
1223 if (!sone.isKnown()) {
1224 sone.setKnown(true);
1225 synchronized (knownSones) {
1226 knownSones.add(sone.getId());
1228 eventBus.post(new MarkSoneKnownEvent(sone));
1229 touchConfiguration();
1234 * Loads and updates the given Sone from the configuration. If any error is
1235 * encountered, loading is aborted and the given Sone is not changed.
1238 * The Sone to load and update
1240 public void loadSone(Sone sone) {
1241 if (!sone.isLocal()) {
1242 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1246 /* initialize options. */
1247 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1248 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1249 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1250 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1251 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1252 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1255 String sonePrefix = "Sone/" + sone.getId();
1256 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1257 if (soneTime == null) {
1258 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1261 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1264 Profile profile = new Profile(sone);
1265 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1266 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1267 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1268 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1269 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1270 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1272 /* load profile fields. */
1274 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1275 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1276 if (fieldName == null) {
1279 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1280 profile.addField(fieldName).setValue(fieldValue);
1284 Set<Post> posts = new HashSet<Post>();
1286 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1287 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1288 if (postId == null) {
1291 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1292 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1293 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1294 if ((postTime == 0) || (postText == null)) {
1295 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1298 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1299 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1300 post.setRecipient(getSone(postRecipientId));
1306 Set<PostReply> replies = new HashSet<PostReply>();
1308 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1309 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1310 if (replyId == null) {
1313 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1314 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1315 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1316 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1317 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1320 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1323 /* load post likes. */
1324 Set<String> likedPostIds = new HashSet<String>();
1326 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1327 if (likedPostId == null) {
1330 likedPostIds.add(likedPostId);
1333 /* load reply likes. */
1334 Set<String> likedReplyIds = new HashSet<String>();
1336 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1337 if (likedReplyId == null) {
1340 likedReplyIds.add(likedReplyId);
1344 Set<String> friends = new HashSet<String>();
1346 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1347 if (friendId == null) {
1350 friends.add(friendId);
1354 List<Album> topLevelAlbums = new ArrayList<Album>();
1355 int albumCounter = 0;
1357 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1358 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1359 if (albumId == null) {
1362 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1363 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1364 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1365 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1366 if ((albumTitle == null) || (albumDescription == null)) {
1367 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1370 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1371 if (albumParentId != null) {
1372 Album parentAlbum = getAlbum(albumParentId, false);
1373 if (parentAlbum == null) {
1374 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1377 parentAlbum.addAlbum(album);
1379 if (!topLevelAlbums.contains(album)) {
1380 topLevelAlbums.add(album);
1386 int imageCounter = 0;
1388 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1389 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1390 if (imageId == null) {
1393 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1394 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1395 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1396 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1397 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1398 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1399 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1400 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1401 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1404 Album album = getAlbum(albumId, false);
1405 if (album == null) {
1406 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1409 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1410 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1411 album.addImage(image);
1415 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1416 if (avatarId != null) {
1417 profile.setAvatar(getImage(avatarId, false));
1421 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1422 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1423 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1424 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1425 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1426 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1428 /* if we’re still here, Sone was loaded successfully. */
1429 synchronized (sone) {
1430 sone.setTime(soneTime);
1431 sone.setProfile(profile);
1432 sone.setPosts(posts);
1433 sone.setReplies(replies);
1434 sone.setLikePostIds(likedPostIds);
1435 sone.setLikeReplyIds(likedReplyIds);
1436 for (String friendId : friends) {
1437 followSone(sone, friendId);
1439 sone.setAlbums(topLevelAlbums);
1440 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1442 synchronized (knownSones) {
1443 for (String friend : friends) {
1444 knownSones.add(friend);
1447 synchronized (knownPosts) {
1448 for (Post post : posts) {
1449 knownPosts.add(post.getId());
1452 synchronized (knownReplies) {
1453 for (PostReply reply : replies) {
1454 knownReplies.add(reply.getId());
1460 * Creates a new post.
1463 * The Sone that creates the post
1465 * The text of the post
1466 * @return The created post
1468 public Post createPost(Sone sone, String text) {
1469 return createPost(sone, System.currentTimeMillis(), text);
1473 * Creates a new post.
1476 * The Sone that creates the post
1478 * The time of the post
1480 * The text of the post
1481 * @return The created post
1483 public Post createPost(Sone sone, long time, String text) {
1484 return createPost(sone, null, time, text);
1488 * Creates a new post.
1491 * The Sone that creates the post
1493 * The recipient Sone, or {@code null} if this post does not have
1496 * The text of the post
1497 * @return The created post
1499 public Post createPost(Sone sone, Sone recipient, String text) {
1500 return createPost(sone, recipient, System.currentTimeMillis(), text);
1504 * Creates a new post.
1507 * The Sone that creates the post
1509 * The recipient Sone, or {@code null} if this post does not have
1512 * The time of the post
1514 * The text of the post
1515 * @return The created post
1517 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1518 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1519 if (!sone.isLocal()) {
1520 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1523 final Post post = new PostImpl(sone, time, text);
1524 if (recipient != null) {
1525 post.setRecipient(recipient);
1527 synchronized (posts) {
1528 posts.put(post.getId(), post);
1530 eventBus.post(new NewPostFoundEvent(post));
1532 touchConfiguration();
1533 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1540 markPostKnown(post);
1542 }, "Mark " + post + " read.");
1547 * Deletes the given post.
1550 * The post to delete
1552 public void deletePost(Post post) {
1553 if (!post.getSone().isLocal()) {
1554 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1557 post.getSone().removePost(post);
1558 synchronized (posts) {
1559 posts.remove(post.getId());
1561 eventBus.post(new PostRemovedEvent(post));
1562 markPostKnown(post);
1563 touchConfiguration();
1567 * Marks the given post as known, if it is currently not a known post
1568 * (according to {@link Post#isKnown()}).
1571 * The post to mark as known
1573 public void markPostKnown(Post post) {
1574 post.setKnown(true);
1575 synchronized (knownPosts) {
1576 eventBus.post(new MarkPostKnownEvent(post));
1577 if (knownPosts.add(post.getId())) {
1578 touchConfiguration();
1581 for (PostReply reply : getReplies(post)) {
1582 markReplyKnown(reply);
1587 * Bookmarks the given post.
1590 * The post to bookmark
1592 public void bookmark(Post post) {
1593 bookmarkPost(post.getId());
1597 * Bookmarks the post with the given ID.
1600 * The ID of the post to bookmark
1602 public void bookmarkPost(String id) {
1603 synchronized (bookmarkedPosts) {
1604 bookmarkedPosts.add(id);
1609 * Removes the given post from the bookmarks.
1612 * The post to unbookmark
1614 public void unbookmark(Post post) {
1615 unbookmarkPost(post.getId());
1619 * Removes the post with the given ID from the bookmarks.
1622 * The ID of the post to unbookmark
1624 public void unbookmarkPost(String id) {
1625 synchronized (bookmarkedPosts) {
1626 bookmarkedPosts.remove(id);
1631 * Creates a new reply.
1634 * The Sone that creates the reply
1636 * The post that this reply refers to
1638 * The text of the reply
1639 * @return The created reply
1641 public PostReply createReply(Sone sone, Post post, String text) {
1642 return createReply(sone, post, System.currentTimeMillis(), text);
1646 * Creates a new reply.
1649 * The Sone that creates the reply
1651 * The post that this reply refers to
1653 * The time of the reply
1655 * The text of the reply
1656 * @return The created reply
1658 public PostReply createReply(Sone sone, Post post, long time, String text) {
1659 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1660 if (!sone.isLocal()) {
1661 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1664 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1665 synchronized (replies) {
1666 replies.put(reply.getId(), reply);
1668 synchronized (knownReplies) {
1669 eventBus.post(new NewPostReplyFoundEvent(reply));
1671 sone.addReply(reply);
1672 touchConfiguration();
1673 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1680 markReplyKnown(reply);
1682 }, "Mark " + reply + " read.");
1687 * Deletes the given reply.
1690 * The reply to delete
1692 public void deleteReply(PostReply reply) {
1693 Sone sone = reply.getSone();
1694 if (!sone.isLocal()) {
1695 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1698 synchronized (replies) {
1699 replies.remove(reply.getId());
1701 synchronized (knownReplies) {
1702 markReplyKnown(reply);
1703 knownReplies.remove(reply.getId());
1705 sone.removeReply(reply);
1706 touchConfiguration();
1710 * Marks the given reply as known, if it is currently not a known reply
1711 * (according to {@link Reply#isKnown()}).
1714 * The reply to mark as known
1716 public void markReplyKnown(PostReply reply) {
1717 reply.setKnown(true);
1718 synchronized (knownReplies) {
1719 eventBus.post(new MarkPostReplyKnownEvent(reply));
1720 if (knownReplies.add(reply.getId())) {
1721 touchConfiguration();
1727 * Creates a new top-level album for the given Sone.
1730 * The Sone to create the album for
1731 * @return The new album
1733 public Album createAlbum(Sone sone) {
1734 return createAlbum(sone, null);
1738 * Creates a new album for the given Sone.
1741 * The Sone to create the album for
1743 * The parent of the album (may be {@code null} to create a
1745 * @return The new album
1747 public Album createAlbum(Sone sone, Album parent) {
1748 Album album = new Album();
1749 synchronized (albums) {
1750 albums.put(album.getId(), album);
1752 album.setSone(sone);
1753 if (parent != null) {
1754 parent.addAlbum(album);
1756 sone.addAlbum(album);
1762 * Deletes the given album. The owner of the album has to be a local Sone,
1763 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1766 * The album to remove
1768 public void deleteAlbum(Album album) {
1769 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1770 if (!album.isEmpty()) {
1773 if (album.getParent() == null) {
1774 album.getSone().removeAlbum(album);
1776 album.getParent().removeAlbum(album);
1778 synchronized (albums) {
1779 albums.remove(album.getId());
1781 touchConfiguration();
1785 * Creates a new image.
1788 * The Sone creating the image
1790 * The album the image will be inserted into
1791 * @param temporaryImage
1792 * The temporary image to create the image from
1793 * @return The newly created image
1795 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1796 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();
1797 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1798 album.addImage(image);
1799 synchronized (images) {
1800 images.put(image.getId(), image);
1802 imageInserter.insertImage(temporaryImage, image);
1807 * Deletes the given image. This method will also delete a matching
1810 * @see #deleteTemporaryImage(TemporaryImage)
1812 * The image to delete
1814 public void deleteImage(Image image) {
1815 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1816 deleteTemporaryImage(image.getId());
1817 image.getAlbum().removeImage(image);
1818 synchronized (images) {
1819 images.remove(image.getId());
1821 touchConfiguration();
1825 * Creates a new temporary image.
1828 * The MIME type of the temporary image
1830 * The encoded data of the image
1831 * @return The temporary image
1833 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1834 TemporaryImage temporaryImage = new TemporaryImage();
1835 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1836 synchronized (temporaryImages) {
1837 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1839 return temporaryImage;
1843 * Deletes the given temporary image.
1845 * @param temporaryImage
1846 * The temporary image to delete
1848 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1849 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1850 deleteTemporaryImage(temporaryImage.getId());
1854 * Deletes the temporary image with the given ID.
1857 * The ID of the temporary image to delete
1859 public void deleteTemporaryImage(String imageId) {
1860 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1861 synchronized (temporaryImages) {
1862 temporaryImages.remove(imageId);
1864 Image image = getImage(imageId, false);
1865 if (image != null) {
1866 imageInserter.cancelImageInsert(image);
1871 * Notifies the core that the configuration, either of the core or of a
1872 * single local Sone, has changed, and that the configuration should be
1875 public void touchConfiguration() {
1876 lastConfigurationUpdate = System.currentTimeMillis();
1887 public void serviceStart() {
1888 loadConfiguration();
1889 updateChecker.addUpdateListener(this);
1890 updateChecker.start();
1891 identityManager.addIdentityListener(this);
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 updateChecker.removeUpdateListener(this);
1931 soneDownloader.stop();
1932 identityManager.removeIdentityListener(this);
1933 identityManager.stop();
1941 * Saves the given Sone. This will persist all local settings for the given
1942 * Sone, such as the friends list and similar, private options.
1947 private synchronized void saveSone(Sone sone) {
1948 if (!sone.isLocal()) {
1949 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1952 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1953 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1957 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1959 /* save Sone into configuration. */
1960 String sonePrefix = "Sone/" + sone.getId();
1961 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1962 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1965 Profile profile = sone.getProfile();
1966 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1967 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1968 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1969 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1970 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1971 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1972 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1974 /* save profile fields. */
1975 int fieldCounter = 0;
1976 for (Field profileField : profile.getFields()) {
1977 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1978 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1979 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1981 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1984 int postCounter = 0;
1985 for (Post post : sone.getPosts()) {
1986 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1987 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1988 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1989 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1990 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1992 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1995 int replyCounter = 0;
1996 for (PostReply reply : sone.getReplies()) {
1997 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1998 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1999 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2000 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2001 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2003 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2005 /* save post likes. */
2006 int postLikeCounter = 0;
2007 for (String postId : sone.getLikedPostIds()) {
2008 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2010 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2012 /* save reply likes. */
2013 int replyLikeCounter = 0;
2014 for (String replyId : sone.getLikedReplyIds()) {
2015 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2017 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2020 int friendCounter = 0;
2021 for (String friendId : sone.getFriends()) {
2022 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2024 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2026 /* save albums. first, collect in a flat structure, top-level first. */
2027 List<Album> albums = sone.getAllAlbums();
2029 int albumCounter = 0;
2030 for (Album album : albums) {
2031 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2032 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2033 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2034 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2035 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2036 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2038 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2041 int imageCounter = 0;
2042 for (Album album : albums) {
2043 for (Image image : album.getImages()) {
2044 if (!image.isInserted()) {
2047 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2048 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2049 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2050 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2051 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2052 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2053 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2054 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2055 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2058 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2061 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2062 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2063 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2064 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2065 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2066 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2068 configuration.save();
2070 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2072 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2073 } catch (ConfigurationException ce1) {
2074 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2079 * Saves the current options.
2081 private void saveConfiguration() {
2082 synchronized (configuration) {
2083 if (storingConfiguration) {
2084 logger.log(Level.FINE, "Already storing configuration…");
2087 storingConfiguration = true;
2090 /* store the options first. */
2092 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2093 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2094 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2095 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2096 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2097 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2098 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2099 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2100 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2101 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2102 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2103 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2105 /* save known Sones. */
2106 int soneCounter = 0;
2107 synchronized (knownSones) {
2108 for (String knownSoneId : knownSones) {
2109 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2111 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2114 /* save Sone following times. */
2116 synchronized (soneFollowingTimes) {
2117 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2118 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2119 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2122 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2125 /* save known posts. */
2126 int postCounter = 0;
2127 synchronized (knownPosts) {
2128 for (String knownPostId : knownPosts) {
2129 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2131 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2134 /* save known replies. */
2135 int replyCounter = 0;
2136 synchronized (knownReplies) {
2137 for (String knownReplyId : knownReplies) {
2138 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2140 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2143 /* save bookmarked posts. */
2144 int bookmarkedPostCounter = 0;
2145 synchronized (bookmarkedPosts) {
2146 for (String bookmarkedPostId : bookmarkedPosts) {
2147 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2150 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2153 configuration.save();
2155 } catch (ConfigurationException ce1) {
2156 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2158 synchronized (configuration) {
2159 storingConfiguration = false;
2165 * Loads the configuration.
2167 @SuppressWarnings("unchecked")
2168 private void loadConfiguration() {
2169 /* create options. */
2170 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2173 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2174 SoneInserter.setInsertionDelay(newValue);
2178 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2179 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2180 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2181 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2182 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2183 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2184 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2185 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2186 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2189 @SuppressWarnings("synthetic-access")
2190 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2191 fcpInterface.setActive(newValue);
2194 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2197 @SuppressWarnings("synthetic-access")
2198 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2199 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2204 loadConfigurationValue("InsertionDelay");
2205 loadConfigurationValue("PostsPerPage");
2206 loadConfigurationValue("ImagesPerPage");
2207 loadConfigurationValue("CharactersPerPost");
2208 loadConfigurationValue("PostCutOffLength");
2209 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2210 loadConfigurationValue("PositiveTrust");
2211 loadConfigurationValue("NegativeTrust");
2212 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2213 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2214 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2216 /* load known Sones. */
2217 int soneCounter = 0;
2219 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2220 if (knownSoneId == null) {
2223 synchronized (knownSones) {
2224 knownSones.add(knownSoneId);
2228 /* load Sone following times. */
2231 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2232 if (soneId == null) {
2235 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2236 Sone followedSone = getSone(soneId);
2237 if (followedSone == null) {
2238 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2240 synchronized (soneFollowingTimes) {
2241 soneFollowingTimes.put(getSone(soneId), time);
2247 /* load known posts. */
2248 int postCounter = 0;
2250 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2251 if (knownPostId == null) {
2254 synchronized (knownPosts) {
2255 knownPosts.add(knownPostId);
2259 /* load known replies. */
2260 int replyCounter = 0;
2262 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2263 if (knownReplyId == null) {
2266 synchronized (knownReplies) {
2267 knownReplies.add(knownReplyId);
2271 /* load bookmarked posts. */
2272 int bookmarkedPostCounter = 0;
2274 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2275 if (bookmarkedPostId == null) {
2278 synchronized (bookmarkedPosts) {
2279 bookmarkedPosts.add(bookmarkedPostId);
2286 * Loads an {@link Integer} configuration value for the option with the
2287 * given name, logging validation failures.
2290 * The name of the option to load
2292 private void loadConfigurationValue(String optionName) {
2294 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2295 } catch (IllegalArgumentException iae1) {
2296 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2301 * Generate a Sone URI from the given URI and latest edition.
2304 * The URI to derive the Sone URI from
2305 * @return The derived URI
2307 private static FreenetURI getSoneUri(String uriString) {
2309 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2311 } catch (MalformedURLException mue1) {
2312 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2318 // INTERFACE IdentityListener
2325 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2326 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2327 if (ownIdentity.hasContext("Sone")) {
2328 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2329 addLocalSone(ownIdentity);
2337 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2338 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2339 trustedIdentities.remove(ownIdentity);
2346 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2347 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2348 trustedIdentities.get(ownIdentity).add(identity);
2349 addRemoteSone(identity);
2356 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2357 soneDownloaders.execute(new Runnable() {
2360 @SuppressWarnings("synthetic-access")
2362 Sone sone = getRemoteSone(identity.getId(), false);
2363 sone.setIdentity(identity);
2364 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2365 soneDownloader.addSone(sone);
2366 soneDownloader.fetchSone(sone);
2375 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2376 trustedIdentities.get(ownIdentity).remove(identity);
2377 boolean foundIdentity = false;
2378 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2379 if (trustedIdentity.getKey().equals(ownIdentity)) {
2382 if (trustedIdentity.getValue().contains(identity)) {
2383 foundIdentity = true;
2386 if (foundIdentity) {
2387 /* some local identity still trusts this identity, don’t remove. */
2390 Sone sone = getSone(identity.getId(), false);
2392 /* TODO - we don’t have the Sone anymore. should this happen? */
2395 synchronized (posts) {
2396 synchronized (knownPosts) {
2397 for (Post post : sone.getPosts()) {
2398 posts.remove(post.getId());
2399 eventBus.post(new PostRemovedEvent(post));
2403 synchronized (replies) {
2404 synchronized (knownReplies) {
2405 for (PostReply reply : sone.getReplies()) {
2406 replies.remove(reply.getId());
2407 eventBus.post(new PostReplyRemovedEvent(reply));
2411 synchronized (sones) {
2412 sones.remove(identity.getId());
2414 eventBus.post(new SoneRemovedEvent(sone));
2418 // INTERFACE UpdateListener
2425 public void updateFound(Version version, long releaseTime, long latestEdition) {
2426 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2430 * Deletes the temporary image.
2432 * @param imageInsertFinishedEvent
2436 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2437 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2438 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2439 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2440 touchConfiguration();
2444 * Convenience interface for external classes that want to access the core’s
2447 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2449 public static class Preferences {
2451 /** The wrapped options. */
2452 private final Options options;
2455 * Creates a new preferences object wrapped around the given options.
2458 * The options to wrap
2460 public Preferences(Options options) {
2461 this.options = options;
2465 * Returns the insertion delay.
2467 * @return The insertion delay
2469 public int getInsertionDelay() {
2470 return options.getIntegerOption("InsertionDelay").get();
2474 * Validates the given insertion delay.
2476 * @param insertionDelay
2477 * The insertion delay to validate
2478 * @return {@code true} if the given insertion delay was valid,
2479 * {@code false} otherwise
2481 public boolean validateInsertionDelay(Integer insertionDelay) {
2482 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2486 * Sets the insertion delay
2488 * @param insertionDelay
2489 * The new insertion delay, or {@code null} to restore it to
2491 * @return This preferences
2493 public Preferences setInsertionDelay(Integer insertionDelay) {
2494 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2499 * Returns the number of posts to show per page.
2501 * @return The number of posts to show per page
2503 public int getPostsPerPage() {
2504 return options.getIntegerOption("PostsPerPage").get();
2508 * Validates the number of posts per page.
2510 * @param postsPerPage
2511 * The number of posts per page
2512 * @return {@code true} if the number of posts per page was valid,
2513 * {@code false} otherwise
2515 public boolean validatePostsPerPage(Integer postsPerPage) {
2516 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2520 * Sets the number of posts to show per page.
2522 * @param postsPerPage
2523 * The number of posts to show per page
2524 * @return This preferences object
2526 public Preferences setPostsPerPage(Integer postsPerPage) {
2527 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2532 * Returns the number of images to show per page.
2534 * @return The number of images to show per page
2536 public int getImagesPerPage() {
2537 return options.getIntegerOption("ImagesPerPage").get();
2541 * Validates the number of images per page.
2543 * @param imagesPerPage
2544 * The number of images per page
2545 * @return {@code true} if the number of images per page was valid,
2546 * {@code false} otherwise
2548 public boolean validateImagesPerPage(Integer imagesPerPage) {
2549 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2553 * Sets the number of images per page.
2555 * @param imagesPerPage
2556 * The number of images per page
2557 * @return This preferences object
2559 public Preferences setImagesPerPage(Integer imagesPerPage) {
2560 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2565 * Returns the number of characters per post, or <code>-1</code> if the
2566 * posts should not be cut off.
2568 * @return The numbers of characters per post
2570 public int getCharactersPerPost() {
2571 return options.getIntegerOption("CharactersPerPost").get();
2575 * Validates the number of characters per post.
2577 * @param charactersPerPost
2578 * The number of characters per post
2579 * @return {@code true} if the number of characters per post was valid,
2580 * {@code false} otherwise
2582 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2583 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2587 * Sets the number of characters per post.
2589 * @param charactersPerPost
2590 * The number of characters per post, or <code>-1</code> to
2591 * not cut off the posts
2592 * @return This preferences objects
2594 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2595 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2600 * Returns the number of characters the shortened post should have.
2602 * @return The number of characters of the snippet
2604 public int getPostCutOffLength() {
2605 return options.getIntegerOption("PostCutOffLength").get();
2609 * Validates the number of characters after which to cut off the post.
2611 * @param postCutOffLength
2612 * The number of characters of the snippet
2613 * @return {@code true} if the number of characters of the snippet is
2614 * valid, {@code false} otherwise
2616 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2617 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2621 * Sets the number of characters the shortened post should have.
2623 * @param postCutOffLength
2624 * The number of characters of the snippet
2625 * @return This preferences
2627 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2628 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2633 * Returns whether Sone requires full access to be even visible.
2635 * @return {@code true} if Sone requires full access, {@code false}
2638 public boolean isRequireFullAccess() {
2639 return options.getBooleanOption("RequireFullAccess").get();
2643 * Sets whether Sone requires full access to be even visible.
2645 * @param requireFullAccess
2646 * {@code true} if Sone requires full access, {@code false}
2649 public void setRequireFullAccess(Boolean requireFullAccess) {
2650 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2654 * Returns the positive trust.
2656 * @return The positive trust
2658 public int getPositiveTrust() {
2659 return options.getIntegerOption("PositiveTrust").get();
2663 * Validates the positive trust.
2665 * @param positiveTrust
2666 * The positive trust to validate
2667 * @return {@code true} if the positive trust was valid, {@code false}
2670 public boolean validatePositiveTrust(Integer positiveTrust) {
2671 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2675 * Sets the positive trust.
2677 * @param positiveTrust
2678 * The new positive trust, or {@code null} to restore it to
2680 * @return This preferences
2682 public Preferences setPositiveTrust(Integer positiveTrust) {
2683 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2688 * Returns the negative trust.
2690 * @return The negative trust
2692 public int getNegativeTrust() {
2693 return options.getIntegerOption("NegativeTrust").get();
2697 * Validates the negative trust.
2699 * @param negativeTrust
2700 * The negative trust to validate
2701 * @return {@code true} if the negative trust was valid, {@code false}
2704 public boolean validateNegativeTrust(Integer negativeTrust) {
2705 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2709 * Sets the negative trust.
2711 * @param negativeTrust
2712 * The negative trust, or {@code null} to restore it to the
2714 * @return The preferences
2716 public Preferences setNegativeTrust(Integer negativeTrust) {
2717 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2722 * Returns the trust comment. This is the comment that is set in the web
2723 * of trust when a trust value is assigned to an identity.
2725 * @return The trust comment
2727 public String getTrustComment() {
2728 return options.getStringOption("TrustComment").get();
2732 * Sets the trust comment.
2734 * @param trustComment
2735 * The trust comment, or {@code null} to restore it to the
2737 * @return This preferences
2739 public Preferences setTrustComment(String trustComment) {
2740 options.getStringOption("TrustComment").set(trustComment);
2745 * Returns whether the {@link FcpInterface FCP interface} is currently
2748 * @see FcpInterface#setActive(boolean)
2749 * @return {@code true} if the FCP interface is currently active,
2750 * {@code false} otherwise
2752 public boolean isFcpInterfaceActive() {
2753 return options.getBooleanOption("ActivateFcpInterface").get();
2757 * Sets whether the {@link FcpInterface FCP interface} is currently
2760 * @see FcpInterface#setActive(boolean)
2761 * @param fcpInterfaceActive
2762 * {@code true} to activate the FCP interface, {@code false}
2763 * to deactivate the FCP interface
2764 * @return This preferences object
2766 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2767 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2772 * Returns the action level for which full access to the FCP interface
2775 * @return The action level for which full access to the FCP interface
2778 public FullAccessRequired getFcpFullAccessRequired() {
2779 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2783 * Sets the action level for which full access to the FCP interface is
2786 * @param fcpFullAccessRequired
2788 * @return This preferences
2790 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2791 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);