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.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
41 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
42 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
43 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
44 import net.pterodactylus.sone.core.event.PostRemovedEvent;
45 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
46 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
47 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
48 import net.pterodactylus.sone.core.event.SoneLockedEvent;
49 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
50 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
51 import net.pterodactylus.sone.data.Album;
52 import net.pterodactylus.sone.data.Client;
53 import net.pterodactylus.sone.data.Image;
54 import net.pterodactylus.sone.data.Post;
55 import net.pterodactylus.sone.data.PostReply;
56 import net.pterodactylus.sone.data.Profile;
57 import net.pterodactylus.sone.data.Profile.Field;
58 import net.pterodactylus.sone.data.Reply;
59 import net.pterodactylus.sone.data.Sone;
60 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
61 import net.pterodactylus.sone.data.Sone.SoneStatus;
62 import net.pterodactylus.sone.data.TemporaryImage;
63 import net.pterodactylus.sone.data.impl.PostImpl;
64 import net.pterodactylus.sone.fcp.FcpInterface;
65 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
66 import net.pterodactylus.sone.freenet.wot.Identity;
67 import net.pterodactylus.sone.freenet.wot.IdentityListener;
68 import net.pterodactylus.sone.freenet.wot.IdentityManager;
69 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
70 import net.pterodactylus.sone.main.SonePlugin;
71 import net.pterodactylus.util.config.Configuration;
72 import net.pterodactylus.util.config.ConfigurationException;
73 import net.pterodactylus.util.logging.Logging;
74 import net.pterodactylus.util.number.Numbers;
75 import net.pterodactylus.util.service.AbstractService;
76 import net.pterodactylus.util.thread.NamedThreadFactory;
77 import net.pterodactylus.util.thread.Ticker;
78 import net.pterodactylus.util.validation.EqualityValidator;
79 import net.pterodactylus.util.validation.IntegerRangeValidator;
80 import net.pterodactylus.util.validation.OrValidator;
81 import net.pterodactylus.util.validation.Validation;
82 import net.pterodactylus.util.version.Version;
84 import com.google.common.base.Predicate;
85 import com.google.common.collect.Collections2;
86 import com.google.common.eventbus.EventBus;
87 import com.google.inject.Inject;
89 import freenet.keys.FreenetURI;
94 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
96 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
99 private static final Logger logger = Logging.getLogger(Core.class);
101 /** The start time. */
102 private final long startupTime = System.currentTimeMillis();
105 private final Options options = new Options();
107 /** The preferences. */
108 private final Preferences preferences = new Preferences(options);
110 /** The core listener manager. */
111 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
113 /** The event bus. */
114 private final EventBus eventBus;
116 /** The configuration. */
117 private Configuration configuration;
119 /** Whether we’re currently saving the configuration. */
120 private boolean storingConfiguration = false;
122 /** The identity manager. */
123 private final IdentityManager identityManager;
125 /** Interface to freenet. */
126 private final FreenetInterface freenetInterface;
128 /** The Sone downloader. */
129 private final SoneDownloader soneDownloader;
131 /** The image inserter. */
132 private final ImageInserter imageInserter;
134 /** Sone downloader thread-pool. */
135 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
137 /** The update checker. */
138 private final UpdateChecker updateChecker;
140 /** The trust updater. */
141 private final WebOfTrustUpdater webOfTrustUpdater;
143 /** The FCP interface. */
144 private volatile FcpInterface fcpInterface;
146 /** The times Sones were followed. */
147 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
149 /** Locked local Sones. */
150 /* synchronize on itself. */
151 private final Set<Sone> lockedSones = new HashSet<Sone>();
153 /** Sone inserters. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
157 /** Sone rescuers. */
158 /* synchronize access on this on sones. */
159 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
162 /* synchronize access on this on itself. */
163 private final Map<String, Sone> sones = new HashMap<String, Sone>();
165 /** All known Sones. */
166 private final Set<String> knownSones = new HashSet<String>();
169 private final Map<String, Post> posts = new HashMap<String, Post>();
171 /** All known posts. */
172 private final Set<String> knownPosts = new HashSet<String>();
175 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
177 /** All known replies. */
178 private final Set<String> knownReplies = new HashSet<String>();
180 /** All bookmarked posts. */
181 /* synchronize access on itself. */
182 private final Set<String> bookmarkedPosts = new HashSet<String>();
184 /** Trusted identities, sorted by own identities. */
185 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
187 /** All known albums. */
188 private final Map<String, Album> albums = new HashMap<String, Album>();
190 /** All known images. */
191 private final Map<String, Image> images = new HashMap<String, Image>();
193 /** All temporary images. */
194 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
196 /** Ticker for threads that mark own elements as known. */
197 private final Ticker localElementTicker = new Ticker();
199 /** The time the configuration was last touched. */
200 private volatile long lastConfigurationUpdate;
203 * Creates a new core.
205 * @param configuration
206 * The configuration of the core
207 * @param freenetInterface
208 * The freenet interface
209 * @param identityManager
210 * The identity manager
211 * @param webOfTrustUpdater
212 * The WebOfTrust updater
217 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
219 this.configuration = configuration;
220 this.freenetInterface = freenetInterface;
221 this.identityManager = identityManager;
222 this.soneDownloader = new SoneDownloader(this, freenetInterface);
223 this.imageInserter = new ImageInserter(this, freenetInterface);
224 this.updateChecker = new UpdateChecker(freenetInterface);
225 this.webOfTrustUpdater = webOfTrustUpdater;
226 this.eventBus = eventBus;
230 // LISTENER MANAGEMENT
234 * Adds a new core listener.
236 * @param coreListener
237 * The listener to add
239 public void addCoreListener(CoreListener coreListener) {
240 coreListenerManager.addListener(coreListener);
244 * Removes a core listener.
246 * @param coreListener
247 * The listener to remove
249 public void removeCoreListener(CoreListener coreListener) {
250 coreListenerManager.removeListener(coreListener);
258 * Returns the time Sone was started.
260 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
262 public long getStartupTime() {
267 * Sets the configuration to use. This will automatically save the current
268 * configuration to the given configuration.
270 * @param configuration
271 * The new configuration to use
273 public void setConfiguration(Configuration configuration) {
274 this.configuration = configuration;
275 touchConfiguration();
279 * Returns the options used by the core.
281 * @return The options of the core
283 public Preferences getPreferences() {
288 * Returns the identity manager used by the core.
290 * @return The identity manager
292 public IdentityManager getIdentityManager() {
293 return identityManager;
297 * Returns the update checker.
299 * @return The update checker
301 public UpdateChecker getUpdateChecker() {
302 return updateChecker;
306 * Sets the FCP interface to use.
308 * @param fcpInterface
309 * The FCP interface to use
311 public void setFcpInterface(FcpInterface fcpInterface) {
312 this.fcpInterface = fcpInterface;
316 * Returns the Sone rescuer for the given local Sone.
319 * The local Sone to get the rescuer for
320 * @return The Sone rescuer for the given Sone
322 public SoneRescuer getSoneRescuer(Sone sone) {
323 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
324 synchronized (sones) {
325 SoneRescuer soneRescuer = soneRescuers.get(sone);
326 if (soneRescuer == null) {
327 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
328 soneRescuers.put(sone, soneRescuer);
336 * Returns whether the given Sone is currently locked.
340 * @return {@code true} if the Sone is locked, {@code false} if it is not
342 public boolean isLocked(Sone sone) {
343 synchronized (lockedSones) {
344 return lockedSones.contains(sone);
349 * Returns all Sones, remote and local.
353 public Set<Sone> getSones() {
354 return new HashSet<Sone>(sones.values());
358 * Returns the Sone with the given ID, regardless whether it’s local or
362 * The ID of the Sone to get
363 * @return The Sone with the given ID, or {@code null} if there is no such
366 public Sone getSone(String id) {
367 return getSone(id, true);
371 * Returns the Sone with the given ID, regardless whether it’s local or
375 * The ID of the Sone to get
377 * {@code true} to create a new Sone if none exists,
378 * {@code false} to return {@code null} if a Sone with the given
380 * @return The Sone with the given ID, or {@code null} if there is no such
384 public Sone getSone(String id, boolean create) {
385 synchronized (sones) {
386 if (!sones.containsKey(id)) {
387 Sone sone = new Sone(id, false);
390 return sones.get(id);
395 * Checks whether the core knows a Sone with the given ID.
399 * @return {@code true} if there is a Sone with the given ID, {@code false}
402 public boolean hasSone(String id) {
403 synchronized (sones) {
404 return sones.containsKey(id);
409 * Returns all local Sones.
411 * @return All local Sones
413 public Collection<Sone> getLocalSones() {
414 synchronized (sones) {
415 return Collections2.filter(sones.values(), new Predicate<Sone>() {
418 public boolean apply(Sone sone) {
419 return sone.isLocal();
426 * Returns the local Sone with the given ID, optionally creating a new Sone.
431 * {@code true} to create a new Sone if none exists,
432 * {@code false} to return null if none exists
433 * @return The Sone with the given ID, or {@code null}
435 public Sone getLocalSone(String id, boolean create) {
436 synchronized (sones) {
437 Sone sone = sones.get(id);
438 if ((sone == null) && create) {
439 sone = new Sone(id, true);
442 if ((sone != null) && !sone.isLocal()) {
443 sone = new Sone(id, true);
451 * Returns all remote Sones.
453 * @return All remote Sones
455 public Collection<Sone> getRemoteSones() {
456 synchronized (sones) {
457 return Collections2.filter(sones.values(), new Predicate<Sone>() {
460 public boolean apply(Sone sone) {
461 return !sone.isLocal();
468 * Returns the remote Sone with the given ID.
471 * The ID of the remote Sone to get
473 * {@code true} to always create a Sone, {@code false} to return
474 * {@code null} if no Sone with the given ID exists
475 * @return The Sone with the given ID
477 public Sone getRemoteSone(String id, boolean create) {
478 synchronized (sones) {
479 Sone sone = sones.get(id);
480 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
481 sone = new Sone(id, false);
489 * Returns whether the given Sone has been modified.
492 * The Sone to check for modifications
493 * @return {@code true} if a modification has been detected in the Sone,
494 * {@code false} otherwise
496 public boolean isModifiedSone(Sone sone) {
497 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
501 * Returns the time when the given was first followed by any local Sone.
504 * The Sone to get the time for
505 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
506 * been followed, or {@link Long#MAX_VALUE}
508 public long getSoneFollowingTime(Sone sone) {
509 synchronized (soneFollowingTimes) {
510 if (soneFollowingTimes.containsKey(sone)) {
511 return soneFollowingTimes.get(sone);
513 return Long.MAX_VALUE;
518 * Returns whether the target Sone is trusted by the origin Sone.
524 * @return {@code true} if the target Sone is trusted by the origin Sone
526 public boolean isSoneTrusted(Sone origin, Sone target) {
527 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
528 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
532 * Returns the post with the given ID.
535 * The ID of the post to get
536 * @return The post with the given ID, or a new post with the given ID
538 public Post getPost(String postId) {
539 return getPost(postId, true);
543 * Returns the post with the given ID, optionally creating a new post.
546 * The ID of the post to get
548 * {@code true} it create a new post if no post with the given ID
549 * exists, {@code false} to return {@code null}
550 * @return The post, or {@code null} if there is no such post
553 public Post getPost(String postId, boolean create) {
554 synchronized (posts) {
555 Post post = posts.get(postId);
556 if ((post == null) && create) {
557 post = new PostImpl(postId);
558 posts.put(postId, post);
565 * Returns all posts that have the given Sone as recipient.
567 * @see Post#getRecipient()
569 * The recipient of the posts
570 * @return All posts that have the given Sone as recipient
572 public Set<Post> getDirectedPosts(Sone recipient) {
573 Validation.begin().isNotNull("Recipient", recipient).check();
574 Set<Post> directedPosts = new HashSet<Post>();
575 synchronized (posts) {
576 for (Post post : posts.values()) {
577 if (recipient.equals(post.getRecipient())) {
578 directedPosts.add(post);
582 return directedPosts;
586 * Returns the reply with the given ID. If there is no reply with the given
587 * ID yet, a new one is created, unless {@code create} is false in which
588 * case {@code null} is returned.
591 * The ID of the reply to get
593 * {@code true} to always return a {@link Reply}, {@code false}
594 * to return {@code null} if no reply can be found
595 * @return The reply, or {@code null} if there is no such reply
597 public PostReply getPostReply(String replyId, boolean create) {
598 synchronized (replies) {
599 PostReply reply = replies.get(replyId);
600 if (create && (reply == null)) {
601 reply = new PostReply(replyId);
602 replies.put(replyId, reply);
609 * Returns all replies for the given post, order ascending by time.
612 * The post to get all replies for
613 * @return All replies for the given post
615 public List<PostReply> getReplies(Post post) {
616 Set<Sone> sones = getSones();
617 List<PostReply> replies = new ArrayList<PostReply>();
618 for (Sone sone : sones) {
619 for (PostReply reply : sone.getReplies()) {
620 if (reply.getPost().equals(post)) {
625 Collections.sort(replies, Reply.TIME_COMPARATOR);
630 * Returns all Sones that have liked the given post.
633 * The post to get the liking Sones for
634 * @return The Sones that like the given post
636 public Set<Sone> getLikes(Post post) {
637 Set<Sone> sones = new HashSet<Sone>();
638 for (Sone sone : getSones()) {
639 if (sone.getLikedPostIds().contains(post.getId())) {
647 * Returns all Sones that have liked the given reply.
650 * The reply to get the liking Sones for
651 * @return The Sones that like the given reply
653 public Set<Sone> getLikes(PostReply reply) {
654 Set<Sone> sones = new HashSet<Sone>();
655 for (Sone sone : getSones()) {
656 if (sone.getLikedReplyIds().contains(reply.getId())) {
664 * Returns whether the given post is bookmarked.
668 * @return {@code true} if the given post is bookmarked, {@code false}
671 public boolean isBookmarked(Post post) {
672 return isPostBookmarked(post.getId());
676 * Returns whether the post with the given ID is bookmarked.
679 * The ID of the post to check
680 * @return {@code true} if the post with the given ID is bookmarked,
681 * {@code false} otherwise
683 public boolean isPostBookmarked(String id) {
684 synchronized (bookmarkedPosts) {
685 return bookmarkedPosts.contains(id);
690 * Returns all currently known bookmarked posts.
692 * @return All bookmarked posts
694 public Set<Post> getBookmarkedPosts() {
695 Set<Post> posts = new HashSet<Post>();
696 synchronized (bookmarkedPosts) {
697 for (String bookmarkedPostId : bookmarkedPosts) {
698 Post post = getPost(bookmarkedPostId, false);
708 * Returns the album with the given ID, creating a new album if no album
709 * with the given ID can be found.
712 * The ID of the album
713 * @return The album with the given ID
715 public Album getAlbum(String albumId) {
716 return getAlbum(albumId, true);
720 * Returns the album with the given ID, optionally creating a new album if
721 * an album with the given ID can not be found.
724 * The ID of the album
726 * {@code true} to create a new album if none exists for the
728 * @return The album with the given ID, or {@code null} if no album with the
729 * given ID exists and {@code create} is {@code false}
731 public Album getAlbum(String albumId, boolean create) {
732 synchronized (albums) {
733 Album album = albums.get(albumId);
734 if (create && (album == null)) {
735 album = new Album(albumId);
736 albums.put(albumId, album);
743 * Returns the image with the given ID, creating it if necessary.
746 * The ID of the image
747 * @return The image with the given ID
749 public Image getImage(String imageId) {
750 return getImage(imageId, true);
754 * Returns the image with the given ID, optionally creating it if it does
758 * The ID of the image
760 * {@code true} to create an image if none exists with the given
762 * @return The image with the given ID, or {@code null} if none exists and
765 public Image getImage(String imageId, boolean create) {
766 synchronized (images) {
767 Image image = images.get(imageId);
768 if (create && (image == null)) {
769 image = new Image(imageId);
770 images.put(imageId, image);
777 * Returns the temporary image with the given ID.
780 * The ID of the temporary image
781 * @return The temporary image, or {@code null} if there is no temporary
782 * image with the given ID
784 public TemporaryImage getTemporaryImage(String imageId) {
785 synchronized (temporaryImages) {
786 return temporaryImages.get(imageId);
795 * Locks the given Sone. A locked Sone will not be inserted by
796 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
802 public void lockSone(Sone sone) {
803 synchronized (lockedSones) {
804 if (lockedSones.add(sone)) {
805 eventBus.post(new SoneLockedEvent(sone));
811 * Unlocks the given Sone.
813 * @see #lockSone(Sone)
817 public void unlockSone(Sone sone) {
818 synchronized (lockedSones) {
819 if (lockedSones.remove(sone)) {
820 eventBus.post(new SoneUnlockedEvent(sone));
826 * Adds a local Sone from the given own identity.
829 * The own identity to create a Sone from
830 * @return The added (or already existing) Sone
832 public Sone addLocalSone(OwnIdentity ownIdentity) {
833 if (ownIdentity == null) {
834 logger.log(Level.WARNING, "Given OwnIdentity is null!");
837 synchronized (sones) {
840 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
841 } catch (MalformedURLException mue1) {
842 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
845 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
846 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
848 /* TODO - load posts ’n stuff */
849 sones.put(ownIdentity.getId(), sone);
850 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
851 soneInserter.addSoneInsertListener(this);
852 soneInserters.put(sone, soneInserter);
853 sone.setStatus(SoneStatus.idle);
855 soneInserter.start();
861 * Creates a new Sone for the given own identity.
864 * The own identity to create a Sone for
865 * @return The created Sone
867 public Sone createSone(OwnIdentity ownIdentity) {
868 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
869 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
872 Sone sone = addLocalSone(ownIdentity);
873 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
874 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
875 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
876 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
877 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
878 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
880 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
881 touchConfiguration();
886 * Adds the Sone of the given identity.
889 * The identity whose Sone to add
890 * @return The added or already existing Sone
892 public Sone addRemoteSone(Identity identity) {
893 if (identity == null) {
894 logger.log(Level.WARNING, "Given Identity is null!");
897 synchronized (sones) {
898 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
899 boolean newSone = sone.getRequestUri() == null;
900 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
901 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
903 synchronized (knownSones) {
904 newSone = !knownSones.contains(sone.getId());
906 sone.setKnown(!newSone);
908 eventBus.post(new NewSoneFoundEvent(sone));
909 for (Sone localSone : getLocalSones()) {
910 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
911 followSone(localSone, sone);
916 soneDownloader.addSone(sone);
917 soneDownloaders.execute(new Runnable() {
920 @SuppressWarnings("synthetic-access")
922 soneDownloader.fetchSone(sone, sone.getRequestUri());
931 * Lets the given local Sone follow the Sone with the given ID.
934 * The local Sone that should follow another Sone
936 * The ID of the Sone to follow
938 public void followSone(Sone sone, String soneId) {
939 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
940 Sone followedSone = getSone(soneId, true);
941 if (followedSone == null) {
942 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
945 followSone(sone, getSone(soneId));
949 * Lets the given local Sone follow the other given Sone. If the given Sone
950 * was not followed by any local Sone before, this will mark all elements of
951 * the followed Sone as read that have been created before the current
955 * The local Sone that should follow the other Sone
956 * @param followedSone
957 * The Sone that should be followed
959 public void followSone(Sone sone, Sone followedSone) {
960 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
961 sone.addFriend(followedSone.getId());
962 synchronized (soneFollowingTimes) {
963 if (!soneFollowingTimes.containsKey(followedSone)) {
964 long now = System.currentTimeMillis();
965 soneFollowingTimes.put(followedSone, now);
966 for (Post post : followedSone.getPosts()) {
967 if (post.getTime() < now) {
971 for (PostReply reply : followedSone.getReplies()) {
972 if (reply.getTime() < now) {
973 markReplyKnown(reply);
978 touchConfiguration();
982 * Lets the given local Sone unfollow the Sone with the given ID.
985 * The local Sone that should unfollow another Sone
987 * The ID of the Sone being unfollowed
989 public void unfollowSone(Sone sone, String soneId) {
990 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
991 unfollowSone(sone, getSone(soneId, false));
995 * Lets the given local Sone unfollow the other given Sone. If the given
996 * local Sone is the last local Sone that followed the given Sone, its
997 * following time will be removed.
1000 * The local Sone that should unfollow another Sone
1001 * @param unfollowedSone
1002 * The Sone being unfollowed
1004 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1005 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1006 sone.removeFriend(unfollowedSone.getId());
1007 boolean unfollowedSoneStillFollowed = false;
1008 for (Sone localSone : getLocalSones()) {
1009 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1011 if (!unfollowedSoneStillFollowed) {
1012 synchronized (soneFollowingTimes) {
1013 soneFollowingTimes.remove(unfollowedSone);
1016 touchConfiguration();
1020 * Sets the trust value of the given origin Sone for the target Sone.
1027 * The trust value (from {@code -100} to {@code 100})
1029 public void setTrust(Sone origin, Sone target, int trustValue) {
1030 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();
1031 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1035 * Removes any trust assignment for the given target Sone.
1042 public void removeTrust(Sone origin, Sone target) {
1043 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1044 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1048 * Assigns the configured positive trust value for the given target.
1055 public void trustSone(Sone origin, Sone target) {
1056 setTrust(origin, target, preferences.getPositiveTrust());
1060 * Assigns the configured negative trust value for the given target.
1067 public void distrustSone(Sone origin, Sone target) {
1068 setTrust(origin, target, preferences.getNegativeTrust());
1072 * Removes the trust assignment for the given target.
1079 public void untrustSone(Sone origin, Sone target) {
1080 removeTrust(origin, target);
1084 * Updates the stored Sone with the given Sone.
1089 public void updateSone(Sone sone) {
1090 updateSone(sone, false);
1094 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1095 * {@code true}, an older Sone than the current Sone can be given to restore
1099 * The Sone to update
1100 * @param soneRescueMode
1101 * {@code true} if the stored Sone should be updated regardless
1102 * of the age of the given Sone
1104 public void updateSone(Sone sone, boolean soneRescueMode) {
1105 if (hasSone(sone.getId())) {
1106 Sone storedSone = getSone(sone.getId());
1107 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1108 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1111 synchronized (posts) {
1112 if (!soneRescueMode) {
1113 for (Post post : storedSone.getPosts()) {
1114 posts.remove(post.getId());
1115 if (!sone.getPosts().contains(post)) {
1116 eventBus.post(new PostRemovedEvent(post));
1120 List<Post> storedPosts = storedSone.getPosts();
1121 synchronized (knownPosts) {
1122 for (Post post : sone.getPosts()) {
1123 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1124 if (!storedPosts.contains(post)) {
1125 if (post.getTime() < getSoneFollowingTime(sone)) {
1126 knownPosts.add(post.getId());
1127 post.setKnown(true);
1128 } else if (!knownPosts.contains(post.getId())) {
1129 eventBus.post(new NewPostFoundEvent(post));
1132 posts.put(post.getId(), post);
1136 synchronized (replies) {
1137 if (!soneRescueMode) {
1138 for (PostReply reply : storedSone.getReplies()) {
1139 replies.remove(reply.getId());
1140 if (!sone.getReplies().contains(reply)) {
1141 eventBus.post(new PostReplyRemovedEvent(reply));
1145 Set<PostReply> storedReplies = storedSone.getReplies();
1146 synchronized (knownReplies) {
1147 for (PostReply reply : sone.getReplies()) {
1148 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1149 if (!storedReplies.contains(reply)) {
1150 if (reply.getTime() < getSoneFollowingTime(sone)) {
1151 knownReplies.add(reply.getId());
1152 reply.setKnown(true);
1153 } else if (!knownReplies.contains(reply.getId())) {
1154 eventBus.post(new NewPostReplyFoundEvent(reply));
1157 replies.put(reply.getId(), reply);
1161 synchronized (albums) {
1162 synchronized (images) {
1163 for (Album album : storedSone.getAlbums()) {
1164 albums.remove(album.getId());
1165 for (Image image : album.getImages()) {
1166 images.remove(image.getId());
1169 for (Album album : sone.getAlbums()) {
1170 albums.put(album.getId(), album);
1171 for (Image image : album.getImages()) {
1172 images.put(image.getId(), image);
1177 synchronized (storedSone) {
1178 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1179 storedSone.setTime(sone.getTime());
1181 storedSone.setClient(sone.getClient());
1182 storedSone.setProfile(sone.getProfile());
1183 if (soneRescueMode) {
1184 for (Post post : sone.getPosts()) {
1185 storedSone.addPost(post);
1187 for (PostReply reply : sone.getReplies()) {
1188 storedSone.addReply(reply);
1190 for (String likedPostId : sone.getLikedPostIds()) {
1191 storedSone.addLikedPostId(likedPostId);
1193 for (String likedReplyId : sone.getLikedReplyIds()) {
1194 storedSone.addLikedReplyId(likedReplyId);
1196 for (Album album : sone.getAlbums()) {
1197 storedSone.addAlbum(album);
1200 storedSone.setPosts(sone.getPosts());
1201 storedSone.setReplies(sone.getReplies());
1202 storedSone.setLikePostIds(sone.getLikedPostIds());
1203 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1204 storedSone.setAlbums(sone.getAlbums());
1206 storedSone.setLatestEdition(sone.getLatestEdition());
1212 * Deletes the given Sone. This will remove the Sone from the
1213 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1214 * remove the context from its identity.
1217 * The Sone to delete
1219 public void deleteSone(Sone sone) {
1220 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1221 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1224 synchronized (sones) {
1225 if (!getLocalSones().contains(sone)) {
1226 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1229 sones.remove(sone.getId());
1230 SoneInserter soneInserter = soneInserters.remove(sone);
1231 soneInserter.removeSoneInsertListener(this);
1232 soneInserter.stop();
1234 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1235 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1237 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1238 } catch (ConfigurationException ce1) {
1239 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1244 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1245 * known} before, a {@link MarkSoneKnownEvent} is fired.
1248 * The Sone to mark as known
1250 public void markSoneKnown(Sone sone) {
1251 if (!sone.isKnown()) {
1252 sone.setKnown(true);
1253 synchronized (knownSones) {
1254 knownSones.add(sone.getId());
1256 eventBus.post(new MarkSoneKnownEvent(sone));
1257 touchConfiguration();
1262 * Loads and updates the given Sone from the configuration. If any error is
1263 * encountered, loading is aborted and the given Sone is not changed.
1266 * The Sone to load and update
1268 public void loadSone(Sone sone) {
1269 if (!sone.isLocal()) {
1270 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1274 /* initialize options. */
1275 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1276 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1277 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1278 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1279 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1280 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1283 String sonePrefix = "Sone/" + sone.getId();
1284 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1285 if (soneTime == null) {
1286 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1289 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1292 Profile profile = new Profile(sone);
1293 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1294 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1295 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1296 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1297 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1298 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1300 /* load profile fields. */
1302 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1303 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1304 if (fieldName == null) {
1307 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1308 profile.addField(fieldName).setValue(fieldValue);
1312 Set<Post> posts = new HashSet<Post>();
1314 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1315 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1316 if (postId == null) {
1319 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1320 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1321 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1322 if ((postTime == 0) || (postText == null)) {
1323 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1326 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1327 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1328 post.setRecipient(getSone(postRecipientId));
1334 Set<PostReply> replies = new HashSet<PostReply>();
1336 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1337 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1338 if (replyId == null) {
1341 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1342 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1343 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1344 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1345 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1348 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1351 /* load post likes. */
1352 Set<String> likedPostIds = new HashSet<String>();
1354 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1355 if (likedPostId == null) {
1358 likedPostIds.add(likedPostId);
1361 /* load reply likes. */
1362 Set<String> likedReplyIds = new HashSet<String>();
1364 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1365 if (likedReplyId == null) {
1368 likedReplyIds.add(likedReplyId);
1372 Set<String> friends = new HashSet<String>();
1374 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1375 if (friendId == null) {
1378 friends.add(friendId);
1382 List<Album> topLevelAlbums = new ArrayList<Album>();
1383 int albumCounter = 0;
1385 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1386 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1387 if (albumId == null) {
1390 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1391 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1392 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1393 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1394 if ((albumTitle == null) || (albumDescription == null)) {
1395 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1398 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1399 if (albumParentId != null) {
1400 Album parentAlbum = getAlbum(albumParentId, false);
1401 if (parentAlbum == null) {
1402 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1405 parentAlbum.addAlbum(album);
1407 if (!topLevelAlbums.contains(album)) {
1408 topLevelAlbums.add(album);
1414 int imageCounter = 0;
1416 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1417 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1418 if (imageId == null) {
1421 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1422 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1423 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1424 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1425 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1426 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1427 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1428 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1429 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1432 Album album = getAlbum(albumId, false);
1433 if (album == null) {
1434 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1437 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1438 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1439 album.addImage(image);
1443 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1444 if (avatarId != null) {
1445 profile.setAvatar(getImage(avatarId, false));
1449 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1450 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1451 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1452 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1453 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1454 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1456 /* if we’re still here, Sone was loaded successfully. */
1457 synchronized (sone) {
1458 sone.setTime(soneTime);
1459 sone.setProfile(profile);
1460 sone.setPosts(posts);
1461 sone.setReplies(replies);
1462 sone.setLikePostIds(likedPostIds);
1463 sone.setLikeReplyIds(likedReplyIds);
1464 for (String friendId : friends) {
1465 followSone(sone, friendId);
1467 sone.setAlbums(topLevelAlbums);
1468 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1470 synchronized (knownSones) {
1471 for (String friend : friends) {
1472 knownSones.add(friend);
1475 synchronized (knownPosts) {
1476 for (Post post : posts) {
1477 knownPosts.add(post.getId());
1480 synchronized (knownReplies) {
1481 for (PostReply reply : replies) {
1482 knownReplies.add(reply.getId());
1488 * Creates a new post.
1491 * The Sone that creates the post
1493 * The text of the post
1494 * @return The created post
1496 public Post createPost(Sone sone, String text) {
1497 return createPost(sone, System.currentTimeMillis(), text);
1501 * Creates a new post.
1504 * The Sone that creates the post
1506 * The time of the post
1508 * The text of the post
1509 * @return The created post
1511 public Post createPost(Sone sone, long time, String text) {
1512 return createPost(sone, null, time, text);
1516 * Creates a new post.
1519 * The Sone that creates the post
1521 * The recipient Sone, or {@code null} if this post does not have
1524 * The text of the post
1525 * @return The created post
1527 public Post createPost(Sone sone, Sone recipient, String text) {
1528 return createPost(sone, recipient, System.currentTimeMillis(), text);
1532 * Creates a new post.
1535 * The Sone that creates the post
1537 * The recipient Sone, or {@code null} if this post does not have
1540 * The time of the post
1542 * The text of the post
1543 * @return The created post
1545 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1546 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1547 if (!sone.isLocal()) {
1548 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1551 final Post post = new PostImpl(sone, time, text);
1552 if (recipient != null) {
1553 post.setRecipient(recipient);
1555 synchronized (posts) {
1556 posts.put(post.getId(), post);
1558 eventBus.post(new NewPostFoundEvent(post));
1560 touchConfiguration();
1561 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1568 markPostKnown(post);
1570 }, "Mark " + post + " read.");
1575 * Deletes the given post.
1578 * The post to delete
1580 public void deletePost(Post post) {
1581 if (!post.getSone().isLocal()) {
1582 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1585 post.getSone().removePost(post);
1586 synchronized (posts) {
1587 posts.remove(post.getId());
1589 eventBus.post(new PostRemovedEvent(post));
1590 markPostKnown(post);
1591 touchConfiguration();
1595 * Marks the given post as known, if it is currently not a known post
1596 * (according to {@link Post#isKnown()}).
1599 * The post to mark as known
1601 public void markPostKnown(Post post) {
1602 post.setKnown(true);
1603 synchronized (knownPosts) {
1604 eventBus.post(new MarkPostKnownEvent(post));
1605 if (knownPosts.add(post.getId())) {
1606 touchConfiguration();
1609 for (PostReply reply : getReplies(post)) {
1610 markReplyKnown(reply);
1615 * Bookmarks the given post.
1618 * The post to bookmark
1620 public void bookmark(Post post) {
1621 bookmarkPost(post.getId());
1625 * Bookmarks the post with the given ID.
1628 * The ID of the post to bookmark
1630 public void bookmarkPost(String id) {
1631 synchronized (bookmarkedPosts) {
1632 bookmarkedPosts.add(id);
1637 * Removes the given post from the bookmarks.
1640 * The post to unbookmark
1642 public void unbookmark(Post post) {
1643 unbookmarkPost(post.getId());
1647 * Removes the post with the given ID from the bookmarks.
1650 * The ID of the post to unbookmark
1652 public void unbookmarkPost(String id) {
1653 synchronized (bookmarkedPosts) {
1654 bookmarkedPosts.remove(id);
1659 * Creates a new reply.
1662 * The Sone that creates the reply
1664 * The post that this reply refers to
1666 * The text of the reply
1667 * @return The created reply
1669 public PostReply createReply(Sone sone, Post post, String text) {
1670 return createReply(sone, post, System.currentTimeMillis(), text);
1674 * Creates a new reply.
1677 * The Sone that creates the reply
1679 * The post that this reply refers to
1681 * The time of the reply
1683 * The text of the reply
1684 * @return The created reply
1686 public PostReply createReply(Sone sone, Post post, long time, String text) {
1687 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1688 if (!sone.isLocal()) {
1689 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1692 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1693 synchronized (replies) {
1694 replies.put(reply.getId(), reply);
1696 synchronized (knownReplies) {
1697 eventBus.post(new NewPostReplyFoundEvent(reply));
1699 sone.addReply(reply);
1700 touchConfiguration();
1701 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1708 markReplyKnown(reply);
1710 }, "Mark " + reply + " read.");
1715 * Deletes the given reply.
1718 * The reply to delete
1720 public void deleteReply(PostReply reply) {
1721 Sone sone = reply.getSone();
1722 if (!sone.isLocal()) {
1723 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1726 synchronized (replies) {
1727 replies.remove(reply.getId());
1729 synchronized (knownReplies) {
1730 markReplyKnown(reply);
1731 knownReplies.remove(reply.getId());
1733 sone.removeReply(reply);
1734 touchConfiguration();
1738 * Marks the given reply as known, if it is currently not a known reply
1739 * (according to {@link Reply#isKnown()}).
1742 * The reply to mark as known
1744 public void markReplyKnown(PostReply reply) {
1745 reply.setKnown(true);
1746 synchronized (knownReplies) {
1747 eventBus.post(new MarkPostReplyKnownEvent(reply));
1748 if (knownReplies.add(reply.getId())) {
1749 touchConfiguration();
1755 * Creates a new top-level album for the given Sone.
1758 * The Sone to create the album for
1759 * @return The new album
1761 public Album createAlbum(Sone sone) {
1762 return createAlbum(sone, null);
1766 * Creates a new album for the given Sone.
1769 * The Sone to create the album for
1771 * The parent of the album (may be {@code null} to create a
1773 * @return The new album
1775 public Album createAlbum(Sone sone, Album parent) {
1776 Album album = new Album();
1777 synchronized (albums) {
1778 albums.put(album.getId(), album);
1780 album.setSone(sone);
1781 if (parent != null) {
1782 parent.addAlbum(album);
1784 sone.addAlbum(album);
1790 * Deletes the given album. The owner of the album has to be a local Sone,
1791 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1794 * The album to remove
1796 public void deleteAlbum(Album album) {
1797 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1798 if (!album.isEmpty()) {
1801 if (album.getParent() == null) {
1802 album.getSone().removeAlbum(album);
1804 album.getParent().removeAlbum(album);
1806 synchronized (albums) {
1807 albums.remove(album.getId());
1809 touchConfiguration();
1813 * Creates a new image.
1816 * The Sone creating the image
1818 * The album the image will be inserted into
1819 * @param temporaryImage
1820 * The temporary image to create the image from
1821 * @return The newly created image
1823 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1824 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();
1825 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1826 album.addImage(image);
1827 synchronized (images) {
1828 images.put(image.getId(), image);
1830 imageInserter.insertImage(temporaryImage, image);
1835 * Deletes the given image. This method will also delete a matching
1838 * @see #deleteTemporaryImage(TemporaryImage)
1840 * The image to delete
1842 public void deleteImage(Image image) {
1843 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1844 deleteTemporaryImage(image.getId());
1845 image.getAlbum().removeImage(image);
1846 synchronized (images) {
1847 images.remove(image.getId());
1849 touchConfiguration();
1853 * Creates a new temporary image.
1856 * The MIME type of the temporary image
1858 * The encoded data of the image
1859 * @return The temporary image
1861 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1862 TemporaryImage temporaryImage = new TemporaryImage();
1863 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1864 synchronized (temporaryImages) {
1865 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1867 return temporaryImage;
1871 * Deletes the given temporary image.
1873 * @param temporaryImage
1874 * The temporary image to delete
1876 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1877 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1878 deleteTemporaryImage(temporaryImage.getId());
1882 * Deletes the temporary image with the given ID.
1885 * The ID of the temporary image to delete
1887 public void deleteTemporaryImage(String imageId) {
1888 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1889 synchronized (temporaryImages) {
1890 temporaryImages.remove(imageId);
1892 Image image = getImage(imageId, false);
1893 if (image != null) {
1894 imageInserter.cancelImageInsert(image);
1899 * Notifies the core that the configuration, either of the core or of a
1900 * single local Sone, has changed, and that the configuration should be
1903 public void touchConfiguration() {
1904 lastConfigurationUpdate = System.currentTimeMillis();
1915 public void serviceStart() {
1916 loadConfiguration();
1917 updateChecker.addUpdateListener(this);
1918 updateChecker.start();
1919 identityManager.addIdentityListener(this);
1920 identityManager.start();
1921 webOfTrustUpdater.init();
1922 webOfTrustUpdater.start();
1929 public void serviceRun() {
1930 long lastSaved = System.currentTimeMillis();
1931 while (!shouldStop()) {
1933 long now = System.currentTimeMillis();
1934 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1935 for (Sone localSone : getLocalSones()) {
1936 saveSone(localSone);
1938 saveConfiguration();
1948 public void serviceStop() {
1949 synchronized (sones) {
1950 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1951 soneInserter.getValue().removeSoneInsertListener(this);
1952 soneInserter.getValue().stop();
1953 saveSone(soneInserter.getKey());
1956 saveConfiguration();
1957 webOfTrustUpdater.stop();
1958 updateChecker.stop();
1959 updateChecker.removeUpdateListener(this);
1960 soneDownloader.stop();
1961 identityManager.removeIdentityListener(this);
1962 identityManager.stop();
1970 * Saves the given Sone. This will persist all local settings for the given
1971 * Sone, such as the friends list and similar, private options.
1976 private synchronized void saveSone(Sone sone) {
1977 if (!sone.isLocal()) {
1978 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1981 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1982 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1986 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1988 /* save Sone into configuration. */
1989 String sonePrefix = "Sone/" + sone.getId();
1990 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1991 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1994 Profile profile = sone.getProfile();
1995 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1996 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1997 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1998 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1999 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2000 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2001 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2003 /* save profile fields. */
2004 int fieldCounter = 0;
2005 for (Field profileField : profile.getFields()) {
2006 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2007 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2008 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2010 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2013 int postCounter = 0;
2014 for (Post post : sone.getPosts()) {
2015 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2016 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2017 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2018 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2019 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2021 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2024 int replyCounter = 0;
2025 for (PostReply reply : sone.getReplies()) {
2026 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2027 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2028 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2029 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2030 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2032 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2034 /* save post likes. */
2035 int postLikeCounter = 0;
2036 for (String postId : sone.getLikedPostIds()) {
2037 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2039 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2041 /* save reply likes. */
2042 int replyLikeCounter = 0;
2043 for (String replyId : sone.getLikedReplyIds()) {
2044 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2046 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2049 int friendCounter = 0;
2050 for (String friendId : sone.getFriends()) {
2051 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2053 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2055 /* save albums. first, collect in a flat structure, top-level first. */
2056 List<Album> albums = sone.getAllAlbums();
2058 int albumCounter = 0;
2059 for (Album album : albums) {
2060 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2061 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2062 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2063 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2064 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2065 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2067 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2070 int imageCounter = 0;
2071 for (Album album : albums) {
2072 for (Image image : album.getImages()) {
2073 if (!image.isInserted()) {
2076 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2077 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2078 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2079 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2080 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2081 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2082 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2083 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2084 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2087 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2090 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2091 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2092 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2093 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2094 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2095 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2097 configuration.save();
2099 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2101 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2102 } catch (ConfigurationException ce1) {
2103 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2108 * Saves the current options.
2110 private void saveConfiguration() {
2111 synchronized (configuration) {
2112 if (storingConfiguration) {
2113 logger.log(Level.FINE, "Already storing configuration…");
2116 storingConfiguration = true;
2119 /* store the options first. */
2121 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2122 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2123 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2124 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2125 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2126 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2127 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2128 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2129 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2130 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2131 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2132 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2134 /* save known Sones. */
2135 int soneCounter = 0;
2136 synchronized (knownSones) {
2137 for (String knownSoneId : knownSones) {
2138 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2140 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2143 /* save Sone following times. */
2145 synchronized (soneFollowingTimes) {
2146 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2147 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2148 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2151 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2154 /* save known posts. */
2155 int postCounter = 0;
2156 synchronized (knownPosts) {
2157 for (String knownPostId : knownPosts) {
2158 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2160 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2163 /* save known replies. */
2164 int replyCounter = 0;
2165 synchronized (knownReplies) {
2166 for (String knownReplyId : knownReplies) {
2167 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2169 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2172 /* save bookmarked posts. */
2173 int bookmarkedPostCounter = 0;
2174 synchronized (bookmarkedPosts) {
2175 for (String bookmarkedPostId : bookmarkedPosts) {
2176 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2179 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2182 configuration.save();
2184 } catch (ConfigurationException ce1) {
2185 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2187 synchronized (configuration) {
2188 storingConfiguration = false;
2194 * Loads the configuration.
2196 @SuppressWarnings("unchecked")
2197 private void loadConfiguration() {
2198 /* create options. */
2199 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2202 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2203 SoneInserter.setInsertionDelay(newValue);
2207 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2208 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2209 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2210 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2211 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2212 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2213 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2214 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2215 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2218 @SuppressWarnings("synthetic-access")
2219 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2220 fcpInterface.setActive(newValue);
2223 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2226 @SuppressWarnings("synthetic-access")
2227 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2228 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2233 loadConfigurationValue("InsertionDelay");
2234 loadConfigurationValue("PostsPerPage");
2235 loadConfigurationValue("ImagesPerPage");
2236 loadConfigurationValue("CharactersPerPost");
2237 loadConfigurationValue("PostCutOffLength");
2238 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2239 loadConfigurationValue("PositiveTrust");
2240 loadConfigurationValue("NegativeTrust");
2241 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2242 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2243 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2245 /* load known Sones. */
2246 int soneCounter = 0;
2248 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2249 if (knownSoneId == null) {
2252 synchronized (knownSones) {
2253 knownSones.add(knownSoneId);
2257 /* load Sone following times. */
2260 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2261 if (soneId == null) {
2264 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2265 Sone followedSone = getSone(soneId);
2266 if (followedSone == null) {
2267 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2269 synchronized (soneFollowingTimes) {
2270 soneFollowingTimes.put(getSone(soneId), time);
2276 /* load known posts. */
2277 int postCounter = 0;
2279 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2280 if (knownPostId == null) {
2283 synchronized (knownPosts) {
2284 knownPosts.add(knownPostId);
2288 /* load known replies. */
2289 int replyCounter = 0;
2291 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2292 if (knownReplyId == null) {
2295 synchronized (knownReplies) {
2296 knownReplies.add(knownReplyId);
2300 /* load bookmarked posts. */
2301 int bookmarkedPostCounter = 0;
2303 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2304 if (bookmarkedPostId == null) {
2307 synchronized (bookmarkedPosts) {
2308 bookmarkedPosts.add(bookmarkedPostId);
2315 * Loads an {@link Integer} configuration value for the option with the
2316 * given name, logging validation failures.
2319 * The name of the option to load
2321 private void loadConfigurationValue(String optionName) {
2323 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2324 } catch (IllegalArgumentException iae1) {
2325 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2330 * Generate a Sone URI from the given URI and latest edition.
2333 * The URI to derive the Sone URI from
2334 * @return The derived URI
2336 private static FreenetURI getSoneUri(String uriString) {
2338 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2340 } catch (MalformedURLException mue1) {
2341 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2347 // INTERFACE IdentityListener
2354 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2355 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2356 if (ownIdentity.hasContext("Sone")) {
2357 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2358 addLocalSone(ownIdentity);
2366 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2367 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2368 trustedIdentities.remove(ownIdentity);
2375 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2376 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2377 trustedIdentities.get(ownIdentity).add(identity);
2378 addRemoteSone(identity);
2385 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2386 soneDownloaders.execute(new Runnable() {
2389 @SuppressWarnings("synthetic-access")
2391 Sone sone = getRemoteSone(identity.getId(), false);
2392 sone.setIdentity(identity);
2393 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2394 soneDownloader.addSone(sone);
2395 soneDownloader.fetchSone(sone);
2404 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2405 trustedIdentities.get(ownIdentity).remove(identity);
2406 boolean foundIdentity = false;
2407 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2408 if (trustedIdentity.getKey().equals(ownIdentity)) {
2411 if (trustedIdentity.getValue().contains(identity)) {
2412 foundIdentity = true;
2415 if (foundIdentity) {
2416 /* some local identity still trusts this identity, don’t remove. */
2419 Sone sone = getSone(identity.getId(), false);
2421 /* TODO - we don’t have the Sone anymore. should this happen? */
2424 synchronized (posts) {
2425 synchronized (knownPosts) {
2426 for (Post post : sone.getPosts()) {
2427 posts.remove(post.getId());
2428 eventBus.post(new PostRemovedEvent(post));
2432 synchronized (replies) {
2433 synchronized (knownReplies) {
2434 for (PostReply reply : sone.getReplies()) {
2435 replies.remove(reply.getId());
2436 eventBus.post(new PostReplyRemovedEvent(reply));
2440 synchronized (sones) {
2441 sones.remove(identity.getId());
2443 eventBus.post(new SoneRemovedEvent(sone));
2447 // INTERFACE UpdateListener
2454 public void updateFound(Version version, long releaseTime, long latestEdition) {
2455 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2459 // INTERFACE ImageInsertListener
2466 public void insertStarted(Sone sone) {
2467 eventBus.post(new SoneInsertingEvent(sone));
2474 public void insertFinished(Sone sone, long insertDuration) {
2475 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2482 public void insertAborted(Sone sone, Throwable cause) {
2483 coreListenerManager.fireSoneInsertAborted(sone, cause);
2487 // SONEINSERTLISTENER METHODS
2494 public void imageInsertStarted(Image image) {
2495 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2496 coreListenerManager.fireImageInsertStarted(image);
2503 public void imageInsertAborted(Image image) {
2504 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2505 coreListenerManager.fireImageInsertAborted(image);
2512 public void imageInsertFinished(Image image, FreenetURI key) {
2513 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2514 image.setKey(key.toString());
2515 deleteTemporaryImage(image.getId());
2516 touchConfiguration();
2517 coreListenerManager.fireImageInsertFinished(image);
2524 public void imageInsertFailed(Image image, Throwable cause) {
2525 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2526 coreListenerManager.fireImageInsertFailed(image, cause);
2530 * Convenience interface for external classes that want to access the core’s
2533 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2535 public static class Preferences {
2537 /** The wrapped options. */
2538 private final Options options;
2541 * Creates a new preferences object wrapped around the given options.
2544 * The options to wrap
2546 public Preferences(Options options) {
2547 this.options = options;
2551 * Returns the insertion delay.
2553 * @return The insertion delay
2555 public int getInsertionDelay() {
2556 return options.getIntegerOption("InsertionDelay").get();
2560 * Validates the given insertion delay.
2562 * @param insertionDelay
2563 * The insertion delay to validate
2564 * @return {@code true} if the given insertion delay was valid,
2565 * {@code false} otherwise
2567 public boolean validateInsertionDelay(Integer insertionDelay) {
2568 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2572 * Sets the insertion delay
2574 * @param insertionDelay
2575 * The new insertion delay, or {@code null} to restore it to
2577 * @return This preferences
2579 public Preferences setInsertionDelay(Integer insertionDelay) {
2580 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2585 * Returns the number of posts to show per page.
2587 * @return The number of posts to show per page
2589 public int getPostsPerPage() {
2590 return options.getIntegerOption("PostsPerPage").get();
2594 * Validates the number of posts per page.
2596 * @param postsPerPage
2597 * The number of posts per page
2598 * @return {@code true} if the number of posts per page was valid,
2599 * {@code false} otherwise
2601 public boolean validatePostsPerPage(Integer postsPerPage) {
2602 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2606 * Sets the number of posts to show per page.
2608 * @param postsPerPage
2609 * The number of posts to show per page
2610 * @return This preferences object
2612 public Preferences setPostsPerPage(Integer postsPerPage) {
2613 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2618 * Returns the number of images to show per page.
2620 * @return The number of images to show per page
2622 public int getImagesPerPage() {
2623 return options.getIntegerOption("ImagesPerPage").get();
2627 * Validates the number of images per page.
2629 * @param imagesPerPage
2630 * The number of images per page
2631 * @return {@code true} if the number of images per page was valid,
2632 * {@code false} otherwise
2634 public boolean validateImagesPerPage(Integer imagesPerPage) {
2635 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2639 * Sets the number of images per page.
2641 * @param imagesPerPage
2642 * The number of images per page
2643 * @return This preferences object
2645 public Preferences setImagesPerPage(Integer imagesPerPage) {
2646 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2651 * Returns the number of characters per post, or <code>-1</code> if the
2652 * posts should not be cut off.
2654 * @return The numbers of characters per post
2656 public int getCharactersPerPost() {
2657 return options.getIntegerOption("CharactersPerPost").get();
2661 * Validates the number of characters per post.
2663 * @param charactersPerPost
2664 * The number of characters per post
2665 * @return {@code true} if the number of characters per post was valid,
2666 * {@code false} otherwise
2668 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2669 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2673 * Sets the number of characters per post.
2675 * @param charactersPerPost
2676 * The number of characters per post, or <code>-1</code> to
2677 * not cut off the posts
2678 * @return This preferences objects
2680 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2681 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2686 * Returns the number of characters the shortened post should have.
2688 * @return The number of characters of the snippet
2690 public int getPostCutOffLength() {
2691 return options.getIntegerOption("PostCutOffLength").get();
2695 * Validates the number of characters after which to cut off the post.
2697 * @param postCutOffLength
2698 * The number of characters of the snippet
2699 * @return {@code true} if the number of characters of the snippet is
2700 * valid, {@code false} otherwise
2702 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2703 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2707 * Sets the number of characters the shortened post should have.
2709 * @param postCutOffLength
2710 * The number of characters of the snippet
2711 * @return This preferences
2713 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2714 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2719 * Returns whether Sone requires full access to be even visible.
2721 * @return {@code true} if Sone requires full access, {@code false}
2724 public boolean isRequireFullAccess() {
2725 return options.getBooleanOption("RequireFullAccess").get();
2729 * Sets whether Sone requires full access to be even visible.
2731 * @param requireFullAccess
2732 * {@code true} if Sone requires full access, {@code false}
2735 public void setRequireFullAccess(Boolean requireFullAccess) {
2736 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2740 * Returns the positive trust.
2742 * @return The positive trust
2744 public int getPositiveTrust() {
2745 return options.getIntegerOption("PositiveTrust").get();
2749 * Validates the positive trust.
2751 * @param positiveTrust
2752 * The positive trust to validate
2753 * @return {@code true} if the positive trust was valid, {@code false}
2756 public boolean validatePositiveTrust(Integer positiveTrust) {
2757 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2761 * Sets the positive trust.
2763 * @param positiveTrust
2764 * The new positive trust, or {@code null} to restore it to
2766 * @return This preferences
2768 public Preferences setPositiveTrust(Integer positiveTrust) {
2769 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2774 * Returns the negative trust.
2776 * @return The negative trust
2778 public int getNegativeTrust() {
2779 return options.getIntegerOption("NegativeTrust").get();
2783 * Validates the negative trust.
2785 * @param negativeTrust
2786 * The negative trust to validate
2787 * @return {@code true} if the negative trust was valid, {@code false}
2790 public boolean validateNegativeTrust(Integer negativeTrust) {
2791 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2795 * Sets the negative trust.
2797 * @param negativeTrust
2798 * The negative trust, or {@code null} to restore it to the
2800 * @return The preferences
2802 public Preferences setNegativeTrust(Integer negativeTrust) {
2803 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2808 * Returns the trust comment. This is the comment that is set in the web
2809 * of trust when a trust value is assigned to an identity.
2811 * @return The trust comment
2813 public String getTrustComment() {
2814 return options.getStringOption("TrustComment").get();
2818 * Sets the trust comment.
2820 * @param trustComment
2821 * The trust comment, or {@code null} to restore it to the
2823 * @return This preferences
2825 public Preferences setTrustComment(String trustComment) {
2826 options.getStringOption("TrustComment").set(trustComment);
2831 * Returns whether the {@link FcpInterface FCP interface} is currently
2834 * @see FcpInterface#setActive(boolean)
2835 * @return {@code true} if the FCP interface is currently active,
2836 * {@code false} otherwise
2838 public boolean isFcpInterfaceActive() {
2839 return options.getBooleanOption("ActivateFcpInterface").get();
2843 * Sets whether the {@link FcpInterface FCP interface} is currently
2846 * @see FcpInterface#setActive(boolean)
2847 * @param fcpInterfaceActive
2848 * {@code true} to activate the FCP interface, {@code false}
2849 * to deactivate the FCP interface
2850 * @return This preferences object
2852 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2853 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2858 * Returns the action level for which full access to the FCP interface
2861 * @return The action level for which full access to the FCP interface
2864 public FullAccessRequired getFcpFullAccessRequired() {
2865 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2869 * Sets the action level for which full access to the FCP interface is
2872 * @param fcpFullAccessRequired
2874 * @return This preferences
2876 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2877 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);