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.ImageInsertStartedEvent;
39 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
41 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
42 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
43 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
44 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
45 import net.pterodactylus.sone.core.event.PostRemovedEvent;
46 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
47 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
48 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
49 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
50 import net.pterodactylus.sone.core.event.SoneLockedEvent;
51 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
53 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.data.impl.PostImpl;
67 import net.pterodactylus.sone.fcp.FcpInterface;
68 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
69 import net.pterodactylus.sone.freenet.wot.Identity;
70 import net.pterodactylus.sone.freenet.wot.IdentityListener;
71 import net.pterodactylus.sone.freenet.wot.IdentityManager;
72 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
73 import net.pterodactylus.sone.main.SonePlugin;
74 import net.pterodactylus.util.config.Configuration;
75 import net.pterodactylus.util.config.ConfigurationException;
76 import net.pterodactylus.util.logging.Logging;
77 import net.pterodactylus.util.number.Numbers;
78 import net.pterodactylus.util.service.AbstractService;
79 import net.pterodactylus.util.thread.NamedThreadFactory;
80 import net.pterodactylus.util.thread.Ticker;
81 import net.pterodactylus.util.validation.EqualityValidator;
82 import net.pterodactylus.util.validation.IntegerRangeValidator;
83 import net.pterodactylus.util.validation.OrValidator;
84 import net.pterodactylus.util.validation.Validation;
85 import net.pterodactylus.util.version.Version;
87 import com.google.common.base.Predicate;
88 import com.google.common.collect.Collections2;
89 import com.google.common.eventbus.EventBus;
90 import com.google.inject.Inject;
92 import freenet.keys.FreenetURI;
97 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
99 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
102 private static final Logger logger = Logging.getLogger(Core.class);
104 /** The start time. */
105 private final long startupTime = System.currentTimeMillis();
108 private final Options options = new Options();
110 /** The preferences. */
111 private final Preferences preferences = new Preferences(options);
113 /** The core listener manager. */
114 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
116 /** The event bus. */
117 private final EventBus eventBus;
119 /** The configuration. */
120 private Configuration configuration;
122 /** Whether we’re currently saving the configuration. */
123 private boolean storingConfiguration = false;
125 /** The identity manager. */
126 private final IdentityManager identityManager;
128 /** Interface to freenet. */
129 private final FreenetInterface freenetInterface;
131 /** The Sone downloader. */
132 private final SoneDownloader soneDownloader;
134 /** The image inserter. */
135 private final ImageInserter imageInserter;
137 /** Sone downloader thread-pool. */
138 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
140 /** The update checker. */
141 private final UpdateChecker updateChecker;
143 /** The trust updater. */
144 private final WebOfTrustUpdater webOfTrustUpdater;
146 /** The FCP interface. */
147 private volatile FcpInterface fcpInterface;
149 /** The times Sones were followed. */
150 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
152 /** Locked local Sones. */
153 /* synchronize on itself. */
154 private final Set<Sone> lockedSones = new HashSet<Sone>();
156 /** Sone inserters. */
157 /* synchronize access on this on sones. */
158 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
160 /** Sone rescuers. */
161 /* synchronize access on this on sones. */
162 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
165 /* synchronize access on this on itself. */
166 private final Map<String, Sone> sones = new HashMap<String, Sone>();
168 /** All known Sones. */
169 private final Set<String> knownSones = new HashSet<String>();
172 private final Map<String, Post> posts = new HashMap<String, Post>();
174 /** All known posts. */
175 private final Set<String> knownPosts = new HashSet<String>();
178 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
180 /** All known replies. */
181 private final Set<String> knownReplies = new HashSet<String>();
183 /** All bookmarked posts. */
184 /* synchronize access on itself. */
185 private final Set<String> bookmarkedPosts = new HashSet<String>();
187 /** Trusted identities, sorted by own identities. */
188 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
190 /** All known albums. */
191 private final Map<String, Album> albums = new HashMap<String, Album>();
193 /** All known images. */
194 private final Map<String, Image> images = new HashMap<String, Image>();
196 /** All temporary images. */
197 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199 /** Ticker for threads that mark own elements as known. */
200 private final Ticker localElementTicker = new Ticker();
202 /** The time the configuration was last touched. */
203 private volatile long lastConfigurationUpdate;
206 * Creates a new core.
208 * @param configuration
209 * The configuration of the core
210 * @param freenetInterface
211 * The freenet interface
212 * @param identityManager
213 * The identity manager
214 * @param webOfTrustUpdater
215 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226 this.imageInserter = new ImageInserter(this, freenetInterface);
227 this.updateChecker = new UpdateChecker(freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
233 // LISTENER MANAGEMENT
237 * Adds a new core listener.
239 * @param coreListener
240 * The listener to add
242 public void addCoreListener(CoreListener coreListener) {
243 coreListenerManager.addListener(coreListener);
247 * Removes a core listener.
249 * @param coreListener
250 * The listener to remove
252 public void removeCoreListener(CoreListener coreListener) {
253 coreListenerManager.removeListener(coreListener);
261 * Returns the time Sone was started.
263 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
265 public long getStartupTime() {
270 * Sets the configuration to use. This will automatically save the current
271 * configuration to the given configuration.
273 * @param configuration
274 * The new configuration to use
276 public void setConfiguration(Configuration configuration) {
277 this.configuration = configuration;
278 touchConfiguration();
282 * Returns the options used by the core.
284 * @return The options of the core
286 public Preferences getPreferences() {
291 * Returns the identity manager used by the core.
293 * @return The identity manager
295 public IdentityManager getIdentityManager() {
296 return identityManager;
300 * Returns the update checker.
302 * @return The update checker
304 public UpdateChecker getUpdateChecker() {
305 return updateChecker;
309 * Sets the FCP interface to use.
311 * @param fcpInterface
312 * The FCP interface to use
314 public void setFcpInterface(FcpInterface fcpInterface) {
315 this.fcpInterface = fcpInterface;
319 * Returns the Sone rescuer for the given local Sone.
322 * The local Sone to get the rescuer for
323 * @return The Sone rescuer for the given Sone
325 public SoneRescuer getSoneRescuer(Sone sone) {
326 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
327 synchronized (sones) {
328 SoneRescuer soneRescuer = soneRescuers.get(sone);
329 if (soneRescuer == null) {
330 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
331 soneRescuers.put(sone, soneRescuer);
339 * Returns whether the given Sone is currently locked.
343 * @return {@code true} if the Sone is locked, {@code false} if it is not
345 public boolean isLocked(Sone sone) {
346 synchronized (lockedSones) {
347 return lockedSones.contains(sone);
352 * Returns all Sones, remote and local.
356 public Set<Sone> getSones() {
357 return new HashSet<Sone>(sones.values());
361 * Returns the Sone with the given ID, regardless whether it’s local or
365 * The ID of the Sone to get
366 * @return The Sone with the given ID, or {@code null} if there is no such
369 public Sone getSone(String id) {
370 return getSone(id, true);
374 * Returns the Sone with the given ID, regardless whether it’s local or
378 * The ID of the Sone to get
380 * {@code true} to create a new Sone if none exists,
381 * {@code false} to return {@code null} if a Sone with the given
383 * @return The Sone with the given ID, or {@code null} if there is no such
387 public Sone getSone(String id, boolean create) {
388 synchronized (sones) {
389 if (!sones.containsKey(id)) {
390 Sone sone = new Sone(id, false);
393 return sones.get(id);
398 * Checks whether the core knows a Sone with the given ID.
402 * @return {@code true} if there is a Sone with the given ID, {@code false}
405 public boolean hasSone(String id) {
406 synchronized (sones) {
407 return sones.containsKey(id);
412 * Returns all local Sones.
414 * @return All local Sones
416 public Collection<Sone> getLocalSones() {
417 synchronized (sones) {
418 return Collections2.filter(sones.values(), new Predicate<Sone>() {
421 public boolean apply(Sone sone) {
422 return sone.isLocal();
429 * Returns the local Sone with the given ID, optionally creating a new Sone.
434 * {@code true} to create a new Sone if none exists,
435 * {@code false} to return null if none exists
436 * @return The Sone with the given ID, or {@code null}
438 public Sone getLocalSone(String id, boolean create) {
439 synchronized (sones) {
440 Sone sone = sones.get(id);
441 if ((sone == null) && create) {
442 sone = new Sone(id, true);
445 if ((sone != null) && !sone.isLocal()) {
446 sone = new Sone(id, true);
454 * Returns all remote Sones.
456 * @return All remote Sones
458 public Collection<Sone> getRemoteSones() {
459 synchronized (sones) {
460 return Collections2.filter(sones.values(), new Predicate<Sone>() {
463 public boolean apply(Sone sone) {
464 return !sone.isLocal();
471 * Returns the remote Sone with the given ID.
474 * The ID of the remote Sone to get
476 * {@code true} to always create a Sone, {@code false} to return
477 * {@code null} if no Sone with the given ID exists
478 * @return The Sone with the given ID
480 public Sone getRemoteSone(String id, boolean create) {
481 synchronized (sones) {
482 Sone sone = sones.get(id);
483 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
484 sone = new Sone(id, false);
492 * Returns whether the given Sone has been modified.
495 * The Sone to check for modifications
496 * @return {@code true} if a modification has been detected in the Sone,
497 * {@code false} otherwise
499 public boolean isModifiedSone(Sone sone) {
500 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
504 * Returns the time when the given was first followed by any local Sone.
507 * The Sone to get the time for
508 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
509 * been followed, or {@link Long#MAX_VALUE}
511 public long getSoneFollowingTime(Sone sone) {
512 synchronized (soneFollowingTimes) {
513 if (soneFollowingTimes.containsKey(sone)) {
514 return soneFollowingTimes.get(sone);
516 return Long.MAX_VALUE;
521 * Returns whether the target Sone is trusted by the origin Sone.
527 * @return {@code true} if the target Sone is trusted by the origin Sone
529 public boolean isSoneTrusted(Sone origin, Sone target) {
530 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
531 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
535 * Returns the post with the given ID.
538 * The ID of the post to get
539 * @return The post with the given ID, or a new post with the given ID
541 public Post getPost(String postId) {
542 return getPost(postId, true);
546 * Returns the post with the given ID, optionally creating a new post.
549 * The ID of the post to get
551 * {@code true} it create a new post if no post with the given ID
552 * exists, {@code false} to return {@code null}
553 * @return The post, or {@code null} if there is no such post
556 public Post getPost(String postId, boolean create) {
557 synchronized (posts) {
558 Post post = posts.get(postId);
559 if ((post == null) && create) {
560 post = new PostImpl(postId);
561 posts.put(postId, post);
568 * Returns all posts that have the given Sone as recipient.
570 * @see Post#getRecipient()
572 * The recipient of the posts
573 * @return All posts that have the given Sone as recipient
575 public Set<Post> getDirectedPosts(Sone recipient) {
576 Validation.begin().isNotNull("Recipient", recipient).check();
577 Set<Post> directedPosts = new HashSet<Post>();
578 synchronized (posts) {
579 for (Post post : posts.values()) {
580 if (recipient.equals(post.getRecipient())) {
581 directedPosts.add(post);
585 return directedPosts;
589 * Returns the reply with the given ID. If there is no reply with the given
590 * ID yet, a new one is created, unless {@code create} is false in which
591 * case {@code null} is returned.
594 * The ID of the reply to get
596 * {@code true} to always return a {@link Reply}, {@code false}
597 * to return {@code null} if no reply can be found
598 * @return The reply, or {@code null} if there is no such reply
600 public PostReply getPostReply(String replyId, boolean create) {
601 synchronized (replies) {
602 PostReply reply = replies.get(replyId);
603 if (create && (reply == null)) {
604 reply = new PostReply(replyId);
605 replies.put(replyId, reply);
612 * Returns all replies for the given post, order ascending by time.
615 * The post to get all replies for
616 * @return All replies for the given post
618 public List<PostReply> getReplies(Post post) {
619 Set<Sone> sones = getSones();
620 List<PostReply> replies = new ArrayList<PostReply>();
621 for (Sone sone : sones) {
622 for (PostReply reply : sone.getReplies()) {
623 if (reply.getPost().equals(post)) {
628 Collections.sort(replies, Reply.TIME_COMPARATOR);
633 * Returns all Sones that have liked the given post.
636 * The post to get the liking Sones for
637 * @return The Sones that like the given post
639 public Set<Sone> getLikes(Post post) {
640 Set<Sone> sones = new HashSet<Sone>();
641 for (Sone sone : getSones()) {
642 if (sone.getLikedPostIds().contains(post.getId())) {
650 * Returns all Sones that have liked the given reply.
653 * The reply to get the liking Sones for
654 * @return The Sones that like the given reply
656 public Set<Sone> getLikes(PostReply reply) {
657 Set<Sone> sones = new HashSet<Sone>();
658 for (Sone sone : getSones()) {
659 if (sone.getLikedReplyIds().contains(reply.getId())) {
667 * Returns whether the given post is bookmarked.
671 * @return {@code true} if the given post is bookmarked, {@code false}
674 public boolean isBookmarked(Post post) {
675 return isPostBookmarked(post.getId());
679 * Returns whether the post with the given ID is bookmarked.
682 * The ID of the post to check
683 * @return {@code true} if the post with the given ID is bookmarked,
684 * {@code false} otherwise
686 public boolean isPostBookmarked(String id) {
687 synchronized (bookmarkedPosts) {
688 return bookmarkedPosts.contains(id);
693 * Returns all currently known bookmarked posts.
695 * @return All bookmarked posts
697 public Set<Post> getBookmarkedPosts() {
698 Set<Post> posts = new HashSet<Post>();
699 synchronized (bookmarkedPosts) {
700 for (String bookmarkedPostId : bookmarkedPosts) {
701 Post post = getPost(bookmarkedPostId, false);
711 * Returns the album with the given ID, creating a new album if no album
712 * with the given ID can be found.
715 * The ID of the album
716 * @return The album with the given ID
718 public Album getAlbum(String albumId) {
719 return getAlbum(albumId, true);
723 * Returns the album with the given ID, optionally creating a new album if
724 * an album with the given ID can not be found.
727 * The ID of the album
729 * {@code true} to create a new album if none exists for the
731 * @return The album with the given ID, or {@code null} if no album with the
732 * given ID exists and {@code create} is {@code false}
734 public Album getAlbum(String albumId, boolean create) {
735 synchronized (albums) {
736 Album album = albums.get(albumId);
737 if (create && (album == null)) {
738 album = new Album(albumId);
739 albums.put(albumId, album);
746 * Returns the image with the given ID, creating it if necessary.
749 * The ID of the image
750 * @return The image with the given ID
752 public Image getImage(String imageId) {
753 return getImage(imageId, true);
757 * Returns the image with the given ID, optionally creating it if it does
761 * The ID of the image
763 * {@code true} to create an image if none exists with the given
765 * @return The image with the given ID, or {@code null} if none exists and
768 public Image getImage(String imageId, boolean create) {
769 synchronized (images) {
770 Image image = images.get(imageId);
771 if (create && (image == null)) {
772 image = new Image(imageId);
773 images.put(imageId, image);
780 * Returns the temporary image with the given ID.
783 * The ID of the temporary image
784 * @return The temporary image, or {@code null} if there is no temporary
785 * image with the given ID
787 public TemporaryImage getTemporaryImage(String imageId) {
788 synchronized (temporaryImages) {
789 return temporaryImages.get(imageId);
798 * Locks the given Sone. A locked Sone will not be inserted by
799 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
805 public void lockSone(Sone sone) {
806 synchronized (lockedSones) {
807 if (lockedSones.add(sone)) {
808 eventBus.post(new SoneLockedEvent(sone));
814 * Unlocks the given Sone.
816 * @see #lockSone(Sone)
820 public void unlockSone(Sone sone) {
821 synchronized (lockedSones) {
822 if (lockedSones.remove(sone)) {
823 eventBus.post(new SoneUnlockedEvent(sone));
829 * Adds a local Sone from the given own identity.
832 * The own identity to create a Sone from
833 * @return The added (or already existing) Sone
835 public Sone addLocalSone(OwnIdentity ownIdentity) {
836 if (ownIdentity == null) {
837 logger.log(Level.WARNING, "Given OwnIdentity is null!");
840 synchronized (sones) {
843 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
844 } catch (MalformedURLException mue1) {
845 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
848 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
849 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
851 /* TODO - load posts ’n stuff */
852 sones.put(ownIdentity.getId(), sone);
853 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
854 soneInserter.addSoneInsertListener(this);
855 soneInserters.put(sone, soneInserter);
856 sone.setStatus(SoneStatus.idle);
858 soneInserter.start();
864 * Creates a new Sone for the given own identity.
867 * The own identity to create a Sone for
868 * @return The created Sone
870 public Sone createSone(OwnIdentity ownIdentity) {
871 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
872 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
875 Sone sone = addLocalSone(ownIdentity);
876 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
877 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
878 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
879 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
880 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
881 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
883 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
884 touchConfiguration();
889 * Adds the Sone of the given identity.
892 * The identity whose Sone to add
893 * @return The added or already existing Sone
895 public Sone addRemoteSone(Identity identity) {
896 if (identity == null) {
897 logger.log(Level.WARNING, "Given Identity is null!");
900 synchronized (sones) {
901 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
902 boolean newSone = sone.getRequestUri() == null;
903 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
904 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
906 synchronized (knownSones) {
907 newSone = !knownSones.contains(sone.getId());
909 sone.setKnown(!newSone);
911 eventBus.post(new NewSoneFoundEvent(sone));
912 for (Sone localSone : getLocalSones()) {
913 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
914 followSone(localSone, sone);
919 soneDownloader.addSone(sone);
920 soneDownloaders.execute(new Runnable() {
923 @SuppressWarnings("synthetic-access")
925 soneDownloader.fetchSone(sone, sone.getRequestUri());
934 * Lets the given local Sone follow the Sone with the given ID.
937 * The local Sone that should follow another Sone
939 * The ID of the Sone to follow
941 public void followSone(Sone sone, String soneId) {
942 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
943 Sone followedSone = getSone(soneId, true);
944 if (followedSone == null) {
945 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
948 followSone(sone, getSone(soneId));
952 * Lets the given local Sone follow the other given Sone. If the given Sone
953 * was not followed by any local Sone before, this will mark all elements of
954 * the followed Sone as read that have been created before the current
958 * The local Sone that should follow the other Sone
959 * @param followedSone
960 * The Sone that should be followed
962 public void followSone(Sone sone, Sone followedSone) {
963 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
964 sone.addFriend(followedSone.getId());
965 synchronized (soneFollowingTimes) {
966 if (!soneFollowingTimes.containsKey(followedSone)) {
967 long now = System.currentTimeMillis();
968 soneFollowingTimes.put(followedSone, now);
969 for (Post post : followedSone.getPosts()) {
970 if (post.getTime() < now) {
974 for (PostReply reply : followedSone.getReplies()) {
975 if (reply.getTime() < now) {
976 markReplyKnown(reply);
981 touchConfiguration();
985 * Lets the given local Sone unfollow the Sone with the given ID.
988 * The local Sone that should unfollow another Sone
990 * The ID of the Sone being unfollowed
992 public void unfollowSone(Sone sone, String soneId) {
993 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
994 unfollowSone(sone, getSone(soneId, false));
998 * Lets the given local Sone unfollow the other given Sone. If the given
999 * local Sone is the last local Sone that followed the given Sone, its
1000 * following time will be removed.
1003 * The local Sone that should unfollow another Sone
1004 * @param unfollowedSone
1005 * The Sone being unfollowed
1007 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1008 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1009 sone.removeFriend(unfollowedSone.getId());
1010 boolean unfollowedSoneStillFollowed = false;
1011 for (Sone localSone : getLocalSones()) {
1012 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1014 if (!unfollowedSoneStillFollowed) {
1015 synchronized (soneFollowingTimes) {
1016 soneFollowingTimes.remove(unfollowedSone);
1019 touchConfiguration();
1023 * Sets the trust value of the given origin Sone for the target Sone.
1030 * The trust value (from {@code -100} to {@code 100})
1032 public void setTrust(Sone origin, Sone target, int trustValue) {
1033 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();
1034 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1038 * Removes any trust assignment for the given target Sone.
1045 public void removeTrust(Sone origin, Sone target) {
1046 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1047 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1051 * Assigns the configured positive trust value for the given target.
1058 public void trustSone(Sone origin, Sone target) {
1059 setTrust(origin, target, preferences.getPositiveTrust());
1063 * Assigns the configured negative trust value for the given target.
1070 public void distrustSone(Sone origin, Sone target) {
1071 setTrust(origin, target, preferences.getNegativeTrust());
1075 * Removes the trust assignment for the given target.
1082 public void untrustSone(Sone origin, Sone target) {
1083 removeTrust(origin, target);
1087 * Updates the stored Sone with the given Sone.
1092 public void updateSone(Sone sone) {
1093 updateSone(sone, false);
1097 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1098 * {@code true}, an older Sone than the current Sone can be given to restore
1102 * The Sone to update
1103 * @param soneRescueMode
1104 * {@code true} if the stored Sone should be updated regardless
1105 * of the age of the given Sone
1107 public void updateSone(Sone sone, boolean soneRescueMode) {
1108 if (hasSone(sone.getId())) {
1109 Sone storedSone = getSone(sone.getId());
1110 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1111 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1114 synchronized (posts) {
1115 if (!soneRescueMode) {
1116 for (Post post : storedSone.getPosts()) {
1117 posts.remove(post.getId());
1118 if (!sone.getPosts().contains(post)) {
1119 eventBus.post(new PostRemovedEvent(post));
1123 List<Post> storedPosts = storedSone.getPosts();
1124 synchronized (knownPosts) {
1125 for (Post post : sone.getPosts()) {
1126 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1127 if (!storedPosts.contains(post)) {
1128 if (post.getTime() < getSoneFollowingTime(sone)) {
1129 knownPosts.add(post.getId());
1130 post.setKnown(true);
1131 } else if (!knownPosts.contains(post.getId())) {
1132 eventBus.post(new NewPostFoundEvent(post));
1135 posts.put(post.getId(), post);
1139 synchronized (replies) {
1140 if (!soneRescueMode) {
1141 for (PostReply reply : storedSone.getReplies()) {
1142 replies.remove(reply.getId());
1143 if (!sone.getReplies().contains(reply)) {
1144 eventBus.post(new PostReplyRemovedEvent(reply));
1148 Set<PostReply> storedReplies = storedSone.getReplies();
1149 synchronized (knownReplies) {
1150 for (PostReply reply : sone.getReplies()) {
1151 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1152 if (!storedReplies.contains(reply)) {
1153 if (reply.getTime() < getSoneFollowingTime(sone)) {
1154 knownReplies.add(reply.getId());
1155 reply.setKnown(true);
1156 } else if (!knownReplies.contains(reply.getId())) {
1157 eventBus.post(new NewPostReplyFoundEvent(reply));
1160 replies.put(reply.getId(), reply);
1164 synchronized (albums) {
1165 synchronized (images) {
1166 for (Album album : storedSone.getAlbums()) {
1167 albums.remove(album.getId());
1168 for (Image image : album.getImages()) {
1169 images.remove(image.getId());
1172 for (Album album : sone.getAlbums()) {
1173 albums.put(album.getId(), album);
1174 for (Image image : album.getImages()) {
1175 images.put(image.getId(), image);
1180 synchronized (storedSone) {
1181 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1182 storedSone.setTime(sone.getTime());
1184 storedSone.setClient(sone.getClient());
1185 storedSone.setProfile(sone.getProfile());
1186 if (soneRescueMode) {
1187 for (Post post : sone.getPosts()) {
1188 storedSone.addPost(post);
1190 for (PostReply reply : sone.getReplies()) {
1191 storedSone.addReply(reply);
1193 for (String likedPostId : sone.getLikedPostIds()) {
1194 storedSone.addLikedPostId(likedPostId);
1196 for (String likedReplyId : sone.getLikedReplyIds()) {
1197 storedSone.addLikedReplyId(likedReplyId);
1199 for (Album album : sone.getAlbums()) {
1200 storedSone.addAlbum(album);
1203 storedSone.setPosts(sone.getPosts());
1204 storedSone.setReplies(sone.getReplies());
1205 storedSone.setLikePostIds(sone.getLikedPostIds());
1206 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1207 storedSone.setAlbums(sone.getAlbums());
1209 storedSone.setLatestEdition(sone.getLatestEdition());
1215 * Deletes the given Sone. This will remove the Sone from the
1216 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1217 * remove the context from its identity.
1220 * The Sone to delete
1222 public void deleteSone(Sone sone) {
1223 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1224 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1227 synchronized (sones) {
1228 if (!getLocalSones().contains(sone)) {
1229 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1232 sones.remove(sone.getId());
1233 SoneInserter soneInserter = soneInserters.remove(sone);
1234 soneInserter.removeSoneInsertListener(this);
1235 soneInserter.stop();
1237 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1238 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1240 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1241 } catch (ConfigurationException ce1) {
1242 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1247 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1248 * known} before, a {@link MarkSoneKnownEvent} is fired.
1251 * The Sone to mark as known
1253 public void markSoneKnown(Sone sone) {
1254 if (!sone.isKnown()) {
1255 sone.setKnown(true);
1256 synchronized (knownSones) {
1257 knownSones.add(sone.getId());
1259 eventBus.post(new MarkSoneKnownEvent(sone));
1260 touchConfiguration();
1265 * Loads and updates the given Sone from the configuration. If any error is
1266 * encountered, loading is aborted and the given Sone is not changed.
1269 * The Sone to load and update
1271 public void loadSone(Sone sone) {
1272 if (!sone.isLocal()) {
1273 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1277 /* initialize options. */
1278 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1279 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1280 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1281 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1282 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1283 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1286 String sonePrefix = "Sone/" + sone.getId();
1287 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1288 if (soneTime == null) {
1289 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1292 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1295 Profile profile = new Profile(sone);
1296 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1297 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1298 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1299 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1300 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1301 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1303 /* load profile fields. */
1305 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1306 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1307 if (fieldName == null) {
1310 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1311 profile.addField(fieldName).setValue(fieldValue);
1315 Set<Post> posts = new HashSet<Post>();
1317 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1318 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1319 if (postId == null) {
1322 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1323 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1324 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1325 if ((postTime == 0) || (postText == null)) {
1326 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1329 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1330 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1331 post.setRecipient(getSone(postRecipientId));
1337 Set<PostReply> replies = new HashSet<PostReply>();
1339 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1340 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1341 if (replyId == null) {
1344 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1345 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1346 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1347 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1348 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1351 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1354 /* load post likes. */
1355 Set<String> likedPostIds = new HashSet<String>();
1357 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1358 if (likedPostId == null) {
1361 likedPostIds.add(likedPostId);
1364 /* load reply likes. */
1365 Set<String> likedReplyIds = new HashSet<String>();
1367 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1368 if (likedReplyId == null) {
1371 likedReplyIds.add(likedReplyId);
1375 Set<String> friends = new HashSet<String>();
1377 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1378 if (friendId == null) {
1381 friends.add(friendId);
1385 List<Album> topLevelAlbums = new ArrayList<Album>();
1386 int albumCounter = 0;
1388 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1389 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1390 if (albumId == null) {
1393 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1394 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1395 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1396 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1397 if ((albumTitle == null) || (albumDescription == null)) {
1398 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1401 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1402 if (albumParentId != null) {
1403 Album parentAlbum = getAlbum(albumParentId, false);
1404 if (parentAlbum == null) {
1405 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1408 parentAlbum.addAlbum(album);
1410 if (!topLevelAlbums.contains(album)) {
1411 topLevelAlbums.add(album);
1417 int imageCounter = 0;
1419 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1420 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1421 if (imageId == null) {
1424 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1425 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1426 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1427 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1428 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1429 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1430 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1431 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1432 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1435 Album album = getAlbum(albumId, false);
1436 if (album == null) {
1437 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1440 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1441 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1442 album.addImage(image);
1446 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1447 if (avatarId != null) {
1448 profile.setAvatar(getImage(avatarId, false));
1452 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1453 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1454 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1455 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1456 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1457 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1459 /* if we’re still here, Sone was loaded successfully. */
1460 synchronized (sone) {
1461 sone.setTime(soneTime);
1462 sone.setProfile(profile);
1463 sone.setPosts(posts);
1464 sone.setReplies(replies);
1465 sone.setLikePostIds(likedPostIds);
1466 sone.setLikeReplyIds(likedReplyIds);
1467 for (String friendId : friends) {
1468 followSone(sone, friendId);
1470 sone.setAlbums(topLevelAlbums);
1471 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1473 synchronized (knownSones) {
1474 for (String friend : friends) {
1475 knownSones.add(friend);
1478 synchronized (knownPosts) {
1479 for (Post post : posts) {
1480 knownPosts.add(post.getId());
1483 synchronized (knownReplies) {
1484 for (PostReply reply : replies) {
1485 knownReplies.add(reply.getId());
1491 * Creates a new post.
1494 * The Sone that creates the post
1496 * The text of the post
1497 * @return The created post
1499 public Post createPost(Sone sone, String text) {
1500 return createPost(sone, System.currentTimeMillis(), text);
1504 * Creates a new post.
1507 * The Sone that creates the post
1509 * The time of the post
1511 * The text of the post
1512 * @return The created post
1514 public Post createPost(Sone sone, long time, String text) {
1515 return createPost(sone, null, time, text);
1519 * Creates a new post.
1522 * The Sone that creates the post
1524 * The recipient Sone, or {@code null} if this post does not have
1527 * The text of the post
1528 * @return The created post
1530 public Post createPost(Sone sone, Sone recipient, String text) {
1531 return createPost(sone, recipient, System.currentTimeMillis(), text);
1535 * Creates a new post.
1538 * The Sone that creates the post
1540 * The recipient Sone, or {@code null} if this post does not have
1543 * The time of the post
1545 * The text of the post
1546 * @return The created post
1548 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1549 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1550 if (!sone.isLocal()) {
1551 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1554 final Post post = new PostImpl(sone, time, text);
1555 if (recipient != null) {
1556 post.setRecipient(recipient);
1558 synchronized (posts) {
1559 posts.put(post.getId(), post);
1561 eventBus.post(new NewPostFoundEvent(post));
1563 touchConfiguration();
1564 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1571 markPostKnown(post);
1573 }, "Mark " + post + " read.");
1578 * Deletes the given post.
1581 * The post to delete
1583 public void deletePost(Post post) {
1584 if (!post.getSone().isLocal()) {
1585 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1588 post.getSone().removePost(post);
1589 synchronized (posts) {
1590 posts.remove(post.getId());
1592 eventBus.post(new PostRemovedEvent(post));
1593 markPostKnown(post);
1594 touchConfiguration();
1598 * Marks the given post as known, if it is currently not a known post
1599 * (according to {@link Post#isKnown()}).
1602 * The post to mark as known
1604 public void markPostKnown(Post post) {
1605 post.setKnown(true);
1606 synchronized (knownPosts) {
1607 eventBus.post(new MarkPostKnownEvent(post));
1608 if (knownPosts.add(post.getId())) {
1609 touchConfiguration();
1612 for (PostReply reply : getReplies(post)) {
1613 markReplyKnown(reply);
1618 * Bookmarks the given post.
1621 * The post to bookmark
1623 public void bookmark(Post post) {
1624 bookmarkPost(post.getId());
1628 * Bookmarks the post with the given ID.
1631 * The ID of the post to bookmark
1633 public void bookmarkPost(String id) {
1634 synchronized (bookmarkedPosts) {
1635 bookmarkedPosts.add(id);
1640 * Removes the given post from the bookmarks.
1643 * The post to unbookmark
1645 public void unbookmark(Post post) {
1646 unbookmarkPost(post.getId());
1650 * Removes the post with the given ID from the bookmarks.
1653 * The ID of the post to unbookmark
1655 public void unbookmarkPost(String id) {
1656 synchronized (bookmarkedPosts) {
1657 bookmarkedPosts.remove(id);
1662 * Creates a new reply.
1665 * The Sone that creates the reply
1667 * The post that this reply refers to
1669 * The text of the reply
1670 * @return The created reply
1672 public PostReply createReply(Sone sone, Post post, String text) {
1673 return createReply(sone, post, System.currentTimeMillis(), text);
1677 * Creates a new reply.
1680 * The Sone that creates the reply
1682 * The post that this reply refers to
1684 * The time of the reply
1686 * The text of the reply
1687 * @return The created reply
1689 public PostReply createReply(Sone sone, Post post, long time, String text) {
1690 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1691 if (!sone.isLocal()) {
1692 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1695 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1696 synchronized (replies) {
1697 replies.put(reply.getId(), reply);
1699 synchronized (knownReplies) {
1700 eventBus.post(new NewPostReplyFoundEvent(reply));
1702 sone.addReply(reply);
1703 touchConfiguration();
1704 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1711 markReplyKnown(reply);
1713 }, "Mark " + reply + " read.");
1718 * Deletes the given reply.
1721 * The reply to delete
1723 public void deleteReply(PostReply reply) {
1724 Sone sone = reply.getSone();
1725 if (!sone.isLocal()) {
1726 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1729 synchronized (replies) {
1730 replies.remove(reply.getId());
1732 synchronized (knownReplies) {
1733 markReplyKnown(reply);
1734 knownReplies.remove(reply.getId());
1736 sone.removeReply(reply);
1737 touchConfiguration();
1741 * Marks the given reply as known, if it is currently not a known reply
1742 * (according to {@link Reply#isKnown()}).
1745 * The reply to mark as known
1747 public void markReplyKnown(PostReply reply) {
1748 reply.setKnown(true);
1749 synchronized (knownReplies) {
1750 eventBus.post(new MarkPostReplyKnownEvent(reply));
1751 if (knownReplies.add(reply.getId())) {
1752 touchConfiguration();
1758 * Creates a new top-level album for the given Sone.
1761 * The Sone to create the album for
1762 * @return The new album
1764 public Album createAlbum(Sone sone) {
1765 return createAlbum(sone, null);
1769 * Creates a new album for the given Sone.
1772 * The Sone to create the album for
1774 * The parent of the album (may be {@code null} to create a
1776 * @return The new album
1778 public Album createAlbum(Sone sone, Album parent) {
1779 Album album = new Album();
1780 synchronized (albums) {
1781 albums.put(album.getId(), album);
1783 album.setSone(sone);
1784 if (parent != null) {
1785 parent.addAlbum(album);
1787 sone.addAlbum(album);
1793 * Deletes the given album. The owner of the album has to be a local Sone,
1794 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1797 * The album to remove
1799 public void deleteAlbum(Album album) {
1800 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1801 if (!album.isEmpty()) {
1804 if (album.getParent() == null) {
1805 album.getSone().removeAlbum(album);
1807 album.getParent().removeAlbum(album);
1809 synchronized (albums) {
1810 albums.remove(album.getId());
1812 touchConfiguration();
1816 * Creates a new image.
1819 * The Sone creating the image
1821 * The album the image will be inserted into
1822 * @param temporaryImage
1823 * The temporary image to create the image from
1824 * @return The newly created image
1826 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1827 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();
1828 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1829 album.addImage(image);
1830 synchronized (images) {
1831 images.put(image.getId(), image);
1833 imageInserter.insertImage(temporaryImage, image);
1838 * Deletes the given image. This method will also delete a matching
1841 * @see #deleteTemporaryImage(TemporaryImage)
1843 * The image to delete
1845 public void deleteImage(Image image) {
1846 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1847 deleteTemporaryImage(image.getId());
1848 image.getAlbum().removeImage(image);
1849 synchronized (images) {
1850 images.remove(image.getId());
1852 touchConfiguration();
1856 * Creates a new temporary image.
1859 * The MIME type of the temporary image
1861 * The encoded data of the image
1862 * @return The temporary image
1864 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1865 TemporaryImage temporaryImage = new TemporaryImage();
1866 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1867 synchronized (temporaryImages) {
1868 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1870 return temporaryImage;
1874 * Deletes the given temporary image.
1876 * @param temporaryImage
1877 * The temporary image to delete
1879 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1880 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1881 deleteTemporaryImage(temporaryImage.getId());
1885 * Deletes the temporary image with the given ID.
1888 * The ID of the temporary image to delete
1890 public void deleteTemporaryImage(String imageId) {
1891 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1892 synchronized (temporaryImages) {
1893 temporaryImages.remove(imageId);
1895 Image image = getImage(imageId, false);
1896 if (image != null) {
1897 imageInserter.cancelImageInsert(image);
1902 * Notifies the core that the configuration, either of the core or of a
1903 * single local Sone, has changed, and that the configuration should be
1906 public void touchConfiguration() {
1907 lastConfigurationUpdate = System.currentTimeMillis();
1918 public void serviceStart() {
1919 loadConfiguration();
1920 updateChecker.addUpdateListener(this);
1921 updateChecker.start();
1922 identityManager.addIdentityListener(this);
1923 identityManager.start();
1924 webOfTrustUpdater.init();
1925 webOfTrustUpdater.start();
1932 public void serviceRun() {
1933 long lastSaved = System.currentTimeMillis();
1934 while (!shouldStop()) {
1936 long now = System.currentTimeMillis();
1937 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1938 for (Sone localSone : getLocalSones()) {
1939 saveSone(localSone);
1941 saveConfiguration();
1951 public void serviceStop() {
1952 synchronized (sones) {
1953 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1954 soneInserter.getValue().removeSoneInsertListener(this);
1955 soneInserter.getValue().stop();
1956 saveSone(soneInserter.getKey());
1959 saveConfiguration();
1960 webOfTrustUpdater.stop();
1961 updateChecker.stop();
1962 updateChecker.removeUpdateListener(this);
1963 soneDownloader.stop();
1964 identityManager.removeIdentityListener(this);
1965 identityManager.stop();
1973 * Saves the given Sone. This will persist all local settings for the given
1974 * Sone, such as the friends list and similar, private options.
1979 private synchronized void saveSone(Sone sone) {
1980 if (!sone.isLocal()) {
1981 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1984 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1985 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1989 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1991 /* save Sone into configuration. */
1992 String sonePrefix = "Sone/" + sone.getId();
1993 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1994 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1997 Profile profile = sone.getProfile();
1998 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1999 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2000 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2001 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2002 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2003 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2004 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2006 /* save profile fields. */
2007 int fieldCounter = 0;
2008 for (Field profileField : profile.getFields()) {
2009 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2010 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2011 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2013 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2016 int postCounter = 0;
2017 for (Post post : sone.getPosts()) {
2018 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2019 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2020 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2021 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2022 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2024 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2027 int replyCounter = 0;
2028 for (PostReply reply : sone.getReplies()) {
2029 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2030 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2031 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2032 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2033 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2035 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2037 /* save post likes. */
2038 int postLikeCounter = 0;
2039 for (String postId : sone.getLikedPostIds()) {
2040 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2042 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2044 /* save reply likes. */
2045 int replyLikeCounter = 0;
2046 for (String replyId : sone.getLikedReplyIds()) {
2047 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2049 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2052 int friendCounter = 0;
2053 for (String friendId : sone.getFriends()) {
2054 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2056 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2058 /* save albums. first, collect in a flat structure, top-level first. */
2059 List<Album> albums = sone.getAllAlbums();
2061 int albumCounter = 0;
2062 for (Album album : albums) {
2063 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2064 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2065 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2066 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2067 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2068 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2070 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2073 int imageCounter = 0;
2074 for (Album album : albums) {
2075 for (Image image : album.getImages()) {
2076 if (!image.isInserted()) {
2079 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2080 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2081 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2082 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2083 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2084 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2085 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2086 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2087 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2090 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2093 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2094 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2095 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2096 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2097 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2098 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2100 configuration.save();
2102 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2104 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2105 } catch (ConfigurationException ce1) {
2106 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2111 * Saves the current options.
2113 private void saveConfiguration() {
2114 synchronized (configuration) {
2115 if (storingConfiguration) {
2116 logger.log(Level.FINE, "Already storing configuration…");
2119 storingConfiguration = true;
2122 /* store the options first. */
2124 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2125 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2126 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2127 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2128 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2129 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2130 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2131 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2132 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2133 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2134 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2135 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2137 /* save known Sones. */
2138 int soneCounter = 0;
2139 synchronized (knownSones) {
2140 for (String knownSoneId : knownSones) {
2141 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2143 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2146 /* save Sone following times. */
2148 synchronized (soneFollowingTimes) {
2149 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2150 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2151 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2154 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2157 /* save known posts. */
2158 int postCounter = 0;
2159 synchronized (knownPosts) {
2160 for (String knownPostId : knownPosts) {
2161 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2163 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2166 /* save known replies. */
2167 int replyCounter = 0;
2168 synchronized (knownReplies) {
2169 for (String knownReplyId : knownReplies) {
2170 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2172 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2175 /* save bookmarked posts. */
2176 int bookmarkedPostCounter = 0;
2177 synchronized (bookmarkedPosts) {
2178 for (String bookmarkedPostId : bookmarkedPosts) {
2179 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2182 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2185 configuration.save();
2187 } catch (ConfigurationException ce1) {
2188 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2190 synchronized (configuration) {
2191 storingConfiguration = false;
2197 * Loads the configuration.
2199 @SuppressWarnings("unchecked")
2200 private void loadConfiguration() {
2201 /* create options. */
2202 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2205 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2206 SoneInserter.setInsertionDelay(newValue);
2210 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2211 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2212 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2213 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2214 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2215 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2216 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2217 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2218 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2221 @SuppressWarnings("synthetic-access")
2222 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2223 fcpInterface.setActive(newValue);
2226 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2229 @SuppressWarnings("synthetic-access")
2230 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2231 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2236 loadConfigurationValue("InsertionDelay");
2237 loadConfigurationValue("PostsPerPage");
2238 loadConfigurationValue("ImagesPerPage");
2239 loadConfigurationValue("CharactersPerPost");
2240 loadConfigurationValue("PostCutOffLength");
2241 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2242 loadConfigurationValue("PositiveTrust");
2243 loadConfigurationValue("NegativeTrust");
2244 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2245 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2246 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2248 /* load known Sones. */
2249 int soneCounter = 0;
2251 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2252 if (knownSoneId == null) {
2255 synchronized (knownSones) {
2256 knownSones.add(knownSoneId);
2260 /* load Sone following times. */
2263 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2264 if (soneId == null) {
2267 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2268 Sone followedSone = getSone(soneId);
2269 if (followedSone == null) {
2270 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2272 synchronized (soneFollowingTimes) {
2273 soneFollowingTimes.put(getSone(soneId), time);
2279 /* load known posts. */
2280 int postCounter = 0;
2282 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2283 if (knownPostId == null) {
2286 synchronized (knownPosts) {
2287 knownPosts.add(knownPostId);
2291 /* load known replies. */
2292 int replyCounter = 0;
2294 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2295 if (knownReplyId == null) {
2298 synchronized (knownReplies) {
2299 knownReplies.add(knownReplyId);
2303 /* load bookmarked posts. */
2304 int bookmarkedPostCounter = 0;
2306 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2307 if (bookmarkedPostId == null) {
2310 synchronized (bookmarkedPosts) {
2311 bookmarkedPosts.add(bookmarkedPostId);
2318 * Loads an {@link Integer} configuration value for the option with the
2319 * given name, logging validation failures.
2322 * The name of the option to load
2324 private void loadConfigurationValue(String optionName) {
2326 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2327 } catch (IllegalArgumentException iae1) {
2328 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2333 * Generate a Sone URI from the given URI and latest edition.
2336 * The URI to derive the Sone URI from
2337 * @return The derived URI
2339 private static FreenetURI getSoneUri(String uriString) {
2341 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2343 } catch (MalformedURLException mue1) {
2344 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2350 // INTERFACE IdentityListener
2357 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2358 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2359 if (ownIdentity.hasContext("Sone")) {
2360 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2361 addLocalSone(ownIdentity);
2369 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2370 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2371 trustedIdentities.remove(ownIdentity);
2378 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2379 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2380 trustedIdentities.get(ownIdentity).add(identity);
2381 addRemoteSone(identity);
2388 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2389 soneDownloaders.execute(new Runnable() {
2392 @SuppressWarnings("synthetic-access")
2394 Sone sone = getRemoteSone(identity.getId(), false);
2395 sone.setIdentity(identity);
2396 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2397 soneDownloader.addSone(sone);
2398 soneDownloader.fetchSone(sone);
2407 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2408 trustedIdentities.get(ownIdentity).remove(identity);
2409 boolean foundIdentity = false;
2410 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2411 if (trustedIdentity.getKey().equals(ownIdentity)) {
2414 if (trustedIdentity.getValue().contains(identity)) {
2415 foundIdentity = true;
2418 if (foundIdentity) {
2419 /* some local identity still trusts this identity, don’t remove. */
2422 Sone sone = getSone(identity.getId(), false);
2424 /* TODO - we don’t have the Sone anymore. should this happen? */
2427 synchronized (posts) {
2428 synchronized (knownPosts) {
2429 for (Post post : sone.getPosts()) {
2430 posts.remove(post.getId());
2431 eventBus.post(new PostRemovedEvent(post));
2435 synchronized (replies) {
2436 synchronized (knownReplies) {
2437 for (PostReply reply : sone.getReplies()) {
2438 replies.remove(reply.getId());
2439 eventBus.post(new PostReplyRemovedEvent(reply));
2443 synchronized (sones) {
2444 sones.remove(identity.getId());
2446 eventBus.post(new SoneRemovedEvent(sone));
2450 // INTERFACE UpdateListener
2457 public void updateFound(Version version, long releaseTime, long latestEdition) {
2458 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2462 // INTERFACE ImageInsertListener
2469 public void insertStarted(Sone sone) {
2470 eventBus.post(new SoneInsertingEvent(sone));
2477 public void insertFinished(Sone sone, long insertDuration) {
2478 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2485 public void insertAborted(Sone sone, Throwable cause) {
2486 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2490 // SONEINSERTLISTENER METHODS
2497 public void imageInsertStarted(Image image) {
2498 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2499 eventBus.post(new ImageInsertStartedEvent(image));
2506 public void imageInsertAborted(Image image) {
2507 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2508 coreListenerManager.fireImageInsertAborted(image);
2515 public void imageInsertFinished(Image image, FreenetURI key) {
2516 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2517 image.setKey(key.toString());
2518 deleteTemporaryImage(image.getId());
2519 touchConfiguration();
2520 coreListenerManager.fireImageInsertFinished(image);
2527 public void imageInsertFailed(Image image, Throwable cause) {
2528 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2529 coreListenerManager.fireImageInsertFailed(image, cause);
2533 * Convenience interface for external classes that want to access the core’s
2536 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2538 public static class Preferences {
2540 /** The wrapped options. */
2541 private final Options options;
2544 * Creates a new preferences object wrapped around the given options.
2547 * The options to wrap
2549 public Preferences(Options options) {
2550 this.options = options;
2554 * Returns the insertion delay.
2556 * @return The insertion delay
2558 public int getInsertionDelay() {
2559 return options.getIntegerOption("InsertionDelay").get();
2563 * Validates the given insertion delay.
2565 * @param insertionDelay
2566 * The insertion delay to validate
2567 * @return {@code true} if the given insertion delay was valid,
2568 * {@code false} otherwise
2570 public boolean validateInsertionDelay(Integer insertionDelay) {
2571 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2575 * Sets the insertion delay
2577 * @param insertionDelay
2578 * The new insertion delay, or {@code null} to restore it to
2580 * @return This preferences
2582 public Preferences setInsertionDelay(Integer insertionDelay) {
2583 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2588 * Returns the number of posts to show per page.
2590 * @return The number of posts to show per page
2592 public int getPostsPerPage() {
2593 return options.getIntegerOption("PostsPerPage").get();
2597 * Validates the number of posts per page.
2599 * @param postsPerPage
2600 * The number of posts per page
2601 * @return {@code true} if the number of posts per page was valid,
2602 * {@code false} otherwise
2604 public boolean validatePostsPerPage(Integer postsPerPage) {
2605 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2609 * Sets the number of posts to show per page.
2611 * @param postsPerPage
2612 * The number of posts to show per page
2613 * @return This preferences object
2615 public Preferences setPostsPerPage(Integer postsPerPage) {
2616 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2621 * Returns the number of images to show per page.
2623 * @return The number of images to show per page
2625 public int getImagesPerPage() {
2626 return options.getIntegerOption("ImagesPerPage").get();
2630 * Validates the number of images per page.
2632 * @param imagesPerPage
2633 * The number of images per page
2634 * @return {@code true} if the number of images per page was valid,
2635 * {@code false} otherwise
2637 public boolean validateImagesPerPage(Integer imagesPerPage) {
2638 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2642 * Sets the number of images per page.
2644 * @param imagesPerPage
2645 * The number of images per page
2646 * @return This preferences object
2648 public Preferences setImagesPerPage(Integer imagesPerPage) {
2649 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2654 * Returns the number of characters per post, or <code>-1</code> if the
2655 * posts should not be cut off.
2657 * @return The numbers of characters per post
2659 public int getCharactersPerPost() {
2660 return options.getIntegerOption("CharactersPerPost").get();
2664 * Validates the number of characters per post.
2666 * @param charactersPerPost
2667 * The number of characters per post
2668 * @return {@code true} if the number of characters per post was valid,
2669 * {@code false} otherwise
2671 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2672 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2676 * Sets the number of characters per post.
2678 * @param charactersPerPost
2679 * The number of characters per post, or <code>-1</code> to
2680 * not cut off the posts
2681 * @return This preferences objects
2683 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2684 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2689 * Returns the number of characters the shortened post should have.
2691 * @return The number of characters of the snippet
2693 public int getPostCutOffLength() {
2694 return options.getIntegerOption("PostCutOffLength").get();
2698 * Validates the number of characters after which to cut off the post.
2700 * @param postCutOffLength
2701 * The number of characters of the snippet
2702 * @return {@code true} if the number of characters of the snippet is
2703 * valid, {@code false} otherwise
2705 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2706 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2710 * Sets the number of characters the shortened post should have.
2712 * @param postCutOffLength
2713 * The number of characters of the snippet
2714 * @return This preferences
2716 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2717 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2722 * Returns whether Sone requires full access to be even visible.
2724 * @return {@code true} if Sone requires full access, {@code false}
2727 public boolean isRequireFullAccess() {
2728 return options.getBooleanOption("RequireFullAccess").get();
2732 * Sets whether Sone requires full access to be even visible.
2734 * @param requireFullAccess
2735 * {@code true} if Sone requires full access, {@code false}
2738 public void setRequireFullAccess(Boolean requireFullAccess) {
2739 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2743 * Returns the positive trust.
2745 * @return The positive trust
2747 public int getPositiveTrust() {
2748 return options.getIntegerOption("PositiveTrust").get();
2752 * Validates the positive trust.
2754 * @param positiveTrust
2755 * The positive trust to validate
2756 * @return {@code true} if the positive trust was valid, {@code false}
2759 public boolean validatePositiveTrust(Integer positiveTrust) {
2760 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2764 * Sets the positive trust.
2766 * @param positiveTrust
2767 * The new positive trust, or {@code null} to restore it to
2769 * @return This preferences
2771 public Preferences setPositiveTrust(Integer positiveTrust) {
2772 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2777 * Returns the negative trust.
2779 * @return The negative trust
2781 public int getNegativeTrust() {
2782 return options.getIntegerOption("NegativeTrust").get();
2786 * Validates the negative trust.
2788 * @param negativeTrust
2789 * The negative trust to validate
2790 * @return {@code true} if the negative trust was valid, {@code false}
2793 public boolean validateNegativeTrust(Integer negativeTrust) {
2794 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2798 * Sets the negative trust.
2800 * @param negativeTrust
2801 * The negative trust, or {@code null} to restore it to the
2803 * @return The preferences
2805 public Preferences setNegativeTrust(Integer negativeTrust) {
2806 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2811 * Returns the trust comment. This is the comment that is set in the web
2812 * of trust when a trust value is assigned to an identity.
2814 * @return The trust comment
2816 public String getTrustComment() {
2817 return options.getStringOption("TrustComment").get();
2821 * Sets the trust comment.
2823 * @param trustComment
2824 * The trust comment, or {@code null} to restore it to the
2826 * @return This preferences
2828 public Preferences setTrustComment(String trustComment) {
2829 options.getStringOption("TrustComment").set(trustComment);
2834 * Returns whether the {@link FcpInterface FCP interface} is currently
2837 * @see FcpInterface#setActive(boolean)
2838 * @return {@code true} if the FCP interface is currently active,
2839 * {@code false} otherwise
2841 public boolean isFcpInterfaceActive() {
2842 return options.getBooleanOption("ActivateFcpInterface").get();
2846 * Sets whether the {@link FcpInterface FCP interface} is currently
2849 * @see FcpInterface#setActive(boolean)
2850 * @param fcpInterfaceActive
2851 * {@code true} to activate the FCP interface, {@code false}
2852 * to deactivate the FCP interface
2853 * @return This preferences object
2855 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2856 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2861 * Returns the action level for which full access to the FCP interface
2864 * @return The action level for which full access to the FCP interface
2867 public FullAccessRequired getFcpFullAccessRequired() {
2868 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2872 * Sets the action level for which full access to the FCP interface is
2875 * @param fcpFullAccessRequired
2877 * @return This preferences
2879 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2880 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);