2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
41 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
42 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
43 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
44 import net.pterodactylus.sone.core.event.PostRemovedEvent;
45 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
46 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
47 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
48 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
49 import net.pterodactylus.sone.core.event.SoneLockedEvent;
50 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
52 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
53 import net.pterodactylus.sone.data.Album;
54 import net.pterodactylus.sone.data.Client;
55 import net.pterodactylus.sone.data.Image;
56 import net.pterodactylus.sone.data.Post;
57 import net.pterodactylus.sone.data.PostReply;
58 import net.pterodactylus.sone.data.Profile;
59 import net.pterodactylus.sone.data.Profile.Field;
60 import net.pterodactylus.sone.data.Reply;
61 import net.pterodactylus.sone.data.Sone;
62 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.TemporaryImage;
65 import net.pterodactylus.sone.data.impl.PostImpl;
66 import net.pterodactylus.sone.fcp.FcpInterface;
67 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
68 import net.pterodactylus.sone.freenet.wot.Identity;
69 import net.pterodactylus.sone.freenet.wot.IdentityListener;
70 import net.pterodactylus.sone.freenet.wot.IdentityManager;
71 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
72 import net.pterodactylus.sone.main.SonePlugin;
73 import net.pterodactylus.util.config.Configuration;
74 import net.pterodactylus.util.config.ConfigurationException;
75 import net.pterodactylus.util.logging.Logging;
76 import net.pterodactylus.util.number.Numbers;
77 import net.pterodactylus.util.service.AbstractService;
78 import net.pterodactylus.util.thread.NamedThreadFactory;
79 import net.pterodactylus.util.thread.Ticker;
80 import net.pterodactylus.util.validation.EqualityValidator;
81 import net.pterodactylus.util.validation.IntegerRangeValidator;
82 import net.pterodactylus.util.validation.OrValidator;
83 import net.pterodactylus.util.validation.Validation;
84 import net.pterodactylus.util.version.Version;
86 import com.google.common.base.Predicate;
87 import com.google.common.collect.Collections2;
88 import com.google.common.eventbus.EventBus;
89 import com.google.inject.Inject;
91 import freenet.keys.FreenetURI;
96 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
98 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
101 private static final Logger logger = Logging.getLogger(Core.class);
103 /** The start time. */
104 private final long startupTime = System.currentTimeMillis();
107 private final Options options = new Options();
109 /** The preferences. */
110 private final Preferences preferences = new Preferences(options);
112 /** The core listener manager. */
113 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
115 /** The event bus. */
116 private final EventBus eventBus;
118 /** The configuration. */
119 private Configuration configuration;
121 /** Whether we’re currently saving the configuration. */
122 private boolean storingConfiguration = false;
124 /** The identity manager. */
125 private final IdentityManager identityManager;
127 /** Interface to freenet. */
128 private final FreenetInterface freenetInterface;
130 /** The Sone downloader. */
131 private final SoneDownloader soneDownloader;
133 /** The image inserter. */
134 private final ImageInserter imageInserter;
136 /** Sone downloader thread-pool. */
137 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
139 /** The update checker. */
140 private final UpdateChecker updateChecker;
142 /** The trust updater. */
143 private final WebOfTrustUpdater webOfTrustUpdater;
145 /** The FCP interface. */
146 private volatile FcpInterface fcpInterface;
148 /** The times Sones were followed. */
149 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
151 /** Locked local Sones. */
152 /* synchronize on itself. */
153 private final Set<Sone> lockedSones = new HashSet<Sone>();
155 /** Sone inserters. */
156 /* synchronize access on this on sones. */
157 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
159 /** Sone rescuers. */
160 /* synchronize access on this on sones. */
161 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
164 /* synchronize access on this on itself. */
165 private final Map<String, Sone> sones = new HashMap<String, Sone>();
167 /** All known Sones. */
168 private final Set<String> knownSones = new HashSet<String>();
171 private final Map<String, Post> posts = new HashMap<String, Post>();
173 /** All known posts. */
174 private final Set<String> knownPosts = new HashSet<String>();
177 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
179 /** All known replies. */
180 private final Set<String> knownReplies = new HashSet<String>();
182 /** All bookmarked posts. */
183 /* synchronize access on itself. */
184 private final Set<String> bookmarkedPosts = new HashSet<String>();
186 /** Trusted identities, sorted by own identities. */
187 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
189 /** All known albums. */
190 private final Map<String, Album> albums = new HashMap<String, Album>();
192 /** All known images. */
193 private final Map<String, Image> images = new HashMap<String, Image>();
195 /** All temporary images. */
196 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
198 /** Ticker for threads that mark own elements as known. */
199 private final Ticker localElementTicker = new Ticker();
201 /** The time the configuration was last touched. */
202 private volatile long lastConfigurationUpdate;
205 * Creates a new core.
207 * @param configuration
208 * The configuration of the core
209 * @param freenetInterface
210 * The freenet interface
211 * @param identityManager
212 * The identity manager
213 * @param webOfTrustUpdater
214 * The WebOfTrust updater
219 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
221 this.configuration = configuration;
222 this.freenetInterface = freenetInterface;
223 this.identityManager = identityManager;
224 this.soneDownloader = new SoneDownloader(this, freenetInterface);
225 this.imageInserter = new ImageInserter(this, freenetInterface);
226 this.updateChecker = new UpdateChecker(freenetInterface);
227 this.webOfTrustUpdater = webOfTrustUpdater;
228 this.eventBus = eventBus;
232 // LISTENER MANAGEMENT
236 * Adds a new core listener.
238 * @param coreListener
239 * The listener to add
241 public void addCoreListener(CoreListener coreListener) {
242 coreListenerManager.addListener(coreListener);
246 * Removes a core listener.
248 * @param coreListener
249 * The listener to remove
251 public void removeCoreListener(CoreListener coreListener) {
252 coreListenerManager.removeListener(coreListener);
260 * Returns the time Sone was started.
262 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
264 public long getStartupTime() {
269 * Sets the configuration to use. This will automatically save the current
270 * configuration to the given configuration.
272 * @param configuration
273 * The new configuration to use
275 public void setConfiguration(Configuration configuration) {
276 this.configuration = configuration;
277 touchConfiguration();
281 * Returns the options used by the core.
283 * @return The options of the core
285 public Preferences getPreferences() {
290 * Returns the identity manager used by the core.
292 * @return The identity manager
294 public IdentityManager getIdentityManager() {
295 return identityManager;
299 * Returns the update checker.
301 * @return The update checker
303 public UpdateChecker getUpdateChecker() {
304 return updateChecker;
308 * Sets the FCP interface to use.
310 * @param fcpInterface
311 * The FCP interface to use
313 public void setFcpInterface(FcpInterface fcpInterface) {
314 this.fcpInterface = fcpInterface;
318 * Returns the Sone rescuer for the given local Sone.
321 * The local Sone to get the rescuer for
322 * @return The Sone rescuer for the given Sone
324 public SoneRescuer getSoneRescuer(Sone sone) {
325 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
326 synchronized (sones) {
327 SoneRescuer soneRescuer = soneRescuers.get(sone);
328 if (soneRescuer == null) {
329 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
330 soneRescuers.put(sone, soneRescuer);
338 * Returns whether the given Sone is currently locked.
342 * @return {@code true} if the Sone is locked, {@code false} if it is not
344 public boolean isLocked(Sone sone) {
345 synchronized (lockedSones) {
346 return lockedSones.contains(sone);
351 * Returns all Sones, remote and local.
355 public Set<Sone> getSones() {
356 return new HashSet<Sone>(sones.values());
360 * Returns the Sone with the given ID, regardless whether it’s local or
364 * The ID of the Sone to get
365 * @return The Sone with the given ID, or {@code null} if there is no such
368 public Sone getSone(String id) {
369 return getSone(id, true);
373 * Returns the Sone with the given ID, regardless whether it’s local or
377 * The ID of the Sone to get
379 * {@code true} to create a new Sone if none exists,
380 * {@code false} to return {@code null} if a Sone with the given
382 * @return The Sone with the given ID, or {@code null} if there is no such
386 public Sone getSone(String id, boolean create) {
387 synchronized (sones) {
388 if (!sones.containsKey(id)) {
389 Sone sone = new Sone(id, false);
392 return sones.get(id);
397 * Checks whether the core knows a Sone with the given ID.
401 * @return {@code true} if there is a Sone with the given ID, {@code false}
404 public boolean hasSone(String id) {
405 synchronized (sones) {
406 return sones.containsKey(id);
411 * Returns all local Sones.
413 * @return All local Sones
415 public Collection<Sone> getLocalSones() {
416 synchronized (sones) {
417 return Collections2.filter(sones.values(), new Predicate<Sone>() {
420 public boolean apply(Sone sone) {
421 return sone.isLocal();
428 * Returns the local Sone with the given ID, optionally creating a new Sone.
433 * {@code true} to create a new Sone if none exists,
434 * {@code false} to return null if none exists
435 * @return The Sone with the given ID, or {@code null}
437 public Sone getLocalSone(String id, boolean create) {
438 synchronized (sones) {
439 Sone sone = sones.get(id);
440 if ((sone == null) && create) {
441 sone = new Sone(id, true);
444 if ((sone != null) && !sone.isLocal()) {
445 sone = new Sone(id, true);
453 * Returns all remote Sones.
455 * @return All remote Sones
457 public Collection<Sone> getRemoteSones() {
458 synchronized (sones) {
459 return Collections2.filter(sones.values(), new Predicate<Sone>() {
462 public boolean apply(Sone sone) {
463 return !sone.isLocal();
470 * Returns the remote Sone with the given ID.
473 * The ID of the remote Sone to get
475 * {@code true} to always create a Sone, {@code false} to return
476 * {@code null} if no Sone with the given ID exists
477 * @return The Sone with the given ID
479 public Sone getRemoteSone(String id, boolean create) {
480 synchronized (sones) {
481 Sone sone = sones.get(id);
482 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
483 sone = new Sone(id, false);
491 * Returns whether the given Sone has been modified.
494 * The Sone to check for modifications
495 * @return {@code true} if a modification has been detected in the Sone,
496 * {@code false} otherwise
498 public boolean isModifiedSone(Sone sone) {
499 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
503 * Returns the time when the given was first followed by any local Sone.
506 * The Sone to get the time for
507 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
508 * been followed, or {@link Long#MAX_VALUE}
510 public long getSoneFollowingTime(Sone sone) {
511 synchronized (soneFollowingTimes) {
512 if (soneFollowingTimes.containsKey(sone)) {
513 return soneFollowingTimes.get(sone);
515 return Long.MAX_VALUE;
520 * Returns whether the target Sone is trusted by the origin Sone.
526 * @return {@code true} if the target Sone is trusted by the origin Sone
528 public boolean isSoneTrusted(Sone origin, Sone target) {
529 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
530 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
534 * Returns the post with the given ID.
537 * The ID of the post to get
538 * @return The post with the given ID, or a new post with the given ID
540 public Post getPost(String postId) {
541 return getPost(postId, true);
545 * Returns the post with the given ID, optionally creating a new post.
548 * The ID of the post to get
550 * {@code true} it create a new post if no post with the given ID
551 * exists, {@code false} to return {@code null}
552 * @return The post, or {@code null} if there is no such post
555 public Post getPost(String postId, boolean create) {
556 synchronized (posts) {
557 Post post = posts.get(postId);
558 if ((post == null) && create) {
559 post = new PostImpl(postId);
560 posts.put(postId, post);
567 * Returns all posts that have the given Sone as recipient.
569 * @see Post#getRecipient()
571 * The recipient of the posts
572 * @return All posts that have the given Sone as recipient
574 public Set<Post> getDirectedPosts(Sone recipient) {
575 Validation.begin().isNotNull("Recipient", recipient).check();
576 Set<Post> directedPosts = new HashSet<Post>();
577 synchronized (posts) {
578 for (Post post : posts.values()) {
579 if (recipient.equals(post.getRecipient())) {
580 directedPosts.add(post);
584 return directedPosts;
588 * Returns the reply with the given ID. If there is no reply with the given
589 * ID yet, a new one is created, unless {@code create} is false in which
590 * case {@code null} is returned.
593 * The ID of the reply to get
595 * {@code true} to always return a {@link Reply}, {@code false}
596 * to return {@code null} if no reply can be found
597 * @return The reply, or {@code null} if there is no such reply
599 public PostReply getPostReply(String replyId, boolean create) {
600 synchronized (replies) {
601 PostReply reply = replies.get(replyId);
602 if (create && (reply == null)) {
603 reply = new PostReply(replyId);
604 replies.put(replyId, reply);
611 * Returns all replies for the given post, order ascending by time.
614 * The post to get all replies for
615 * @return All replies for the given post
617 public List<PostReply> getReplies(Post post) {
618 Set<Sone> sones = getSones();
619 List<PostReply> replies = new ArrayList<PostReply>();
620 for (Sone sone : sones) {
621 for (PostReply reply : sone.getReplies()) {
622 if (reply.getPost().equals(post)) {
627 Collections.sort(replies, Reply.TIME_COMPARATOR);
632 * Returns all Sones that have liked the given post.
635 * The post to get the liking Sones for
636 * @return The Sones that like the given post
638 public Set<Sone> getLikes(Post post) {
639 Set<Sone> sones = new HashSet<Sone>();
640 for (Sone sone : getSones()) {
641 if (sone.getLikedPostIds().contains(post.getId())) {
649 * Returns all Sones that have liked the given reply.
652 * The reply to get the liking Sones for
653 * @return The Sones that like the given reply
655 public Set<Sone> getLikes(PostReply reply) {
656 Set<Sone> sones = new HashSet<Sone>();
657 for (Sone sone : getSones()) {
658 if (sone.getLikedReplyIds().contains(reply.getId())) {
666 * Returns whether the given post is bookmarked.
670 * @return {@code true} if the given post is bookmarked, {@code false}
673 public boolean isBookmarked(Post post) {
674 return isPostBookmarked(post.getId());
678 * Returns whether the post with the given ID is bookmarked.
681 * The ID of the post to check
682 * @return {@code true} if the post with the given ID is bookmarked,
683 * {@code false} otherwise
685 public boolean isPostBookmarked(String id) {
686 synchronized (bookmarkedPosts) {
687 return bookmarkedPosts.contains(id);
692 * Returns all currently known bookmarked posts.
694 * @return All bookmarked posts
696 public Set<Post> getBookmarkedPosts() {
697 Set<Post> posts = new HashSet<Post>();
698 synchronized (bookmarkedPosts) {
699 for (String bookmarkedPostId : bookmarkedPosts) {
700 Post post = getPost(bookmarkedPostId, false);
710 * Returns the album with the given ID, creating a new album if no album
711 * with the given ID can be found.
714 * The ID of the album
715 * @return The album with the given ID
717 public Album getAlbum(String albumId) {
718 return getAlbum(albumId, true);
722 * Returns the album with the given ID, optionally creating a new album if
723 * an album with the given ID can not be found.
726 * The ID of the album
728 * {@code true} to create a new album if none exists for the
730 * @return The album with the given ID, or {@code null} if no album with the
731 * given ID exists and {@code create} is {@code false}
733 public Album getAlbum(String albumId, boolean create) {
734 synchronized (albums) {
735 Album album = albums.get(albumId);
736 if (create && (album == null)) {
737 album = new Album(albumId);
738 albums.put(albumId, album);
745 * Returns the image with the given ID, creating it if necessary.
748 * The ID of the image
749 * @return The image with the given ID
751 public Image getImage(String imageId) {
752 return getImage(imageId, true);
756 * Returns the image with the given ID, optionally creating it if it does
760 * The ID of the image
762 * {@code true} to create an image if none exists with the given
764 * @return The image with the given ID, or {@code null} if none exists and
767 public Image getImage(String imageId, boolean create) {
768 synchronized (images) {
769 Image image = images.get(imageId);
770 if (create && (image == null)) {
771 image = new Image(imageId);
772 images.put(imageId, image);
779 * Returns the temporary image with the given ID.
782 * The ID of the temporary image
783 * @return The temporary image, or {@code null} if there is no temporary
784 * image with the given ID
786 public TemporaryImage getTemporaryImage(String imageId) {
787 synchronized (temporaryImages) {
788 return temporaryImages.get(imageId);
797 * Locks the given Sone. A locked Sone will not be inserted by
798 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
804 public void lockSone(Sone sone) {
805 synchronized (lockedSones) {
806 if (lockedSones.add(sone)) {
807 eventBus.post(new SoneLockedEvent(sone));
813 * Unlocks the given Sone.
815 * @see #lockSone(Sone)
819 public void unlockSone(Sone sone) {
820 synchronized (lockedSones) {
821 if (lockedSones.remove(sone)) {
822 eventBus.post(new SoneUnlockedEvent(sone));
828 * Adds a local Sone from the given own identity.
831 * The own identity to create a Sone from
832 * @return The added (or already existing) Sone
834 public Sone addLocalSone(OwnIdentity ownIdentity) {
835 if (ownIdentity == null) {
836 logger.log(Level.WARNING, "Given OwnIdentity is null!");
839 synchronized (sones) {
842 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
843 } catch (MalformedURLException mue1) {
844 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
847 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
848 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
850 /* TODO - load posts ’n stuff */
851 sones.put(ownIdentity.getId(), sone);
852 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
853 soneInserter.addSoneInsertListener(this);
854 soneInserters.put(sone, soneInserter);
855 sone.setStatus(SoneStatus.idle);
857 soneInserter.start();
863 * Creates a new Sone for the given own identity.
866 * The own identity to create a Sone for
867 * @return The created Sone
869 public Sone createSone(OwnIdentity ownIdentity) {
870 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
871 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
874 Sone sone = addLocalSone(ownIdentity);
875 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
876 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
877 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
878 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
879 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
880 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
882 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
883 touchConfiguration();
888 * Adds the Sone of the given identity.
891 * The identity whose Sone to add
892 * @return The added or already existing Sone
894 public Sone addRemoteSone(Identity identity) {
895 if (identity == null) {
896 logger.log(Level.WARNING, "Given Identity is null!");
899 synchronized (sones) {
900 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
901 boolean newSone = sone.getRequestUri() == null;
902 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
903 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
905 synchronized (knownSones) {
906 newSone = !knownSones.contains(sone.getId());
908 sone.setKnown(!newSone);
910 eventBus.post(new NewSoneFoundEvent(sone));
911 for (Sone localSone : getLocalSones()) {
912 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
913 followSone(localSone, sone);
918 soneDownloader.addSone(sone);
919 soneDownloaders.execute(new Runnable() {
922 @SuppressWarnings("synthetic-access")
924 soneDownloader.fetchSone(sone, sone.getRequestUri());
933 * Lets the given local Sone follow the Sone with the given ID.
936 * The local Sone that should follow another Sone
938 * The ID of the Sone to follow
940 public void followSone(Sone sone, String soneId) {
941 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
942 Sone followedSone = getSone(soneId, true);
943 if (followedSone == null) {
944 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
947 followSone(sone, getSone(soneId));
951 * Lets the given local Sone follow the other given Sone. If the given Sone
952 * was not followed by any local Sone before, this will mark all elements of
953 * the followed Sone as read that have been created before the current
957 * The local Sone that should follow the other Sone
958 * @param followedSone
959 * The Sone that should be followed
961 public void followSone(Sone sone, Sone followedSone) {
962 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
963 sone.addFriend(followedSone.getId());
964 synchronized (soneFollowingTimes) {
965 if (!soneFollowingTimes.containsKey(followedSone)) {
966 long now = System.currentTimeMillis();
967 soneFollowingTimes.put(followedSone, now);
968 for (Post post : followedSone.getPosts()) {
969 if (post.getTime() < now) {
973 for (PostReply reply : followedSone.getReplies()) {
974 if (reply.getTime() < now) {
975 markReplyKnown(reply);
980 touchConfiguration();
984 * Lets the given local Sone unfollow the Sone with the given ID.
987 * The local Sone that should unfollow another Sone
989 * The ID of the Sone being unfollowed
991 public void unfollowSone(Sone sone, String soneId) {
992 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
993 unfollowSone(sone, getSone(soneId, false));
997 * Lets the given local Sone unfollow the other given Sone. If the given
998 * local Sone is the last local Sone that followed the given Sone, its
999 * following time will be removed.
1002 * The local Sone that should unfollow another Sone
1003 * @param unfollowedSone
1004 * The Sone being unfollowed
1006 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1007 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1008 sone.removeFriend(unfollowedSone.getId());
1009 boolean unfollowedSoneStillFollowed = false;
1010 for (Sone localSone : getLocalSones()) {
1011 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1013 if (!unfollowedSoneStillFollowed) {
1014 synchronized (soneFollowingTimes) {
1015 soneFollowingTimes.remove(unfollowedSone);
1018 touchConfiguration();
1022 * Sets the trust value of the given origin Sone for the target Sone.
1029 * The trust value (from {@code -100} to {@code 100})
1031 public void setTrust(Sone origin, Sone target, int trustValue) {
1032 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();
1033 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1037 * Removes any trust assignment for the given target Sone.
1044 public void removeTrust(Sone origin, Sone target) {
1045 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1046 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1050 * Assigns the configured positive trust value for the given target.
1057 public void trustSone(Sone origin, Sone target) {
1058 setTrust(origin, target, preferences.getPositiveTrust());
1062 * Assigns the configured negative trust value for the given target.
1069 public void distrustSone(Sone origin, Sone target) {
1070 setTrust(origin, target, preferences.getNegativeTrust());
1074 * Removes the trust assignment for the given target.
1081 public void untrustSone(Sone origin, Sone target) {
1082 removeTrust(origin, target);
1086 * Updates the stored Sone with the given Sone.
1091 public void updateSone(Sone sone) {
1092 updateSone(sone, false);
1096 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1097 * {@code true}, an older Sone than the current Sone can be given to restore
1101 * The Sone to update
1102 * @param soneRescueMode
1103 * {@code true} if the stored Sone should be updated regardless
1104 * of the age of the given Sone
1106 public void updateSone(Sone sone, boolean soneRescueMode) {
1107 if (hasSone(sone.getId())) {
1108 Sone storedSone = getSone(sone.getId());
1109 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1110 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1113 synchronized (posts) {
1114 if (!soneRescueMode) {
1115 for (Post post : storedSone.getPosts()) {
1116 posts.remove(post.getId());
1117 if (!sone.getPosts().contains(post)) {
1118 eventBus.post(new PostRemovedEvent(post));
1122 List<Post> storedPosts = storedSone.getPosts();
1123 synchronized (knownPosts) {
1124 for (Post post : sone.getPosts()) {
1125 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1126 if (!storedPosts.contains(post)) {
1127 if (post.getTime() < getSoneFollowingTime(sone)) {
1128 knownPosts.add(post.getId());
1129 post.setKnown(true);
1130 } else if (!knownPosts.contains(post.getId())) {
1131 eventBus.post(new NewPostFoundEvent(post));
1134 posts.put(post.getId(), post);
1138 synchronized (replies) {
1139 if (!soneRescueMode) {
1140 for (PostReply reply : storedSone.getReplies()) {
1141 replies.remove(reply.getId());
1142 if (!sone.getReplies().contains(reply)) {
1143 eventBus.post(new PostReplyRemovedEvent(reply));
1147 Set<PostReply> storedReplies = storedSone.getReplies();
1148 synchronized (knownReplies) {
1149 for (PostReply reply : sone.getReplies()) {
1150 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1151 if (!storedReplies.contains(reply)) {
1152 if (reply.getTime() < getSoneFollowingTime(sone)) {
1153 knownReplies.add(reply.getId());
1154 reply.setKnown(true);
1155 } else if (!knownReplies.contains(reply.getId())) {
1156 eventBus.post(new NewPostReplyFoundEvent(reply));
1159 replies.put(reply.getId(), reply);
1163 synchronized (albums) {
1164 synchronized (images) {
1165 for (Album album : storedSone.getAlbums()) {
1166 albums.remove(album.getId());
1167 for (Image image : album.getImages()) {
1168 images.remove(image.getId());
1171 for (Album album : sone.getAlbums()) {
1172 albums.put(album.getId(), album);
1173 for (Image image : album.getImages()) {
1174 images.put(image.getId(), image);
1179 synchronized (storedSone) {
1180 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1181 storedSone.setTime(sone.getTime());
1183 storedSone.setClient(sone.getClient());
1184 storedSone.setProfile(sone.getProfile());
1185 if (soneRescueMode) {
1186 for (Post post : sone.getPosts()) {
1187 storedSone.addPost(post);
1189 for (PostReply reply : sone.getReplies()) {
1190 storedSone.addReply(reply);
1192 for (String likedPostId : sone.getLikedPostIds()) {
1193 storedSone.addLikedPostId(likedPostId);
1195 for (String likedReplyId : sone.getLikedReplyIds()) {
1196 storedSone.addLikedReplyId(likedReplyId);
1198 for (Album album : sone.getAlbums()) {
1199 storedSone.addAlbum(album);
1202 storedSone.setPosts(sone.getPosts());
1203 storedSone.setReplies(sone.getReplies());
1204 storedSone.setLikePostIds(sone.getLikedPostIds());
1205 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1206 storedSone.setAlbums(sone.getAlbums());
1208 storedSone.setLatestEdition(sone.getLatestEdition());
1214 * Deletes the given Sone. This will remove the Sone from the
1215 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1216 * remove the context from its identity.
1219 * The Sone to delete
1221 public void deleteSone(Sone sone) {
1222 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1223 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1226 synchronized (sones) {
1227 if (!getLocalSones().contains(sone)) {
1228 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1231 sones.remove(sone.getId());
1232 SoneInserter soneInserter = soneInserters.remove(sone);
1233 soneInserter.removeSoneInsertListener(this);
1234 soneInserter.stop();
1236 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1237 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1239 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1240 } catch (ConfigurationException ce1) {
1241 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1246 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1247 * known} before, a {@link MarkSoneKnownEvent} is fired.
1250 * The Sone to mark as known
1252 public void markSoneKnown(Sone sone) {
1253 if (!sone.isKnown()) {
1254 sone.setKnown(true);
1255 synchronized (knownSones) {
1256 knownSones.add(sone.getId());
1258 eventBus.post(new MarkSoneKnownEvent(sone));
1259 touchConfiguration();
1264 * Loads and updates the given Sone from the configuration. If any error is
1265 * encountered, loading is aborted and the given Sone is not changed.
1268 * The Sone to load and update
1270 public void loadSone(Sone sone) {
1271 if (!sone.isLocal()) {
1272 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1276 /* initialize options. */
1277 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1278 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1279 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1280 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1281 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1282 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1285 String sonePrefix = "Sone/" + sone.getId();
1286 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1287 if (soneTime == null) {
1288 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1291 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1294 Profile profile = new Profile(sone);
1295 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1296 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1297 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1298 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1299 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1300 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1302 /* load profile fields. */
1304 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1305 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1306 if (fieldName == null) {
1309 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1310 profile.addField(fieldName).setValue(fieldValue);
1314 Set<Post> posts = new HashSet<Post>();
1316 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1317 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1318 if (postId == null) {
1321 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1322 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1323 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1324 if ((postTime == 0) || (postText == null)) {
1325 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1328 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1329 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1330 post.setRecipient(getSone(postRecipientId));
1336 Set<PostReply> replies = new HashSet<PostReply>();
1338 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1339 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1340 if (replyId == null) {
1343 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1344 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1345 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1346 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1347 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1350 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1353 /* load post likes. */
1354 Set<String> likedPostIds = new HashSet<String>();
1356 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1357 if (likedPostId == null) {
1360 likedPostIds.add(likedPostId);
1363 /* load reply likes. */
1364 Set<String> likedReplyIds = new HashSet<String>();
1366 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1367 if (likedReplyId == null) {
1370 likedReplyIds.add(likedReplyId);
1374 Set<String> friends = new HashSet<String>();
1376 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1377 if (friendId == null) {
1380 friends.add(friendId);
1384 List<Album> topLevelAlbums = new ArrayList<Album>();
1385 int albumCounter = 0;
1387 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1388 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1389 if (albumId == null) {
1392 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1393 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1394 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1395 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1396 if ((albumTitle == null) || (albumDescription == null)) {
1397 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1400 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1401 if (albumParentId != null) {
1402 Album parentAlbum = getAlbum(albumParentId, false);
1403 if (parentAlbum == null) {
1404 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1407 parentAlbum.addAlbum(album);
1409 if (!topLevelAlbums.contains(album)) {
1410 topLevelAlbums.add(album);
1416 int imageCounter = 0;
1418 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1419 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1420 if (imageId == null) {
1423 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1424 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1425 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1426 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1427 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1428 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1429 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1430 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1431 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1434 Album album = getAlbum(albumId, false);
1435 if (album == null) {
1436 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1439 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1440 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1441 album.addImage(image);
1445 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1446 if (avatarId != null) {
1447 profile.setAvatar(getImage(avatarId, false));
1451 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1452 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1453 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1454 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1455 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1456 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1458 /* if we’re still here, Sone was loaded successfully. */
1459 synchronized (sone) {
1460 sone.setTime(soneTime);
1461 sone.setProfile(profile);
1462 sone.setPosts(posts);
1463 sone.setReplies(replies);
1464 sone.setLikePostIds(likedPostIds);
1465 sone.setLikeReplyIds(likedReplyIds);
1466 for (String friendId : friends) {
1467 followSone(sone, friendId);
1469 sone.setAlbums(topLevelAlbums);
1470 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1472 synchronized (knownSones) {
1473 for (String friend : friends) {
1474 knownSones.add(friend);
1477 synchronized (knownPosts) {
1478 for (Post post : posts) {
1479 knownPosts.add(post.getId());
1482 synchronized (knownReplies) {
1483 for (PostReply reply : replies) {
1484 knownReplies.add(reply.getId());
1490 * Creates a new post.
1493 * The Sone that creates the post
1495 * The text of the post
1496 * @return The created post
1498 public Post createPost(Sone sone, String text) {
1499 return createPost(sone, System.currentTimeMillis(), text);
1503 * Creates a new post.
1506 * The Sone that creates the post
1508 * The time of the post
1510 * The text of the post
1511 * @return The created post
1513 public Post createPost(Sone sone, long time, String text) {
1514 return createPost(sone, null, time, text);
1518 * Creates a new post.
1521 * The Sone that creates the post
1523 * The recipient Sone, or {@code null} if this post does not have
1526 * The text of the post
1527 * @return The created post
1529 public Post createPost(Sone sone, Sone recipient, String text) {
1530 return createPost(sone, recipient, System.currentTimeMillis(), text);
1534 * Creates a new post.
1537 * The Sone that creates the post
1539 * The recipient Sone, or {@code null} if this post does not have
1542 * The time of the post
1544 * The text of the post
1545 * @return The created post
1547 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1548 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1549 if (!sone.isLocal()) {
1550 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1553 final Post post = new PostImpl(sone, time, text);
1554 if (recipient != null) {
1555 post.setRecipient(recipient);
1557 synchronized (posts) {
1558 posts.put(post.getId(), post);
1560 eventBus.post(new NewPostFoundEvent(post));
1562 touchConfiguration();
1563 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1570 markPostKnown(post);
1572 }, "Mark " + post + " read.");
1577 * Deletes the given post.
1580 * The post to delete
1582 public void deletePost(Post post) {
1583 if (!post.getSone().isLocal()) {
1584 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1587 post.getSone().removePost(post);
1588 synchronized (posts) {
1589 posts.remove(post.getId());
1591 eventBus.post(new PostRemovedEvent(post));
1592 markPostKnown(post);
1593 touchConfiguration();
1597 * Marks the given post as known, if it is currently not a known post
1598 * (according to {@link Post#isKnown()}).
1601 * The post to mark as known
1603 public void markPostKnown(Post post) {
1604 post.setKnown(true);
1605 synchronized (knownPosts) {
1606 eventBus.post(new MarkPostKnownEvent(post));
1607 if (knownPosts.add(post.getId())) {
1608 touchConfiguration();
1611 for (PostReply reply : getReplies(post)) {
1612 markReplyKnown(reply);
1617 * Bookmarks the given post.
1620 * The post to bookmark
1622 public void bookmark(Post post) {
1623 bookmarkPost(post.getId());
1627 * Bookmarks the post with the given ID.
1630 * The ID of the post to bookmark
1632 public void bookmarkPost(String id) {
1633 synchronized (bookmarkedPosts) {
1634 bookmarkedPosts.add(id);
1639 * Removes the given post from the bookmarks.
1642 * The post to unbookmark
1644 public void unbookmark(Post post) {
1645 unbookmarkPost(post.getId());
1649 * Removes the post with the given ID from the bookmarks.
1652 * The ID of the post to unbookmark
1654 public void unbookmarkPost(String id) {
1655 synchronized (bookmarkedPosts) {
1656 bookmarkedPosts.remove(id);
1661 * Creates a new reply.
1664 * The Sone that creates the reply
1666 * The post that this reply refers to
1668 * The text of the reply
1669 * @return The created reply
1671 public PostReply createReply(Sone sone, Post post, String text) {
1672 return createReply(sone, post, System.currentTimeMillis(), text);
1676 * Creates a new reply.
1679 * The Sone that creates the reply
1681 * The post that this reply refers to
1683 * The time of the reply
1685 * The text of the reply
1686 * @return The created reply
1688 public PostReply createReply(Sone sone, Post post, long time, String text) {
1689 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1690 if (!sone.isLocal()) {
1691 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1694 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1695 synchronized (replies) {
1696 replies.put(reply.getId(), reply);
1698 synchronized (knownReplies) {
1699 eventBus.post(new NewPostReplyFoundEvent(reply));
1701 sone.addReply(reply);
1702 touchConfiguration();
1703 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1710 markReplyKnown(reply);
1712 }, "Mark " + reply + " read.");
1717 * Deletes the given reply.
1720 * The reply to delete
1722 public void deleteReply(PostReply reply) {
1723 Sone sone = reply.getSone();
1724 if (!sone.isLocal()) {
1725 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1728 synchronized (replies) {
1729 replies.remove(reply.getId());
1731 synchronized (knownReplies) {
1732 markReplyKnown(reply);
1733 knownReplies.remove(reply.getId());
1735 sone.removeReply(reply);
1736 touchConfiguration();
1740 * Marks the given reply as known, if it is currently not a known reply
1741 * (according to {@link Reply#isKnown()}).
1744 * The reply to mark as known
1746 public void markReplyKnown(PostReply reply) {
1747 reply.setKnown(true);
1748 synchronized (knownReplies) {
1749 eventBus.post(new MarkPostReplyKnownEvent(reply));
1750 if (knownReplies.add(reply.getId())) {
1751 touchConfiguration();
1757 * Creates a new top-level album for the given Sone.
1760 * The Sone to create the album for
1761 * @return The new album
1763 public Album createAlbum(Sone sone) {
1764 return createAlbum(sone, null);
1768 * Creates a new album for the given Sone.
1771 * The Sone to create the album for
1773 * The parent of the album (may be {@code null} to create a
1775 * @return The new album
1777 public Album createAlbum(Sone sone, Album parent) {
1778 Album album = new Album();
1779 synchronized (albums) {
1780 albums.put(album.getId(), album);
1782 album.setSone(sone);
1783 if (parent != null) {
1784 parent.addAlbum(album);
1786 sone.addAlbum(album);
1792 * Deletes the given album. The owner of the album has to be a local Sone,
1793 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1796 * The album to remove
1798 public void deleteAlbum(Album album) {
1799 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1800 if (!album.isEmpty()) {
1803 if (album.getParent() == null) {
1804 album.getSone().removeAlbum(album);
1806 album.getParent().removeAlbum(album);
1808 synchronized (albums) {
1809 albums.remove(album.getId());
1811 touchConfiguration();
1815 * Creates a new image.
1818 * The Sone creating the image
1820 * The album the image will be inserted into
1821 * @param temporaryImage
1822 * The temporary image to create the image from
1823 * @return The newly created image
1825 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1826 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();
1827 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1828 album.addImage(image);
1829 synchronized (images) {
1830 images.put(image.getId(), image);
1832 imageInserter.insertImage(temporaryImage, image);
1837 * Deletes the given image. This method will also delete a matching
1840 * @see #deleteTemporaryImage(TemporaryImage)
1842 * The image to delete
1844 public void deleteImage(Image image) {
1845 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1846 deleteTemporaryImage(image.getId());
1847 image.getAlbum().removeImage(image);
1848 synchronized (images) {
1849 images.remove(image.getId());
1851 touchConfiguration();
1855 * Creates a new temporary image.
1858 * The MIME type of the temporary image
1860 * The encoded data of the image
1861 * @return The temporary image
1863 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1864 TemporaryImage temporaryImage = new TemporaryImage();
1865 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1866 synchronized (temporaryImages) {
1867 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1869 return temporaryImage;
1873 * Deletes the given temporary image.
1875 * @param temporaryImage
1876 * The temporary image to delete
1878 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1879 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1880 deleteTemporaryImage(temporaryImage.getId());
1884 * Deletes the temporary image with the given ID.
1887 * The ID of the temporary image to delete
1889 public void deleteTemporaryImage(String imageId) {
1890 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1891 synchronized (temporaryImages) {
1892 temporaryImages.remove(imageId);
1894 Image image = getImage(imageId, false);
1895 if (image != null) {
1896 imageInserter.cancelImageInsert(image);
1901 * Notifies the core that the configuration, either of the core or of a
1902 * single local Sone, has changed, and that the configuration should be
1905 public void touchConfiguration() {
1906 lastConfigurationUpdate = System.currentTimeMillis();
1917 public void serviceStart() {
1918 loadConfiguration();
1919 updateChecker.addUpdateListener(this);
1920 updateChecker.start();
1921 identityManager.addIdentityListener(this);
1922 identityManager.start();
1923 webOfTrustUpdater.init();
1924 webOfTrustUpdater.start();
1931 public void serviceRun() {
1932 long lastSaved = System.currentTimeMillis();
1933 while (!shouldStop()) {
1935 long now = System.currentTimeMillis();
1936 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1937 for (Sone localSone : getLocalSones()) {
1938 saveSone(localSone);
1940 saveConfiguration();
1950 public void serviceStop() {
1951 synchronized (sones) {
1952 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1953 soneInserter.getValue().removeSoneInsertListener(this);
1954 soneInserter.getValue().stop();
1955 saveSone(soneInserter.getKey());
1958 saveConfiguration();
1959 webOfTrustUpdater.stop();
1960 updateChecker.stop();
1961 updateChecker.removeUpdateListener(this);
1962 soneDownloader.stop();
1963 identityManager.removeIdentityListener(this);
1964 identityManager.stop();
1972 * Saves the given Sone. This will persist all local settings for the given
1973 * Sone, such as the friends list and similar, private options.
1978 private synchronized void saveSone(Sone sone) {
1979 if (!sone.isLocal()) {
1980 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1983 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1984 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1988 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1990 /* save Sone into configuration. */
1991 String sonePrefix = "Sone/" + sone.getId();
1992 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1993 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1996 Profile profile = sone.getProfile();
1997 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1998 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1999 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2000 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2001 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2002 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2003 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2005 /* save profile fields. */
2006 int fieldCounter = 0;
2007 for (Field profileField : profile.getFields()) {
2008 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2009 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2010 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2012 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2015 int postCounter = 0;
2016 for (Post post : sone.getPosts()) {
2017 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2018 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2019 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2020 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2021 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2023 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2026 int replyCounter = 0;
2027 for (PostReply reply : sone.getReplies()) {
2028 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2029 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2030 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2031 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2032 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2034 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2036 /* save post likes. */
2037 int postLikeCounter = 0;
2038 for (String postId : sone.getLikedPostIds()) {
2039 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2041 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2043 /* save reply likes. */
2044 int replyLikeCounter = 0;
2045 for (String replyId : sone.getLikedReplyIds()) {
2046 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2048 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2051 int friendCounter = 0;
2052 for (String friendId : sone.getFriends()) {
2053 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2055 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2057 /* save albums. first, collect in a flat structure, top-level first. */
2058 List<Album> albums = sone.getAllAlbums();
2060 int albumCounter = 0;
2061 for (Album album : albums) {
2062 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2063 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2064 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2065 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2066 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2067 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2069 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2072 int imageCounter = 0;
2073 for (Album album : albums) {
2074 for (Image image : album.getImages()) {
2075 if (!image.isInserted()) {
2078 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2079 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2080 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2081 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2082 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2083 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2084 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2085 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2086 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2089 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2092 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2093 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2094 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2095 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2096 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2097 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2099 configuration.save();
2101 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2103 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2104 } catch (ConfigurationException ce1) {
2105 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2110 * Saves the current options.
2112 private void saveConfiguration() {
2113 synchronized (configuration) {
2114 if (storingConfiguration) {
2115 logger.log(Level.FINE, "Already storing configuration…");
2118 storingConfiguration = true;
2121 /* store the options first. */
2123 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2124 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2125 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2126 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2127 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2128 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2129 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2130 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2131 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2132 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2133 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2134 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2136 /* save known Sones. */
2137 int soneCounter = 0;
2138 synchronized (knownSones) {
2139 for (String knownSoneId : knownSones) {
2140 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2142 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2145 /* save Sone following times. */
2147 synchronized (soneFollowingTimes) {
2148 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2149 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2150 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2153 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2156 /* save known posts. */
2157 int postCounter = 0;
2158 synchronized (knownPosts) {
2159 for (String knownPostId : knownPosts) {
2160 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2162 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2165 /* save known replies. */
2166 int replyCounter = 0;
2167 synchronized (knownReplies) {
2168 for (String knownReplyId : knownReplies) {
2169 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2171 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2174 /* save bookmarked posts. */
2175 int bookmarkedPostCounter = 0;
2176 synchronized (bookmarkedPosts) {
2177 for (String bookmarkedPostId : bookmarkedPosts) {
2178 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2181 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2184 configuration.save();
2186 } catch (ConfigurationException ce1) {
2187 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2189 synchronized (configuration) {
2190 storingConfiguration = false;
2196 * Loads the configuration.
2198 @SuppressWarnings("unchecked")
2199 private void loadConfiguration() {
2200 /* create options. */
2201 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2204 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2205 SoneInserter.setInsertionDelay(newValue);
2209 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2210 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2211 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2212 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2213 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2214 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2215 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2216 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2217 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2220 @SuppressWarnings("synthetic-access")
2221 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2222 fcpInterface.setActive(newValue);
2225 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2228 @SuppressWarnings("synthetic-access")
2229 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2230 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2235 loadConfigurationValue("InsertionDelay");
2236 loadConfigurationValue("PostsPerPage");
2237 loadConfigurationValue("ImagesPerPage");
2238 loadConfigurationValue("CharactersPerPost");
2239 loadConfigurationValue("PostCutOffLength");
2240 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2241 loadConfigurationValue("PositiveTrust");
2242 loadConfigurationValue("NegativeTrust");
2243 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2244 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2245 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2247 /* load known Sones. */
2248 int soneCounter = 0;
2250 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2251 if (knownSoneId == null) {
2254 synchronized (knownSones) {
2255 knownSones.add(knownSoneId);
2259 /* load Sone following times. */
2262 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2263 if (soneId == null) {
2266 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2267 Sone followedSone = getSone(soneId);
2268 if (followedSone == null) {
2269 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2271 synchronized (soneFollowingTimes) {
2272 soneFollowingTimes.put(getSone(soneId), time);
2278 /* load known posts. */
2279 int postCounter = 0;
2281 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2282 if (knownPostId == null) {
2285 synchronized (knownPosts) {
2286 knownPosts.add(knownPostId);
2290 /* load known replies. */
2291 int replyCounter = 0;
2293 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2294 if (knownReplyId == null) {
2297 synchronized (knownReplies) {
2298 knownReplies.add(knownReplyId);
2302 /* load bookmarked posts. */
2303 int bookmarkedPostCounter = 0;
2305 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2306 if (bookmarkedPostId == null) {
2309 synchronized (bookmarkedPosts) {
2310 bookmarkedPosts.add(bookmarkedPostId);
2317 * Loads an {@link Integer} configuration value for the option with the
2318 * given name, logging validation failures.
2321 * The name of the option to load
2323 private void loadConfigurationValue(String optionName) {
2325 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2326 } catch (IllegalArgumentException iae1) {
2327 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2332 * Generate a Sone URI from the given URI and latest edition.
2335 * The URI to derive the Sone URI from
2336 * @return The derived URI
2338 private static FreenetURI getSoneUri(String uriString) {
2340 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2342 } catch (MalformedURLException mue1) {
2343 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2349 // INTERFACE IdentityListener
2356 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2357 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2358 if (ownIdentity.hasContext("Sone")) {
2359 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2360 addLocalSone(ownIdentity);
2368 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2369 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2370 trustedIdentities.remove(ownIdentity);
2377 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2378 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2379 trustedIdentities.get(ownIdentity).add(identity);
2380 addRemoteSone(identity);
2387 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2388 soneDownloaders.execute(new Runnable() {
2391 @SuppressWarnings("synthetic-access")
2393 Sone sone = getRemoteSone(identity.getId(), false);
2394 sone.setIdentity(identity);
2395 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2396 soneDownloader.addSone(sone);
2397 soneDownloader.fetchSone(sone);
2406 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2407 trustedIdentities.get(ownIdentity).remove(identity);
2408 boolean foundIdentity = false;
2409 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2410 if (trustedIdentity.getKey().equals(ownIdentity)) {
2413 if (trustedIdentity.getValue().contains(identity)) {
2414 foundIdentity = true;
2417 if (foundIdentity) {
2418 /* some local identity still trusts this identity, don’t remove. */
2421 Sone sone = getSone(identity.getId(), false);
2423 /* TODO - we don’t have the Sone anymore. should this happen? */
2426 synchronized (posts) {
2427 synchronized (knownPosts) {
2428 for (Post post : sone.getPosts()) {
2429 posts.remove(post.getId());
2430 eventBus.post(new PostRemovedEvent(post));
2434 synchronized (replies) {
2435 synchronized (knownReplies) {
2436 for (PostReply reply : sone.getReplies()) {
2437 replies.remove(reply.getId());
2438 eventBus.post(new PostReplyRemovedEvent(reply));
2442 synchronized (sones) {
2443 sones.remove(identity.getId());
2445 eventBus.post(new SoneRemovedEvent(sone));
2449 // INTERFACE UpdateListener
2456 public void updateFound(Version version, long releaseTime, long latestEdition) {
2457 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2461 // INTERFACE ImageInsertListener
2468 public void insertStarted(Sone sone) {
2469 eventBus.post(new SoneInsertingEvent(sone));
2476 public void insertFinished(Sone sone, long insertDuration) {
2477 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2484 public void insertAborted(Sone sone, Throwable cause) {
2485 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2489 // SONEINSERTLISTENER METHODS
2496 public void imageInsertStarted(Image image) {
2497 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2498 coreListenerManager.fireImageInsertStarted(image);
2505 public void imageInsertAborted(Image image) {
2506 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2507 coreListenerManager.fireImageInsertAborted(image);
2514 public void imageInsertFinished(Image image, FreenetURI key) {
2515 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2516 image.setKey(key.toString());
2517 deleteTemporaryImage(image.getId());
2518 touchConfiguration();
2519 coreListenerManager.fireImageInsertFinished(image);
2526 public void imageInsertFailed(Image image, Throwable cause) {
2527 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2528 coreListenerManager.fireImageInsertFailed(image, cause);
2532 * Convenience interface for external classes that want to access the core’s
2535 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2537 public static class Preferences {
2539 /** The wrapped options. */
2540 private final Options options;
2543 * Creates a new preferences object wrapped around the given options.
2546 * The options to wrap
2548 public Preferences(Options options) {
2549 this.options = options;
2553 * Returns the insertion delay.
2555 * @return The insertion delay
2557 public int getInsertionDelay() {
2558 return options.getIntegerOption("InsertionDelay").get();
2562 * Validates the given insertion delay.
2564 * @param insertionDelay
2565 * The insertion delay to validate
2566 * @return {@code true} if the given insertion delay was valid,
2567 * {@code false} otherwise
2569 public boolean validateInsertionDelay(Integer insertionDelay) {
2570 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2574 * Sets the insertion delay
2576 * @param insertionDelay
2577 * The new insertion delay, or {@code null} to restore it to
2579 * @return This preferences
2581 public Preferences setInsertionDelay(Integer insertionDelay) {
2582 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2587 * Returns the number of posts to show per page.
2589 * @return The number of posts to show per page
2591 public int getPostsPerPage() {
2592 return options.getIntegerOption("PostsPerPage").get();
2596 * Validates the number of posts per page.
2598 * @param postsPerPage
2599 * The number of posts per page
2600 * @return {@code true} if the number of posts per page was valid,
2601 * {@code false} otherwise
2603 public boolean validatePostsPerPage(Integer postsPerPage) {
2604 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2608 * Sets the number of posts to show per page.
2610 * @param postsPerPage
2611 * The number of posts to show per page
2612 * @return This preferences object
2614 public Preferences setPostsPerPage(Integer postsPerPage) {
2615 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2620 * Returns the number of images to show per page.
2622 * @return The number of images to show per page
2624 public int getImagesPerPage() {
2625 return options.getIntegerOption("ImagesPerPage").get();
2629 * Validates the number of images per page.
2631 * @param imagesPerPage
2632 * The number of images per page
2633 * @return {@code true} if the number of images per page was valid,
2634 * {@code false} otherwise
2636 public boolean validateImagesPerPage(Integer imagesPerPage) {
2637 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2641 * Sets the number of images per page.
2643 * @param imagesPerPage
2644 * The number of images per page
2645 * @return This preferences object
2647 public Preferences setImagesPerPage(Integer imagesPerPage) {
2648 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2653 * Returns the number of characters per post, or <code>-1</code> if the
2654 * posts should not be cut off.
2656 * @return The numbers of characters per post
2658 public int getCharactersPerPost() {
2659 return options.getIntegerOption("CharactersPerPost").get();
2663 * Validates the number of characters per post.
2665 * @param charactersPerPost
2666 * The number of characters per post
2667 * @return {@code true} if the number of characters per post was valid,
2668 * {@code false} otherwise
2670 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2671 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2675 * Sets the number of characters per post.
2677 * @param charactersPerPost
2678 * The number of characters per post, or <code>-1</code> to
2679 * not cut off the posts
2680 * @return This preferences objects
2682 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2683 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2688 * Returns the number of characters the shortened post should have.
2690 * @return The number of characters of the snippet
2692 public int getPostCutOffLength() {
2693 return options.getIntegerOption("PostCutOffLength").get();
2697 * Validates the number of characters after which to cut off the post.
2699 * @param postCutOffLength
2700 * The number of characters of the snippet
2701 * @return {@code true} if the number of characters of the snippet is
2702 * valid, {@code false} otherwise
2704 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2705 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2709 * Sets the number of characters the shortened post should have.
2711 * @param postCutOffLength
2712 * The number of characters of the snippet
2713 * @return This preferences
2715 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2716 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2721 * Returns whether Sone requires full access to be even visible.
2723 * @return {@code true} if Sone requires full access, {@code false}
2726 public boolean isRequireFullAccess() {
2727 return options.getBooleanOption("RequireFullAccess").get();
2731 * Sets whether Sone requires full access to be even visible.
2733 * @param requireFullAccess
2734 * {@code true} if Sone requires full access, {@code false}
2737 public void setRequireFullAccess(Boolean requireFullAccess) {
2738 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2742 * Returns the positive trust.
2744 * @return The positive trust
2746 public int getPositiveTrust() {
2747 return options.getIntegerOption("PositiveTrust").get();
2751 * Validates the positive trust.
2753 * @param positiveTrust
2754 * The positive trust to validate
2755 * @return {@code true} if the positive trust was valid, {@code false}
2758 public boolean validatePositiveTrust(Integer positiveTrust) {
2759 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2763 * Sets the positive trust.
2765 * @param positiveTrust
2766 * The new positive trust, or {@code null} to restore it to
2768 * @return This preferences
2770 public Preferences setPositiveTrust(Integer positiveTrust) {
2771 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2776 * Returns the negative trust.
2778 * @return The negative trust
2780 public int getNegativeTrust() {
2781 return options.getIntegerOption("NegativeTrust").get();
2785 * Validates the negative trust.
2787 * @param negativeTrust
2788 * The negative trust to validate
2789 * @return {@code true} if the negative trust was valid, {@code false}
2792 public boolean validateNegativeTrust(Integer negativeTrust) {
2793 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2797 * Sets the negative trust.
2799 * @param negativeTrust
2800 * The negative trust, or {@code null} to restore it to the
2802 * @return The preferences
2804 public Preferences setNegativeTrust(Integer negativeTrust) {
2805 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2810 * Returns the trust comment. This is the comment that is set in the web
2811 * of trust when a trust value is assigned to an identity.
2813 * @return The trust comment
2815 public String getTrustComment() {
2816 return options.getStringOption("TrustComment").get();
2820 * Sets the trust comment.
2822 * @param trustComment
2823 * The trust comment, or {@code null} to restore it to the
2825 * @return This preferences
2827 public Preferences setTrustComment(String trustComment) {
2828 options.getStringOption("TrustComment").set(trustComment);
2833 * Returns whether the {@link FcpInterface FCP interface} is currently
2836 * @see FcpInterface#setActive(boolean)
2837 * @return {@code true} if the FCP interface is currently active,
2838 * {@code false} otherwise
2840 public boolean isFcpInterfaceActive() {
2841 return options.getBooleanOption("ActivateFcpInterface").get();
2845 * Sets whether the {@link FcpInterface FCP interface} is currently
2848 * @see FcpInterface#setActive(boolean)
2849 * @param fcpInterfaceActive
2850 * {@code true} to activate the FCP interface, {@code false}
2851 * to deactivate the FCP interface
2852 * @return This preferences object
2854 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2855 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2860 * Returns the action level for which full access to the FCP interface
2863 * @return The action level for which full access to the FCP interface
2866 public FullAccessRequired getFcpFullAccessRequired() {
2867 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2871 * Sets the action level for which full access to the FCP interface is
2874 * @param fcpFullAccessRequired
2876 * @return This preferences
2878 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2879 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);