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.IdentityListener;
67 import net.pterodactylus.sone.freenet.wot.IdentityManager;
68 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
69 import net.pterodactylus.sone.main.SonePlugin;
70 import net.pterodactylus.util.config.Configuration;
71 import net.pterodactylus.util.config.ConfigurationException;
72 import net.pterodactylus.util.logging.Logging;
73 import net.pterodactylus.util.number.Numbers;
74 import net.pterodactylus.util.service.AbstractService;
75 import net.pterodactylus.util.thread.NamedThreadFactory;
76 import net.pterodactylus.util.thread.Ticker;
77 import net.pterodactylus.util.validation.EqualityValidator;
78 import net.pterodactylus.util.validation.IntegerRangeValidator;
79 import net.pterodactylus.util.validation.OrValidator;
80 import net.pterodactylus.util.validation.Validation;
82 import com.google.common.base.Predicate;
83 import com.google.common.collect.Collections2;
84 import com.google.common.eventbus.EventBus;
85 import com.google.common.eventbus.Subscribe;
86 import com.google.inject.Inject;
88 import freenet.keys.FreenetURI;
93 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
95 public class Core extends AbstractService implements IdentityListener, SoneProvider, PostProvider {
98 private static final Logger logger = Logging.getLogger(Core.class);
100 /** The start time. */
101 private final long startupTime = System.currentTimeMillis();
104 private final Options options = new Options();
106 /** The preferences. */
107 private final Preferences preferences = new Preferences(options);
109 /** The event bus. */
110 private final EventBus eventBus;
112 /** The configuration. */
113 private Configuration configuration;
115 /** Whether we’re currently saving the configuration. */
116 private boolean storingConfiguration = false;
118 /** The identity manager. */
119 private final IdentityManager identityManager;
121 /** Interface to freenet. */
122 private final FreenetInterface freenetInterface;
124 /** The Sone downloader. */
125 private final SoneDownloader soneDownloader;
127 /** The image inserter. */
128 private final ImageInserter imageInserter;
130 /** Sone downloader thread-pool. */
131 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
133 /** The update checker. */
134 private final UpdateChecker updateChecker;
136 /** The trust updater. */
137 private final WebOfTrustUpdater webOfTrustUpdater;
139 /** The FCP interface. */
140 private volatile FcpInterface fcpInterface;
142 /** The times Sones were followed. */
143 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
145 /** Locked local Sones. */
146 /* synchronize on itself. */
147 private final Set<Sone> lockedSones = new HashSet<Sone>();
149 /** Sone inserters. */
150 /* synchronize access on this on sones. */
151 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
153 /** Sone rescuers. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
158 /* synchronize access on this on itself. */
159 private final Map<String, Sone> sones = new HashMap<String, Sone>();
161 /** All known Sones. */
162 private final Set<String> knownSones = new HashSet<String>();
165 private final Map<String, Post> posts = new HashMap<String, Post>();
167 /** All known posts. */
168 private final Set<String> knownPosts = new HashSet<String>();
171 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
173 /** All known replies. */
174 private final Set<String> knownReplies = new HashSet<String>();
176 /** All bookmarked posts. */
177 /* synchronize access on itself. */
178 private final Set<String> bookmarkedPosts = new HashSet<String>();
180 /** Trusted identities, sorted by own identities. */
181 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
183 /** All known albums. */
184 private final Map<String, Album> albums = new HashMap<String, Album>();
186 /** All known images. */
187 private final Map<String, Image> images = new HashMap<String, Image>();
189 /** All temporary images. */
190 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
192 /** Ticker for threads that mark own elements as known. */
193 private final Ticker localElementTicker = new Ticker();
195 /** The time the configuration was last touched. */
196 private volatile long lastConfigurationUpdate;
199 * Creates a new core.
201 * @param configuration
202 * The configuration of the core
203 * @param freenetInterface
204 * The freenet interface
205 * @param identityManager
206 * The identity manager
207 * @param webOfTrustUpdater
208 * The WebOfTrust updater
213 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
215 this.configuration = configuration;
216 this.freenetInterface = freenetInterface;
217 this.identityManager = identityManager;
218 this.soneDownloader = new SoneDownloader(this, freenetInterface);
219 this.imageInserter = new ImageInserter(freenetInterface);
220 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
221 this.webOfTrustUpdater = webOfTrustUpdater;
222 this.eventBus = eventBus;
230 * Returns the time Sone was started.
232 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
234 public long getStartupTime() {
239 * Sets the configuration to use. This will automatically save the current
240 * configuration to the given configuration.
242 * @param configuration
243 * The new configuration to use
245 public void setConfiguration(Configuration configuration) {
246 this.configuration = configuration;
247 touchConfiguration();
251 * Returns the options used by the core.
253 * @return The options of the core
255 public Preferences getPreferences() {
260 * Returns the identity manager used by the core.
262 * @return The identity manager
264 public IdentityManager getIdentityManager() {
265 return identityManager;
269 * Returns the update checker.
271 * @return The update checker
273 public UpdateChecker getUpdateChecker() {
274 return updateChecker;
278 * Sets the FCP interface to use.
280 * @param fcpInterface
281 * The FCP interface to use
283 public void setFcpInterface(FcpInterface fcpInterface) {
284 this.fcpInterface = fcpInterface;
288 * Returns the Sone rescuer for the given local Sone.
291 * The local Sone to get the rescuer for
292 * @return The Sone rescuer for the given Sone
294 public SoneRescuer getSoneRescuer(Sone sone) {
295 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
296 synchronized (sones) {
297 SoneRescuer soneRescuer = soneRescuers.get(sone);
298 if (soneRescuer == null) {
299 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
300 soneRescuers.put(sone, soneRescuer);
308 * Returns whether the given Sone is currently locked.
312 * @return {@code true} if the Sone is locked, {@code false} if it is not
314 public boolean isLocked(Sone sone) {
315 synchronized (lockedSones) {
316 return lockedSones.contains(sone);
321 * Returns all Sones, remote and local.
325 public Set<Sone> getSones() {
326 return new HashSet<Sone>(sones.values());
330 * Returns the Sone with the given ID, regardless whether it’s local or
334 * The ID of the Sone to get
335 * @return The Sone with the given ID, or {@code null} if there is no such
338 public Sone getSone(String id) {
339 return getSone(id, true);
343 * Returns the Sone with the given ID, regardless whether it’s local or
347 * The ID of the Sone to get
349 * {@code true} to create a new Sone if none exists,
350 * {@code false} to return {@code null} if a Sone with the given
352 * @return The Sone with the given ID, or {@code null} if there is no such
356 public Sone getSone(String id, boolean create) {
357 synchronized (sones) {
358 if (!sones.containsKey(id) && create) {
359 Sone sone = new Sone(id, false);
362 return sones.get(id);
367 * Checks whether the core knows a Sone with the given ID.
371 * @return {@code true} if there is a Sone with the given ID, {@code false}
374 public boolean hasSone(String id) {
375 synchronized (sones) {
376 return sones.containsKey(id);
381 * Returns all local Sones.
383 * @return All local Sones
385 public Collection<Sone> getLocalSones() {
386 synchronized (sones) {
387 return Collections2.filter(sones.values(), new Predicate<Sone>() {
390 public boolean apply(Sone sone) {
391 return sone.isLocal();
398 * Returns the local Sone with the given ID, optionally creating a new Sone.
403 * {@code true} to create a new Sone if none exists,
404 * {@code false} to return null if none exists
405 * @return The Sone with the given ID, or {@code null}
407 public Sone getLocalSone(String id, boolean create) {
408 synchronized (sones) {
409 Sone sone = sones.get(id);
410 if ((sone == null) && create) {
411 sone = new Sone(id, true);
414 if ((sone != null) && !sone.isLocal()) {
415 sone = new Sone(id, true);
423 * Returns all remote Sones.
425 * @return All remote Sones
427 public Collection<Sone> getRemoteSones() {
428 synchronized (sones) {
429 return Collections2.filter(sones.values(), new Predicate<Sone>() {
432 public boolean apply(Sone sone) {
433 return !sone.isLocal();
440 * Returns the remote Sone with the given ID.
443 * The ID of the remote Sone to get
445 * {@code true} to always create a Sone, {@code false} to return
446 * {@code null} if no Sone with the given ID exists
447 * @return The Sone with the given ID
449 public Sone getRemoteSone(String id, boolean create) {
450 synchronized (sones) {
451 Sone sone = sones.get(id);
452 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
453 sone = new Sone(id, false);
461 * Returns whether the given Sone has been modified.
464 * The Sone to check for modifications
465 * @return {@code true} if a modification has been detected in the Sone,
466 * {@code false} otherwise
468 public boolean isModifiedSone(Sone sone) {
469 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
473 * Returns the time when the given was first followed by any local Sone.
476 * The Sone to get the time for
477 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
478 * been followed, or {@link Long#MAX_VALUE}
480 public long getSoneFollowingTime(Sone sone) {
481 synchronized (soneFollowingTimes) {
482 if (soneFollowingTimes.containsKey(sone)) {
483 return soneFollowingTimes.get(sone);
485 return Long.MAX_VALUE;
490 * Returns whether the target Sone is trusted by the origin Sone.
496 * @return {@code true} if the target Sone is trusted by the origin Sone
498 public boolean isSoneTrusted(Sone origin, Sone target) {
499 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
500 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
504 * Returns the post with the given ID.
507 * The ID of the post to get
508 * @return The post with the given ID, or a new post with the given ID
510 public Post getPost(String postId) {
511 return getPost(postId, true);
515 * Returns the post with the given ID, optionally creating a new post.
518 * The ID of the post to get
520 * {@code true} it create a new post if no post with the given ID
521 * exists, {@code false} to return {@code null}
522 * @return The post, or {@code null} if there is no such post
525 public Post getPost(String postId, boolean create) {
526 synchronized (posts) {
527 Post post = posts.get(postId);
528 if ((post == null) && create) {
529 post = new PostImpl(postId);
530 posts.put(postId, post);
537 * Returns all posts that have the given Sone as recipient.
539 * @see Post#getRecipient()
541 * The recipient of the posts
542 * @return All posts that have the given Sone as recipient
544 public Set<Post> getDirectedPosts(Sone recipient) {
545 Validation.begin().isNotNull("Recipient", recipient).check();
546 Set<Post> directedPosts = new HashSet<Post>();
547 synchronized (posts) {
548 for (Post post : posts.values()) {
549 if (recipient.equals(post.getRecipient())) {
550 directedPosts.add(post);
554 return directedPosts;
558 * Returns the reply with the given ID. If there is no reply with the given
559 * ID yet, a new one is created, unless {@code create} is false in which
560 * case {@code null} is returned.
563 * The ID of the reply to get
565 * {@code true} to always return a {@link Reply}, {@code false}
566 * to return {@code null} if no reply can be found
567 * @return The reply, or {@code null} if there is no such reply
569 public PostReply getPostReply(String replyId, boolean create) {
570 synchronized (replies) {
571 PostReply reply = replies.get(replyId);
572 if (create && (reply == null)) {
573 reply = new PostReply(replyId);
574 replies.put(replyId, reply);
581 * Returns all replies for the given post, order ascending by time.
584 * The post to get all replies for
585 * @return All replies for the given post
587 public List<PostReply> getReplies(Post post) {
588 Set<Sone> sones = getSones();
589 List<PostReply> replies = new ArrayList<PostReply>();
590 for (Sone sone : sones) {
591 for (PostReply reply : sone.getReplies()) {
592 if (reply.getPost().equals(post)) {
597 Collections.sort(replies, Reply.TIME_COMPARATOR);
602 * Returns all Sones that have liked the given post.
605 * The post to get the liking Sones for
606 * @return The Sones that like the given post
608 public Set<Sone> getLikes(Post post) {
609 Set<Sone> sones = new HashSet<Sone>();
610 for (Sone sone : getSones()) {
611 if (sone.getLikedPostIds().contains(post.getId())) {
619 * Returns all Sones that have liked the given reply.
622 * The reply to get the liking Sones for
623 * @return The Sones that like the given reply
625 public Set<Sone> getLikes(PostReply reply) {
626 Set<Sone> sones = new HashSet<Sone>();
627 for (Sone sone : getSones()) {
628 if (sone.getLikedReplyIds().contains(reply.getId())) {
636 * Returns whether the given post is bookmarked.
640 * @return {@code true} if the given post is bookmarked, {@code false}
643 public boolean isBookmarked(Post post) {
644 return isPostBookmarked(post.getId());
648 * Returns whether the post with the given ID is bookmarked.
651 * The ID of the post to check
652 * @return {@code true} if the post with the given ID is bookmarked,
653 * {@code false} otherwise
655 public boolean isPostBookmarked(String id) {
656 synchronized (bookmarkedPosts) {
657 return bookmarkedPosts.contains(id);
662 * Returns all currently known bookmarked posts.
664 * @return All bookmarked posts
666 public Set<Post> getBookmarkedPosts() {
667 Set<Post> posts = new HashSet<Post>();
668 synchronized (bookmarkedPosts) {
669 for (String bookmarkedPostId : bookmarkedPosts) {
670 Post post = getPost(bookmarkedPostId, false);
680 * Returns the album with the given ID, creating a new album if no album
681 * with the given ID can be found.
684 * The ID of the album
685 * @return The album with the given ID
687 public Album getAlbum(String albumId) {
688 return getAlbum(albumId, true);
692 * Returns the album with the given ID, optionally creating a new album if
693 * an album with the given ID can not be found.
696 * The ID of the album
698 * {@code true} to create a new album if none exists for the
700 * @return The album with the given ID, or {@code null} if no album with the
701 * given ID exists and {@code create} is {@code false}
703 public Album getAlbum(String albumId, boolean create) {
704 synchronized (albums) {
705 Album album = albums.get(albumId);
706 if (create && (album == null)) {
707 album = new Album(albumId);
708 albums.put(albumId, album);
715 * Returns the image with the given ID, creating it if necessary.
718 * The ID of the image
719 * @return The image with the given ID
721 public Image getImage(String imageId) {
722 return getImage(imageId, true);
726 * Returns the image with the given ID, optionally creating it if it does
730 * The ID of the image
732 * {@code true} to create an image if none exists with the given
734 * @return The image with the given ID, or {@code null} if none exists and
737 public Image getImage(String imageId, boolean create) {
738 synchronized (images) {
739 Image image = images.get(imageId);
740 if (create && (image == null)) {
741 image = new Image(imageId);
742 images.put(imageId, image);
749 * Returns the temporary image with the given ID.
752 * The ID of the temporary image
753 * @return The temporary image, or {@code null} if there is no temporary
754 * image with the given ID
756 public TemporaryImage getTemporaryImage(String imageId) {
757 synchronized (temporaryImages) {
758 return temporaryImages.get(imageId);
767 * Locks the given Sone. A locked Sone will not be inserted by
768 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
774 public void lockSone(Sone sone) {
775 synchronized (lockedSones) {
776 if (lockedSones.add(sone)) {
777 eventBus.post(new SoneLockedEvent(sone));
783 * Unlocks the given Sone.
785 * @see #lockSone(Sone)
789 public void unlockSone(Sone sone) {
790 synchronized (lockedSones) {
791 if (lockedSones.remove(sone)) {
792 eventBus.post(new SoneUnlockedEvent(sone));
798 * Adds a local Sone from the given own identity.
801 * The own identity to create a Sone from
802 * @return The added (or already existing) Sone
804 public Sone addLocalSone(OwnIdentity ownIdentity) {
805 if (ownIdentity == null) {
806 logger.log(Level.WARNING, "Given OwnIdentity is null!");
809 synchronized (sones) {
812 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
813 } catch (MalformedURLException mue1) {
814 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
817 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
818 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
820 /* TODO - load posts ’n stuff */
821 sones.put(ownIdentity.getId(), sone);
822 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
823 soneInserters.put(sone, soneInserter);
824 sone.setStatus(SoneStatus.idle);
826 soneInserter.start();
832 * Creates a new Sone for the given own identity.
835 * The own identity to create a Sone for
836 * @return The created Sone
838 public Sone createSone(OwnIdentity ownIdentity) {
839 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
840 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
843 Sone sone = addLocalSone(ownIdentity);
844 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
845 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
846 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
847 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
848 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
849 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
851 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
852 touchConfiguration();
857 * Adds the Sone of the given identity.
860 * The identity whose Sone to add
861 * @return The added or already existing Sone
863 public Sone addRemoteSone(Identity identity) {
864 if (identity == null) {
865 logger.log(Level.WARNING, "Given Identity is null!");
868 synchronized (sones) {
869 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
870 boolean newSone = sone.getRequestUri() == null;
871 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
872 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
874 synchronized (knownSones) {
875 newSone = !knownSones.contains(sone.getId());
877 sone.setKnown(!newSone);
879 eventBus.post(new NewSoneFoundEvent(sone));
880 for (Sone localSone : getLocalSones()) {
881 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
882 followSone(localSone, sone);
887 soneDownloader.addSone(sone);
888 soneDownloaders.execute(new Runnable() {
891 @SuppressWarnings("synthetic-access")
893 soneDownloader.fetchSone(sone, sone.getRequestUri());
902 * Lets the given local Sone follow the Sone with the given ID.
905 * The local Sone that should follow another Sone
907 * The ID of the Sone to follow
909 public void followSone(Sone sone, String soneId) {
910 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
911 Sone followedSone = getSone(soneId, true);
912 if (followedSone == null) {
913 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
916 followSone(sone, getSone(soneId));
920 * Lets the given local Sone follow the other given Sone. If the given Sone
921 * was not followed by any local Sone before, this will mark all elements of
922 * the followed Sone as read that have been created before the current
926 * The local Sone that should follow the other Sone
927 * @param followedSone
928 * The Sone that should be followed
930 public void followSone(Sone sone, Sone followedSone) {
931 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
932 sone.addFriend(followedSone.getId());
933 synchronized (soneFollowingTimes) {
934 if (!soneFollowingTimes.containsKey(followedSone)) {
935 long now = System.currentTimeMillis();
936 soneFollowingTimes.put(followedSone, now);
937 for (Post post : followedSone.getPosts()) {
938 if (post.getTime() < now) {
942 for (PostReply reply : followedSone.getReplies()) {
943 if (reply.getTime() < now) {
944 markReplyKnown(reply);
949 touchConfiguration();
953 * Lets the given local Sone unfollow the Sone with the given ID.
956 * The local Sone that should unfollow another Sone
958 * The ID of the Sone being unfollowed
960 public void unfollowSone(Sone sone, String soneId) {
961 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
962 unfollowSone(sone, getSone(soneId, false));
966 * Lets the given local Sone unfollow the other given Sone. If the given
967 * local Sone is the last local Sone that followed the given Sone, its
968 * following time will be removed.
971 * The local Sone that should unfollow another Sone
972 * @param unfollowedSone
973 * The Sone being unfollowed
975 public void unfollowSone(Sone sone, Sone unfollowedSone) {
976 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
977 sone.removeFriend(unfollowedSone.getId());
978 boolean unfollowedSoneStillFollowed = false;
979 for (Sone localSone : getLocalSones()) {
980 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
982 if (!unfollowedSoneStillFollowed) {
983 synchronized (soneFollowingTimes) {
984 soneFollowingTimes.remove(unfollowedSone);
987 touchConfiguration();
991 * Sets the trust value of the given origin Sone for the target Sone.
998 * The trust value (from {@code -100} to {@code 100})
1000 public void setTrust(Sone origin, Sone target, int trustValue) {
1001 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();
1002 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1006 * Removes any trust assignment for the given target Sone.
1013 public void removeTrust(Sone origin, Sone target) {
1014 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1015 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1019 * Assigns the configured positive trust value for the given target.
1026 public void trustSone(Sone origin, Sone target) {
1027 setTrust(origin, target, preferences.getPositiveTrust());
1031 * Assigns the configured negative trust value for the given target.
1038 public void distrustSone(Sone origin, Sone target) {
1039 setTrust(origin, target, preferences.getNegativeTrust());
1043 * Removes the trust assignment for the given target.
1050 public void untrustSone(Sone origin, Sone target) {
1051 removeTrust(origin, target);
1055 * Updates the stored Sone with the given Sone.
1060 public void updateSone(Sone sone) {
1061 updateSone(sone, false);
1065 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1066 * {@code true}, an older Sone than the current Sone can be given to restore
1070 * The Sone to update
1071 * @param soneRescueMode
1072 * {@code true} if the stored Sone should be updated regardless
1073 * of the age of the given Sone
1075 public void updateSone(Sone sone, boolean soneRescueMode) {
1076 if (hasSone(sone.getId())) {
1077 Sone storedSone = getSone(sone.getId());
1078 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1079 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1082 synchronized (posts) {
1083 if (!soneRescueMode) {
1084 for (Post post : storedSone.getPosts()) {
1085 posts.remove(post.getId());
1086 if (!sone.getPosts().contains(post)) {
1087 eventBus.post(new PostRemovedEvent(post));
1091 List<Post> storedPosts = storedSone.getPosts();
1092 synchronized (knownPosts) {
1093 for (Post post : sone.getPosts()) {
1094 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1095 if (!storedPosts.contains(post)) {
1096 if (post.getTime() < getSoneFollowingTime(sone)) {
1097 knownPosts.add(post.getId());
1098 post.setKnown(true);
1099 } else if (!knownPosts.contains(post.getId())) {
1100 eventBus.post(new NewPostFoundEvent(post));
1103 posts.put(post.getId(), post);
1107 synchronized (replies) {
1108 if (!soneRescueMode) {
1109 for (PostReply reply : storedSone.getReplies()) {
1110 replies.remove(reply.getId());
1111 if (!sone.getReplies().contains(reply)) {
1112 eventBus.post(new PostReplyRemovedEvent(reply));
1116 Set<PostReply> storedReplies = storedSone.getReplies();
1117 synchronized (knownReplies) {
1118 for (PostReply reply : sone.getReplies()) {
1119 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1120 if (!storedReplies.contains(reply)) {
1121 if (reply.getTime() < getSoneFollowingTime(sone)) {
1122 knownReplies.add(reply.getId());
1123 reply.setKnown(true);
1124 } else if (!knownReplies.contains(reply.getId())) {
1125 eventBus.post(new NewPostReplyFoundEvent(reply));
1128 replies.put(reply.getId(), reply);
1132 synchronized (albums) {
1133 synchronized (images) {
1134 for (Album album : storedSone.getAlbums()) {
1135 albums.remove(album.getId());
1136 for (Image image : album.getImages()) {
1137 images.remove(image.getId());
1140 for (Album album : sone.getAlbums()) {
1141 albums.put(album.getId(), album);
1142 for (Image image : album.getImages()) {
1143 images.put(image.getId(), image);
1148 synchronized (storedSone) {
1149 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1150 storedSone.setTime(sone.getTime());
1152 storedSone.setClient(sone.getClient());
1153 storedSone.setProfile(sone.getProfile());
1154 if (soneRescueMode) {
1155 for (Post post : sone.getPosts()) {
1156 storedSone.addPost(post);
1158 for (PostReply reply : sone.getReplies()) {
1159 storedSone.addReply(reply);
1161 for (String likedPostId : sone.getLikedPostIds()) {
1162 storedSone.addLikedPostId(likedPostId);
1164 for (String likedReplyId : sone.getLikedReplyIds()) {
1165 storedSone.addLikedReplyId(likedReplyId);
1167 for (Album album : sone.getAlbums()) {
1168 storedSone.addAlbum(album);
1171 storedSone.setPosts(sone.getPosts());
1172 storedSone.setReplies(sone.getReplies());
1173 storedSone.setLikePostIds(sone.getLikedPostIds());
1174 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1175 storedSone.setAlbums(sone.getAlbums());
1177 storedSone.setLatestEdition(sone.getLatestEdition());
1183 * Deletes the given Sone. This will remove the Sone from the
1184 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1185 * remove the context from its identity.
1188 * The Sone to delete
1190 public void deleteSone(Sone sone) {
1191 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1192 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1195 synchronized (sones) {
1196 if (!getLocalSones().contains(sone)) {
1197 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1200 sones.remove(sone.getId());
1201 SoneInserter soneInserter = soneInserters.remove(sone);
1202 soneInserter.stop();
1204 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1205 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1207 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1208 } catch (ConfigurationException ce1) {
1209 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1214 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1215 * known} before, a {@link MarkSoneKnownEvent} is fired.
1218 * The Sone to mark as known
1220 public void markSoneKnown(Sone sone) {
1221 if (!sone.isKnown()) {
1222 sone.setKnown(true);
1223 synchronized (knownSones) {
1224 knownSones.add(sone.getId());
1226 eventBus.post(new MarkSoneKnownEvent(sone));
1227 touchConfiguration();
1232 * Loads and updates the given Sone from the configuration. If any error is
1233 * encountered, loading is aborted and the given Sone is not changed.
1236 * The Sone to load and update
1238 public void loadSone(Sone sone) {
1239 if (!sone.isLocal()) {
1240 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1244 /* initialize options. */
1245 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1246 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1247 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1248 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1249 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1250 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1253 String sonePrefix = "Sone/" + sone.getId();
1254 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1255 if (soneTime == null) {
1256 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1259 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1262 Profile profile = new Profile(sone);
1263 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1264 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1265 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1266 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1267 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1268 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1270 /* load profile fields. */
1272 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1273 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1274 if (fieldName == null) {
1277 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1278 profile.addField(fieldName).setValue(fieldValue);
1282 Set<Post> posts = new HashSet<Post>();
1284 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1285 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1286 if (postId == null) {
1289 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1290 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1291 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1292 if ((postTime == 0) || (postText == null)) {
1293 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1296 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1297 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1298 post.setRecipient(getSone(postRecipientId));
1304 Set<PostReply> replies = new HashSet<PostReply>();
1306 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1307 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1308 if (replyId == null) {
1311 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1312 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1313 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1314 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1315 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1318 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1321 /* load post likes. */
1322 Set<String> likedPostIds = new HashSet<String>();
1324 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1325 if (likedPostId == null) {
1328 likedPostIds.add(likedPostId);
1331 /* load reply likes. */
1332 Set<String> likedReplyIds = new HashSet<String>();
1334 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1335 if (likedReplyId == null) {
1338 likedReplyIds.add(likedReplyId);
1342 Set<String> friends = new HashSet<String>();
1344 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1345 if (friendId == null) {
1348 friends.add(friendId);
1352 List<Album> topLevelAlbums = new ArrayList<Album>();
1353 int albumCounter = 0;
1355 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1356 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1357 if (albumId == null) {
1360 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1361 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1362 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1363 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1364 if ((albumTitle == null) || (albumDescription == null)) {
1365 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1368 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1369 if (albumParentId != null) {
1370 Album parentAlbum = getAlbum(albumParentId, false);
1371 if (parentAlbum == null) {
1372 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1375 parentAlbum.addAlbum(album);
1377 if (!topLevelAlbums.contains(album)) {
1378 topLevelAlbums.add(album);
1384 int imageCounter = 0;
1386 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1387 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1388 if (imageId == null) {
1391 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1392 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1393 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1394 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1395 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1396 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1397 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1398 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1399 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1402 Album album = getAlbum(albumId, false);
1403 if (album == null) {
1404 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1407 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1408 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1409 album.addImage(image);
1413 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1414 if (avatarId != null) {
1415 profile.setAvatar(getImage(avatarId, false));
1419 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1420 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1421 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1422 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1423 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1424 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1426 /* if we’re still here, Sone was loaded successfully. */
1427 synchronized (sone) {
1428 sone.setTime(soneTime);
1429 sone.setProfile(profile);
1430 sone.setPosts(posts);
1431 sone.setReplies(replies);
1432 sone.setLikePostIds(likedPostIds);
1433 sone.setLikeReplyIds(likedReplyIds);
1434 for (String friendId : friends) {
1435 followSone(sone, friendId);
1437 sone.setAlbums(topLevelAlbums);
1438 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1440 synchronized (knownSones) {
1441 for (String friend : friends) {
1442 knownSones.add(friend);
1445 synchronized (knownPosts) {
1446 for (Post post : posts) {
1447 knownPosts.add(post.getId());
1450 synchronized (knownReplies) {
1451 for (PostReply reply : replies) {
1452 knownReplies.add(reply.getId());
1458 * Creates a new post.
1461 * The Sone that creates the post
1463 * The text of the post
1464 * @return The created post
1466 public Post createPost(Sone sone, String text) {
1467 return createPost(sone, System.currentTimeMillis(), text);
1471 * Creates a new post.
1474 * The Sone that creates the post
1476 * The time of the post
1478 * The text of the post
1479 * @return The created post
1481 public Post createPost(Sone sone, long time, String text) {
1482 return createPost(sone, null, time, text);
1486 * Creates a new post.
1489 * The Sone that creates the post
1491 * The recipient Sone, or {@code null} if this post does not have
1494 * The text of the post
1495 * @return The created post
1497 public Post createPost(Sone sone, Sone recipient, String text) {
1498 return createPost(sone, recipient, System.currentTimeMillis(), text);
1502 * Creates a new post.
1505 * The Sone that creates the post
1507 * The recipient Sone, or {@code null} if this post does not have
1510 * The time of the post
1512 * The text of the post
1513 * @return The created post
1515 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1516 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1517 if (!sone.isLocal()) {
1518 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1521 final Post post = new PostImpl(sone, time, text);
1522 if (recipient != null) {
1523 post.setRecipient(recipient);
1525 synchronized (posts) {
1526 posts.put(post.getId(), post);
1528 eventBus.post(new NewPostFoundEvent(post));
1530 touchConfiguration();
1531 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1538 markPostKnown(post);
1540 }, "Mark " + post + " read.");
1545 * Deletes the given post.
1548 * The post to delete
1550 public void deletePost(Post post) {
1551 if (!post.getSone().isLocal()) {
1552 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1555 post.getSone().removePost(post);
1556 synchronized (posts) {
1557 posts.remove(post.getId());
1559 eventBus.post(new PostRemovedEvent(post));
1560 markPostKnown(post);
1561 touchConfiguration();
1565 * Marks the given post as known, if it is currently not a known post
1566 * (according to {@link Post#isKnown()}).
1569 * The post to mark as known
1571 public void markPostKnown(Post post) {
1572 post.setKnown(true);
1573 synchronized (knownPosts) {
1574 eventBus.post(new MarkPostKnownEvent(post));
1575 if (knownPosts.add(post.getId())) {
1576 touchConfiguration();
1579 for (PostReply reply : getReplies(post)) {
1580 markReplyKnown(reply);
1585 * Bookmarks the given post.
1588 * The post to bookmark
1590 public void bookmark(Post post) {
1591 bookmarkPost(post.getId());
1595 * Bookmarks the post with the given ID.
1598 * The ID of the post to bookmark
1600 public void bookmarkPost(String id) {
1601 synchronized (bookmarkedPosts) {
1602 bookmarkedPosts.add(id);
1607 * Removes the given post from the bookmarks.
1610 * The post to unbookmark
1612 public void unbookmark(Post post) {
1613 unbookmarkPost(post.getId());
1617 * Removes the post with the given ID from the bookmarks.
1620 * The ID of the post to unbookmark
1622 public void unbookmarkPost(String id) {
1623 synchronized (bookmarkedPosts) {
1624 bookmarkedPosts.remove(id);
1629 * Creates a new reply.
1632 * The Sone that creates the reply
1634 * The post that this reply refers to
1636 * The text of the reply
1637 * @return The created reply
1639 public PostReply createReply(Sone sone, Post post, String text) {
1640 return createReply(sone, post, System.currentTimeMillis(), text);
1644 * Creates a new reply.
1647 * The Sone that creates the reply
1649 * The post that this reply refers to
1651 * The time of the reply
1653 * The text of the reply
1654 * @return The created reply
1656 public PostReply createReply(Sone sone, Post post, long time, String text) {
1657 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1658 if (!sone.isLocal()) {
1659 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1662 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1663 synchronized (replies) {
1664 replies.put(reply.getId(), reply);
1666 synchronized (knownReplies) {
1667 eventBus.post(new NewPostReplyFoundEvent(reply));
1669 sone.addReply(reply);
1670 touchConfiguration();
1671 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1678 markReplyKnown(reply);
1680 }, "Mark " + reply + " read.");
1685 * Deletes the given reply.
1688 * The reply to delete
1690 public void deleteReply(PostReply reply) {
1691 Sone sone = reply.getSone();
1692 if (!sone.isLocal()) {
1693 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1696 synchronized (replies) {
1697 replies.remove(reply.getId());
1699 synchronized (knownReplies) {
1700 markReplyKnown(reply);
1701 knownReplies.remove(reply.getId());
1703 sone.removeReply(reply);
1704 touchConfiguration();
1708 * Marks the given reply as known, if it is currently not a known reply
1709 * (according to {@link Reply#isKnown()}).
1712 * The reply to mark as known
1714 public void markReplyKnown(PostReply reply) {
1715 reply.setKnown(true);
1716 synchronized (knownReplies) {
1717 eventBus.post(new MarkPostReplyKnownEvent(reply));
1718 if (knownReplies.add(reply.getId())) {
1719 touchConfiguration();
1725 * Creates a new top-level album for the given Sone.
1728 * The Sone to create the album for
1729 * @return The new album
1731 public Album createAlbum(Sone sone) {
1732 return createAlbum(sone, null);
1736 * Creates a new album for the given Sone.
1739 * The Sone to create the album for
1741 * The parent of the album (may be {@code null} to create a
1743 * @return The new album
1745 public Album createAlbum(Sone sone, Album parent) {
1746 Album album = new Album();
1747 synchronized (albums) {
1748 albums.put(album.getId(), album);
1750 album.setSone(sone);
1751 if (parent != null) {
1752 parent.addAlbum(album);
1754 sone.addAlbum(album);
1760 * Deletes the given album. The owner of the album has to be a local Sone,
1761 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1764 * The album to remove
1766 public void deleteAlbum(Album album) {
1767 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1768 if (!album.isEmpty()) {
1771 if (album.getParent() == null) {
1772 album.getSone().removeAlbum(album);
1774 album.getParent().removeAlbum(album);
1776 synchronized (albums) {
1777 albums.remove(album.getId());
1779 touchConfiguration();
1783 * Creates a new image.
1786 * The Sone creating the image
1788 * The album the image will be inserted into
1789 * @param temporaryImage
1790 * The temporary image to create the image from
1791 * @return The newly created image
1793 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1794 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();
1795 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1796 album.addImage(image);
1797 synchronized (images) {
1798 images.put(image.getId(), image);
1800 imageInserter.insertImage(temporaryImage, image);
1805 * Deletes the given image. This method will also delete a matching
1808 * @see #deleteTemporaryImage(TemporaryImage)
1810 * The image to delete
1812 public void deleteImage(Image image) {
1813 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1814 deleteTemporaryImage(image.getId());
1815 image.getAlbum().removeImage(image);
1816 synchronized (images) {
1817 images.remove(image.getId());
1819 touchConfiguration();
1823 * Creates a new temporary image.
1826 * The MIME type of the temporary image
1828 * The encoded data of the image
1829 * @return The temporary image
1831 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1832 TemporaryImage temporaryImage = new TemporaryImage();
1833 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1834 synchronized (temporaryImages) {
1835 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1837 return temporaryImage;
1841 * Deletes the given temporary image.
1843 * @param temporaryImage
1844 * The temporary image to delete
1846 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1847 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1848 deleteTemporaryImage(temporaryImage.getId());
1852 * Deletes the temporary image with the given ID.
1855 * The ID of the temporary image to delete
1857 public void deleteTemporaryImage(String imageId) {
1858 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1859 synchronized (temporaryImages) {
1860 temporaryImages.remove(imageId);
1862 Image image = getImage(imageId, false);
1863 if (image != null) {
1864 imageInserter.cancelImageInsert(image);
1869 * Notifies the core that the configuration, either of the core or of a
1870 * single local Sone, has changed, and that the configuration should be
1873 public void touchConfiguration() {
1874 lastConfigurationUpdate = System.currentTimeMillis();
1885 public void serviceStart() {
1886 loadConfiguration();
1887 updateChecker.start();
1888 identityManager.addIdentityListener(this);
1889 identityManager.start();
1890 webOfTrustUpdater.init();
1891 webOfTrustUpdater.start();
1898 public void serviceRun() {
1899 long lastSaved = System.currentTimeMillis();
1900 while (!shouldStop()) {
1902 long now = System.currentTimeMillis();
1903 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1904 for (Sone localSone : getLocalSones()) {
1905 saveSone(localSone);
1907 saveConfiguration();
1917 public void serviceStop() {
1918 synchronized (sones) {
1919 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1920 soneInserter.getValue().stop();
1921 saveSone(soneInserter.getKey());
1924 saveConfiguration();
1925 webOfTrustUpdater.stop();
1926 updateChecker.stop();
1927 soneDownloader.stop();
1928 identityManager.removeIdentityListener(this);
1929 identityManager.stop();
1937 * Saves the given Sone. This will persist all local settings for the given
1938 * Sone, such as the friends list and similar, private options.
1943 private synchronized void saveSone(Sone sone) {
1944 if (!sone.isLocal()) {
1945 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1948 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1949 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1953 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1955 /* save Sone into configuration. */
1956 String sonePrefix = "Sone/" + sone.getId();
1957 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1958 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1961 Profile profile = sone.getProfile();
1962 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1963 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1964 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1965 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1966 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1967 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1968 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1970 /* save profile fields. */
1971 int fieldCounter = 0;
1972 for (Field profileField : profile.getFields()) {
1973 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1974 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1975 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1977 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1980 int postCounter = 0;
1981 for (Post post : sone.getPosts()) {
1982 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1983 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1984 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1985 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1986 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1988 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1991 int replyCounter = 0;
1992 for (PostReply reply : sone.getReplies()) {
1993 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1994 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1995 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1996 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1997 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1999 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2001 /* save post likes. */
2002 int postLikeCounter = 0;
2003 for (String postId : sone.getLikedPostIds()) {
2004 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2006 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2008 /* save reply likes. */
2009 int replyLikeCounter = 0;
2010 for (String replyId : sone.getLikedReplyIds()) {
2011 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2013 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2016 int friendCounter = 0;
2017 for (String friendId : sone.getFriends()) {
2018 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2020 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2022 /* save albums. first, collect in a flat structure, top-level first. */
2023 List<Album> albums = sone.getAllAlbums();
2025 int albumCounter = 0;
2026 for (Album album : albums) {
2027 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2028 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2029 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2030 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2031 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2032 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2034 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2037 int imageCounter = 0;
2038 for (Album album : albums) {
2039 for (Image image : album.getImages()) {
2040 if (!image.isInserted()) {
2043 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2044 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2045 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2046 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2047 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2048 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2049 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2050 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2051 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2054 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2057 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2058 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2059 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2060 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2061 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2062 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2064 configuration.save();
2066 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2068 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2069 } catch (ConfigurationException ce1) {
2070 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2075 * Saves the current options.
2077 private void saveConfiguration() {
2078 synchronized (configuration) {
2079 if (storingConfiguration) {
2080 logger.log(Level.FINE, "Already storing configuration…");
2083 storingConfiguration = true;
2086 /* store the options first. */
2088 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2089 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2090 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2091 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2092 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2093 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2094 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2095 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2096 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2097 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2098 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2099 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2101 /* save known Sones. */
2102 int soneCounter = 0;
2103 synchronized (knownSones) {
2104 for (String knownSoneId : knownSones) {
2105 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2107 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2110 /* save Sone following times. */
2112 synchronized (soneFollowingTimes) {
2113 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2114 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2115 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2118 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2121 /* save known posts. */
2122 int postCounter = 0;
2123 synchronized (knownPosts) {
2124 for (String knownPostId : knownPosts) {
2125 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2127 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2130 /* save known replies. */
2131 int replyCounter = 0;
2132 synchronized (knownReplies) {
2133 for (String knownReplyId : knownReplies) {
2134 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2136 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2139 /* save bookmarked posts. */
2140 int bookmarkedPostCounter = 0;
2141 synchronized (bookmarkedPosts) {
2142 for (String bookmarkedPostId : bookmarkedPosts) {
2143 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2146 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2149 configuration.save();
2151 } catch (ConfigurationException ce1) {
2152 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2154 synchronized (configuration) {
2155 storingConfiguration = false;
2161 * Loads the configuration.
2163 @SuppressWarnings("unchecked")
2164 private void loadConfiguration() {
2165 /* create options. */
2166 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2169 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2170 SoneInserter.setInsertionDelay(newValue);
2174 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2175 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2176 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2177 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2178 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2179 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2180 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2181 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2182 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2185 @SuppressWarnings("synthetic-access")
2186 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2187 fcpInterface.setActive(newValue);
2190 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2193 @SuppressWarnings("synthetic-access")
2194 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2195 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2200 loadConfigurationValue("InsertionDelay");
2201 loadConfigurationValue("PostsPerPage");
2202 loadConfigurationValue("ImagesPerPage");
2203 loadConfigurationValue("CharactersPerPost");
2204 loadConfigurationValue("PostCutOffLength");
2205 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2206 loadConfigurationValue("PositiveTrust");
2207 loadConfigurationValue("NegativeTrust");
2208 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2209 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2210 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2212 /* load known Sones. */
2213 int soneCounter = 0;
2215 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2216 if (knownSoneId == null) {
2219 synchronized (knownSones) {
2220 knownSones.add(knownSoneId);
2224 /* load Sone following times. */
2227 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2228 if (soneId == null) {
2231 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2232 Sone followedSone = getSone(soneId);
2233 if (followedSone == null) {
2234 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2236 synchronized (soneFollowingTimes) {
2237 soneFollowingTimes.put(getSone(soneId), time);
2243 /* load known posts. */
2244 int postCounter = 0;
2246 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2247 if (knownPostId == null) {
2250 synchronized (knownPosts) {
2251 knownPosts.add(knownPostId);
2255 /* load known replies. */
2256 int replyCounter = 0;
2258 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2259 if (knownReplyId == null) {
2262 synchronized (knownReplies) {
2263 knownReplies.add(knownReplyId);
2267 /* load bookmarked posts. */
2268 int bookmarkedPostCounter = 0;
2270 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2271 if (bookmarkedPostId == null) {
2274 synchronized (bookmarkedPosts) {
2275 bookmarkedPosts.add(bookmarkedPostId);
2282 * Loads an {@link Integer} configuration value for the option with the
2283 * given name, logging validation failures.
2286 * The name of the option to load
2288 private void loadConfigurationValue(String optionName) {
2290 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2291 } catch (IllegalArgumentException iae1) {
2292 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2297 * Generate a Sone URI from the given URI and latest edition.
2300 * The URI to derive the Sone URI from
2301 * @return The derived URI
2303 private static FreenetURI getSoneUri(String uriString) {
2305 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2307 } catch (MalformedURLException mue1) {
2308 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2314 // INTERFACE IdentityListener
2321 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2322 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2323 if (ownIdentity.hasContext("Sone")) {
2324 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2325 addLocalSone(ownIdentity);
2333 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2334 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2335 trustedIdentities.remove(ownIdentity);
2342 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2343 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2344 trustedIdentities.get(ownIdentity).add(identity);
2345 addRemoteSone(identity);
2352 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2353 soneDownloaders.execute(new Runnable() {
2356 @SuppressWarnings("synthetic-access")
2358 Sone sone = getRemoteSone(identity.getId(), false);
2359 sone.setIdentity(identity);
2360 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2361 soneDownloader.addSone(sone);
2362 soneDownloader.fetchSone(sone);
2371 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2372 trustedIdentities.get(ownIdentity).remove(identity);
2373 boolean foundIdentity = false;
2374 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2375 if (trustedIdentity.getKey().equals(ownIdentity)) {
2378 if (trustedIdentity.getValue().contains(identity)) {
2379 foundIdentity = true;
2382 if (foundIdentity) {
2383 /* some local identity still trusts this identity, don’t remove. */
2386 Sone sone = getSone(identity.getId(), false);
2388 /* TODO - we don’t have the Sone anymore. should this happen? */
2391 synchronized (posts) {
2392 synchronized (knownPosts) {
2393 for (Post post : sone.getPosts()) {
2394 posts.remove(post.getId());
2395 eventBus.post(new PostRemovedEvent(post));
2399 synchronized (replies) {
2400 synchronized (knownReplies) {
2401 for (PostReply reply : sone.getReplies()) {
2402 replies.remove(reply.getId());
2403 eventBus.post(new PostReplyRemovedEvent(reply));
2407 synchronized (sones) {
2408 sones.remove(identity.getId());
2410 eventBus.post(new SoneRemovedEvent(sone));
2414 * Deletes the temporary image.
2416 * @param imageInsertFinishedEvent
2420 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2421 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2422 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2423 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2424 touchConfiguration();
2428 * Convenience interface for external classes that want to access the core’s
2431 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2433 public static class Preferences {
2435 /** The wrapped options. */
2436 private final Options options;
2439 * Creates a new preferences object wrapped around the given options.
2442 * The options to wrap
2444 public Preferences(Options options) {
2445 this.options = options;
2449 * Returns the insertion delay.
2451 * @return The insertion delay
2453 public int getInsertionDelay() {
2454 return options.getIntegerOption("InsertionDelay").get();
2458 * Validates the given insertion delay.
2460 * @param insertionDelay
2461 * The insertion delay to validate
2462 * @return {@code true} if the given insertion delay was valid,
2463 * {@code false} otherwise
2465 public boolean validateInsertionDelay(Integer insertionDelay) {
2466 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2470 * Sets the insertion delay
2472 * @param insertionDelay
2473 * The new insertion delay, or {@code null} to restore it to
2475 * @return This preferences
2477 public Preferences setInsertionDelay(Integer insertionDelay) {
2478 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2483 * Returns the number of posts to show per page.
2485 * @return The number of posts to show per page
2487 public int getPostsPerPage() {
2488 return options.getIntegerOption("PostsPerPage").get();
2492 * Validates the number of posts per page.
2494 * @param postsPerPage
2495 * The number of posts per page
2496 * @return {@code true} if the number of posts per page was valid,
2497 * {@code false} otherwise
2499 public boolean validatePostsPerPage(Integer postsPerPage) {
2500 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2504 * Sets the number of posts to show per page.
2506 * @param postsPerPage
2507 * The number of posts to show per page
2508 * @return This preferences object
2510 public Preferences setPostsPerPage(Integer postsPerPage) {
2511 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2516 * Returns the number of images to show per page.
2518 * @return The number of images to show per page
2520 public int getImagesPerPage() {
2521 return options.getIntegerOption("ImagesPerPage").get();
2525 * Validates the number of images per page.
2527 * @param imagesPerPage
2528 * The number of images per page
2529 * @return {@code true} if the number of images per page was valid,
2530 * {@code false} otherwise
2532 public boolean validateImagesPerPage(Integer imagesPerPage) {
2533 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2537 * Sets the number of images per page.
2539 * @param imagesPerPage
2540 * The number of images per page
2541 * @return This preferences object
2543 public Preferences setImagesPerPage(Integer imagesPerPage) {
2544 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2549 * Returns the number of characters per post, or <code>-1</code> if the
2550 * posts should not be cut off.
2552 * @return The numbers of characters per post
2554 public int getCharactersPerPost() {
2555 return options.getIntegerOption("CharactersPerPost").get();
2559 * Validates the number of characters per post.
2561 * @param charactersPerPost
2562 * The number of characters per post
2563 * @return {@code true} if the number of characters per post was valid,
2564 * {@code false} otherwise
2566 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2567 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2571 * Sets the number of characters per post.
2573 * @param charactersPerPost
2574 * The number of characters per post, or <code>-1</code> to
2575 * not cut off the posts
2576 * @return This preferences objects
2578 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2579 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2584 * Returns the number of characters the shortened post should have.
2586 * @return The number of characters of the snippet
2588 public int getPostCutOffLength() {
2589 return options.getIntegerOption("PostCutOffLength").get();
2593 * Validates the number of characters after which to cut off the post.
2595 * @param postCutOffLength
2596 * The number of characters of the snippet
2597 * @return {@code true} if the number of characters of the snippet is
2598 * valid, {@code false} otherwise
2600 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2601 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2605 * Sets the number of characters the shortened post should have.
2607 * @param postCutOffLength
2608 * The number of characters of the snippet
2609 * @return This preferences
2611 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2612 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2617 * Returns whether Sone requires full access to be even visible.
2619 * @return {@code true} if Sone requires full access, {@code false}
2622 public boolean isRequireFullAccess() {
2623 return options.getBooleanOption("RequireFullAccess").get();
2627 * Sets whether Sone requires full access to be even visible.
2629 * @param requireFullAccess
2630 * {@code true} if Sone requires full access, {@code false}
2633 public void setRequireFullAccess(Boolean requireFullAccess) {
2634 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2638 * Returns the positive trust.
2640 * @return The positive trust
2642 public int getPositiveTrust() {
2643 return options.getIntegerOption("PositiveTrust").get();
2647 * Validates the positive trust.
2649 * @param positiveTrust
2650 * The positive trust to validate
2651 * @return {@code true} if the positive trust was valid, {@code false}
2654 public boolean validatePositiveTrust(Integer positiveTrust) {
2655 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2659 * Sets the positive trust.
2661 * @param positiveTrust
2662 * The new positive trust, or {@code null} to restore it to
2664 * @return This preferences
2666 public Preferences setPositiveTrust(Integer positiveTrust) {
2667 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2672 * Returns the negative trust.
2674 * @return The negative trust
2676 public int getNegativeTrust() {
2677 return options.getIntegerOption("NegativeTrust").get();
2681 * Validates the negative trust.
2683 * @param negativeTrust
2684 * The negative trust to validate
2685 * @return {@code true} if the negative trust was valid, {@code false}
2688 public boolean validateNegativeTrust(Integer negativeTrust) {
2689 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2693 * Sets the negative trust.
2695 * @param negativeTrust
2696 * The negative trust, or {@code null} to restore it to the
2698 * @return The preferences
2700 public Preferences setNegativeTrust(Integer negativeTrust) {
2701 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2706 * Returns the trust comment. This is the comment that is set in the web
2707 * of trust when a trust value is assigned to an identity.
2709 * @return The trust comment
2711 public String getTrustComment() {
2712 return options.getStringOption("TrustComment").get();
2716 * Sets the trust comment.
2718 * @param trustComment
2719 * The trust comment, or {@code null} to restore it to the
2721 * @return This preferences
2723 public Preferences setTrustComment(String trustComment) {
2724 options.getStringOption("TrustComment").set(trustComment);
2729 * Returns whether the {@link FcpInterface FCP interface} is currently
2732 * @see FcpInterface#setActive(boolean)
2733 * @return {@code true} if the FCP interface is currently active,
2734 * {@code false} otherwise
2736 public boolean isFcpInterfaceActive() {
2737 return options.getBooleanOption("ActivateFcpInterface").get();
2741 * Sets whether the {@link FcpInterface FCP interface} is currently
2744 * @see FcpInterface#setActive(boolean)
2745 * @param fcpInterfaceActive
2746 * {@code true} to activate the FCP interface, {@code false}
2747 * to deactivate the FCP interface
2748 * @return This preferences object
2750 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2751 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2756 * Returns the action level for which full access to the FCP interface
2759 * @return The action level for which full access to the FCP interface
2762 public FullAccessRequired getFcpFullAccessRequired() {
2763 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2767 * Sets the action level for which full access to the FCP interface is
2770 * @param fcpFullAccessRequired
2772 * @return This preferences
2774 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2775 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);