2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
40 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
41 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
42 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
43 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
45 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
46 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
47 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
48 import net.pterodactylus.sone.core.event.PostRemovedEvent;
49 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
50 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
51 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
52 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
53 import net.pterodactylus.sone.core.event.SoneLockedEvent;
54 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
56 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.data.impl.PostImpl;
70 import net.pterodactylus.sone.fcp.FcpInterface;
71 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
72 import net.pterodactylus.sone.freenet.wot.Identity;
73 import net.pterodactylus.sone.freenet.wot.IdentityListener;
74 import net.pterodactylus.sone.freenet.wot.IdentityManager;
75 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
76 import net.pterodactylus.sone.main.SonePlugin;
77 import net.pterodactylus.util.config.Configuration;
78 import net.pterodactylus.util.config.ConfigurationException;
79 import net.pterodactylus.util.logging.Logging;
80 import net.pterodactylus.util.number.Numbers;
81 import net.pterodactylus.util.service.AbstractService;
82 import net.pterodactylus.util.thread.NamedThreadFactory;
83 import net.pterodactylus.util.thread.Ticker;
84 import net.pterodactylus.util.validation.EqualityValidator;
85 import net.pterodactylus.util.validation.IntegerRangeValidator;
86 import net.pterodactylus.util.validation.OrValidator;
87 import net.pterodactylus.util.validation.Validation;
88 import net.pterodactylus.util.version.Version;
90 import com.google.common.base.Predicate;
91 import com.google.common.collect.Collections2;
92 import com.google.common.eventbus.EventBus;
93 import com.google.inject.Inject;
95 import freenet.keys.FreenetURI;
100 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
102 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
105 private static final Logger logger = Logging.getLogger(Core.class);
107 /** The start time. */
108 private final long startupTime = System.currentTimeMillis();
111 private final Options options = new Options();
113 /** The preferences. */
114 private final Preferences preferences = new Preferences(options);
116 /** The event bus. */
117 private final EventBus eventBus;
119 /** The configuration. */
120 private Configuration configuration;
122 /** Whether we’re currently saving the configuration. */
123 private boolean storingConfiguration = false;
125 /** The identity manager. */
126 private final IdentityManager identityManager;
128 /** Interface to freenet. */
129 private final FreenetInterface freenetInterface;
131 /** The Sone downloader. */
132 private final SoneDownloader soneDownloader;
134 /** The image inserter. */
135 private final ImageInserter imageInserter;
137 /** Sone downloader thread-pool. */
138 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
140 /** The update checker. */
141 private final UpdateChecker updateChecker;
143 /** The trust updater. */
144 private final WebOfTrustUpdater webOfTrustUpdater;
146 /** The FCP interface. */
147 private volatile FcpInterface fcpInterface;
149 /** The times Sones were followed. */
150 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
152 /** Locked local Sones. */
153 /* synchronize on itself. */
154 private final Set<Sone> lockedSones = new HashSet<Sone>();
156 /** Sone inserters. */
157 /* synchronize access on this on sones. */
158 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
160 /** Sone rescuers. */
161 /* synchronize access on this on sones. */
162 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
165 /* synchronize access on this on itself. */
166 private final Map<String, Sone> sones = new HashMap<String, Sone>();
168 /** All known Sones. */
169 private final Set<String> knownSones = new HashSet<String>();
172 private final Map<String, Post> posts = new HashMap<String, Post>();
174 /** All known posts. */
175 private final Set<String> knownPosts = new HashSet<String>();
178 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
180 /** All known replies. */
181 private final Set<String> knownReplies = new HashSet<String>();
183 /** All bookmarked posts. */
184 /* synchronize access on itself. */
185 private final Set<String> bookmarkedPosts = new HashSet<String>();
187 /** Trusted identities, sorted by own identities. */
188 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
190 /** All known albums. */
191 private final Map<String, Album> albums = new HashMap<String, Album>();
193 /** All known images. */
194 private final Map<String, Image> images = new HashMap<String, Image>();
196 /** All temporary images. */
197 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199 /** Ticker for threads that mark own elements as known. */
200 private final Ticker localElementTicker = new Ticker();
202 /** The time the configuration was last touched. */
203 private volatile long lastConfigurationUpdate;
206 * Creates a new core.
208 * @param configuration
209 * The configuration of the core
210 * @param freenetInterface
211 * The freenet interface
212 * @param identityManager
213 * The identity manager
214 * @param webOfTrustUpdater
215 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226 this.imageInserter = new ImageInserter(this, freenetInterface);
227 this.updateChecker = new UpdateChecker(freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
237 * Returns the time Sone was started.
239 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
241 public long getStartupTime() {
246 * Sets the configuration to use. This will automatically save the current
247 * configuration to the given configuration.
249 * @param configuration
250 * The new configuration to use
252 public void setConfiguration(Configuration configuration) {
253 this.configuration = configuration;
254 touchConfiguration();
258 * Returns the options used by the core.
260 * @return The options of the core
262 public Preferences getPreferences() {
267 * Returns the identity manager used by the core.
269 * @return The identity manager
271 public IdentityManager getIdentityManager() {
272 return identityManager;
276 * Returns the update checker.
278 * @return The update checker
280 public UpdateChecker getUpdateChecker() {
281 return updateChecker;
285 * Sets the FCP interface to use.
287 * @param fcpInterface
288 * The FCP interface to use
290 public void setFcpInterface(FcpInterface fcpInterface) {
291 this.fcpInterface = fcpInterface;
295 * Returns the Sone rescuer for the given local Sone.
298 * The local Sone to get the rescuer for
299 * @return The Sone rescuer for the given Sone
301 public SoneRescuer getSoneRescuer(Sone sone) {
302 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
303 synchronized (sones) {
304 SoneRescuer soneRescuer = soneRescuers.get(sone);
305 if (soneRescuer == null) {
306 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
307 soneRescuers.put(sone, soneRescuer);
315 * Returns whether the given Sone is currently locked.
319 * @return {@code true} if the Sone is locked, {@code false} if it is not
321 public boolean isLocked(Sone sone) {
322 synchronized (lockedSones) {
323 return lockedSones.contains(sone);
328 * Returns all Sones, remote and local.
332 public Set<Sone> getSones() {
333 return new HashSet<Sone>(sones.values());
337 * Returns the Sone with the given ID, regardless whether it’s local or
341 * The ID of the Sone to get
342 * @return The Sone with the given ID, or {@code null} if there is no such
345 public Sone getSone(String id) {
346 return getSone(id, true);
350 * Returns the Sone with the given ID, regardless whether it’s local or
354 * The ID of the Sone to get
356 * {@code true} to create a new Sone if none exists,
357 * {@code false} to return {@code null} if a Sone with the given
359 * @return The Sone with the given ID, or {@code null} if there is no such
363 public Sone getSone(String id, boolean create) {
364 synchronized (sones) {
365 if (!sones.containsKey(id)) {
366 Sone sone = new Sone(id, false);
369 return sones.get(id);
374 * Checks whether the core knows a Sone with the given ID.
378 * @return {@code true} if there is a Sone with the given ID, {@code false}
381 public boolean hasSone(String id) {
382 synchronized (sones) {
383 return sones.containsKey(id);
388 * Returns all local Sones.
390 * @return All local Sones
392 public Collection<Sone> getLocalSones() {
393 synchronized (sones) {
394 return Collections2.filter(sones.values(), new Predicate<Sone>() {
397 public boolean apply(Sone sone) {
398 return sone.isLocal();
405 * Returns the local Sone with the given ID, optionally creating a new Sone.
410 * {@code true} to create a new Sone if none exists,
411 * {@code false} to return null if none exists
412 * @return The Sone with the given ID, or {@code null}
414 public Sone getLocalSone(String id, boolean create) {
415 synchronized (sones) {
416 Sone sone = sones.get(id);
417 if ((sone == null) && create) {
418 sone = new Sone(id, true);
421 if ((sone != null) && !sone.isLocal()) {
422 sone = new Sone(id, true);
430 * Returns all remote Sones.
432 * @return All remote Sones
434 public Collection<Sone> getRemoteSones() {
435 synchronized (sones) {
436 return Collections2.filter(sones.values(), new Predicate<Sone>() {
439 public boolean apply(Sone sone) {
440 return !sone.isLocal();
447 * Returns the remote Sone with the given ID.
450 * The ID of the remote Sone to get
452 * {@code true} to always create a Sone, {@code false} to return
453 * {@code null} if no Sone with the given ID exists
454 * @return The Sone with the given ID
456 public Sone getRemoteSone(String id, boolean create) {
457 synchronized (sones) {
458 Sone sone = sones.get(id);
459 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
460 sone = new Sone(id, false);
468 * Returns whether the given Sone has been modified.
471 * The Sone to check for modifications
472 * @return {@code true} if a modification has been detected in the Sone,
473 * {@code false} otherwise
475 public boolean isModifiedSone(Sone sone) {
476 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
480 * Returns the time when the given was first followed by any local Sone.
483 * The Sone to get the time for
484 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
485 * been followed, or {@link Long#MAX_VALUE}
487 public long getSoneFollowingTime(Sone sone) {
488 synchronized (soneFollowingTimes) {
489 if (soneFollowingTimes.containsKey(sone)) {
490 return soneFollowingTimes.get(sone);
492 return Long.MAX_VALUE;
497 * Returns whether the target Sone is trusted by the origin Sone.
503 * @return {@code true} if the target Sone is trusted by the origin Sone
505 public boolean isSoneTrusted(Sone origin, Sone target) {
506 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
507 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
511 * Returns the post with the given ID.
514 * The ID of the post to get
515 * @return The post with the given ID, or a new post with the given ID
517 public Post getPost(String postId) {
518 return getPost(postId, true);
522 * Returns the post with the given ID, optionally creating a new post.
525 * The ID of the post to get
527 * {@code true} it create a new post if no post with the given ID
528 * exists, {@code false} to return {@code null}
529 * @return The post, or {@code null} if there is no such post
532 public Post getPost(String postId, boolean create) {
533 synchronized (posts) {
534 Post post = posts.get(postId);
535 if ((post == null) && create) {
536 post = new PostImpl(postId);
537 posts.put(postId, post);
544 * Returns all posts that have the given Sone as recipient.
546 * @see Post#getRecipient()
548 * The recipient of the posts
549 * @return All posts that have the given Sone as recipient
551 public Set<Post> getDirectedPosts(Sone recipient) {
552 Validation.begin().isNotNull("Recipient", recipient).check();
553 Set<Post> directedPosts = new HashSet<Post>();
554 synchronized (posts) {
555 for (Post post : posts.values()) {
556 if (recipient.equals(post.getRecipient())) {
557 directedPosts.add(post);
561 return directedPosts;
565 * Returns the reply with the given ID. If there is no reply with the given
566 * ID yet, a new one is created, unless {@code create} is false in which
567 * case {@code null} is returned.
570 * The ID of the reply to get
572 * {@code true} to always return a {@link Reply}, {@code false}
573 * to return {@code null} if no reply can be found
574 * @return The reply, or {@code null} if there is no such reply
576 public PostReply getPostReply(String replyId, boolean create) {
577 synchronized (replies) {
578 PostReply reply = replies.get(replyId);
579 if (create && (reply == null)) {
580 reply = new PostReply(replyId);
581 replies.put(replyId, reply);
588 * Returns all replies for the given post, order ascending by time.
591 * The post to get all replies for
592 * @return All replies for the given post
594 public List<PostReply> getReplies(Post post) {
595 Set<Sone> sones = getSones();
596 List<PostReply> replies = new ArrayList<PostReply>();
597 for (Sone sone : sones) {
598 for (PostReply reply : sone.getReplies()) {
599 if (reply.getPost().equals(post)) {
604 Collections.sort(replies, Reply.TIME_COMPARATOR);
609 * Returns all Sones that have liked the given post.
612 * The post to get the liking Sones for
613 * @return The Sones that like the given post
615 public Set<Sone> getLikes(Post post) {
616 Set<Sone> sones = new HashSet<Sone>();
617 for (Sone sone : getSones()) {
618 if (sone.getLikedPostIds().contains(post.getId())) {
626 * Returns all Sones that have liked the given reply.
629 * The reply to get the liking Sones for
630 * @return The Sones that like the given reply
632 public Set<Sone> getLikes(PostReply reply) {
633 Set<Sone> sones = new HashSet<Sone>();
634 for (Sone sone : getSones()) {
635 if (sone.getLikedReplyIds().contains(reply.getId())) {
643 * Returns whether the given post is bookmarked.
647 * @return {@code true} if the given post is bookmarked, {@code false}
650 public boolean isBookmarked(Post post) {
651 return isPostBookmarked(post.getId());
655 * Returns whether the post with the given ID is bookmarked.
658 * The ID of the post to check
659 * @return {@code true} if the post with the given ID is bookmarked,
660 * {@code false} otherwise
662 public boolean isPostBookmarked(String id) {
663 synchronized (bookmarkedPosts) {
664 return bookmarkedPosts.contains(id);
669 * Returns all currently known bookmarked posts.
671 * @return All bookmarked posts
673 public Set<Post> getBookmarkedPosts() {
674 Set<Post> posts = new HashSet<Post>();
675 synchronized (bookmarkedPosts) {
676 for (String bookmarkedPostId : bookmarkedPosts) {
677 Post post = getPost(bookmarkedPostId, false);
687 * Returns the album with the given ID, creating a new album if no album
688 * with the given ID can be found.
691 * The ID of the album
692 * @return The album with the given ID
694 public Album getAlbum(String albumId) {
695 return getAlbum(albumId, true);
699 * Returns the album with the given ID, optionally creating a new album if
700 * an album with the given ID can not be found.
703 * The ID of the album
705 * {@code true} to create a new album if none exists for the
707 * @return The album with the given ID, or {@code null} if no album with the
708 * given ID exists and {@code create} is {@code false}
710 public Album getAlbum(String albumId, boolean create) {
711 synchronized (albums) {
712 Album album = albums.get(albumId);
713 if (create && (album == null)) {
714 album = new Album(albumId);
715 albums.put(albumId, album);
722 * Returns the image with the given ID, creating it if necessary.
725 * The ID of the image
726 * @return The image with the given ID
728 public Image getImage(String imageId) {
729 return getImage(imageId, true);
733 * Returns the image with the given ID, optionally creating it if it does
737 * The ID of the image
739 * {@code true} to create an image if none exists with the given
741 * @return The image with the given ID, or {@code null} if none exists and
744 public Image getImage(String imageId, boolean create) {
745 synchronized (images) {
746 Image image = images.get(imageId);
747 if (create && (image == null)) {
748 image = new Image(imageId);
749 images.put(imageId, image);
756 * Returns the temporary image with the given ID.
759 * The ID of the temporary image
760 * @return The temporary image, or {@code null} if there is no temporary
761 * image with the given ID
763 public TemporaryImage getTemporaryImage(String imageId) {
764 synchronized (temporaryImages) {
765 return temporaryImages.get(imageId);
774 * Locks the given Sone. A locked Sone will not be inserted by
775 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
781 public void lockSone(Sone sone) {
782 synchronized (lockedSones) {
783 if (lockedSones.add(sone)) {
784 eventBus.post(new SoneLockedEvent(sone));
790 * Unlocks the given Sone.
792 * @see #lockSone(Sone)
796 public void unlockSone(Sone sone) {
797 synchronized (lockedSones) {
798 if (lockedSones.remove(sone)) {
799 eventBus.post(new SoneUnlockedEvent(sone));
805 * Adds a local Sone from the given own identity.
808 * The own identity to create a Sone from
809 * @return The added (or already existing) Sone
811 public Sone addLocalSone(OwnIdentity ownIdentity) {
812 if (ownIdentity == null) {
813 logger.log(Level.WARNING, "Given OwnIdentity is null!");
816 synchronized (sones) {
819 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
820 } catch (MalformedURLException mue1) {
821 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
824 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
825 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
827 /* TODO - load posts ’n stuff */
828 sones.put(ownIdentity.getId(), sone);
829 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
830 soneInserter.addSoneInsertListener(this);
831 soneInserters.put(sone, soneInserter);
832 sone.setStatus(SoneStatus.idle);
834 soneInserter.start();
840 * Creates a new Sone for the given own identity.
843 * The own identity to create a Sone for
844 * @return The created Sone
846 public Sone createSone(OwnIdentity ownIdentity) {
847 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
848 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
851 Sone sone = addLocalSone(ownIdentity);
852 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
853 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
854 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
855 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
856 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
857 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
859 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
860 touchConfiguration();
865 * Adds the Sone of the given identity.
868 * The identity whose Sone to add
869 * @return The added or already existing Sone
871 public Sone addRemoteSone(Identity identity) {
872 if (identity == null) {
873 logger.log(Level.WARNING, "Given Identity is null!");
876 synchronized (sones) {
877 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
878 boolean newSone = sone.getRequestUri() == null;
879 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
880 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
882 synchronized (knownSones) {
883 newSone = !knownSones.contains(sone.getId());
885 sone.setKnown(!newSone);
887 eventBus.post(new NewSoneFoundEvent(sone));
888 for (Sone localSone : getLocalSones()) {
889 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
890 followSone(localSone, sone);
895 soneDownloader.addSone(sone);
896 soneDownloaders.execute(new Runnable() {
899 @SuppressWarnings("synthetic-access")
901 soneDownloader.fetchSone(sone, sone.getRequestUri());
910 * Lets the given local Sone follow the Sone with the given ID.
913 * The local Sone that should follow another Sone
915 * The ID of the Sone to follow
917 public void followSone(Sone sone, String soneId) {
918 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
919 Sone followedSone = getSone(soneId, true);
920 if (followedSone == null) {
921 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
924 followSone(sone, getSone(soneId));
928 * Lets the given local Sone follow the other given Sone. If the given Sone
929 * was not followed by any local Sone before, this will mark all elements of
930 * the followed Sone as read that have been created before the current
934 * The local Sone that should follow the other Sone
935 * @param followedSone
936 * The Sone that should be followed
938 public void followSone(Sone sone, Sone followedSone) {
939 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
940 sone.addFriend(followedSone.getId());
941 synchronized (soneFollowingTimes) {
942 if (!soneFollowingTimes.containsKey(followedSone)) {
943 long now = System.currentTimeMillis();
944 soneFollowingTimes.put(followedSone, now);
945 for (Post post : followedSone.getPosts()) {
946 if (post.getTime() < now) {
950 for (PostReply reply : followedSone.getReplies()) {
951 if (reply.getTime() < now) {
952 markReplyKnown(reply);
957 touchConfiguration();
961 * Lets the given local Sone unfollow the Sone with the given ID.
964 * The local Sone that should unfollow another Sone
966 * The ID of the Sone being unfollowed
968 public void unfollowSone(Sone sone, String soneId) {
969 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
970 unfollowSone(sone, getSone(soneId, false));
974 * Lets the given local Sone unfollow the other given Sone. If the given
975 * local Sone is the last local Sone that followed the given Sone, its
976 * following time will be removed.
979 * The local Sone that should unfollow another Sone
980 * @param unfollowedSone
981 * The Sone being unfollowed
983 public void unfollowSone(Sone sone, Sone unfollowedSone) {
984 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
985 sone.removeFriend(unfollowedSone.getId());
986 boolean unfollowedSoneStillFollowed = false;
987 for (Sone localSone : getLocalSones()) {
988 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
990 if (!unfollowedSoneStillFollowed) {
991 synchronized (soneFollowingTimes) {
992 soneFollowingTimes.remove(unfollowedSone);
995 touchConfiguration();
999 * Sets the trust value of the given origin Sone for the target Sone.
1006 * The trust value (from {@code -100} to {@code 100})
1008 public void setTrust(Sone origin, Sone target, int trustValue) {
1009 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();
1010 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1014 * Removes any trust assignment for the given target Sone.
1021 public void removeTrust(Sone origin, Sone target) {
1022 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1023 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1027 * Assigns the configured positive trust value for the given target.
1034 public void trustSone(Sone origin, Sone target) {
1035 setTrust(origin, target, preferences.getPositiveTrust());
1039 * Assigns the configured negative trust value for the given target.
1046 public void distrustSone(Sone origin, Sone target) {
1047 setTrust(origin, target, preferences.getNegativeTrust());
1051 * Removes the trust assignment for the given target.
1058 public void untrustSone(Sone origin, Sone target) {
1059 removeTrust(origin, target);
1063 * Updates the stored Sone with the given Sone.
1068 public void updateSone(Sone sone) {
1069 updateSone(sone, false);
1073 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1074 * {@code true}, an older Sone than the current Sone can be given to restore
1078 * The Sone to update
1079 * @param soneRescueMode
1080 * {@code true} if the stored Sone should be updated regardless
1081 * of the age of the given Sone
1083 public void updateSone(Sone sone, boolean soneRescueMode) {
1084 if (hasSone(sone.getId())) {
1085 Sone storedSone = getSone(sone.getId());
1086 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1087 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1090 synchronized (posts) {
1091 if (!soneRescueMode) {
1092 for (Post post : storedSone.getPosts()) {
1093 posts.remove(post.getId());
1094 if (!sone.getPosts().contains(post)) {
1095 eventBus.post(new PostRemovedEvent(post));
1099 List<Post> storedPosts = storedSone.getPosts();
1100 synchronized (knownPosts) {
1101 for (Post post : sone.getPosts()) {
1102 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1103 if (!storedPosts.contains(post)) {
1104 if (post.getTime() < getSoneFollowingTime(sone)) {
1105 knownPosts.add(post.getId());
1106 post.setKnown(true);
1107 } else if (!knownPosts.contains(post.getId())) {
1108 eventBus.post(new NewPostFoundEvent(post));
1111 posts.put(post.getId(), post);
1115 synchronized (replies) {
1116 if (!soneRescueMode) {
1117 for (PostReply reply : storedSone.getReplies()) {
1118 replies.remove(reply.getId());
1119 if (!sone.getReplies().contains(reply)) {
1120 eventBus.post(new PostReplyRemovedEvent(reply));
1124 Set<PostReply> storedReplies = storedSone.getReplies();
1125 synchronized (knownReplies) {
1126 for (PostReply reply : sone.getReplies()) {
1127 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1128 if (!storedReplies.contains(reply)) {
1129 if (reply.getTime() < getSoneFollowingTime(sone)) {
1130 knownReplies.add(reply.getId());
1131 reply.setKnown(true);
1132 } else if (!knownReplies.contains(reply.getId())) {
1133 eventBus.post(new NewPostReplyFoundEvent(reply));
1136 replies.put(reply.getId(), reply);
1140 synchronized (albums) {
1141 synchronized (images) {
1142 for (Album album : storedSone.getAlbums()) {
1143 albums.remove(album.getId());
1144 for (Image image : album.getImages()) {
1145 images.remove(image.getId());
1148 for (Album album : sone.getAlbums()) {
1149 albums.put(album.getId(), album);
1150 for (Image image : album.getImages()) {
1151 images.put(image.getId(), image);
1156 synchronized (storedSone) {
1157 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1158 storedSone.setTime(sone.getTime());
1160 storedSone.setClient(sone.getClient());
1161 storedSone.setProfile(sone.getProfile());
1162 if (soneRescueMode) {
1163 for (Post post : sone.getPosts()) {
1164 storedSone.addPost(post);
1166 for (PostReply reply : sone.getReplies()) {
1167 storedSone.addReply(reply);
1169 for (String likedPostId : sone.getLikedPostIds()) {
1170 storedSone.addLikedPostId(likedPostId);
1172 for (String likedReplyId : sone.getLikedReplyIds()) {
1173 storedSone.addLikedReplyId(likedReplyId);
1175 for (Album album : sone.getAlbums()) {
1176 storedSone.addAlbum(album);
1179 storedSone.setPosts(sone.getPosts());
1180 storedSone.setReplies(sone.getReplies());
1181 storedSone.setLikePostIds(sone.getLikedPostIds());
1182 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1183 storedSone.setAlbums(sone.getAlbums());
1185 storedSone.setLatestEdition(sone.getLatestEdition());
1191 * Deletes the given Sone. This will remove the Sone from the
1192 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1193 * remove the context from its identity.
1196 * The Sone to delete
1198 public void deleteSone(Sone sone) {
1199 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1200 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1203 synchronized (sones) {
1204 if (!getLocalSones().contains(sone)) {
1205 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1208 sones.remove(sone.getId());
1209 SoneInserter soneInserter = soneInserters.remove(sone);
1210 soneInserter.removeSoneInsertListener(this);
1211 soneInserter.stop();
1213 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1214 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1216 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1217 } catch (ConfigurationException ce1) {
1218 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1223 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1224 * known} before, a {@link MarkSoneKnownEvent} is fired.
1227 * The Sone to mark as known
1229 public void markSoneKnown(Sone sone) {
1230 if (!sone.isKnown()) {
1231 sone.setKnown(true);
1232 synchronized (knownSones) {
1233 knownSones.add(sone.getId());
1235 eventBus.post(new MarkSoneKnownEvent(sone));
1236 touchConfiguration();
1241 * Loads and updates the given Sone from the configuration. If any error is
1242 * encountered, loading is aborted and the given Sone is not changed.
1245 * The Sone to load and update
1247 public void loadSone(Sone sone) {
1248 if (!sone.isLocal()) {
1249 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1253 /* initialize options. */
1254 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1255 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1256 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1257 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1258 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1259 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1262 String sonePrefix = "Sone/" + sone.getId();
1263 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1264 if (soneTime == null) {
1265 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1268 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1271 Profile profile = new Profile(sone);
1272 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1273 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1274 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1275 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1276 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1277 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1279 /* load profile fields. */
1281 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1282 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1283 if (fieldName == null) {
1286 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1287 profile.addField(fieldName).setValue(fieldValue);
1291 Set<Post> posts = new HashSet<Post>();
1293 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1294 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1295 if (postId == null) {
1298 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1299 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1300 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1301 if ((postTime == 0) || (postText == null)) {
1302 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1305 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1306 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1307 post.setRecipient(getSone(postRecipientId));
1313 Set<PostReply> replies = new HashSet<PostReply>();
1315 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1316 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1317 if (replyId == null) {
1320 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1321 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1322 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1323 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1324 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1327 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1330 /* load post likes. */
1331 Set<String> likedPostIds = new HashSet<String>();
1333 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1334 if (likedPostId == null) {
1337 likedPostIds.add(likedPostId);
1340 /* load reply likes. */
1341 Set<String> likedReplyIds = new HashSet<String>();
1343 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1344 if (likedReplyId == null) {
1347 likedReplyIds.add(likedReplyId);
1351 Set<String> friends = new HashSet<String>();
1353 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1354 if (friendId == null) {
1357 friends.add(friendId);
1361 List<Album> topLevelAlbums = new ArrayList<Album>();
1362 int albumCounter = 0;
1364 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1365 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1366 if (albumId == null) {
1369 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1370 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1371 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1372 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1373 if ((albumTitle == null) || (albumDescription == null)) {
1374 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1377 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1378 if (albumParentId != null) {
1379 Album parentAlbum = getAlbum(albumParentId, false);
1380 if (parentAlbum == null) {
1381 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1384 parentAlbum.addAlbum(album);
1386 if (!topLevelAlbums.contains(album)) {
1387 topLevelAlbums.add(album);
1393 int imageCounter = 0;
1395 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1396 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1397 if (imageId == null) {
1400 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1401 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1402 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1403 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1404 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1405 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1406 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1407 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1408 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1411 Album album = getAlbum(albumId, false);
1412 if (album == null) {
1413 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1416 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1417 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1418 album.addImage(image);
1422 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1423 if (avatarId != null) {
1424 profile.setAvatar(getImage(avatarId, false));
1428 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1429 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1430 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1431 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1432 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1433 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1435 /* if we’re still here, Sone was loaded successfully. */
1436 synchronized (sone) {
1437 sone.setTime(soneTime);
1438 sone.setProfile(profile);
1439 sone.setPosts(posts);
1440 sone.setReplies(replies);
1441 sone.setLikePostIds(likedPostIds);
1442 sone.setLikeReplyIds(likedReplyIds);
1443 for (String friendId : friends) {
1444 followSone(sone, friendId);
1446 sone.setAlbums(topLevelAlbums);
1447 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1449 synchronized (knownSones) {
1450 for (String friend : friends) {
1451 knownSones.add(friend);
1454 synchronized (knownPosts) {
1455 for (Post post : posts) {
1456 knownPosts.add(post.getId());
1459 synchronized (knownReplies) {
1460 for (PostReply reply : replies) {
1461 knownReplies.add(reply.getId());
1467 * Creates a new post.
1470 * The Sone that creates the post
1472 * The text of the post
1473 * @return The created post
1475 public Post createPost(Sone sone, String text) {
1476 return createPost(sone, System.currentTimeMillis(), text);
1480 * Creates a new post.
1483 * The Sone that creates the post
1485 * The time of the post
1487 * The text of the post
1488 * @return The created post
1490 public Post createPost(Sone sone, long time, String text) {
1491 return createPost(sone, null, time, text);
1495 * Creates a new post.
1498 * The Sone that creates the post
1500 * The recipient Sone, or {@code null} if this post does not have
1503 * The text of the post
1504 * @return The created post
1506 public Post createPost(Sone sone, Sone recipient, String text) {
1507 return createPost(sone, recipient, System.currentTimeMillis(), text);
1511 * Creates a new post.
1514 * The Sone that creates the post
1516 * The recipient Sone, or {@code null} if this post does not have
1519 * The time of the post
1521 * The text of the post
1522 * @return The created post
1524 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1525 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1526 if (!sone.isLocal()) {
1527 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1530 final Post post = new PostImpl(sone, time, text);
1531 if (recipient != null) {
1532 post.setRecipient(recipient);
1534 synchronized (posts) {
1535 posts.put(post.getId(), post);
1537 eventBus.post(new NewPostFoundEvent(post));
1539 touchConfiguration();
1540 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1547 markPostKnown(post);
1549 }, "Mark " + post + " read.");
1554 * Deletes the given post.
1557 * The post to delete
1559 public void deletePost(Post post) {
1560 if (!post.getSone().isLocal()) {
1561 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1564 post.getSone().removePost(post);
1565 synchronized (posts) {
1566 posts.remove(post.getId());
1568 eventBus.post(new PostRemovedEvent(post));
1569 markPostKnown(post);
1570 touchConfiguration();
1574 * Marks the given post as known, if it is currently not a known post
1575 * (according to {@link Post#isKnown()}).
1578 * The post to mark as known
1580 public void markPostKnown(Post post) {
1581 post.setKnown(true);
1582 synchronized (knownPosts) {
1583 eventBus.post(new MarkPostKnownEvent(post));
1584 if (knownPosts.add(post.getId())) {
1585 touchConfiguration();
1588 for (PostReply reply : getReplies(post)) {
1589 markReplyKnown(reply);
1594 * Bookmarks the given post.
1597 * The post to bookmark
1599 public void bookmark(Post post) {
1600 bookmarkPost(post.getId());
1604 * Bookmarks the post with the given ID.
1607 * The ID of the post to bookmark
1609 public void bookmarkPost(String id) {
1610 synchronized (bookmarkedPosts) {
1611 bookmarkedPosts.add(id);
1616 * Removes the given post from the bookmarks.
1619 * The post to unbookmark
1621 public void unbookmark(Post post) {
1622 unbookmarkPost(post.getId());
1626 * Removes the post with the given ID from the bookmarks.
1629 * The ID of the post to unbookmark
1631 public void unbookmarkPost(String id) {
1632 synchronized (bookmarkedPosts) {
1633 bookmarkedPosts.remove(id);
1638 * Creates a new reply.
1641 * The Sone that creates the reply
1643 * The post that this reply refers to
1645 * The text of the reply
1646 * @return The created reply
1648 public PostReply createReply(Sone sone, Post post, String text) {
1649 return createReply(sone, post, System.currentTimeMillis(), text);
1653 * Creates a new reply.
1656 * The Sone that creates the reply
1658 * The post that this reply refers to
1660 * The time of the reply
1662 * The text of the reply
1663 * @return The created reply
1665 public PostReply createReply(Sone sone, Post post, long time, String text) {
1666 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1667 if (!sone.isLocal()) {
1668 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1671 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1672 synchronized (replies) {
1673 replies.put(reply.getId(), reply);
1675 synchronized (knownReplies) {
1676 eventBus.post(new NewPostReplyFoundEvent(reply));
1678 sone.addReply(reply);
1679 touchConfiguration();
1680 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1687 markReplyKnown(reply);
1689 }, "Mark " + reply + " read.");
1694 * Deletes the given reply.
1697 * The reply to delete
1699 public void deleteReply(PostReply reply) {
1700 Sone sone = reply.getSone();
1701 if (!sone.isLocal()) {
1702 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1705 synchronized (replies) {
1706 replies.remove(reply.getId());
1708 synchronized (knownReplies) {
1709 markReplyKnown(reply);
1710 knownReplies.remove(reply.getId());
1712 sone.removeReply(reply);
1713 touchConfiguration();
1717 * Marks the given reply as known, if it is currently not a known reply
1718 * (according to {@link Reply#isKnown()}).
1721 * The reply to mark as known
1723 public void markReplyKnown(PostReply reply) {
1724 reply.setKnown(true);
1725 synchronized (knownReplies) {
1726 eventBus.post(new MarkPostReplyKnownEvent(reply));
1727 if (knownReplies.add(reply.getId())) {
1728 touchConfiguration();
1734 * Creates a new top-level album for the given Sone.
1737 * The Sone to create the album for
1738 * @return The new album
1740 public Album createAlbum(Sone sone) {
1741 return createAlbum(sone, null);
1745 * Creates a new album for the given Sone.
1748 * The Sone to create the album for
1750 * The parent of the album (may be {@code null} to create a
1752 * @return The new album
1754 public Album createAlbum(Sone sone, Album parent) {
1755 Album album = new Album();
1756 synchronized (albums) {
1757 albums.put(album.getId(), album);
1759 album.setSone(sone);
1760 if (parent != null) {
1761 parent.addAlbum(album);
1763 sone.addAlbum(album);
1769 * Deletes the given album. The owner of the album has to be a local Sone,
1770 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1773 * The album to remove
1775 public void deleteAlbum(Album album) {
1776 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1777 if (!album.isEmpty()) {
1780 if (album.getParent() == null) {
1781 album.getSone().removeAlbum(album);
1783 album.getParent().removeAlbum(album);
1785 synchronized (albums) {
1786 albums.remove(album.getId());
1788 touchConfiguration();
1792 * Creates a new image.
1795 * The Sone creating the image
1797 * The album the image will be inserted into
1798 * @param temporaryImage
1799 * The temporary image to create the image from
1800 * @return The newly created image
1802 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1803 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();
1804 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1805 album.addImage(image);
1806 synchronized (images) {
1807 images.put(image.getId(), image);
1809 imageInserter.insertImage(temporaryImage, image);
1814 * Deletes the given image. This method will also delete a matching
1817 * @see #deleteTemporaryImage(TemporaryImage)
1819 * The image to delete
1821 public void deleteImage(Image image) {
1822 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1823 deleteTemporaryImage(image.getId());
1824 image.getAlbum().removeImage(image);
1825 synchronized (images) {
1826 images.remove(image.getId());
1828 touchConfiguration();
1832 * Creates a new temporary image.
1835 * The MIME type of the temporary image
1837 * The encoded data of the image
1838 * @return The temporary image
1840 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1841 TemporaryImage temporaryImage = new TemporaryImage();
1842 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1843 synchronized (temporaryImages) {
1844 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1846 return temporaryImage;
1850 * Deletes the given temporary image.
1852 * @param temporaryImage
1853 * The temporary image to delete
1855 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1856 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1857 deleteTemporaryImage(temporaryImage.getId());
1861 * Deletes the temporary image with the given ID.
1864 * The ID of the temporary image to delete
1866 public void deleteTemporaryImage(String imageId) {
1867 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1868 synchronized (temporaryImages) {
1869 temporaryImages.remove(imageId);
1871 Image image = getImage(imageId, false);
1872 if (image != null) {
1873 imageInserter.cancelImageInsert(image);
1878 * Notifies the core that the configuration, either of the core or of a
1879 * single local Sone, has changed, and that the configuration should be
1882 public void touchConfiguration() {
1883 lastConfigurationUpdate = System.currentTimeMillis();
1894 public void serviceStart() {
1895 loadConfiguration();
1896 updateChecker.addUpdateListener(this);
1897 updateChecker.start();
1898 identityManager.addIdentityListener(this);
1899 identityManager.start();
1900 webOfTrustUpdater.init();
1901 webOfTrustUpdater.start();
1908 public void serviceRun() {
1909 long lastSaved = System.currentTimeMillis();
1910 while (!shouldStop()) {
1912 long now = System.currentTimeMillis();
1913 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1914 for (Sone localSone : getLocalSones()) {
1915 saveSone(localSone);
1917 saveConfiguration();
1927 public void serviceStop() {
1928 synchronized (sones) {
1929 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1930 soneInserter.getValue().removeSoneInsertListener(this);
1931 soneInserter.getValue().stop();
1932 saveSone(soneInserter.getKey());
1935 saveConfiguration();
1936 webOfTrustUpdater.stop();
1937 updateChecker.stop();
1938 updateChecker.removeUpdateListener(this);
1939 soneDownloader.stop();
1940 identityManager.removeIdentityListener(this);
1941 identityManager.stop();
1949 * Saves the given Sone. This will persist all local settings for the given
1950 * Sone, such as the friends list and similar, private options.
1955 private synchronized void saveSone(Sone sone) {
1956 if (!sone.isLocal()) {
1957 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1960 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1961 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1965 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1967 /* save Sone into configuration. */
1968 String sonePrefix = "Sone/" + sone.getId();
1969 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1970 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1973 Profile profile = sone.getProfile();
1974 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1975 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1976 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1977 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1978 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1979 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1980 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1982 /* save profile fields. */
1983 int fieldCounter = 0;
1984 for (Field profileField : profile.getFields()) {
1985 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1986 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1987 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1989 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1992 int postCounter = 0;
1993 for (Post post : sone.getPosts()) {
1994 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1995 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1996 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1997 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1998 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2000 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2003 int replyCounter = 0;
2004 for (PostReply reply : sone.getReplies()) {
2005 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2006 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2007 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2008 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2009 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2011 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2013 /* save post likes. */
2014 int postLikeCounter = 0;
2015 for (String postId : sone.getLikedPostIds()) {
2016 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2018 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2020 /* save reply likes. */
2021 int replyLikeCounter = 0;
2022 for (String replyId : sone.getLikedReplyIds()) {
2023 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2025 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2028 int friendCounter = 0;
2029 for (String friendId : sone.getFriends()) {
2030 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2032 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2034 /* save albums. first, collect in a flat structure, top-level first. */
2035 List<Album> albums = sone.getAllAlbums();
2037 int albumCounter = 0;
2038 for (Album album : albums) {
2039 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2040 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2041 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2042 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2043 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2044 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2046 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2049 int imageCounter = 0;
2050 for (Album album : albums) {
2051 for (Image image : album.getImages()) {
2052 if (!image.isInserted()) {
2055 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2056 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2057 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2058 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2059 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2060 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2061 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2062 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2063 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2066 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2069 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2070 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2071 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2072 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2073 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2074 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2076 configuration.save();
2078 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2080 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2081 } catch (ConfigurationException ce1) {
2082 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2087 * Saves the current options.
2089 private void saveConfiguration() {
2090 synchronized (configuration) {
2091 if (storingConfiguration) {
2092 logger.log(Level.FINE, "Already storing configuration…");
2095 storingConfiguration = true;
2098 /* store the options first. */
2100 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2101 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2102 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2103 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2104 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2105 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2106 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2107 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2108 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2109 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2110 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2111 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2113 /* save known Sones. */
2114 int soneCounter = 0;
2115 synchronized (knownSones) {
2116 for (String knownSoneId : knownSones) {
2117 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2119 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2122 /* save Sone following times. */
2124 synchronized (soneFollowingTimes) {
2125 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2126 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2127 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2130 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2133 /* save known posts. */
2134 int postCounter = 0;
2135 synchronized (knownPosts) {
2136 for (String knownPostId : knownPosts) {
2137 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2139 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2142 /* save known replies. */
2143 int replyCounter = 0;
2144 synchronized (knownReplies) {
2145 for (String knownReplyId : knownReplies) {
2146 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2148 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2151 /* save bookmarked posts. */
2152 int bookmarkedPostCounter = 0;
2153 synchronized (bookmarkedPosts) {
2154 for (String bookmarkedPostId : bookmarkedPosts) {
2155 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2158 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2161 configuration.save();
2163 } catch (ConfigurationException ce1) {
2164 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2166 synchronized (configuration) {
2167 storingConfiguration = false;
2173 * Loads the configuration.
2175 @SuppressWarnings("unchecked")
2176 private void loadConfiguration() {
2177 /* create options. */
2178 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2181 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2182 SoneInserter.setInsertionDelay(newValue);
2186 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2187 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2188 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2189 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2190 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2191 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2192 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2193 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2194 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2197 @SuppressWarnings("synthetic-access")
2198 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2199 fcpInterface.setActive(newValue);
2202 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2205 @SuppressWarnings("synthetic-access")
2206 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2207 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2212 loadConfigurationValue("InsertionDelay");
2213 loadConfigurationValue("PostsPerPage");
2214 loadConfigurationValue("ImagesPerPage");
2215 loadConfigurationValue("CharactersPerPost");
2216 loadConfigurationValue("PostCutOffLength");
2217 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2218 loadConfigurationValue("PositiveTrust");
2219 loadConfigurationValue("NegativeTrust");
2220 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2221 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2222 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2224 /* load known Sones. */
2225 int soneCounter = 0;
2227 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2228 if (knownSoneId == null) {
2231 synchronized (knownSones) {
2232 knownSones.add(knownSoneId);
2236 /* load Sone following times. */
2239 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2240 if (soneId == null) {
2243 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2244 Sone followedSone = getSone(soneId);
2245 if (followedSone == null) {
2246 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2248 synchronized (soneFollowingTimes) {
2249 soneFollowingTimes.put(getSone(soneId), time);
2255 /* load known posts. */
2256 int postCounter = 0;
2258 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2259 if (knownPostId == null) {
2262 synchronized (knownPosts) {
2263 knownPosts.add(knownPostId);
2267 /* load known replies. */
2268 int replyCounter = 0;
2270 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2271 if (knownReplyId == null) {
2274 synchronized (knownReplies) {
2275 knownReplies.add(knownReplyId);
2279 /* load bookmarked posts. */
2280 int bookmarkedPostCounter = 0;
2282 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2283 if (bookmarkedPostId == null) {
2286 synchronized (bookmarkedPosts) {
2287 bookmarkedPosts.add(bookmarkedPostId);
2294 * Loads an {@link Integer} configuration value for the option with the
2295 * given name, logging validation failures.
2298 * The name of the option to load
2300 private void loadConfigurationValue(String optionName) {
2302 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2303 } catch (IllegalArgumentException iae1) {
2304 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2309 * Generate a Sone URI from the given URI and latest edition.
2312 * The URI to derive the Sone URI from
2313 * @return The derived URI
2315 private static FreenetURI getSoneUri(String uriString) {
2317 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2319 } catch (MalformedURLException mue1) {
2320 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2326 // INTERFACE IdentityListener
2333 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2334 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2335 if (ownIdentity.hasContext("Sone")) {
2336 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2337 addLocalSone(ownIdentity);
2345 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2346 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2347 trustedIdentities.remove(ownIdentity);
2354 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2355 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2356 trustedIdentities.get(ownIdentity).add(identity);
2357 addRemoteSone(identity);
2364 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2365 soneDownloaders.execute(new Runnable() {
2368 @SuppressWarnings("synthetic-access")
2370 Sone sone = getRemoteSone(identity.getId(), false);
2371 sone.setIdentity(identity);
2372 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2373 soneDownloader.addSone(sone);
2374 soneDownloader.fetchSone(sone);
2383 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2384 trustedIdentities.get(ownIdentity).remove(identity);
2385 boolean foundIdentity = false;
2386 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2387 if (trustedIdentity.getKey().equals(ownIdentity)) {
2390 if (trustedIdentity.getValue().contains(identity)) {
2391 foundIdentity = true;
2394 if (foundIdentity) {
2395 /* some local identity still trusts this identity, don’t remove. */
2398 Sone sone = getSone(identity.getId(), false);
2400 /* TODO - we don’t have the Sone anymore. should this happen? */
2403 synchronized (posts) {
2404 synchronized (knownPosts) {
2405 for (Post post : sone.getPosts()) {
2406 posts.remove(post.getId());
2407 eventBus.post(new PostRemovedEvent(post));
2411 synchronized (replies) {
2412 synchronized (knownReplies) {
2413 for (PostReply reply : sone.getReplies()) {
2414 replies.remove(reply.getId());
2415 eventBus.post(new PostReplyRemovedEvent(reply));
2419 synchronized (sones) {
2420 sones.remove(identity.getId());
2422 eventBus.post(new SoneRemovedEvent(sone));
2426 // INTERFACE UpdateListener
2433 public void updateFound(Version version, long releaseTime, long latestEdition) {
2434 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2438 // INTERFACE ImageInsertListener
2445 public void insertStarted(Sone sone) {
2446 eventBus.post(new SoneInsertingEvent(sone));
2453 public void insertFinished(Sone sone, long insertDuration) {
2454 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2461 public void insertAborted(Sone sone, Throwable cause) {
2462 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2466 // SONEINSERTLISTENER METHODS
2473 public void imageInsertStarted(Image image) {
2474 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2475 eventBus.post(new ImageInsertStartedEvent(image));
2482 public void imageInsertAborted(Image image) {
2483 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2484 eventBus.post(new ImageInsertAbortedEvent(image));
2491 public void imageInsertFinished(Image image, FreenetURI key) {
2492 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2493 image.setKey(key.toString());
2494 deleteTemporaryImage(image.getId());
2495 touchConfiguration();
2496 eventBus.post(new ImageInsertFinishedEvent(image));
2503 public void imageInsertFailed(Image image, Throwable cause) {
2504 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2505 eventBus.post(new ImageInsertFailedEvent(image, cause));
2509 * Convenience interface for external classes that want to access the core’s
2512 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2514 public static class Preferences {
2516 /** The wrapped options. */
2517 private final Options options;
2520 * Creates a new preferences object wrapped around the given options.
2523 * The options to wrap
2525 public Preferences(Options options) {
2526 this.options = options;
2530 * Returns the insertion delay.
2532 * @return The insertion delay
2534 public int getInsertionDelay() {
2535 return options.getIntegerOption("InsertionDelay").get();
2539 * Validates the given insertion delay.
2541 * @param insertionDelay
2542 * The insertion delay to validate
2543 * @return {@code true} if the given insertion delay was valid,
2544 * {@code false} otherwise
2546 public boolean validateInsertionDelay(Integer insertionDelay) {
2547 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2551 * Sets the insertion delay
2553 * @param insertionDelay
2554 * The new insertion delay, or {@code null} to restore it to
2556 * @return This preferences
2558 public Preferences setInsertionDelay(Integer insertionDelay) {
2559 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2564 * Returns the number of posts to show per page.
2566 * @return The number of posts to show per page
2568 public int getPostsPerPage() {
2569 return options.getIntegerOption("PostsPerPage").get();
2573 * Validates the number of posts per page.
2575 * @param postsPerPage
2576 * The number of posts per page
2577 * @return {@code true} if the number of posts per page was valid,
2578 * {@code false} otherwise
2580 public boolean validatePostsPerPage(Integer postsPerPage) {
2581 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2585 * Sets the number of posts to show per page.
2587 * @param postsPerPage
2588 * The number of posts to show per page
2589 * @return This preferences object
2591 public Preferences setPostsPerPage(Integer postsPerPage) {
2592 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2597 * Returns the number of images to show per page.
2599 * @return The number of images to show per page
2601 public int getImagesPerPage() {
2602 return options.getIntegerOption("ImagesPerPage").get();
2606 * Validates the number of images per page.
2608 * @param imagesPerPage
2609 * The number of images per page
2610 * @return {@code true} if the number of images per page was valid,
2611 * {@code false} otherwise
2613 public boolean validateImagesPerPage(Integer imagesPerPage) {
2614 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2618 * Sets the number of images per page.
2620 * @param imagesPerPage
2621 * The number of images per page
2622 * @return This preferences object
2624 public Preferences setImagesPerPage(Integer imagesPerPage) {
2625 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2630 * Returns the number of characters per post, or <code>-1</code> if the
2631 * posts should not be cut off.
2633 * @return The numbers of characters per post
2635 public int getCharactersPerPost() {
2636 return options.getIntegerOption("CharactersPerPost").get();
2640 * Validates the number of characters per post.
2642 * @param charactersPerPost
2643 * The number of characters per post
2644 * @return {@code true} if the number of characters per post was valid,
2645 * {@code false} otherwise
2647 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2648 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2652 * Sets the number of characters per post.
2654 * @param charactersPerPost
2655 * The number of characters per post, or <code>-1</code> to
2656 * not cut off the posts
2657 * @return This preferences objects
2659 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2660 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2665 * Returns the number of characters the shortened post should have.
2667 * @return The number of characters of the snippet
2669 public int getPostCutOffLength() {
2670 return options.getIntegerOption("PostCutOffLength").get();
2674 * Validates the number of characters after which to cut off the post.
2676 * @param postCutOffLength
2677 * The number of characters of the snippet
2678 * @return {@code true} if the number of characters of the snippet is
2679 * valid, {@code false} otherwise
2681 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2682 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2686 * Sets the number of characters the shortened post should have.
2688 * @param postCutOffLength
2689 * The number of characters of the snippet
2690 * @return This preferences
2692 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2693 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2698 * Returns whether Sone requires full access to be even visible.
2700 * @return {@code true} if Sone requires full access, {@code false}
2703 public boolean isRequireFullAccess() {
2704 return options.getBooleanOption("RequireFullAccess").get();
2708 * Sets whether Sone requires full access to be even visible.
2710 * @param requireFullAccess
2711 * {@code true} if Sone requires full access, {@code false}
2714 public void setRequireFullAccess(Boolean requireFullAccess) {
2715 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2719 * Returns the positive trust.
2721 * @return The positive trust
2723 public int getPositiveTrust() {
2724 return options.getIntegerOption("PositiveTrust").get();
2728 * Validates the positive trust.
2730 * @param positiveTrust
2731 * The positive trust to validate
2732 * @return {@code true} if the positive trust was valid, {@code false}
2735 public boolean validatePositiveTrust(Integer positiveTrust) {
2736 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2740 * Sets the positive trust.
2742 * @param positiveTrust
2743 * The new positive trust, or {@code null} to restore it to
2745 * @return This preferences
2747 public Preferences setPositiveTrust(Integer positiveTrust) {
2748 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2753 * Returns the negative trust.
2755 * @return The negative trust
2757 public int getNegativeTrust() {
2758 return options.getIntegerOption("NegativeTrust").get();
2762 * Validates the negative trust.
2764 * @param negativeTrust
2765 * The negative trust to validate
2766 * @return {@code true} if the negative trust was valid, {@code false}
2769 public boolean validateNegativeTrust(Integer negativeTrust) {
2770 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2774 * Sets the negative trust.
2776 * @param negativeTrust
2777 * The negative trust, or {@code null} to restore it to the
2779 * @return The preferences
2781 public Preferences setNegativeTrust(Integer negativeTrust) {
2782 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2787 * Returns the trust comment. This is the comment that is set in the web
2788 * of trust when a trust value is assigned to an identity.
2790 * @return The trust comment
2792 public String getTrustComment() {
2793 return options.getStringOption("TrustComment").get();
2797 * Sets the trust comment.
2799 * @param trustComment
2800 * The trust comment, or {@code null} to restore it to the
2802 * @return This preferences
2804 public Preferences setTrustComment(String trustComment) {
2805 options.getStringOption("TrustComment").set(trustComment);
2810 * Returns whether the {@link FcpInterface FCP interface} is currently
2813 * @see FcpInterface#setActive(boolean)
2814 * @return {@code true} if the FCP interface is currently active,
2815 * {@code false} otherwise
2817 public boolean isFcpInterfaceActive() {
2818 return options.getBooleanOption("ActivateFcpInterface").get();
2822 * Sets whether the {@link FcpInterface FCP interface} is currently
2825 * @see FcpInterface#setActive(boolean)
2826 * @param fcpInterfaceActive
2827 * {@code true} to activate the FCP interface, {@code false}
2828 * to deactivate the FCP interface
2829 * @return This preferences object
2831 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2832 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2837 * Returns the action level for which full access to the FCP interface
2840 * @return The action level for which full access to the FCP interface
2843 public FullAccessRequired getFcpFullAccessRequired() {
2844 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2848 * Sets the action level for which full access to the FCP interface is
2851 * @param fcpFullAccessRequired
2853 * @return This preferences
2855 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2856 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);