2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
40 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
41 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
42 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
43 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
45 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
46 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
47 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
48 import net.pterodactylus.sone.core.event.PostRemovedEvent;
49 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
50 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
51 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
52 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
53 import net.pterodactylus.sone.core.event.SoneLockedEvent;
54 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
56 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.data.impl.PostImpl;
70 import net.pterodactylus.sone.fcp.FcpInterface;
71 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
72 import net.pterodactylus.sone.freenet.wot.Identity;
73 import net.pterodactylus.sone.freenet.wot.IdentityListener;
74 import net.pterodactylus.sone.freenet.wot.IdentityManager;
75 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
76 import net.pterodactylus.sone.main.SonePlugin;
77 import net.pterodactylus.util.config.Configuration;
78 import net.pterodactylus.util.config.ConfigurationException;
79 import net.pterodactylus.util.logging.Logging;
80 import net.pterodactylus.util.number.Numbers;
81 import net.pterodactylus.util.service.AbstractService;
82 import net.pterodactylus.util.thread.NamedThreadFactory;
83 import net.pterodactylus.util.thread.Ticker;
84 import net.pterodactylus.util.validation.EqualityValidator;
85 import net.pterodactylus.util.validation.IntegerRangeValidator;
86 import net.pterodactylus.util.validation.OrValidator;
87 import net.pterodactylus.util.validation.Validation;
88 import net.pterodactylus.util.version.Version;
90 import com.google.common.base.Predicate;
91 import com.google.common.collect.Collections2;
92 import com.google.common.eventbus.EventBus;
93 import com.google.inject.Inject;
95 import freenet.keys.FreenetURI;
100 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
102 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
105 private static final Logger logger = Logging.getLogger(Core.class);
107 /** The start time. */
108 private final long startupTime = System.currentTimeMillis();
111 private final Options options = new Options();
113 /** The preferences. */
114 private final Preferences preferences = new Preferences(options);
116 /** The core listener manager. */
117 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
119 /** The event bus. */
120 private final EventBus eventBus;
122 /** The configuration. */
123 private Configuration configuration;
125 /** Whether we’re currently saving the configuration. */
126 private boolean storingConfiguration = false;
128 /** The identity manager. */
129 private final IdentityManager identityManager;
131 /** Interface to freenet. */
132 private final FreenetInterface freenetInterface;
134 /** The Sone downloader. */
135 private final SoneDownloader soneDownloader;
137 /** The image inserter. */
138 private final ImageInserter imageInserter;
140 /** Sone downloader thread-pool. */
141 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
143 /** The update checker. */
144 private final UpdateChecker updateChecker;
146 /** The trust updater. */
147 private final WebOfTrustUpdater webOfTrustUpdater;
149 /** The FCP interface. */
150 private volatile FcpInterface fcpInterface;
152 /** The times Sones were followed. */
153 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
155 /** Locked local Sones. */
156 /* synchronize on itself. */
157 private final Set<Sone> lockedSones = new HashSet<Sone>();
159 /** Sone inserters. */
160 /* synchronize access on this on sones. */
161 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
163 /** Sone rescuers. */
164 /* synchronize access on this on sones. */
165 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
168 /* synchronize access on this on itself. */
169 private final Map<String, Sone> sones = new HashMap<String, Sone>();
171 /** All known Sones. */
172 private final Set<String> knownSones = new HashSet<String>();
175 private final Map<String, Post> posts = new HashMap<String, Post>();
177 /** All known posts. */
178 private final Set<String> knownPosts = new HashSet<String>();
181 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
183 /** All known replies. */
184 private final Set<String> knownReplies = new HashSet<String>();
186 /** All bookmarked posts. */
187 /* synchronize access on itself. */
188 private final Set<String> bookmarkedPosts = new HashSet<String>();
190 /** Trusted identities, sorted by own identities. */
191 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
193 /** All known albums. */
194 private final Map<String, Album> albums = new HashMap<String, Album>();
196 /** All known images. */
197 private final Map<String, Image> images = new HashMap<String, Image>();
199 /** All temporary images. */
200 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
202 /** Ticker for threads that mark own elements as known. */
203 private final Ticker localElementTicker = new Ticker();
205 /** The time the configuration was last touched. */
206 private volatile long lastConfigurationUpdate;
209 * Creates a new core.
211 * @param configuration
212 * The configuration of the core
213 * @param freenetInterface
214 * The freenet interface
215 * @param identityManager
216 * The identity manager
217 * @param webOfTrustUpdater
218 * The WebOfTrust updater
223 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
225 this.configuration = configuration;
226 this.freenetInterface = freenetInterface;
227 this.identityManager = identityManager;
228 this.soneDownloader = new SoneDownloader(this, freenetInterface);
229 this.imageInserter = new ImageInserter(this, freenetInterface);
230 this.updateChecker = new UpdateChecker(freenetInterface);
231 this.webOfTrustUpdater = webOfTrustUpdater;
232 this.eventBus = eventBus;
236 // LISTENER MANAGEMENT
240 * Adds a new core listener.
242 * @param coreListener
243 * The listener to add
245 public void addCoreListener(CoreListener coreListener) {
246 coreListenerManager.addListener(coreListener);
250 * Removes a core listener.
252 * @param coreListener
253 * The listener to remove
255 public void removeCoreListener(CoreListener coreListener) {
256 coreListenerManager.removeListener(coreListener);
264 * Returns the time Sone was started.
266 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
268 public long getStartupTime() {
273 * Sets the configuration to use. This will automatically save the current
274 * configuration to the given configuration.
276 * @param configuration
277 * The new configuration to use
279 public void setConfiguration(Configuration configuration) {
280 this.configuration = configuration;
281 touchConfiguration();
285 * Returns the options used by the core.
287 * @return The options of the core
289 public Preferences getPreferences() {
294 * Returns the identity manager used by the core.
296 * @return The identity manager
298 public IdentityManager getIdentityManager() {
299 return identityManager;
303 * Returns the update checker.
305 * @return The update checker
307 public UpdateChecker getUpdateChecker() {
308 return updateChecker;
312 * Sets the FCP interface to use.
314 * @param fcpInterface
315 * The FCP interface to use
317 public void setFcpInterface(FcpInterface fcpInterface) {
318 this.fcpInterface = fcpInterface;
322 * Returns the Sone rescuer for the given local Sone.
325 * The local Sone to get the rescuer for
326 * @return The Sone rescuer for the given Sone
328 public SoneRescuer getSoneRescuer(Sone sone) {
329 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
330 synchronized (sones) {
331 SoneRescuer soneRescuer = soneRescuers.get(sone);
332 if (soneRescuer == null) {
333 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
334 soneRescuers.put(sone, soneRescuer);
342 * Returns whether the given Sone is currently locked.
346 * @return {@code true} if the Sone is locked, {@code false} if it is not
348 public boolean isLocked(Sone sone) {
349 synchronized (lockedSones) {
350 return lockedSones.contains(sone);
355 * Returns all Sones, remote and local.
359 public Set<Sone> getSones() {
360 return new HashSet<Sone>(sones.values());
364 * Returns the Sone with the given ID, regardless whether it’s local or
368 * The ID of the Sone to get
369 * @return The Sone with the given ID, or {@code null} if there is no such
372 public Sone getSone(String id) {
373 return getSone(id, true);
377 * Returns the Sone with the given ID, regardless whether it’s local or
381 * The ID of the Sone to get
383 * {@code true} to create a new Sone if none exists,
384 * {@code false} to return {@code null} if a Sone with the given
386 * @return The Sone with the given ID, or {@code null} if there is no such
390 public Sone getSone(String id, boolean create) {
391 synchronized (sones) {
392 if (!sones.containsKey(id)) {
393 Sone sone = new Sone(id, false);
396 return sones.get(id);
401 * Checks whether the core knows a Sone with the given ID.
405 * @return {@code true} if there is a Sone with the given ID, {@code false}
408 public boolean hasSone(String id) {
409 synchronized (sones) {
410 return sones.containsKey(id);
415 * Returns all local Sones.
417 * @return All local Sones
419 public Collection<Sone> getLocalSones() {
420 synchronized (sones) {
421 return Collections2.filter(sones.values(), new Predicate<Sone>() {
424 public boolean apply(Sone sone) {
425 return sone.isLocal();
432 * Returns the local Sone with the given ID, optionally creating a new Sone.
437 * {@code true} to create a new Sone if none exists,
438 * {@code false} to return null if none exists
439 * @return The Sone with the given ID, or {@code null}
441 public Sone getLocalSone(String id, boolean create) {
442 synchronized (sones) {
443 Sone sone = sones.get(id);
444 if ((sone == null) && create) {
445 sone = new Sone(id, true);
448 if ((sone != null) && !sone.isLocal()) {
449 sone = new Sone(id, true);
457 * Returns all remote Sones.
459 * @return All remote Sones
461 public Collection<Sone> getRemoteSones() {
462 synchronized (sones) {
463 return Collections2.filter(sones.values(), new Predicate<Sone>() {
466 public boolean apply(Sone sone) {
467 return !sone.isLocal();
474 * Returns the remote Sone with the given ID.
477 * The ID of the remote Sone to get
479 * {@code true} to always create a Sone, {@code false} to return
480 * {@code null} if no Sone with the given ID exists
481 * @return The Sone with the given ID
483 public Sone getRemoteSone(String id, boolean create) {
484 synchronized (sones) {
485 Sone sone = sones.get(id);
486 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
487 sone = new Sone(id, false);
495 * Returns whether the given Sone has been modified.
498 * The Sone to check for modifications
499 * @return {@code true} if a modification has been detected in the Sone,
500 * {@code false} otherwise
502 public boolean isModifiedSone(Sone sone) {
503 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
507 * Returns the time when the given was first followed by any local Sone.
510 * The Sone to get the time for
511 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
512 * been followed, or {@link Long#MAX_VALUE}
514 public long getSoneFollowingTime(Sone sone) {
515 synchronized (soneFollowingTimes) {
516 if (soneFollowingTimes.containsKey(sone)) {
517 return soneFollowingTimes.get(sone);
519 return Long.MAX_VALUE;
524 * Returns whether the target Sone is trusted by the origin Sone.
530 * @return {@code true} if the target Sone is trusted by the origin Sone
532 public boolean isSoneTrusted(Sone origin, Sone target) {
533 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
534 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
538 * Returns the post with the given ID.
541 * The ID of the post to get
542 * @return The post with the given ID, or a new post with the given ID
544 public Post getPost(String postId) {
545 return getPost(postId, true);
549 * Returns the post with the given ID, optionally creating a new post.
552 * The ID of the post to get
554 * {@code true} it create a new post if no post with the given ID
555 * exists, {@code false} to return {@code null}
556 * @return The post, or {@code null} if there is no such post
559 public Post getPost(String postId, boolean create) {
560 synchronized (posts) {
561 Post post = posts.get(postId);
562 if ((post == null) && create) {
563 post = new PostImpl(postId);
564 posts.put(postId, post);
571 * Returns all posts that have the given Sone as recipient.
573 * @see Post#getRecipient()
575 * The recipient of the posts
576 * @return All posts that have the given Sone as recipient
578 public Set<Post> getDirectedPosts(Sone recipient) {
579 Validation.begin().isNotNull("Recipient", recipient).check();
580 Set<Post> directedPosts = new HashSet<Post>();
581 synchronized (posts) {
582 for (Post post : posts.values()) {
583 if (recipient.equals(post.getRecipient())) {
584 directedPosts.add(post);
588 return directedPosts;
592 * Returns the reply with the given ID. If there is no reply with the given
593 * ID yet, a new one is created, unless {@code create} is false in which
594 * case {@code null} is returned.
597 * The ID of the reply to get
599 * {@code true} to always return a {@link Reply}, {@code false}
600 * to return {@code null} if no reply can be found
601 * @return The reply, or {@code null} if there is no such reply
603 public PostReply getPostReply(String replyId, boolean create) {
604 synchronized (replies) {
605 PostReply reply = replies.get(replyId);
606 if (create && (reply == null)) {
607 reply = new PostReply(replyId);
608 replies.put(replyId, reply);
615 * Returns all replies for the given post, order ascending by time.
618 * The post to get all replies for
619 * @return All replies for the given post
621 public List<PostReply> getReplies(Post post) {
622 Set<Sone> sones = getSones();
623 List<PostReply> replies = new ArrayList<PostReply>();
624 for (Sone sone : sones) {
625 for (PostReply reply : sone.getReplies()) {
626 if (reply.getPost().equals(post)) {
631 Collections.sort(replies, Reply.TIME_COMPARATOR);
636 * Returns all Sones that have liked the given post.
639 * The post to get the liking Sones for
640 * @return The Sones that like the given post
642 public Set<Sone> getLikes(Post post) {
643 Set<Sone> sones = new HashSet<Sone>();
644 for (Sone sone : getSones()) {
645 if (sone.getLikedPostIds().contains(post.getId())) {
653 * Returns all Sones that have liked the given reply.
656 * The reply to get the liking Sones for
657 * @return The Sones that like the given reply
659 public Set<Sone> getLikes(PostReply reply) {
660 Set<Sone> sones = new HashSet<Sone>();
661 for (Sone sone : getSones()) {
662 if (sone.getLikedReplyIds().contains(reply.getId())) {
670 * Returns whether the given post is bookmarked.
674 * @return {@code true} if the given post is bookmarked, {@code false}
677 public boolean isBookmarked(Post post) {
678 return isPostBookmarked(post.getId());
682 * Returns whether the post with the given ID is bookmarked.
685 * The ID of the post to check
686 * @return {@code true} if the post with the given ID is bookmarked,
687 * {@code false} otherwise
689 public boolean isPostBookmarked(String id) {
690 synchronized (bookmarkedPosts) {
691 return bookmarkedPosts.contains(id);
696 * Returns all currently known bookmarked posts.
698 * @return All bookmarked posts
700 public Set<Post> getBookmarkedPosts() {
701 Set<Post> posts = new HashSet<Post>();
702 synchronized (bookmarkedPosts) {
703 for (String bookmarkedPostId : bookmarkedPosts) {
704 Post post = getPost(bookmarkedPostId, false);
714 * Returns the album with the given ID, creating a new album if no album
715 * with the given ID can be found.
718 * The ID of the album
719 * @return The album with the given ID
721 public Album getAlbum(String albumId) {
722 return getAlbum(albumId, true);
726 * Returns the album with the given ID, optionally creating a new album if
727 * an album with the given ID can not be found.
730 * The ID of the album
732 * {@code true} to create a new album if none exists for the
734 * @return The album with the given ID, or {@code null} if no album with the
735 * given ID exists and {@code create} is {@code false}
737 public Album getAlbum(String albumId, boolean create) {
738 synchronized (albums) {
739 Album album = albums.get(albumId);
740 if (create && (album == null)) {
741 album = new Album(albumId);
742 albums.put(albumId, album);
749 * Returns the image with the given ID, creating it if necessary.
752 * The ID of the image
753 * @return The image with the given ID
755 public Image getImage(String imageId) {
756 return getImage(imageId, true);
760 * Returns the image with the given ID, optionally creating it if it does
764 * The ID of the image
766 * {@code true} to create an image if none exists with the given
768 * @return The image with the given ID, or {@code null} if none exists and
771 public Image getImage(String imageId, boolean create) {
772 synchronized (images) {
773 Image image = images.get(imageId);
774 if (create && (image == null)) {
775 image = new Image(imageId);
776 images.put(imageId, image);
783 * Returns the temporary image with the given ID.
786 * The ID of the temporary image
787 * @return The temporary image, or {@code null} if there is no temporary
788 * image with the given ID
790 public TemporaryImage getTemporaryImage(String imageId) {
791 synchronized (temporaryImages) {
792 return temporaryImages.get(imageId);
801 * Locks the given Sone. A locked Sone will not be inserted by
802 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
808 public void lockSone(Sone sone) {
809 synchronized (lockedSones) {
810 if (lockedSones.add(sone)) {
811 eventBus.post(new SoneLockedEvent(sone));
817 * Unlocks the given Sone.
819 * @see #lockSone(Sone)
823 public void unlockSone(Sone sone) {
824 synchronized (lockedSones) {
825 if (lockedSones.remove(sone)) {
826 eventBus.post(new SoneUnlockedEvent(sone));
832 * Adds a local Sone from the given own identity.
835 * The own identity to create a Sone from
836 * @return The added (or already existing) Sone
838 public Sone addLocalSone(OwnIdentity ownIdentity) {
839 if (ownIdentity == null) {
840 logger.log(Level.WARNING, "Given OwnIdentity is null!");
843 synchronized (sones) {
846 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
847 } catch (MalformedURLException mue1) {
848 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
851 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
852 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
854 /* TODO - load posts ’n stuff */
855 sones.put(ownIdentity.getId(), sone);
856 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
857 soneInserter.addSoneInsertListener(this);
858 soneInserters.put(sone, soneInserter);
859 sone.setStatus(SoneStatus.idle);
861 soneInserter.start();
867 * Creates a new Sone for the given own identity.
870 * The own identity to create a Sone for
871 * @return The created Sone
873 public Sone createSone(OwnIdentity ownIdentity) {
874 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
875 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
878 Sone sone = addLocalSone(ownIdentity);
879 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
880 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
881 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
882 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
883 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
884 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
886 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
887 touchConfiguration();
892 * Adds the Sone of the given identity.
895 * The identity whose Sone to add
896 * @return The added or already existing Sone
898 public Sone addRemoteSone(Identity identity) {
899 if (identity == null) {
900 logger.log(Level.WARNING, "Given Identity is null!");
903 synchronized (sones) {
904 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
905 boolean newSone = sone.getRequestUri() == null;
906 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
907 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
909 synchronized (knownSones) {
910 newSone = !knownSones.contains(sone.getId());
912 sone.setKnown(!newSone);
914 eventBus.post(new NewSoneFoundEvent(sone));
915 for (Sone localSone : getLocalSones()) {
916 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
917 followSone(localSone, sone);
922 soneDownloader.addSone(sone);
923 soneDownloaders.execute(new Runnable() {
926 @SuppressWarnings("synthetic-access")
928 soneDownloader.fetchSone(sone, sone.getRequestUri());
937 * Lets the given local Sone follow the Sone with the given ID.
940 * The local Sone that should follow another Sone
942 * The ID of the Sone to follow
944 public void followSone(Sone sone, String soneId) {
945 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
946 Sone followedSone = getSone(soneId, true);
947 if (followedSone == null) {
948 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
951 followSone(sone, getSone(soneId));
955 * Lets the given local Sone follow the other given Sone. If the given Sone
956 * was not followed by any local Sone before, this will mark all elements of
957 * the followed Sone as read that have been created before the current
961 * The local Sone that should follow the other Sone
962 * @param followedSone
963 * The Sone that should be followed
965 public void followSone(Sone sone, Sone followedSone) {
966 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
967 sone.addFriend(followedSone.getId());
968 synchronized (soneFollowingTimes) {
969 if (!soneFollowingTimes.containsKey(followedSone)) {
970 long now = System.currentTimeMillis();
971 soneFollowingTimes.put(followedSone, now);
972 for (Post post : followedSone.getPosts()) {
973 if (post.getTime() < now) {
977 for (PostReply reply : followedSone.getReplies()) {
978 if (reply.getTime() < now) {
979 markReplyKnown(reply);
984 touchConfiguration();
988 * Lets the given local Sone unfollow the Sone with the given ID.
991 * The local Sone that should unfollow another Sone
993 * The ID of the Sone being unfollowed
995 public void unfollowSone(Sone sone, String soneId) {
996 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
997 unfollowSone(sone, getSone(soneId, false));
1001 * Lets the given local Sone unfollow the other given Sone. If the given
1002 * local Sone is the last local Sone that followed the given Sone, its
1003 * following time will be removed.
1006 * The local Sone that should unfollow another Sone
1007 * @param unfollowedSone
1008 * The Sone being unfollowed
1010 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1011 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1012 sone.removeFriend(unfollowedSone.getId());
1013 boolean unfollowedSoneStillFollowed = false;
1014 for (Sone localSone : getLocalSones()) {
1015 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1017 if (!unfollowedSoneStillFollowed) {
1018 synchronized (soneFollowingTimes) {
1019 soneFollowingTimes.remove(unfollowedSone);
1022 touchConfiguration();
1026 * Sets the trust value of the given origin Sone for the target Sone.
1033 * The trust value (from {@code -100} to {@code 100})
1035 public void setTrust(Sone origin, Sone target, int trustValue) {
1036 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();
1037 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1041 * Removes any trust assignment for the given target Sone.
1048 public void removeTrust(Sone origin, Sone target) {
1049 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1050 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1054 * Assigns the configured positive trust value for the given target.
1061 public void trustSone(Sone origin, Sone target) {
1062 setTrust(origin, target, preferences.getPositiveTrust());
1066 * Assigns the configured negative trust value for the given target.
1073 public void distrustSone(Sone origin, Sone target) {
1074 setTrust(origin, target, preferences.getNegativeTrust());
1078 * Removes the trust assignment for the given target.
1085 public void untrustSone(Sone origin, Sone target) {
1086 removeTrust(origin, target);
1090 * Updates the stored Sone with the given Sone.
1095 public void updateSone(Sone sone) {
1096 updateSone(sone, false);
1100 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1101 * {@code true}, an older Sone than the current Sone can be given to restore
1105 * The Sone to update
1106 * @param soneRescueMode
1107 * {@code true} if the stored Sone should be updated regardless
1108 * of the age of the given Sone
1110 public void updateSone(Sone sone, boolean soneRescueMode) {
1111 if (hasSone(sone.getId())) {
1112 Sone storedSone = getSone(sone.getId());
1113 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1114 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1117 synchronized (posts) {
1118 if (!soneRescueMode) {
1119 for (Post post : storedSone.getPosts()) {
1120 posts.remove(post.getId());
1121 if (!sone.getPosts().contains(post)) {
1122 eventBus.post(new PostRemovedEvent(post));
1126 List<Post> storedPosts = storedSone.getPosts();
1127 synchronized (knownPosts) {
1128 for (Post post : sone.getPosts()) {
1129 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1130 if (!storedPosts.contains(post)) {
1131 if (post.getTime() < getSoneFollowingTime(sone)) {
1132 knownPosts.add(post.getId());
1133 post.setKnown(true);
1134 } else if (!knownPosts.contains(post.getId())) {
1135 eventBus.post(new NewPostFoundEvent(post));
1138 posts.put(post.getId(), post);
1142 synchronized (replies) {
1143 if (!soneRescueMode) {
1144 for (PostReply reply : storedSone.getReplies()) {
1145 replies.remove(reply.getId());
1146 if (!sone.getReplies().contains(reply)) {
1147 eventBus.post(new PostReplyRemovedEvent(reply));
1151 Set<PostReply> storedReplies = storedSone.getReplies();
1152 synchronized (knownReplies) {
1153 for (PostReply reply : sone.getReplies()) {
1154 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1155 if (!storedReplies.contains(reply)) {
1156 if (reply.getTime() < getSoneFollowingTime(sone)) {
1157 knownReplies.add(reply.getId());
1158 reply.setKnown(true);
1159 } else if (!knownReplies.contains(reply.getId())) {
1160 eventBus.post(new NewPostReplyFoundEvent(reply));
1163 replies.put(reply.getId(), reply);
1167 synchronized (albums) {
1168 synchronized (images) {
1169 for (Album album : storedSone.getAlbums()) {
1170 albums.remove(album.getId());
1171 for (Image image : album.getImages()) {
1172 images.remove(image.getId());
1175 for (Album album : sone.getAlbums()) {
1176 albums.put(album.getId(), album);
1177 for (Image image : album.getImages()) {
1178 images.put(image.getId(), image);
1183 synchronized (storedSone) {
1184 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1185 storedSone.setTime(sone.getTime());
1187 storedSone.setClient(sone.getClient());
1188 storedSone.setProfile(sone.getProfile());
1189 if (soneRescueMode) {
1190 for (Post post : sone.getPosts()) {
1191 storedSone.addPost(post);
1193 for (PostReply reply : sone.getReplies()) {
1194 storedSone.addReply(reply);
1196 for (String likedPostId : sone.getLikedPostIds()) {
1197 storedSone.addLikedPostId(likedPostId);
1199 for (String likedReplyId : sone.getLikedReplyIds()) {
1200 storedSone.addLikedReplyId(likedReplyId);
1202 for (Album album : sone.getAlbums()) {
1203 storedSone.addAlbum(album);
1206 storedSone.setPosts(sone.getPosts());
1207 storedSone.setReplies(sone.getReplies());
1208 storedSone.setLikePostIds(sone.getLikedPostIds());
1209 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1210 storedSone.setAlbums(sone.getAlbums());
1212 storedSone.setLatestEdition(sone.getLatestEdition());
1218 * Deletes the given Sone. This will remove the Sone from the
1219 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1220 * remove the context from its identity.
1223 * The Sone to delete
1225 public void deleteSone(Sone sone) {
1226 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1227 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1230 synchronized (sones) {
1231 if (!getLocalSones().contains(sone)) {
1232 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1235 sones.remove(sone.getId());
1236 SoneInserter soneInserter = soneInserters.remove(sone);
1237 soneInserter.removeSoneInsertListener(this);
1238 soneInserter.stop();
1240 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1241 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1243 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1244 } catch (ConfigurationException ce1) {
1245 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1250 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1251 * known} before, a {@link MarkSoneKnownEvent} is fired.
1254 * The Sone to mark as known
1256 public void markSoneKnown(Sone sone) {
1257 if (!sone.isKnown()) {
1258 sone.setKnown(true);
1259 synchronized (knownSones) {
1260 knownSones.add(sone.getId());
1262 eventBus.post(new MarkSoneKnownEvent(sone));
1263 touchConfiguration();
1268 * Loads and updates the given Sone from the configuration. If any error is
1269 * encountered, loading is aborted and the given Sone is not changed.
1272 * The Sone to load and update
1274 public void loadSone(Sone sone) {
1275 if (!sone.isLocal()) {
1276 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1280 /* initialize options. */
1281 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1282 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1283 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1284 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1285 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1286 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1289 String sonePrefix = "Sone/" + sone.getId();
1290 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1291 if (soneTime == null) {
1292 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1295 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1298 Profile profile = new Profile(sone);
1299 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1300 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1301 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1302 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1303 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1304 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1306 /* load profile fields. */
1308 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1309 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1310 if (fieldName == null) {
1313 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1314 profile.addField(fieldName).setValue(fieldValue);
1318 Set<Post> posts = new HashSet<Post>();
1320 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1321 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1322 if (postId == null) {
1325 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1326 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1327 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1328 if ((postTime == 0) || (postText == null)) {
1329 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1332 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1333 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1334 post.setRecipient(getSone(postRecipientId));
1340 Set<PostReply> replies = new HashSet<PostReply>();
1342 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1343 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1344 if (replyId == null) {
1347 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1348 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1349 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1350 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1351 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1354 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1357 /* load post likes. */
1358 Set<String> likedPostIds = new HashSet<String>();
1360 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1361 if (likedPostId == null) {
1364 likedPostIds.add(likedPostId);
1367 /* load reply likes. */
1368 Set<String> likedReplyIds = new HashSet<String>();
1370 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1371 if (likedReplyId == null) {
1374 likedReplyIds.add(likedReplyId);
1378 Set<String> friends = new HashSet<String>();
1380 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1381 if (friendId == null) {
1384 friends.add(friendId);
1388 List<Album> topLevelAlbums = new ArrayList<Album>();
1389 int albumCounter = 0;
1391 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1392 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1393 if (albumId == null) {
1396 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1397 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1398 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1399 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1400 if ((albumTitle == null) || (albumDescription == null)) {
1401 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1404 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1405 if (albumParentId != null) {
1406 Album parentAlbum = getAlbum(albumParentId, false);
1407 if (parentAlbum == null) {
1408 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1411 parentAlbum.addAlbum(album);
1413 if (!topLevelAlbums.contains(album)) {
1414 topLevelAlbums.add(album);
1420 int imageCounter = 0;
1422 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1423 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1424 if (imageId == null) {
1427 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1428 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1429 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1430 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1431 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1432 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1433 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1434 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1435 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1438 Album album = getAlbum(albumId, false);
1439 if (album == null) {
1440 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1443 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1444 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1445 album.addImage(image);
1449 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1450 if (avatarId != null) {
1451 profile.setAvatar(getImage(avatarId, false));
1455 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1456 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1457 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1458 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1459 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1460 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1462 /* if we’re still here, Sone was loaded successfully. */
1463 synchronized (sone) {
1464 sone.setTime(soneTime);
1465 sone.setProfile(profile);
1466 sone.setPosts(posts);
1467 sone.setReplies(replies);
1468 sone.setLikePostIds(likedPostIds);
1469 sone.setLikeReplyIds(likedReplyIds);
1470 for (String friendId : friends) {
1471 followSone(sone, friendId);
1473 sone.setAlbums(topLevelAlbums);
1474 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1476 synchronized (knownSones) {
1477 for (String friend : friends) {
1478 knownSones.add(friend);
1481 synchronized (knownPosts) {
1482 for (Post post : posts) {
1483 knownPosts.add(post.getId());
1486 synchronized (knownReplies) {
1487 for (PostReply reply : replies) {
1488 knownReplies.add(reply.getId());
1494 * Creates a new post.
1497 * The Sone that creates the post
1499 * The text of the post
1500 * @return The created post
1502 public Post createPost(Sone sone, String text) {
1503 return createPost(sone, System.currentTimeMillis(), text);
1507 * Creates a new post.
1510 * The Sone that creates the post
1512 * The time of the post
1514 * The text of the post
1515 * @return The created post
1517 public Post createPost(Sone sone, long time, String text) {
1518 return createPost(sone, null, time, text);
1522 * Creates a new post.
1525 * The Sone that creates the post
1527 * The recipient Sone, or {@code null} if this post does not have
1530 * The text of the post
1531 * @return The created post
1533 public Post createPost(Sone sone, Sone recipient, String text) {
1534 return createPost(sone, recipient, System.currentTimeMillis(), text);
1538 * Creates a new post.
1541 * The Sone that creates the post
1543 * The recipient Sone, or {@code null} if this post does not have
1546 * The time of the post
1548 * The text of the post
1549 * @return The created post
1551 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1552 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1553 if (!sone.isLocal()) {
1554 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1557 final Post post = new PostImpl(sone, time, text);
1558 if (recipient != null) {
1559 post.setRecipient(recipient);
1561 synchronized (posts) {
1562 posts.put(post.getId(), post);
1564 eventBus.post(new NewPostFoundEvent(post));
1566 touchConfiguration();
1567 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1574 markPostKnown(post);
1576 }, "Mark " + post + " read.");
1581 * Deletes the given post.
1584 * The post to delete
1586 public void deletePost(Post post) {
1587 if (!post.getSone().isLocal()) {
1588 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1591 post.getSone().removePost(post);
1592 synchronized (posts) {
1593 posts.remove(post.getId());
1595 eventBus.post(new PostRemovedEvent(post));
1596 markPostKnown(post);
1597 touchConfiguration();
1601 * Marks the given post as known, if it is currently not a known post
1602 * (according to {@link Post#isKnown()}).
1605 * The post to mark as known
1607 public void markPostKnown(Post post) {
1608 post.setKnown(true);
1609 synchronized (knownPosts) {
1610 eventBus.post(new MarkPostKnownEvent(post));
1611 if (knownPosts.add(post.getId())) {
1612 touchConfiguration();
1615 for (PostReply reply : getReplies(post)) {
1616 markReplyKnown(reply);
1621 * Bookmarks the given post.
1624 * The post to bookmark
1626 public void bookmark(Post post) {
1627 bookmarkPost(post.getId());
1631 * Bookmarks the post with the given ID.
1634 * The ID of the post to bookmark
1636 public void bookmarkPost(String id) {
1637 synchronized (bookmarkedPosts) {
1638 bookmarkedPosts.add(id);
1643 * Removes the given post from the bookmarks.
1646 * The post to unbookmark
1648 public void unbookmark(Post post) {
1649 unbookmarkPost(post.getId());
1653 * Removes the post with the given ID from the bookmarks.
1656 * The ID of the post to unbookmark
1658 public void unbookmarkPost(String id) {
1659 synchronized (bookmarkedPosts) {
1660 bookmarkedPosts.remove(id);
1665 * Creates a new reply.
1668 * The Sone that creates the reply
1670 * The post that this reply refers to
1672 * The text of the reply
1673 * @return The created reply
1675 public PostReply createReply(Sone sone, Post post, String text) {
1676 return createReply(sone, post, System.currentTimeMillis(), text);
1680 * Creates a new reply.
1683 * The Sone that creates the reply
1685 * The post that this reply refers to
1687 * The time of the reply
1689 * The text of the reply
1690 * @return The created reply
1692 public PostReply createReply(Sone sone, Post post, long time, String text) {
1693 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1694 if (!sone.isLocal()) {
1695 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1698 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1699 synchronized (replies) {
1700 replies.put(reply.getId(), reply);
1702 synchronized (knownReplies) {
1703 eventBus.post(new NewPostReplyFoundEvent(reply));
1705 sone.addReply(reply);
1706 touchConfiguration();
1707 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1714 markReplyKnown(reply);
1716 }, "Mark " + reply + " read.");
1721 * Deletes the given reply.
1724 * The reply to delete
1726 public void deleteReply(PostReply reply) {
1727 Sone sone = reply.getSone();
1728 if (!sone.isLocal()) {
1729 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1732 synchronized (replies) {
1733 replies.remove(reply.getId());
1735 synchronized (knownReplies) {
1736 markReplyKnown(reply);
1737 knownReplies.remove(reply.getId());
1739 sone.removeReply(reply);
1740 touchConfiguration();
1744 * Marks the given reply as known, if it is currently not a known reply
1745 * (according to {@link Reply#isKnown()}).
1748 * The reply to mark as known
1750 public void markReplyKnown(PostReply reply) {
1751 reply.setKnown(true);
1752 synchronized (knownReplies) {
1753 eventBus.post(new MarkPostReplyKnownEvent(reply));
1754 if (knownReplies.add(reply.getId())) {
1755 touchConfiguration();
1761 * Creates a new top-level album for the given Sone.
1764 * The Sone to create the album for
1765 * @return The new album
1767 public Album createAlbum(Sone sone) {
1768 return createAlbum(sone, null);
1772 * Creates a new album for the given Sone.
1775 * The Sone to create the album for
1777 * The parent of the album (may be {@code null} to create a
1779 * @return The new album
1781 public Album createAlbum(Sone sone, Album parent) {
1782 Album album = new Album();
1783 synchronized (albums) {
1784 albums.put(album.getId(), album);
1786 album.setSone(sone);
1787 if (parent != null) {
1788 parent.addAlbum(album);
1790 sone.addAlbum(album);
1796 * Deletes the given album. The owner of the album has to be a local Sone,
1797 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1800 * The album to remove
1802 public void deleteAlbum(Album album) {
1803 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1804 if (!album.isEmpty()) {
1807 if (album.getParent() == null) {
1808 album.getSone().removeAlbum(album);
1810 album.getParent().removeAlbum(album);
1812 synchronized (albums) {
1813 albums.remove(album.getId());
1815 touchConfiguration();
1819 * Creates a new image.
1822 * The Sone creating the image
1824 * The album the image will be inserted into
1825 * @param temporaryImage
1826 * The temporary image to create the image from
1827 * @return The newly created image
1829 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1830 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();
1831 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1832 album.addImage(image);
1833 synchronized (images) {
1834 images.put(image.getId(), image);
1836 imageInserter.insertImage(temporaryImage, image);
1841 * Deletes the given image. This method will also delete a matching
1844 * @see #deleteTemporaryImage(TemporaryImage)
1846 * The image to delete
1848 public void deleteImage(Image image) {
1849 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1850 deleteTemporaryImage(image.getId());
1851 image.getAlbum().removeImage(image);
1852 synchronized (images) {
1853 images.remove(image.getId());
1855 touchConfiguration();
1859 * Creates a new temporary image.
1862 * The MIME type of the temporary image
1864 * The encoded data of the image
1865 * @return The temporary image
1867 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1868 TemporaryImage temporaryImage = new TemporaryImage();
1869 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1870 synchronized (temporaryImages) {
1871 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1873 return temporaryImage;
1877 * Deletes the given temporary image.
1879 * @param temporaryImage
1880 * The temporary image to delete
1882 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1883 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1884 deleteTemporaryImage(temporaryImage.getId());
1888 * Deletes the temporary image with the given ID.
1891 * The ID of the temporary image to delete
1893 public void deleteTemporaryImage(String imageId) {
1894 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1895 synchronized (temporaryImages) {
1896 temporaryImages.remove(imageId);
1898 Image image = getImage(imageId, false);
1899 if (image != null) {
1900 imageInserter.cancelImageInsert(image);
1905 * Notifies the core that the configuration, either of the core or of a
1906 * single local Sone, has changed, and that the configuration should be
1909 public void touchConfiguration() {
1910 lastConfigurationUpdate = System.currentTimeMillis();
1921 public void serviceStart() {
1922 loadConfiguration();
1923 updateChecker.addUpdateListener(this);
1924 updateChecker.start();
1925 identityManager.addIdentityListener(this);
1926 identityManager.start();
1927 webOfTrustUpdater.init();
1928 webOfTrustUpdater.start();
1935 public void serviceRun() {
1936 long lastSaved = System.currentTimeMillis();
1937 while (!shouldStop()) {
1939 long now = System.currentTimeMillis();
1940 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1941 for (Sone localSone : getLocalSones()) {
1942 saveSone(localSone);
1944 saveConfiguration();
1954 public void serviceStop() {
1955 synchronized (sones) {
1956 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1957 soneInserter.getValue().removeSoneInsertListener(this);
1958 soneInserter.getValue().stop();
1959 saveSone(soneInserter.getKey());
1962 saveConfiguration();
1963 webOfTrustUpdater.stop();
1964 updateChecker.stop();
1965 updateChecker.removeUpdateListener(this);
1966 soneDownloader.stop();
1967 identityManager.removeIdentityListener(this);
1968 identityManager.stop();
1976 * Saves the given Sone. This will persist all local settings for the given
1977 * Sone, such as the friends list and similar, private options.
1982 private synchronized void saveSone(Sone sone) {
1983 if (!sone.isLocal()) {
1984 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1987 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1988 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1992 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1994 /* save Sone into configuration. */
1995 String sonePrefix = "Sone/" + sone.getId();
1996 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1997 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2000 Profile profile = sone.getProfile();
2001 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2002 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2003 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2004 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2005 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2006 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2007 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2009 /* save profile fields. */
2010 int fieldCounter = 0;
2011 for (Field profileField : profile.getFields()) {
2012 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2013 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2014 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2016 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2019 int postCounter = 0;
2020 for (Post post : sone.getPosts()) {
2021 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2022 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2023 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2024 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2025 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2027 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2030 int replyCounter = 0;
2031 for (PostReply reply : sone.getReplies()) {
2032 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2033 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2034 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2035 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2036 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2038 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2040 /* save post likes. */
2041 int postLikeCounter = 0;
2042 for (String postId : sone.getLikedPostIds()) {
2043 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2045 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2047 /* save reply likes. */
2048 int replyLikeCounter = 0;
2049 for (String replyId : sone.getLikedReplyIds()) {
2050 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2052 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2055 int friendCounter = 0;
2056 for (String friendId : sone.getFriends()) {
2057 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2059 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2061 /* save albums. first, collect in a flat structure, top-level first. */
2062 List<Album> albums = sone.getAllAlbums();
2064 int albumCounter = 0;
2065 for (Album album : albums) {
2066 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2067 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2068 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2069 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2070 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2071 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2073 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2076 int imageCounter = 0;
2077 for (Album album : albums) {
2078 for (Image image : album.getImages()) {
2079 if (!image.isInserted()) {
2082 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2083 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2084 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2085 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2086 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2087 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2088 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2089 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2090 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2093 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2096 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2097 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2098 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2099 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2100 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2101 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2103 configuration.save();
2105 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2107 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2108 } catch (ConfigurationException ce1) {
2109 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2114 * Saves the current options.
2116 private void saveConfiguration() {
2117 synchronized (configuration) {
2118 if (storingConfiguration) {
2119 logger.log(Level.FINE, "Already storing configuration…");
2122 storingConfiguration = true;
2125 /* store the options first. */
2127 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2128 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2129 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2130 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2131 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2132 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2133 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2134 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2135 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2136 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2137 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2138 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2140 /* save known Sones. */
2141 int soneCounter = 0;
2142 synchronized (knownSones) {
2143 for (String knownSoneId : knownSones) {
2144 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2146 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2149 /* save Sone following times. */
2151 synchronized (soneFollowingTimes) {
2152 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2153 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2154 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2157 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2160 /* save known posts. */
2161 int postCounter = 0;
2162 synchronized (knownPosts) {
2163 for (String knownPostId : knownPosts) {
2164 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2166 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2169 /* save known replies. */
2170 int replyCounter = 0;
2171 synchronized (knownReplies) {
2172 for (String knownReplyId : knownReplies) {
2173 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2175 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2178 /* save bookmarked posts. */
2179 int bookmarkedPostCounter = 0;
2180 synchronized (bookmarkedPosts) {
2181 for (String bookmarkedPostId : bookmarkedPosts) {
2182 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2185 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2188 configuration.save();
2190 } catch (ConfigurationException ce1) {
2191 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2193 synchronized (configuration) {
2194 storingConfiguration = false;
2200 * Loads the configuration.
2202 @SuppressWarnings("unchecked")
2203 private void loadConfiguration() {
2204 /* create options. */
2205 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2208 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2209 SoneInserter.setInsertionDelay(newValue);
2213 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2214 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2215 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2216 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2217 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2218 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2219 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2220 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2221 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2224 @SuppressWarnings("synthetic-access")
2225 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2226 fcpInterface.setActive(newValue);
2229 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2232 @SuppressWarnings("synthetic-access")
2233 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2234 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2239 loadConfigurationValue("InsertionDelay");
2240 loadConfigurationValue("PostsPerPage");
2241 loadConfigurationValue("ImagesPerPage");
2242 loadConfigurationValue("CharactersPerPost");
2243 loadConfigurationValue("PostCutOffLength");
2244 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2245 loadConfigurationValue("PositiveTrust");
2246 loadConfigurationValue("NegativeTrust");
2247 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2248 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2249 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2251 /* load known Sones. */
2252 int soneCounter = 0;
2254 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2255 if (knownSoneId == null) {
2258 synchronized (knownSones) {
2259 knownSones.add(knownSoneId);
2263 /* load Sone following times. */
2266 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2267 if (soneId == null) {
2270 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2271 Sone followedSone = getSone(soneId);
2272 if (followedSone == null) {
2273 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2275 synchronized (soneFollowingTimes) {
2276 soneFollowingTimes.put(getSone(soneId), time);
2282 /* load known posts. */
2283 int postCounter = 0;
2285 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2286 if (knownPostId == null) {
2289 synchronized (knownPosts) {
2290 knownPosts.add(knownPostId);
2294 /* load known replies. */
2295 int replyCounter = 0;
2297 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2298 if (knownReplyId == null) {
2301 synchronized (knownReplies) {
2302 knownReplies.add(knownReplyId);
2306 /* load bookmarked posts. */
2307 int bookmarkedPostCounter = 0;
2309 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2310 if (bookmarkedPostId == null) {
2313 synchronized (bookmarkedPosts) {
2314 bookmarkedPosts.add(bookmarkedPostId);
2321 * Loads an {@link Integer} configuration value for the option with the
2322 * given name, logging validation failures.
2325 * The name of the option to load
2327 private void loadConfigurationValue(String optionName) {
2329 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2330 } catch (IllegalArgumentException iae1) {
2331 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2336 * Generate a Sone URI from the given URI and latest edition.
2339 * The URI to derive the Sone URI from
2340 * @return The derived URI
2342 private static FreenetURI getSoneUri(String uriString) {
2344 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2346 } catch (MalformedURLException mue1) {
2347 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2353 // INTERFACE IdentityListener
2360 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2361 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2362 if (ownIdentity.hasContext("Sone")) {
2363 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2364 addLocalSone(ownIdentity);
2372 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2373 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2374 trustedIdentities.remove(ownIdentity);
2381 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2382 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2383 trustedIdentities.get(ownIdentity).add(identity);
2384 addRemoteSone(identity);
2391 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2392 soneDownloaders.execute(new Runnable() {
2395 @SuppressWarnings("synthetic-access")
2397 Sone sone = getRemoteSone(identity.getId(), false);
2398 sone.setIdentity(identity);
2399 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2400 soneDownloader.addSone(sone);
2401 soneDownloader.fetchSone(sone);
2410 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2411 trustedIdentities.get(ownIdentity).remove(identity);
2412 boolean foundIdentity = false;
2413 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2414 if (trustedIdentity.getKey().equals(ownIdentity)) {
2417 if (trustedIdentity.getValue().contains(identity)) {
2418 foundIdentity = true;
2421 if (foundIdentity) {
2422 /* some local identity still trusts this identity, don’t remove. */
2425 Sone sone = getSone(identity.getId(), false);
2427 /* TODO - we don’t have the Sone anymore. should this happen? */
2430 synchronized (posts) {
2431 synchronized (knownPosts) {
2432 for (Post post : sone.getPosts()) {
2433 posts.remove(post.getId());
2434 eventBus.post(new PostRemovedEvent(post));
2438 synchronized (replies) {
2439 synchronized (knownReplies) {
2440 for (PostReply reply : sone.getReplies()) {
2441 replies.remove(reply.getId());
2442 eventBus.post(new PostReplyRemovedEvent(reply));
2446 synchronized (sones) {
2447 sones.remove(identity.getId());
2449 eventBus.post(new SoneRemovedEvent(sone));
2453 // INTERFACE UpdateListener
2460 public void updateFound(Version version, long releaseTime, long latestEdition) {
2461 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2465 // INTERFACE ImageInsertListener
2472 public void insertStarted(Sone sone) {
2473 eventBus.post(new SoneInsertingEvent(sone));
2480 public void insertFinished(Sone sone, long insertDuration) {
2481 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2488 public void insertAborted(Sone sone, Throwable cause) {
2489 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2493 // SONEINSERTLISTENER METHODS
2500 public void imageInsertStarted(Image image) {
2501 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2502 eventBus.post(new ImageInsertStartedEvent(image));
2509 public void imageInsertAborted(Image image) {
2510 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2511 eventBus.post(new ImageInsertAbortedEvent(image));
2518 public void imageInsertFinished(Image image, FreenetURI key) {
2519 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2520 image.setKey(key.toString());
2521 deleteTemporaryImage(image.getId());
2522 touchConfiguration();
2523 eventBus.post(new ImageInsertFinishedEvent(image));
2530 public void imageInsertFailed(Image image, Throwable cause) {
2531 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2532 eventBus.post(new ImageInsertFailedEvent(image, cause));
2536 * Convenience interface for external classes that want to access the core’s
2539 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2541 public static class Preferences {
2543 /** The wrapped options. */
2544 private final Options options;
2547 * Creates a new preferences object wrapped around the given options.
2550 * The options to wrap
2552 public Preferences(Options options) {
2553 this.options = options;
2557 * Returns the insertion delay.
2559 * @return The insertion delay
2561 public int getInsertionDelay() {
2562 return options.getIntegerOption("InsertionDelay").get();
2566 * Validates the given insertion delay.
2568 * @param insertionDelay
2569 * The insertion delay to validate
2570 * @return {@code true} if the given insertion delay was valid,
2571 * {@code false} otherwise
2573 public boolean validateInsertionDelay(Integer insertionDelay) {
2574 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2578 * Sets the insertion delay
2580 * @param insertionDelay
2581 * The new insertion delay, or {@code null} to restore it to
2583 * @return This preferences
2585 public Preferences setInsertionDelay(Integer insertionDelay) {
2586 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2591 * Returns the number of posts to show per page.
2593 * @return The number of posts to show per page
2595 public int getPostsPerPage() {
2596 return options.getIntegerOption("PostsPerPage").get();
2600 * Validates the number of posts per page.
2602 * @param postsPerPage
2603 * The number of posts per page
2604 * @return {@code true} if the number of posts per page was valid,
2605 * {@code false} otherwise
2607 public boolean validatePostsPerPage(Integer postsPerPage) {
2608 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2612 * Sets the number of posts to show per page.
2614 * @param postsPerPage
2615 * The number of posts to show per page
2616 * @return This preferences object
2618 public Preferences setPostsPerPage(Integer postsPerPage) {
2619 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2624 * Returns the number of images to show per page.
2626 * @return The number of images to show per page
2628 public int getImagesPerPage() {
2629 return options.getIntegerOption("ImagesPerPage").get();
2633 * Validates the number of images per page.
2635 * @param imagesPerPage
2636 * The number of images per page
2637 * @return {@code true} if the number of images per page was valid,
2638 * {@code false} otherwise
2640 public boolean validateImagesPerPage(Integer imagesPerPage) {
2641 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2645 * Sets the number of images per page.
2647 * @param imagesPerPage
2648 * The number of images per page
2649 * @return This preferences object
2651 public Preferences setImagesPerPage(Integer imagesPerPage) {
2652 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2657 * Returns the number of characters per post, or <code>-1</code> if the
2658 * posts should not be cut off.
2660 * @return The numbers of characters per post
2662 public int getCharactersPerPost() {
2663 return options.getIntegerOption("CharactersPerPost").get();
2667 * Validates the number of characters per post.
2669 * @param charactersPerPost
2670 * The number of characters per post
2671 * @return {@code true} if the number of characters per post was valid,
2672 * {@code false} otherwise
2674 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2675 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2679 * Sets the number of characters per post.
2681 * @param charactersPerPost
2682 * The number of characters per post, or <code>-1</code> to
2683 * not cut off the posts
2684 * @return This preferences objects
2686 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2687 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2692 * Returns the number of characters the shortened post should have.
2694 * @return The number of characters of the snippet
2696 public int getPostCutOffLength() {
2697 return options.getIntegerOption("PostCutOffLength").get();
2701 * Validates the number of characters after which to cut off the post.
2703 * @param postCutOffLength
2704 * The number of characters of the snippet
2705 * @return {@code true} if the number of characters of the snippet is
2706 * valid, {@code false} otherwise
2708 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2709 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2713 * Sets the number of characters the shortened post should have.
2715 * @param postCutOffLength
2716 * The number of characters of the snippet
2717 * @return This preferences
2719 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2720 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2725 * Returns whether Sone requires full access to be even visible.
2727 * @return {@code true} if Sone requires full access, {@code false}
2730 public boolean isRequireFullAccess() {
2731 return options.getBooleanOption("RequireFullAccess").get();
2735 * Sets whether Sone requires full access to be even visible.
2737 * @param requireFullAccess
2738 * {@code true} if Sone requires full access, {@code false}
2741 public void setRequireFullAccess(Boolean requireFullAccess) {
2742 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2746 * Returns the positive trust.
2748 * @return The positive trust
2750 public int getPositiveTrust() {
2751 return options.getIntegerOption("PositiveTrust").get();
2755 * Validates the positive trust.
2757 * @param positiveTrust
2758 * The positive trust to validate
2759 * @return {@code true} if the positive trust was valid, {@code false}
2762 public boolean validatePositiveTrust(Integer positiveTrust) {
2763 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2767 * Sets the positive trust.
2769 * @param positiveTrust
2770 * The new positive trust, or {@code null} to restore it to
2772 * @return This preferences
2774 public Preferences setPositiveTrust(Integer positiveTrust) {
2775 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2780 * Returns the negative trust.
2782 * @return The negative trust
2784 public int getNegativeTrust() {
2785 return options.getIntegerOption("NegativeTrust").get();
2789 * Validates the negative trust.
2791 * @param negativeTrust
2792 * The negative trust to validate
2793 * @return {@code true} if the negative trust was valid, {@code false}
2796 public boolean validateNegativeTrust(Integer negativeTrust) {
2797 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2801 * Sets the negative trust.
2803 * @param negativeTrust
2804 * The negative trust, or {@code null} to restore it to the
2806 * @return The preferences
2808 public Preferences setNegativeTrust(Integer negativeTrust) {
2809 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2814 * Returns the trust comment. This is the comment that is set in the web
2815 * of trust when a trust value is assigned to an identity.
2817 * @return The trust comment
2819 public String getTrustComment() {
2820 return options.getStringOption("TrustComment").get();
2824 * Sets the trust comment.
2826 * @param trustComment
2827 * The trust comment, or {@code null} to restore it to the
2829 * @return This preferences
2831 public Preferences setTrustComment(String trustComment) {
2832 options.getStringOption("TrustComment").set(trustComment);
2837 * Returns whether the {@link FcpInterface FCP interface} is currently
2840 * @see FcpInterface#setActive(boolean)
2841 * @return {@code true} if the FCP interface is currently active,
2842 * {@code false} otherwise
2844 public boolean isFcpInterfaceActive() {
2845 return options.getBooleanOption("ActivateFcpInterface").get();
2849 * Sets whether the {@link FcpInterface FCP interface} is currently
2852 * @see FcpInterface#setActive(boolean)
2853 * @param fcpInterfaceActive
2854 * {@code true} to activate the FCP interface, {@code false}
2855 * to deactivate the FCP interface
2856 * @return This preferences object
2858 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2859 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2864 * Returns the action level for which full access to the FCP interface
2867 * @return The action level for which full access to the FCP interface
2870 public FullAccessRequired getFcpFullAccessRequired() {
2871 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2875 * Sets the action level for which full access to the FCP interface is
2878 * @param fcpFullAccessRequired
2880 * @return This preferences
2882 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2883 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);