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.SoneInsertingEvent;
47 import net.pterodactylus.sone.core.event.SoneLockedEvent;
48 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
49 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
50 import net.pterodactylus.sone.data.Album;
51 import net.pterodactylus.sone.data.Client;
52 import net.pterodactylus.sone.data.Image;
53 import net.pterodactylus.sone.data.Post;
54 import net.pterodactylus.sone.data.PostReply;
55 import net.pterodactylus.sone.data.Profile;
56 import net.pterodactylus.sone.data.Profile.Field;
57 import net.pterodactylus.sone.data.Reply;
58 import net.pterodactylus.sone.data.Sone;
59 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
60 import net.pterodactylus.sone.data.Sone.SoneStatus;
61 import net.pterodactylus.sone.data.TemporaryImage;
62 import net.pterodactylus.sone.data.impl.PostImpl;
63 import net.pterodactylus.sone.fcp.FcpInterface;
64 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
65 import net.pterodactylus.sone.freenet.wot.Identity;
66 import net.pterodactylus.sone.freenet.wot.IdentityListener;
67 import net.pterodactylus.sone.freenet.wot.IdentityManager;
68 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
69 import net.pterodactylus.sone.main.SonePlugin;
70 import net.pterodactylus.util.config.Configuration;
71 import net.pterodactylus.util.config.ConfigurationException;
72 import net.pterodactylus.util.logging.Logging;
73 import net.pterodactylus.util.number.Numbers;
74 import net.pterodactylus.util.service.AbstractService;
75 import net.pterodactylus.util.thread.NamedThreadFactory;
76 import net.pterodactylus.util.thread.Ticker;
77 import net.pterodactylus.util.validation.EqualityValidator;
78 import net.pterodactylus.util.validation.IntegerRangeValidator;
79 import net.pterodactylus.util.validation.OrValidator;
80 import net.pterodactylus.util.validation.Validation;
81 import net.pterodactylus.util.version.Version;
83 import com.google.common.base.Predicate;
84 import com.google.common.collect.Collections2;
85 import com.google.common.eventbus.EventBus;
86 import com.google.inject.Inject;
88 import freenet.keys.FreenetURI;
93 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
95 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
98 private static final Logger logger = Logging.getLogger(Core.class);
100 /** The start time. */
101 private final long startupTime = System.currentTimeMillis();
104 private final Options options = new Options();
106 /** The preferences. */
107 private final Preferences preferences = new Preferences(options);
109 /** The core listener manager. */
110 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
112 /** The event bus. */
113 private final EventBus eventBus;
115 /** The configuration. */
116 private Configuration configuration;
118 /** Whether we’re currently saving the configuration. */
119 private boolean storingConfiguration = false;
121 /** The identity manager. */
122 private final IdentityManager identityManager;
124 /** Interface to freenet. */
125 private final FreenetInterface freenetInterface;
127 /** The Sone downloader. */
128 private final SoneDownloader soneDownloader;
130 /** The image inserter. */
131 private final ImageInserter imageInserter;
133 /** Sone downloader thread-pool. */
134 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
136 /** The update checker. */
137 private final UpdateChecker updateChecker;
139 /** The trust updater. */
140 private final WebOfTrustUpdater webOfTrustUpdater;
142 /** The FCP interface. */
143 private volatile FcpInterface fcpInterface;
145 /** The times Sones were followed. */
146 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
148 /** Locked local Sones. */
149 /* synchronize on itself. */
150 private final Set<Sone> lockedSones = new HashSet<Sone>();
152 /** Sone inserters. */
153 /* synchronize access on this on sones. */
154 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
156 /** Sone rescuers. */
157 /* synchronize access on this on sones. */
158 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
161 /* synchronize access on this on itself. */
162 private final Map<String, Sone> sones = new HashMap<String, Sone>();
164 /** All known Sones. */
165 private final Set<String> knownSones = new HashSet<String>();
168 private final Map<String, Post> posts = new HashMap<String, Post>();
170 /** All known posts. */
171 private final Set<String> knownPosts = new HashSet<String>();
174 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
176 /** All known replies. */
177 private final Set<String> knownReplies = new HashSet<String>();
179 /** All bookmarked posts. */
180 /* synchronize access on itself. */
181 private final Set<String> bookmarkedPosts = new HashSet<String>();
183 /** Trusted identities, sorted by own identities. */
184 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
186 /** All known albums. */
187 private final Map<String, Album> albums = new HashMap<String, Album>();
189 /** All known images. */
190 private final Map<String, Image> images = new HashMap<String, Image>();
192 /** All temporary images. */
193 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
195 /** Ticker for threads that mark own elements as known. */
196 private final Ticker localElementTicker = new Ticker();
198 /** The time the configuration was last touched. */
199 private volatile long lastConfigurationUpdate;
202 * Creates a new core.
204 * @param configuration
205 * The configuration of the core
206 * @param freenetInterface
207 * The freenet interface
208 * @param identityManager
209 * The identity manager
210 * @param webOfTrustUpdater
211 * The WebOfTrust updater
216 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
218 this.configuration = configuration;
219 this.freenetInterface = freenetInterface;
220 this.identityManager = identityManager;
221 this.soneDownloader = new SoneDownloader(this, freenetInterface);
222 this.imageInserter = new ImageInserter(this, freenetInterface);
223 this.updateChecker = new UpdateChecker(freenetInterface);
224 this.webOfTrustUpdater = webOfTrustUpdater;
225 this.eventBus = eventBus;
229 // LISTENER MANAGEMENT
233 * Adds a new core listener.
235 * @param coreListener
236 * The listener to add
238 public void addCoreListener(CoreListener coreListener) {
239 coreListenerManager.addListener(coreListener);
243 * Removes a core listener.
245 * @param coreListener
246 * The listener to remove
248 public void removeCoreListener(CoreListener coreListener) {
249 coreListenerManager.removeListener(coreListener);
257 * Returns the time Sone was started.
259 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
261 public long getStartupTime() {
266 * Sets the configuration to use. This will automatically save the current
267 * configuration to the given configuration.
269 * @param configuration
270 * The new configuration to use
272 public void setConfiguration(Configuration configuration) {
273 this.configuration = configuration;
274 touchConfiguration();
278 * Returns the options used by the core.
280 * @return The options of the core
282 public Preferences getPreferences() {
287 * Returns the identity manager used by the core.
289 * @return The identity manager
291 public IdentityManager getIdentityManager() {
292 return identityManager;
296 * Returns the update checker.
298 * @return The update checker
300 public UpdateChecker getUpdateChecker() {
301 return updateChecker;
305 * Sets the FCP interface to use.
307 * @param fcpInterface
308 * The FCP interface to use
310 public void setFcpInterface(FcpInterface fcpInterface) {
311 this.fcpInterface = fcpInterface;
315 * Returns the Sone rescuer for the given local Sone.
318 * The local Sone to get the rescuer for
319 * @return The Sone rescuer for the given Sone
321 public SoneRescuer getSoneRescuer(Sone sone) {
322 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
323 synchronized (sones) {
324 SoneRescuer soneRescuer = soneRescuers.get(sone);
325 if (soneRescuer == null) {
326 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
327 soneRescuers.put(sone, soneRescuer);
335 * Returns whether the given Sone is currently locked.
339 * @return {@code true} if the Sone is locked, {@code false} if it is not
341 public boolean isLocked(Sone sone) {
342 synchronized (lockedSones) {
343 return lockedSones.contains(sone);
348 * Returns all Sones, remote and local.
352 public Set<Sone> getSones() {
353 return new HashSet<Sone>(sones.values());
357 * Returns the Sone with the given ID, regardless whether it’s local or
361 * The ID of the Sone to get
362 * @return The Sone with the given ID, or {@code null} if there is no such
365 public Sone getSone(String id) {
366 return getSone(id, true);
370 * Returns the Sone with the given ID, regardless whether it’s local or
374 * The ID of the Sone to get
376 * {@code true} to create a new Sone if none exists,
377 * {@code false} to return {@code null} if a Sone with the given
379 * @return The Sone with the given ID, or {@code null} if there is no such
383 public Sone getSone(String id, boolean create) {
384 synchronized (sones) {
385 if (!sones.containsKey(id)) {
386 Sone sone = new Sone(id, false);
389 return sones.get(id);
394 * Checks whether the core knows a Sone with the given ID.
398 * @return {@code true} if there is a Sone with the given ID, {@code false}
401 public boolean hasSone(String id) {
402 synchronized (sones) {
403 return sones.containsKey(id);
408 * Returns all local Sones.
410 * @return All local Sones
412 public Collection<Sone> getLocalSones() {
413 synchronized (sones) {
414 return Collections2.filter(sones.values(), new Predicate<Sone>() {
417 public boolean apply(Sone sone) {
418 return sone.isLocal();
425 * Returns the local Sone with the given ID, optionally creating a new Sone.
430 * {@code true} to create a new Sone if none exists,
431 * {@code false} to return null if none exists
432 * @return The Sone with the given ID, or {@code null}
434 public Sone getLocalSone(String id, boolean create) {
435 synchronized (sones) {
436 Sone sone = sones.get(id);
437 if ((sone == null) && create) {
438 sone = new Sone(id, true);
441 if ((sone != null) && !sone.isLocal()) {
442 sone = new Sone(id, true);
450 * Returns all remote Sones.
452 * @return All remote Sones
454 public Collection<Sone> getRemoteSones() {
455 synchronized (sones) {
456 return Collections2.filter(sones.values(), new Predicate<Sone>() {
459 public boolean apply(Sone sone) {
460 return !sone.isLocal();
467 * Returns the remote Sone with the given ID.
470 * The ID of the remote Sone to get
472 * {@code true} to always create a Sone, {@code false} to return
473 * {@code null} if no Sone with the given ID exists
474 * @return The Sone with the given ID
476 public Sone getRemoteSone(String id, boolean create) {
477 synchronized (sones) {
478 Sone sone = sones.get(id);
479 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
480 sone = new Sone(id, false);
488 * Returns whether the given Sone has been modified.
491 * The Sone to check for modifications
492 * @return {@code true} if a modification has been detected in the Sone,
493 * {@code false} otherwise
495 public boolean isModifiedSone(Sone sone) {
496 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
500 * Returns the time when the given was first followed by any local Sone.
503 * The Sone to get the time for
504 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
505 * been followed, or {@link Long#MAX_VALUE}
507 public long getSoneFollowingTime(Sone sone) {
508 synchronized (soneFollowingTimes) {
509 if (soneFollowingTimes.containsKey(sone)) {
510 return soneFollowingTimes.get(sone);
512 return Long.MAX_VALUE;
517 * Returns whether the target Sone is trusted by the origin Sone.
523 * @return {@code true} if the target Sone is trusted by the origin Sone
525 public boolean isSoneTrusted(Sone origin, Sone target) {
526 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
527 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
531 * Returns the post with the given ID.
534 * The ID of the post to get
535 * @return The post with the given ID, or a new post with the given ID
537 public Post getPost(String postId) {
538 return getPost(postId, true);
542 * Returns the post with the given ID, optionally creating a new post.
545 * The ID of the post to get
547 * {@code true} it create a new post if no post with the given ID
548 * exists, {@code false} to return {@code null}
549 * @return The post, or {@code null} if there is no such post
552 public Post getPost(String postId, boolean create) {
553 synchronized (posts) {
554 Post post = posts.get(postId);
555 if ((post == null) && create) {
556 post = new PostImpl(postId);
557 posts.put(postId, post);
564 * Returns all posts that have the given Sone as recipient.
566 * @see Post#getRecipient()
568 * The recipient of the posts
569 * @return All posts that have the given Sone as recipient
571 public Set<Post> getDirectedPosts(Sone recipient) {
572 Validation.begin().isNotNull("Recipient", recipient).check();
573 Set<Post> directedPosts = new HashSet<Post>();
574 synchronized (posts) {
575 for (Post post : posts.values()) {
576 if (recipient.equals(post.getRecipient())) {
577 directedPosts.add(post);
581 return directedPosts;
585 * Returns the reply with the given ID. If there is no reply with the given
586 * ID yet, a new one is created, unless {@code create} is false in which
587 * case {@code null} is returned.
590 * The ID of the reply to get
592 * {@code true} to always return a {@link Reply}, {@code false}
593 * to return {@code null} if no reply can be found
594 * @return The reply, or {@code null} if there is no such reply
596 public PostReply getPostReply(String replyId, boolean create) {
597 synchronized (replies) {
598 PostReply reply = replies.get(replyId);
599 if (create && (reply == null)) {
600 reply = new PostReply(replyId);
601 replies.put(replyId, reply);
608 * Returns all replies for the given post, order ascending by time.
611 * The post to get all replies for
612 * @return All replies for the given post
614 public List<PostReply> getReplies(Post post) {
615 Set<Sone> sones = getSones();
616 List<PostReply> replies = new ArrayList<PostReply>();
617 for (Sone sone : sones) {
618 for (PostReply reply : sone.getReplies()) {
619 if (reply.getPost().equals(post)) {
624 Collections.sort(replies, Reply.TIME_COMPARATOR);
629 * Returns all Sones that have liked the given post.
632 * The post to get the liking Sones for
633 * @return The Sones that like the given post
635 public Set<Sone> getLikes(Post post) {
636 Set<Sone> sones = new HashSet<Sone>();
637 for (Sone sone : getSones()) {
638 if (sone.getLikedPostIds().contains(post.getId())) {
646 * Returns all Sones that have liked the given reply.
649 * The reply to get the liking Sones for
650 * @return The Sones that like the given reply
652 public Set<Sone> getLikes(PostReply reply) {
653 Set<Sone> sones = new HashSet<Sone>();
654 for (Sone sone : getSones()) {
655 if (sone.getLikedReplyIds().contains(reply.getId())) {
663 * Returns whether the given post is bookmarked.
667 * @return {@code true} if the given post is bookmarked, {@code false}
670 public boolean isBookmarked(Post post) {
671 return isPostBookmarked(post.getId());
675 * Returns whether the post with the given ID is bookmarked.
678 * The ID of the post to check
679 * @return {@code true} if the post with the given ID is bookmarked,
680 * {@code false} otherwise
682 public boolean isPostBookmarked(String id) {
683 synchronized (bookmarkedPosts) {
684 return bookmarkedPosts.contains(id);
689 * Returns all currently known bookmarked posts.
691 * @return All bookmarked posts
693 public Set<Post> getBookmarkedPosts() {
694 Set<Post> posts = new HashSet<Post>();
695 synchronized (bookmarkedPosts) {
696 for (String bookmarkedPostId : bookmarkedPosts) {
697 Post post = getPost(bookmarkedPostId, false);
707 * Returns the album with the given ID, creating a new album if no album
708 * with the given ID can be found.
711 * The ID of the album
712 * @return The album with the given ID
714 public Album getAlbum(String albumId) {
715 return getAlbum(albumId, true);
719 * Returns the album with the given ID, optionally creating a new album if
720 * an album with the given ID can not be found.
723 * The ID of the album
725 * {@code true} to create a new album if none exists for the
727 * @return The album with the given ID, or {@code null} if no album with the
728 * given ID exists and {@code create} is {@code false}
730 public Album getAlbum(String albumId, boolean create) {
731 synchronized (albums) {
732 Album album = albums.get(albumId);
733 if (create && (album == null)) {
734 album = new Album(albumId);
735 albums.put(albumId, album);
742 * Returns the image with the given ID, creating it if necessary.
745 * The ID of the image
746 * @return The image with the given ID
748 public Image getImage(String imageId) {
749 return getImage(imageId, true);
753 * Returns the image with the given ID, optionally creating it if it does
757 * The ID of the image
759 * {@code true} to create an image if none exists with the given
761 * @return The image with the given ID, or {@code null} if none exists and
764 public Image getImage(String imageId, boolean create) {
765 synchronized (images) {
766 Image image = images.get(imageId);
767 if (create && (image == null)) {
768 image = new Image(imageId);
769 images.put(imageId, image);
776 * Returns the temporary image with the given ID.
779 * The ID of the temporary image
780 * @return The temporary image, or {@code null} if there is no temporary
781 * image with the given ID
783 public TemporaryImage getTemporaryImage(String imageId) {
784 synchronized (temporaryImages) {
785 return temporaryImages.get(imageId);
794 * Locks the given Sone. A locked Sone will not be inserted by
795 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
801 public void lockSone(Sone sone) {
802 synchronized (lockedSones) {
803 if (lockedSones.add(sone)) {
804 eventBus.post(new SoneLockedEvent(sone));
810 * Unlocks the given Sone.
812 * @see #lockSone(Sone)
816 public void unlockSone(Sone sone) {
817 synchronized (lockedSones) {
818 if (lockedSones.remove(sone)) {
819 eventBus.post(new SoneUnlockedEvent(sone));
825 * Adds a local Sone from the given own identity.
828 * The own identity to create a Sone from
829 * @return The added (or already existing) Sone
831 public Sone addLocalSone(OwnIdentity ownIdentity) {
832 if (ownIdentity == null) {
833 logger.log(Level.WARNING, "Given OwnIdentity is null!");
836 synchronized (sones) {
839 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
840 } catch (MalformedURLException mue1) {
841 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
844 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
845 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
847 /* TODO - load posts ’n stuff */
848 sones.put(ownIdentity.getId(), sone);
849 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
850 soneInserter.addSoneInsertListener(this);
851 soneInserters.put(sone, soneInserter);
852 sone.setStatus(SoneStatus.idle);
854 soneInserter.start();
860 * Creates a new Sone for the given own identity.
863 * The own identity to create a Sone for
864 * @return The created Sone
866 public Sone createSone(OwnIdentity ownIdentity) {
867 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
868 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
871 Sone sone = addLocalSone(ownIdentity);
872 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
873 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
874 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
875 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
876 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
877 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
879 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
880 touchConfiguration();
885 * Adds the Sone of the given identity.
888 * The identity whose Sone to add
889 * @return The added or already existing Sone
891 public Sone addRemoteSone(Identity identity) {
892 if (identity == null) {
893 logger.log(Level.WARNING, "Given Identity is null!");
896 synchronized (sones) {
897 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
898 boolean newSone = sone.getRequestUri() == null;
899 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
900 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
902 synchronized (knownSones) {
903 newSone = !knownSones.contains(sone.getId());
905 sone.setKnown(!newSone);
907 eventBus.post(new NewSoneFoundEvent(sone));
908 for (Sone localSone : getLocalSones()) {
909 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
910 followSone(localSone, sone);
915 soneDownloader.addSone(sone);
916 soneDownloaders.execute(new Runnable() {
919 @SuppressWarnings("synthetic-access")
921 soneDownloader.fetchSone(sone, sone.getRequestUri());
930 * Lets the given local Sone follow the Sone with the given ID.
933 * The local Sone that should follow another Sone
935 * The ID of the Sone to follow
937 public void followSone(Sone sone, String soneId) {
938 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
939 Sone followedSone = getSone(soneId, true);
940 if (followedSone == null) {
941 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
944 followSone(sone, getSone(soneId));
948 * Lets the given local Sone follow the other given Sone. If the given Sone
949 * was not followed by any local Sone before, this will mark all elements of
950 * the followed Sone as read that have been created before the current
954 * The local Sone that should follow the other Sone
955 * @param followedSone
956 * The Sone that should be followed
958 public void followSone(Sone sone, Sone followedSone) {
959 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
960 sone.addFriend(followedSone.getId());
961 synchronized (soneFollowingTimes) {
962 if (!soneFollowingTimes.containsKey(followedSone)) {
963 long now = System.currentTimeMillis();
964 soneFollowingTimes.put(followedSone, now);
965 for (Post post : followedSone.getPosts()) {
966 if (post.getTime() < now) {
970 for (PostReply reply : followedSone.getReplies()) {
971 if (reply.getTime() < now) {
972 markReplyKnown(reply);
977 touchConfiguration();
981 * Lets the given local Sone unfollow the Sone with the given ID.
984 * The local Sone that should unfollow another Sone
986 * The ID of the Sone being unfollowed
988 public void unfollowSone(Sone sone, String soneId) {
989 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
990 unfollowSone(sone, getSone(soneId, false));
994 * Lets the given local Sone unfollow the other given Sone. If the given
995 * local Sone is the last local Sone that followed the given Sone, its
996 * following time will be removed.
999 * The local Sone that should unfollow another Sone
1000 * @param unfollowedSone
1001 * The Sone being unfollowed
1003 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1004 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1005 sone.removeFriend(unfollowedSone.getId());
1006 boolean unfollowedSoneStillFollowed = false;
1007 for (Sone localSone : getLocalSones()) {
1008 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1010 if (!unfollowedSoneStillFollowed) {
1011 synchronized (soneFollowingTimes) {
1012 soneFollowingTimes.remove(unfollowedSone);
1015 touchConfiguration();
1019 * Sets the trust value of the given origin Sone for the target Sone.
1026 * The trust value (from {@code -100} to {@code 100})
1028 public void setTrust(Sone origin, Sone target, int trustValue) {
1029 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();
1030 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1034 * Removes any trust assignment for the given target Sone.
1041 public void removeTrust(Sone origin, Sone target) {
1042 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1043 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1047 * Assigns the configured positive trust value for the given target.
1054 public void trustSone(Sone origin, Sone target) {
1055 setTrust(origin, target, preferences.getPositiveTrust());
1059 * Assigns the configured negative trust value for the given target.
1066 public void distrustSone(Sone origin, Sone target) {
1067 setTrust(origin, target, preferences.getNegativeTrust());
1071 * Removes the trust assignment for the given target.
1078 public void untrustSone(Sone origin, Sone target) {
1079 removeTrust(origin, target);
1083 * Updates the stored Sone with the given Sone.
1088 public void updateSone(Sone sone) {
1089 updateSone(sone, false);
1093 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1094 * {@code true}, an older Sone than the current Sone can be given to restore
1098 * The Sone to update
1099 * @param soneRescueMode
1100 * {@code true} if the stored Sone should be updated regardless
1101 * of the age of the given Sone
1103 public void updateSone(Sone sone, boolean soneRescueMode) {
1104 if (hasSone(sone.getId())) {
1105 Sone storedSone = getSone(sone.getId());
1106 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1107 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1110 synchronized (posts) {
1111 if (!soneRescueMode) {
1112 for (Post post : storedSone.getPosts()) {
1113 posts.remove(post.getId());
1114 if (!sone.getPosts().contains(post)) {
1115 eventBus.post(new PostRemovedEvent(post));
1119 List<Post> storedPosts = storedSone.getPosts();
1120 synchronized (knownPosts) {
1121 for (Post post : sone.getPosts()) {
1122 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1123 if (!storedPosts.contains(post)) {
1124 if (post.getTime() < getSoneFollowingTime(sone)) {
1125 knownPosts.add(post.getId());
1126 post.setKnown(true);
1127 } else if (!knownPosts.contains(post.getId())) {
1128 eventBus.post(new NewPostFoundEvent(post));
1131 posts.put(post.getId(), post);
1135 synchronized (replies) {
1136 if (!soneRescueMode) {
1137 for (PostReply reply : storedSone.getReplies()) {
1138 replies.remove(reply.getId());
1139 if (!sone.getReplies().contains(reply)) {
1140 eventBus.post(new PostReplyRemovedEvent(reply));
1144 Set<PostReply> storedReplies = storedSone.getReplies();
1145 synchronized (knownReplies) {
1146 for (PostReply reply : sone.getReplies()) {
1147 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1148 if (!storedReplies.contains(reply)) {
1149 if (reply.getTime() < getSoneFollowingTime(sone)) {
1150 knownReplies.add(reply.getId());
1151 reply.setKnown(true);
1152 } else if (!knownReplies.contains(reply.getId())) {
1153 eventBus.post(new NewPostReplyFoundEvent(reply));
1156 replies.put(reply.getId(), reply);
1160 synchronized (albums) {
1161 synchronized (images) {
1162 for (Album album : storedSone.getAlbums()) {
1163 albums.remove(album.getId());
1164 for (Image image : album.getImages()) {
1165 images.remove(image.getId());
1168 for (Album album : sone.getAlbums()) {
1169 albums.put(album.getId(), album);
1170 for (Image image : album.getImages()) {
1171 images.put(image.getId(), image);
1176 synchronized (storedSone) {
1177 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1178 storedSone.setTime(sone.getTime());
1180 storedSone.setClient(sone.getClient());
1181 storedSone.setProfile(sone.getProfile());
1182 if (soneRescueMode) {
1183 for (Post post : sone.getPosts()) {
1184 storedSone.addPost(post);
1186 for (PostReply reply : sone.getReplies()) {
1187 storedSone.addReply(reply);
1189 for (String likedPostId : sone.getLikedPostIds()) {
1190 storedSone.addLikedPostId(likedPostId);
1192 for (String likedReplyId : sone.getLikedReplyIds()) {
1193 storedSone.addLikedReplyId(likedReplyId);
1195 for (Album album : sone.getAlbums()) {
1196 storedSone.addAlbum(album);
1199 storedSone.setPosts(sone.getPosts());
1200 storedSone.setReplies(sone.getReplies());
1201 storedSone.setLikePostIds(sone.getLikedPostIds());
1202 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1203 storedSone.setAlbums(sone.getAlbums());
1205 storedSone.setLatestEdition(sone.getLatestEdition());
1211 * Deletes the given Sone. This will remove the Sone from the
1212 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1213 * remove the context from its identity.
1216 * The Sone to delete
1218 public void deleteSone(Sone sone) {
1219 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1220 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1223 synchronized (sones) {
1224 if (!getLocalSones().contains(sone)) {
1225 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1228 sones.remove(sone.getId());
1229 SoneInserter soneInserter = soneInserters.remove(sone);
1230 soneInserter.removeSoneInsertListener(this);
1231 soneInserter.stop();
1233 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1234 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1236 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1237 } catch (ConfigurationException ce1) {
1238 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1243 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1244 * known} before, a {@link MarkSoneKnownEvent} is fired.
1247 * The Sone to mark as known
1249 public void markSoneKnown(Sone sone) {
1250 if (!sone.isKnown()) {
1251 sone.setKnown(true);
1252 synchronized (knownSones) {
1253 knownSones.add(sone.getId());
1255 eventBus.post(new MarkSoneKnownEvent(sone));
1256 touchConfiguration();
1261 * Loads and updates the given Sone from the configuration. If any error is
1262 * encountered, loading is aborted and the given Sone is not changed.
1265 * The Sone to load and update
1267 public void loadSone(Sone sone) {
1268 if (!sone.isLocal()) {
1269 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1273 /* initialize options. */
1274 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1275 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1276 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1277 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1278 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1279 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1282 String sonePrefix = "Sone/" + sone.getId();
1283 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1284 if (soneTime == null) {
1285 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1288 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1291 Profile profile = new Profile(sone);
1292 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1293 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1294 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1295 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1296 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1297 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1299 /* load profile fields. */
1301 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1302 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1303 if (fieldName == null) {
1306 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1307 profile.addField(fieldName).setValue(fieldValue);
1311 Set<Post> posts = new HashSet<Post>();
1313 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1314 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1315 if (postId == null) {
1318 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1319 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1320 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1321 if ((postTime == 0) || (postText == null)) {
1322 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1325 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1326 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1327 post.setRecipient(getSone(postRecipientId));
1333 Set<PostReply> replies = new HashSet<PostReply>();
1335 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1336 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1337 if (replyId == null) {
1340 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1341 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1342 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1343 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1344 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1347 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1350 /* load post likes. */
1351 Set<String> likedPostIds = new HashSet<String>();
1353 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1354 if (likedPostId == null) {
1357 likedPostIds.add(likedPostId);
1360 /* load reply likes. */
1361 Set<String> likedReplyIds = new HashSet<String>();
1363 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1364 if (likedReplyId == null) {
1367 likedReplyIds.add(likedReplyId);
1371 Set<String> friends = new HashSet<String>();
1373 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1374 if (friendId == null) {
1377 friends.add(friendId);
1381 List<Album> topLevelAlbums = new ArrayList<Album>();
1382 int albumCounter = 0;
1384 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1385 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1386 if (albumId == null) {
1389 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1390 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1391 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1392 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1393 if ((albumTitle == null) || (albumDescription == null)) {
1394 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1397 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1398 if (albumParentId != null) {
1399 Album parentAlbum = getAlbum(albumParentId, false);
1400 if (parentAlbum == null) {
1401 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1404 parentAlbum.addAlbum(album);
1406 if (!topLevelAlbums.contains(album)) {
1407 topLevelAlbums.add(album);
1413 int imageCounter = 0;
1415 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1416 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1417 if (imageId == null) {
1420 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1421 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1422 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1423 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1424 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1425 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1426 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1427 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1428 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1431 Album album = getAlbum(albumId, false);
1432 if (album == null) {
1433 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1436 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1437 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1438 album.addImage(image);
1442 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1443 if (avatarId != null) {
1444 profile.setAvatar(getImage(avatarId, false));
1448 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1449 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1450 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1451 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1452 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1453 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1455 /* if we’re still here, Sone was loaded successfully. */
1456 synchronized (sone) {
1457 sone.setTime(soneTime);
1458 sone.setProfile(profile);
1459 sone.setPosts(posts);
1460 sone.setReplies(replies);
1461 sone.setLikePostIds(likedPostIds);
1462 sone.setLikeReplyIds(likedReplyIds);
1463 for (String friendId : friends) {
1464 followSone(sone, friendId);
1466 sone.setAlbums(topLevelAlbums);
1467 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1469 synchronized (knownSones) {
1470 for (String friend : friends) {
1471 knownSones.add(friend);
1474 synchronized (knownPosts) {
1475 for (Post post : posts) {
1476 knownPosts.add(post.getId());
1479 synchronized (knownReplies) {
1480 for (PostReply reply : replies) {
1481 knownReplies.add(reply.getId());
1487 * Creates a new post.
1490 * The Sone that creates the post
1492 * The text of the post
1493 * @return The created post
1495 public Post createPost(Sone sone, String text) {
1496 return createPost(sone, System.currentTimeMillis(), text);
1500 * Creates a new post.
1503 * The Sone that creates the post
1505 * The time of the post
1507 * The text of the post
1508 * @return The created post
1510 public Post createPost(Sone sone, long time, String text) {
1511 return createPost(sone, null, time, text);
1515 * Creates a new post.
1518 * The Sone that creates the post
1520 * The recipient Sone, or {@code null} if this post does not have
1523 * The text of the post
1524 * @return The created post
1526 public Post createPost(Sone sone, Sone recipient, String text) {
1527 return createPost(sone, recipient, System.currentTimeMillis(), text);
1531 * Creates a new post.
1534 * The Sone that creates the post
1536 * The recipient Sone, or {@code null} if this post does not have
1539 * The time of the post
1541 * The text of the post
1542 * @return The created post
1544 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1545 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1546 if (!sone.isLocal()) {
1547 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1550 final Post post = new PostImpl(sone, time, text);
1551 if (recipient != null) {
1552 post.setRecipient(recipient);
1554 synchronized (posts) {
1555 posts.put(post.getId(), post);
1557 eventBus.post(new NewPostFoundEvent(post));
1559 touchConfiguration();
1560 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1567 markPostKnown(post);
1569 }, "Mark " + post + " read.");
1574 * Deletes the given post.
1577 * The post to delete
1579 public void deletePost(Post post) {
1580 if (!post.getSone().isLocal()) {
1581 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1584 post.getSone().removePost(post);
1585 synchronized (posts) {
1586 posts.remove(post.getId());
1588 eventBus.post(new PostRemovedEvent(post));
1589 markPostKnown(post);
1590 touchConfiguration();
1594 * Marks the given post as known, if it is currently not a known post
1595 * (according to {@link Post#isKnown()}).
1598 * The post to mark as known
1600 public void markPostKnown(Post post) {
1601 post.setKnown(true);
1602 synchronized (knownPosts) {
1603 eventBus.post(new MarkPostKnownEvent(post));
1604 if (knownPosts.add(post.getId())) {
1605 touchConfiguration();
1608 for (PostReply reply : getReplies(post)) {
1609 markReplyKnown(reply);
1614 * Bookmarks the given post.
1617 * The post to bookmark
1619 public void bookmark(Post post) {
1620 bookmarkPost(post.getId());
1624 * Bookmarks the post with the given ID.
1627 * The ID of the post to bookmark
1629 public void bookmarkPost(String id) {
1630 synchronized (bookmarkedPosts) {
1631 bookmarkedPosts.add(id);
1636 * Removes the given post from the bookmarks.
1639 * The post to unbookmark
1641 public void unbookmark(Post post) {
1642 unbookmarkPost(post.getId());
1646 * Removes the post with the given ID from the bookmarks.
1649 * The ID of the post to unbookmark
1651 public void unbookmarkPost(String id) {
1652 synchronized (bookmarkedPosts) {
1653 bookmarkedPosts.remove(id);
1658 * Creates a new reply.
1661 * The Sone that creates the reply
1663 * The post that this reply refers to
1665 * The text of the reply
1666 * @return The created reply
1668 public PostReply createReply(Sone sone, Post post, String text) {
1669 return createReply(sone, post, System.currentTimeMillis(), text);
1673 * Creates a new reply.
1676 * The Sone that creates the reply
1678 * The post that this reply refers to
1680 * The time of the reply
1682 * The text of the reply
1683 * @return The created reply
1685 public PostReply createReply(Sone sone, Post post, long time, String text) {
1686 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1687 if (!sone.isLocal()) {
1688 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1691 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1692 synchronized (replies) {
1693 replies.put(reply.getId(), reply);
1695 synchronized (knownReplies) {
1696 eventBus.post(new NewPostReplyFoundEvent(reply));
1698 sone.addReply(reply);
1699 touchConfiguration();
1700 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1707 markReplyKnown(reply);
1709 }, "Mark " + reply + " read.");
1714 * Deletes the given reply.
1717 * The reply to delete
1719 public void deleteReply(PostReply reply) {
1720 Sone sone = reply.getSone();
1721 if (!sone.isLocal()) {
1722 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1725 synchronized (replies) {
1726 replies.remove(reply.getId());
1728 synchronized (knownReplies) {
1729 markReplyKnown(reply);
1730 knownReplies.remove(reply.getId());
1732 sone.removeReply(reply);
1733 touchConfiguration();
1737 * Marks the given reply as known, if it is currently not a known reply
1738 * (according to {@link Reply#isKnown()}).
1741 * The reply to mark as known
1743 public void markReplyKnown(PostReply reply) {
1744 reply.setKnown(true);
1745 synchronized (knownReplies) {
1746 eventBus.post(new MarkPostReplyKnownEvent(reply));
1747 if (knownReplies.add(reply.getId())) {
1748 touchConfiguration();
1754 * Creates a new top-level album for the given Sone.
1757 * The Sone to create the album for
1758 * @return The new album
1760 public Album createAlbum(Sone sone) {
1761 return createAlbum(sone, null);
1765 * Creates a new album for the given Sone.
1768 * The Sone to create the album for
1770 * The parent of the album (may be {@code null} to create a
1772 * @return The new album
1774 public Album createAlbum(Sone sone, Album parent) {
1775 Album album = new Album();
1776 synchronized (albums) {
1777 albums.put(album.getId(), album);
1779 album.setSone(sone);
1780 if (parent != null) {
1781 parent.addAlbum(album);
1783 sone.addAlbum(album);
1789 * Deletes the given album. The owner of the album has to be a local Sone,
1790 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1793 * The album to remove
1795 public void deleteAlbum(Album album) {
1796 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1797 if (!album.isEmpty()) {
1800 if (album.getParent() == null) {
1801 album.getSone().removeAlbum(album);
1803 album.getParent().removeAlbum(album);
1805 synchronized (albums) {
1806 albums.remove(album.getId());
1808 touchConfiguration();
1812 * Creates a new image.
1815 * The Sone creating the image
1817 * The album the image will be inserted into
1818 * @param temporaryImage
1819 * The temporary image to create the image from
1820 * @return The newly created image
1822 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1823 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();
1824 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1825 album.addImage(image);
1826 synchronized (images) {
1827 images.put(image.getId(), image);
1829 imageInserter.insertImage(temporaryImage, image);
1834 * Deletes the given image. This method will also delete a matching
1837 * @see #deleteTemporaryImage(TemporaryImage)
1839 * The image to delete
1841 public void deleteImage(Image image) {
1842 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1843 deleteTemporaryImage(image.getId());
1844 image.getAlbum().removeImage(image);
1845 synchronized (images) {
1846 images.remove(image.getId());
1848 touchConfiguration();
1852 * Creates a new temporary image.
1855 * The MIME type of the temporary image
1857 * The encoded data of the image
1858 * @return The temporary image
1860 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1861 TemporaryImage temporaryImage = new TemporaryImage();
1862 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1863 synchronized (temporaryImages) {
1864 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1866 return temporaryImage;
1870 * Deletes the given temporary image.
1872 * @param temporaryImage
1873 * The temporary image to delete
1875 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1876 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1877 deleteTemporaryImage(temporaryImage.getId());
1881 * Deletes the temporary image with the given ID.
1884 * The ID of the temporary image to delete
1886 public void deleteTemporaryImage(String imageId) {
1887 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1888 synchronized (temporaryImages) {
1889 temporaryImages.remove(imageId);
1891 Image image = getImage(imageId, false);
1892 if (image != null) {
1893 imageInserter.cancelImageInsert(image);
1898 * Notifies the core that the configuration, either of the core or of a
1899 * single local Sone, has changed, and that the configuration should be
1902 public void touchConfiguration() {
1903 lastConfigurationUpdate = System.currentTimeMillis();
1914 public void serviceStart() {
1915 loadConfiguration();
1916 updateChecker.addUpdateListener(this);
1917 updateChecker.start();
1918 identityManager.addIdentityListener(this);
1919 identityManager.start();
1920 webOfTrustUpdater.init();
1921 webOfTrustUpdater.start();
1928 public void serviceRun() {
1929 long lastSaved = System.currentTimeMillis();
1930 while (!shouldStop()) {
1932 long now = System.currentTimeMillis();
1933 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1934 for (Sone localSone : getLocalSones()) {
1935 saveSone(localSone);
1937 saveConfiguration();
1947 public void serviceStop() {
1948 synchronized (sones) {
1949 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1950 soneInserter.getValue().removeSoneInsertListener(this);
1951 soneInserter.getValue().stop();
1952 saveSone(soneInserter.getKey());
1955 saveConfiguration();
1956 webOfTrustUpdater.stop();
1957 updateChecker.stop();
1958 updateChecker.removeUpdateListener(this);
1959 soneDownloader.stop();
1960 identityManager.removeIdentityListener(this);
1961 identityManager.stop();
1969 * Saves the given Sone. This will persist all local settings for the given
1970 * Sone, such as the friends list and similar, private options.
1975 private synchronized void saveSone(Sone sone) {
1976 if (!sone.isLocal()) {
1977 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1980 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1981 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1985 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1987 /* save Sone into configuration. */
1988 String sonePrefix = "Sone/" + sone.getId();
1989 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1990 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1993 Profile profile = sone.getProfile();
1994 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1995 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1996 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1997 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1998 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1999 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2000 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2002 /* save profile fields. */
2003 int fieldCounter = 0;
2004 for (Field profileField : profile.getFields()) {
2005 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2006 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2007 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2009 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2012 int postCounter = 0;
2013 for (Post post : sone.getPosts()) {
2014 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2015 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2016 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2017 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2018 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2020 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2023 int replyCounter = 0;
2024 for (PostReply reply : sone.getReplies()) {
2025 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2026 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2027 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2028 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2029 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2031 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2033 /* save post likes. */
2034 int postLikeCounter = 0;
2035 for (String postId : sone.getLikedPostIds()) {
2036 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2038 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2040 /* save reply likes. */
2041 int replyLikeCounter = 0;
2042 for (String replyId : sone.getLikedReplyIds()) {
2043 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2045 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2048 int friendCounter = 0;
2049 for (String friendId : sone.getFriends()) {
2050 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2052 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2054 /* save albums. first, collect in a flat structure, top-level first. */
2055 List<Album> albums = sone.getAllAlbums();
2057 int albumCounter = 0;
2058 for (Album album : albums) {
2059 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2060 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2061 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2062 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2063 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2064 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2066 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2069 int imageCounter = 0;
2070 for (Album album : albums) {
2071 for (Image image : album.getImages()) {
2072 if (!image.isInserted()) {
2075 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2076 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2077 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2078 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2079 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2080 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2081 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2082 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2083 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2086 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2089 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2090 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2091 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2092 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2093 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2094 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2096 configuration.save();
2098 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2100 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2101 } catch (ConfigurationException ce1) {
2102 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2107 * Saves the current options.
2109 private void saveConfiguration() {
2110 synchronized (configuration) {
2111 if (storingConfiguration) {
2112 logger.log(Level.FINE, "Already storing configuration…");
2115 storingConfiguration = true;
2118 /* store the options first. */
2120 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2121 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2122 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2123 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2124 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2125 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2126 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2127 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2128 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2129 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2130 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2131 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2133 /* save known Sones. */
2134 int soneCounter = 0;
2135 synchronized (knownSones) {
2136 for (String knownSoneId : knownSones) {
2137 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2139 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2142 /* save Sone following times. */
2144 synchronized (soneFollowingTimes) {
2145 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2146 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2147 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2150 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2153 /* save known posts. */
2154 int postCounter = 0;
2155 synchronized (knownPosts) {
2156 for (String knownPostId : knownPosts) {
2157 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2159 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2162 /* save known replies. */
2163 int replyCounter = 0;
2164 synchronized (knownReplies) {
2165 for (String knownReplyId : knownReplies) {
2166 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2168 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2171 /* save bookmarked posts. */
2172 int bookmarkedPostCounter = 0;
2173 synchronized (bookmarkedPosts) {
2174 for (String bookmarkedPostId : bookmarkedPosts) {
2175 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2178 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2181 configuration.save();
2183 } catch (ConfigurationException ce1) {
2184 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2186 synchronized (configuration) {
2187 storingConfiguration = false;
2193 * Loads the configuration.
2195 @SuppressWarnings("unchecked")
2196 private void loadConfiguration() {
2197 /* create options. */
2198 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2201 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2202 SoneInserter.setInsertionDelay(newValue);
2206 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2207 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2208 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2209 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2210 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2211 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2212 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2213 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2214 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2217 @SuppressWarnings("synthetic-access")
2218 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2219 fcpInterface.setActive(newValue);
2222 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2225 @SuppressWarnings("synthetic-access")
2226 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2227 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2232 loadConfigurationValue("InsertionDelay");
2233 loadConfigurationValue("PostsPerPage");
2234 loadConfigurationValue("ImagesPerPage");
2235 loadConfigurationValue("CharactersPerPost");
2236 loadConfigurationValue("PostCutOffLength");
2237 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2238 loadConfigurationValue("PositiveTrust");
2239 loadConfigurationValue("NegativeTrust");
2240 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2241 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2242 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2244 /* load known Sones. */
2245 int soneCounter = 0;
2247 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2248 if (knownSoneId == null) {
2251 synchronized (knownSones) {
2252 knownSones.add(knownSoneId);
2256 /* load Sone following times. */
2259 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2260 if (soneId == null) {
2263 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2264 Sone followedSone = getSone(soneId);
2265 if (followedSone == null) {
2266 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2268 synchronized (soneFollowingTimes) {
2269 soneFollowingTimes.put(getSone(soneId), time);
2275 /* load known posts. */
2276 int postCounter = 0;
2278 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2279 if (knownPostId == null) {
2282 synchronized (knownPosts) {
2283 knownPosts.add(knownPostId);
2287 /* load known replies. */
2288 int replyCounter = 0;
2290 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2291 if (knownReplyId == null) {
2294 synchronized (knownReplies) {
2295 knownReplies.add(knownReplyId);
2299 /* load bookmarked posts. */
2300 int bookmarkedPostCounter = 0;
2302 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2303 if (bookmarkedPostId == null) {
2306 synchronized (bookmarkedPosts) {
2307 bookmarkedPosts.add(bookmarkedPostId);
2314 * Loads an {@link Integer} configuration value for the option with the
2315 * given name, logging validation failures.
2318 * The name of the option to load
2320 private void loadConfigurationValue(String optionName) {
2322 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2323 } catch (IllegalArgumentException iae1) {
2324 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2329 * Generate a Sone URI from the given URI and latest edition.
2332 * The URI to derive the Sone URI from
2333 * @return The derived URI
2335 private static FreenetURI getSoneUri(String uriString) {
2337 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2339 } catch (MalformedURLException mue1) {
2340 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2346 // INTERFACE IdentityListener
2353 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2354 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2355 if (ownIdentity.hasContext("Sone")) {
2356 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2357 addLocalSone(ownIdentity);
2365 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2366 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2367 trustedIdentities.remove(ownIdentity);
2374 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2375 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2376 trustedIdentities.get(ownIdentity).add(identity);
2377 addRemoteSone(identity);
2384 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2385 soneDownloaders.execute(new Runnable() {
2388 @SuppressWarnings("synthetic-access")
2390 Sone sone = getRemoteSone(identity.getId(), false);
2391 sone.setIdentity(identity);
2392 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2393 soneDownloader.addSone(sone);
2394 soneDownloader.fetchSone(sone);
2403 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2404 trustedIdentities.get(ownIdentity).remove(identity);
2405 boolean foundIdentity = false;
2406 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2407 if (trustedIdentity.getKey().equals(ownIdentity)) {
2410 if (trustedIdentity.getValue().contains(identity)) {
2411 foundIdentity = true;
2414 if (foundIdentity) {
2415 /* some local identity still trusts this identity, don’t remove. */
2418 Sone sone = getSone(identity.getId(), false);
2420 /* TODO - we don’t have the Sone anymore. should this happen? */
2423 synchronized (posts) {
2424 synchronized (knownPosts) {
2425 for (Post post : sone.getPosts()) {
2426 posts.remove(post.getId());
2427 eventBus.post(new PostRemovedEvent(post));
2431 synchronized (replies) {
2432 synchronized (knownReplies) {
2433 for (PostReply reply : sone.getReplies()) {
2434 replies.remove(reply.getId());
2435 eventBus.post(new PostReplyRemovedEvent(reply));
2439 synchronized (sones) {
2440 sones.remove(identity.getId());
2442 eventBus.post(new SoneRemovedEvent(sone));
2446 // INTERFACE UpdateListener
2453 public void updateFound(Version version, long releaseTime, long latestEdition) {
2454 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2458 // INTERFACE ImageInsertListener
2465 public void insertStarted(Sone sone) {
2466 eventBus.post(new SoneInsertingEvent(sone));
2473 public void insertFinished(Sone sone, long insertDuration) {
2474 coreListenerManager.fireSoneInserted(sone, insertDuration);
2481 public void insertAborted(Sone sone, Throwable cause) {
2482 coreListenerManager.fireSoneInsertAborted(sone, cause);
2486 // SONEINSERTLISTENER METHODS
2493 public void imageInsertStarted(Image image) {
2494 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2495 coreListenerManager.fireImageInsertStarted(image);
2502 public void imageInsertAborted(Image image) {
2503 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2504 coreListenerManager.fireImageInsertAborted(image);
2511 public void imageInsertFinished(Image image, FreenetURI key) {
2512 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2513 image.setKey(key.toString());
2514 deleteTemporaryImage(image.getId());
2515 touchConfiguration();
2516 coreListenerManager.fireImageInsertFinished(image);
2523 public void imageInsertFailed(Image image, Throwable cause) {
2524 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2525 coreListenerManager.fireImageInsertFailed(image, cause);
2529 * Convenience interface for external classes that want to access the core’s
2532 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2534 public static class Preferences {
2536 /** The wrapped options. */
2537 private final Options options;
2540 * Creates a new preferences object wrapped around the given options.
2543 * The options to wrap
2545 public Preferences(Options options) {
2546 this.options = options;
2550 * Returns the insertion delay.
2552 * @return The insertion delay
2554 public int getInsertionDelay() {
2555 return options.getIntegerOption("InsertionDelay").get();
2559 * Validates the given insertion delay.
2561 * @param insertionDelay
2562 * The insertion delay to validate
2563 * @return {@code true} if the given insertion delay was valid,
2564 * {@code false} otherwise
2566 public boolean validateInsertionDelay(Integer insertionDelay) {
2567 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2571 * Sets the insertion delay
2573 * @param insertionDelay
2574 * The new insertion delay, or {@code null} to restore it to
2576 * @return This preferences
2578 public Preferences setInsertionDelay(Integer insertionDelay) {
2579 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2584 * Returns the number of posts to show per page.
2586 * @return The number of posts to show per page
2588 public int getPostsPerPage() {
2589 return options.getIntegerOption("PostsPerPage").get();
2593 * Validates the number of posts per page.
2595 * @param postsPerPage
2596 * The number of posts per page
2597 * @return {@code true} if the number of posts per page was valid,
2598 * {@code false} otherwise
2600 public boolean validatePostsPerPage(Integer postsPerPage) {
2601 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2605 * Sets the number of posts to show per page.
2607 * @param postsPerPage
2608 * The number of posts to show per page
2609 * @return This preferences object
2611 public Preferences setPostsPerPage(Integer postsPerPage) {
2612 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2617 * Returns the number of images to show per page.
2619 * @return The number of images to show per page
2621 public int getImagesPerPage() {
2622 return options.getIntegerOption("ImagesPerPage").get();
2626 * Validates the number of images per page.
2628 * @param imagesPerPage
2629 * The number of images per page
2630 * @return {@code true} if the number of images per page was valid,
2631 * {@code false} otherwise
2633 public boolean validateImagesPerPage(Integer imagesPerPage) {
2634 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2638 * Sets the number of images per page.
2640 * @param imagesPerPage
2641 * The number of images per page
2642 * @return This preferences object
2644 public Preferences setImagesPerPage(Integer imagesPerPage) {
2645 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2650 * Returns the number of characters per post, or <code>-1</code> if the
2651 * posts should not be cut off.
2653 * @return The numbers of characters per post
2655 public int getCharactersPerPost() {
2656 return options.getIntegerOption("CharactersPerPost").get();
2660 * Validates the number of characters per post.
2662 * @param charactersPerPost
2663 * The number of characters per post
2664 * @return {@code true} if the number of characters per post was valid,
2665 * {@code false} otherwise
2667 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2668 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2672 * Sets the number of characters per post.
2674 * @param charactersPerPost
2675 * The number of characters per post, or <code>-1</code> to
2676 * not cut off the posts
2677 * @return This preferences objects
2679 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2680 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2685 * Returns the number of characters the shortened post should have.
2687 * @return The number of characters of the snippet
2689 public int getPostCutOffLength() {
2690 return options.getIntegerOption("PostCutOffLength").get();
2694 * Validates the number of characters after which to cut off the post.
2696 * @param postCutOffLength
2697 * The number of characters of the snippet
2698 * @return {@code true} if the number of characters of the snippet is
2699 * valid, {@code false} otherwise
2701 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2702 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2706 * Sets the number of characters the shortened post should have.
2708 * @param postCutOffLength
2709 * The number of characters of the snippet
2710 * @return This preferences
2712 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2713 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2718 * Returns whether Sone requires full access to be even visible.
2720 * @return {@code true} if Sone requires full access, {@code false}
2723 public boolean isRequireFullAccess() {
2724 return options.getBooleanOption("RequireFullAccess").get();
2728 * Sets whether Sone requires full access to be even visible.
2730 * @param requireFullAccess
2731 * {@code true} if Sone requires full access, {@code false}
2734 public void setRequireFullAccess(Boolean requireFullAccess) {
2735 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2739 * Returns the positive trust.
2741 * @return The positive trust
2743 public int getPositiveTrust() {
2744 return options.getIntegerOption("PositiveTrust").get();
2748 * Validates the positive trust.
2750 * @param positiveTrust
2751 * The positive trust to validate
2752 * @return {@code true} if the positive trust was valid, {@code false}
2755 public boolean validatePositiveTrust(Integer positiveTrust) {
2756 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2760 * Sets the positive trust.
2762 * @param positiveTrust
2763 * The new positive trust, or {@code null} to restore it to
2765 * @return This preferences
2767 public Preferences setPositiveTrust(Integer positiveTrust) {
2768 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2773 * Returns the negative trust.
2775 * @return The negative trust
2777 public int getNegativeTrust() {
2778 return options.getIntegerOption("NegativeTrust").get();
2782 * Validates the negative trust.
2784 * @param negativeTrust
2785 * The negative trust to validate
2786 * @return {@code true} if the negative trust was valid, {@code false}
2789 public boolean validateNegativeTrust(Integer negativeTrust) {
2790 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2794 * Sets the negative trust.
2796 * @param negativeTrust
2797 * The negative trust, or {@code null} to restore it to the
2799 * @return The preferences
2801 public Preferences setNegativeTrust(Integer negativeTrust) {
2802 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2807 * Returns the trust comment. This is the comment that is set in the web
2808 * of trust when a trust value is assigned to an identity.
2810 * @return The trust comment
2812 public String getTrustComment() {
2813 return options.getStringOption("TrustComment").get();
2817 * Sets the trust comment.
2819 * @param trustComment
2820 * The trust comment, or {@code null} to restore it to the
2822 * @return This preferences
2824 public Preferences setTrustComment(String trustComment) {
2825 options.getStringOption("TrustComment").set(trustComment);
2830 * Returns whether the {@link FcpInterface FCP interface} is currently
2833 * @see FcpInterface#setActive(boolean)
2834 * @return {@code true} if the FCP interface is currently active,
2835 * {@code false} otherwise
2837 public boolean isFcpInterfaceActive() {
2838 return options.getBooleanOption("ActivateFcpInterface").get();
2842 * Sets whether the {@link FcpInterface FCP interface} is currently
2845 * @see FcpInterface#setActive(boolean)
2846 * @param fcpInterfaceActive
2847 * {@code true} to activate the FCP interface, {@code false}
2848 * to deactivate the FCP interface
2849 * @return This preferences object
2851 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2852 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2857 * Returns the action level for which full access to the FCP interface
2860 * @return The action level for which full access to the FCP interface
2863 public FullAccessRequired getFcpFullAccessRequired() {
2864 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2868 * Sets the action level for which full access to the FCP interface is
2871 * @param fcpFullAccessRequired
2873 * @return This preferences
2875 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2876 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);