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.SoneLockedEvent;
47 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
48 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
49 import net.pterodactylus.sone.data.Album;
50 import net.pterodactylus.sone.data.Client;
51 import net.pterodactylus.sone.data.Image;
52 import net.pterodactylus.sone.data.Post;
53 import net.pterodactylus.sone.data.PostReply;
54 import net.pterodactylus.sone.data.Profile;
55 import net.pterodactylus.sone.data.Profile.Field;
56 import net.pterodactylus.sone.data.Reply;
57 import net.pterodactylus.sone.data.Sone;
58 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
59 import net.pterodactylus.sone.data.Sone.SoneStatus;
60 import net.pterodactylus.sone.data.TemporaryImage;
61 import net.pterodactylus.sone.data.impl.PostImpl;
62 import net.pterodactylus.sone.fcp.FcpInterface;
63 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
64 import net.pterodactylus.sone.freenet.wot.Identity;
65 import net.pterodactylus.sone.freenet.wot.IdentityListener;
66 import net.pterodactylus.sone.freenet.wot.IdentityManager;
67 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
68 import net.pterodactylus.sone.main.SonePlugin;
69 import net.pterodactylus.util.config.Configuration;
70 import net.pterodactylus.util.config.ConfigurationException;
71 import net.pterodactylus.util.logging.Logging;
72 import net.pterodactylus.util.number.Numbers;
73 import net.pterodactylus.util.service.AbstractService;
74 import net.pterodactylus.util.thread.NamedThreadFactory;
75 import net.pterodactylus.util.thread.Ticker;
76 import net.pterodactylus.util.validation.EqualityValidator;
77 import net.pterodactylus.util.validation.IntegerRangeValidator;
78 import net.pterodactylus.util.validation.OrValidator;
79 import net.pterodactylus.util.validation.Validation;
80 import net.pterodactylus.util.version.Version;
82 import com.google.common.base.Predicate;
83 import com.google.common.collect.Collections2;
84 import com.google.common.eventbus.EventBus;
85 import com.google.inject.Inject;
87 import freenet.keys.FreenetURI;
92 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
94 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
97 private static final Logger logger = Logging.getLogger(Core.class);
99 /** The start time. */
100 private final long startupTime = System.currentTimeMillis();
103 private final Options options = new Options();
105 /** The preferences. */
106 private final Preferences preferences = new Preferences(options);
108 /** The core listener manager. */
109 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
111 /** The event bus. */
112 private final EventBus eventBus;
114 /** The configuration. */
115 private Configuration configuration;
117 /** Whether we’re currently saving the configuration. */
118 private boolean storingConfiguration = false;
120 /** The identity manager. */
121 private final IdentityManager identityManager;
123 /** Interface to freenet. */
124 private final FreenetInterface freenetInterface;
126 /** The Sone downloader. */
127 private final SoneDownloader soneDownloader;
129 /** The image inserter. */
130 private final ImageInserter imageInserter;
132 /** Sone downloader thread-pool. */
133 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
135 /** The update checker. */
136 private final UpdateChecker updateChecker;
138 /** The trust updater. */
139 private final WebOfTrustUpdater webOfTrustUpdater;
141 /** The FCP interface. */
142 private volatile FcpInterface fcpInterface;
144 /** The times Sones were followed. */
145 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
147 /** Locked local Sones. */
148 /* synchronize on itself. */
149 private final Set<Sone> lockedSones = new HashSet<Sone>();
151 /** Sone inserters. */
152 /* synchronize access on this on sones. */
153 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
155 /** Sone rescuers. */
156 /* synchronize access on this on sones. */
157 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
160 /* synchronize access on this on itself. */
161 private final Map<String, Sone> sones = new HashMap<String, Sone>();
163 /** All known Sones. */
164 private final Set<String> knownSones = new HashSet<String>();
167 private final Map<String, Post> posts = new HashMap<String, Post>();
169 /** All known posts. */
170 private final Set<String> knownPosts = new HashSet<String>();
173 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
175 /** All known replies. */
176 private final Set<String> knownReplies = new HashSet<String>();
178 /** All bookmarked posts. */
179 /* synchronize access on itself. */
180 private final Set<String> bookmarkedPosts = new HashSet<String>();
182 /** Trusted identities, sorted by own identities. */
183 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
185 /** All known albums. */
186 private final Map<String, Album> albums = new HashMap<String, Album>();
188 /** All known images. */
189 private final Map<String, Image> images = new HashMap<String, Image>();
191 /** All temporary images. */
192 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
194 /** Ticker for threads that mark own elements as known. */
195 private final Ticker localElementTicker = new Ticker();
197 /** The time the configuration was last touched. */
198 private volatile long lastConfigurationUpdate;
201 * Creates a new core.
203 * @param configuration
204 * The configuration of the core
205 * @param freenetInterface
206 * The freenet interface
207 * @param identityManager
208 * The identity manager
209 * @param webOfTrustUpdater
210 * The WebOfTrust updater
215 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
217 this.configuration = configuration;
218 this.freenetInterface = freenetInterface;
219 this.identityManager = identityManager;
220 this.soneDownloader = new SoneDownloader(this, freenetInterface);
221 this.imageInserter = new ImageInserter(this, freenetInterface);
222 this.updateChecker = new UpdateChecker(freenetInterface);
223 this.webOfTrustUpdater = webOfTrustUpdater;
224 this.eventBus = eventBus;
228 // LISTENER MANAGEMENT
232 * Adds a new core listener.
234 * @param coreListener
235 * The listener to add
237 public void addCoreListener(CoreListener coreListener) {
238 coreListenerManager.addListener(coreListener);
242 * Removes a core listener.
244 * @param coreListener
245 * The listener to remove
247 public void removeCoreListener(CoreListener coreListener) {
248 coreListenerManager.removeListener(coreListener);
256 * Returns the time Sone was started.
258 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
260 public long getStartupTime() {
265 * Sets the configuration to use. This will automatically save the current
266 * configuration to the given configuration.
268 * @param configuration
269 * The new configuration to use
271 public void setConfiguration(Configuration configuration) {
272 this.configuration = configuration;
273 touchConfiguration();
277 * Returns the options used by the core.
279 * @return The options of the core
281 public Preferences getPreferences() {
286 * Returns the identity manager used by the core.
288 * @return The identity manager
290 public IdentityManager getIdentityManager() {
291 return identityManager;
295 * Returns the update checker.
297 * @return The update checker
299 public UpdateChecker getUpdateChecker() {
300 return updateChecker;
304 * Sets the FCP interface to use.
306 * @param fcpInterface
307 * The FCP interface to use
309 public void setFcpInterface(FcpInterface fcpInterface) {
310 this.fcpInterface = fcpInterface;
314 * Returns the Sone rescuer for the given local Sone.
317 * The local Sone to get the rescuer for
318 * @return The Sone rescuer for the given Sone
320 public SoneRescuer getSoneRescuer(Sone sone) {
321 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
322 synchronized (sones) {
323 SoneRescuer soneRescuer = soneRescuers.get(sone);
324 if (soneRescuer == null) {
325 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
326 soneRescuers.put(sone, soneRescuer);
334 * Returns whether the given Sone is currently locked.
338 * @return {@code true} if the Sone is locked, {@code false} if it is not
340 public boolean isLocked(Sone sone) {
341 synchronized (lockedSones) {
342 return lockedSones.contains(sone);
347 * Returns all Sones, remote and local.
351 public Set<Sone> getSones() {
352 return new HashSet<Sone>(sones.values());
356 * Returns the Sone with the given ID, regardless whether it’s local or
360 * The ID of the Sone to get
361 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Sone getSone(String id) {
365 return getSone(id, true);
369 * Returns the Sone with the given ID, regardless whether it’s local or
373 * The ID of the Sone to get
375 * {@code true} to create a new Sone if none exists,
376 * {@code false} to return {@code null} if a Sone with the given
378 * @return The Sone with the given ID, or {@code null} if there is no such
382 public Sone getSone(String id, boolean create) {
383 synchronized (sones) {
384 if (!sones.containsKey(id)) {
385 Sone sone = new Sone(id, false);
388 return sones.get(id);
393 * Checks whether the core knows a Sone with the given ID.
397 * @return {@code true} if there is a Sone with the given ID, {@code false}
400 public boolean hasSone(String id) {
401 synchronized (sones) {
402 return sones.containsKey(id);
407 * Returns all local Sones.
409 * @return All local Sones
411 public Collection<Sone> getLocalSones() {
412 synchronized (sones) {
413 return Collections2.filter(sones.values(), new Predicate<Sone>() {
416 public boolean apply(Sone sone) {
417 return sone.isLocal();
424 * Returns the local Sone with the given ID, optionally creating a new Sone.
429 * {@code true} to create a new Sone if none exists,
430 * {@code false} to return null if none exists
431 * @return The Sone with the given ID, or {@code null}
433 public Sone getLocalSone(String id, boolean create) {
434 synchronized (sones) {
435 Sone sone = sones.get(id);
436 if ((sone == null) && create) {
437 sone = new Sone(id, true);
440 if ((sone != null) && !sone.isLocal()) {
441 sone = new Sone(id, true);
449 * Returns all remote Sones.
451 * @return All remote Sones
453 public Collection<Sone> getRemoteSones() {
454 synchronized (sones) {
455 return Collections2.filter(sones.values(), new Predicate<Sone>() {
458 public boolean apply(Sone sone) {
459 return !sone.isLocal();
466 * Returns the remote Sone with the given ID.
469 * The ID of the remote Sone to get
471 * {@code true} to always create a Sone, {@code false} to return
472 * {@code null} if no Sone with the given ID exists
473 * @return The Sone with the given ID
475 public Sone getRemoteSone(String id, boolean create) {
476 synchronized (sones) {
477 Sone sone = sones.get(id);
478 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
479 sone = new Sone(id, false);
487 * Returns whether the given Sone has been modified.
490 * The Sone to check for modifications
491 * @return {@code true} if a modification has been detected in the Sone,
492 * {@code false} otherwise
494 public boolean isModifiedSone(Sone sone) {
495 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
499 * Returns the time when the given was first followed by any local Sone.
502 * The Sone to get the time for
503 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
504 * been followed, or {@link Long#MAX_VALUE}
506 public long getSoneFollowingTime(Sone sone) {
507 synchronized (soneFollowingTimes) {
508 if (soneFollowingTimes.containsKey(sone)) {
509 return soneFollowingTimes.get(sone);
511 return Long.MAX_VALUE;
516 * Returns whether the target Sone is trusted by the origin Sone.
522 * @return {@code true} if the target Sone is trusted by the origin Sone
524 public boolean isSoneTrusted(Sone origin, Sone target) {
525 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
526 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
530 * Returns the post with the given ID.
533 * The ID of the post to get
534 * @return The post with the given ID, or a new post with the given ID
536 public Post getPost(String postId) {
537 return getPost(postId, true);
541 * Returns the post with the given ID, optionally creating a new post.
544 * The ID of the post to get
546 * {@code true} it create a new post if no post with the given ID
547 * exists, {@code false} to return {@code null}
548 * @return The post, or {@code null} if there is no such post
551 public Post getPost(String postId, boolean create) {
552 synchronized (posts) {
553 Post post = posts.get(postId);
554 if ((post == null) && create) {
555 post = new PostImpl(postId);
556 posts.put(postId, post);
563 * Returns all posts that have the given Sone as recipient.
565 * @see Post#getRecipient()
567 * The recipient of the posts
568 * @return All posts that have the given Sone as recipient
570 public Set<Post> getDirectedPosts(Sone recipient) {
571 Validation.begin().isNotNull("Recipient", recipient).check();
572 Set<Post> directedPosts = new HashSet<Post>();
573 synchronized (posts) {
574 for (Post post : posts.values()) {
575 if (recipient.equals(post.getRecipient())) {
576 directedPosts.add(post);
580 return directedPosts;
584 * Returns the reply with the given ID. If there is no reply with the given
585 * ID yet, a new one is created, unless {@code create} is false in which
586 * case {@code null} is returned.
589 * The ID of the reply to get
591 * {@code true} to always return a {@link Reply}, {@code false}
592 * to return {@code null} if no reply can be found
593 * @return The reply, or {@code null} if there is no such reply
595 public PostReply getPostReply(String replyId, boolean create) {
596 synchronized (replies) {
597 PostReply reply = replies.get(replyId);
598 if (create && (reply == null)) {
599 reply = new PostReply(replyId);
600 replies.put(replyId, reply);
607 * Returns all replies for the given post, order ascending by time.
610 * The post to get all replies for
611 * @return All replies for the given post
613 public List<PostReply> getReplies(Post post) {
614 Set<Sone> sones = getSones();
615 List<PostReply> replies = new ArrayList<PostReply>();
616 for (Sone sone : sones) {
617 for (PostReply reply : sone.getReplies()) {
618 if (reply.getPost().equals(post)) {
623 Collections.sort(replies, Reply.TIME_COMPARATOR);
628 * Returns all Sones that have liked the given post.
631 * The post to get the liking Sones for
632 * @return The Sones that like the given post
634 public Set<Sone> getLikes(Post post) {
635 Set<Sone> sones = new HashSet<Sone>();
636 for (Sone sone : getSones()) {
637 if (sone.getLikedPostIds().contains(post.getId())) {
645 * Returns all Sones that have liked the given reply.
648 * The reply to get the liking Sones for
649 * @return The Sones that like the given reply
651 public Set<Sone> getLikes(PostReply reply) {
652 Set<Sone> sones = new HashSet<Sone>();
653 for (Sone sone : getSones()) {
654 if (sone.getLikedReplyIds().contains(reply.getId())) {
662 * Returns whether the given post is bookmarked.
666 * @return {@code true} if the given post is bookmarked, {@code false}
669 public boolean isBookmarked(Post post) {
670 return isPostBookmarked(post.getId());
674 * Returns whether the post with the given ID is bookmarked.
677 * The ID of the post to check
678 * @return {@code true} if the post with the given ID is bookmarked,
679 * {@code false} otherwise
681 public boolean isPostBookmarked(String id) {
682 synchronized (bookmarkedPosts) {
683 return bookmarkedPosts.contains(id);
688 * Returns all currently known bookmarked posts.
690 * @return All bookmarked posts
692 public Set<Post> getBookmarkedPosts() {
693 Set<Post> posts = new HashSet<Post>();
694 synchronized (bookmarkedPosts) {
695 for (String bookmarkedPostId : bookmarkedPosts) {
696 Post post = getPost(bookmarkedPostId, false);
706 * Returns the album with the given ID, creating a new album if no album
707 * with the given ID can be found.
710 * The ID of the album
711 * @return The album with the given ID
713 public Album getAlbum(String albumId) {
714 return getAlbum(albumId, true);
718 * Returns the album with the given ID, optionally creating a new album if
719 * an album with the given ID can not be found.
722 * The ID of the album
724 * {@code true} to create a new album if none exists for the
726 * @return The album with the given ID, or {@code null} if no album with the
727 * given ID exists and {@code create} is {@code false}
729 public Album getAlbum(String albumId, boolean create) {
730 synchronized (albums) {
731 Album album = albums.get(albumId);
732 if (create && (album == null)) {
733 album = new Album(albumId);
734 albums.put(albumId, album);
741 * Returns the image with the given ID, creating it if necessary.
744 * The ID of the image
745 * @return The image with the given ID
747 public Image getImage(String imageId) {
748 return getImage(imageId, true);
752 * Returns the image with the given ID, optionally creating it if it does
756 * The ID of the image
758 * {@code true} to create an image if none exists with the given
760 * @return The image with the given ID, or {@code null} if none exists and
763 public Image getImage(String imageId, boolean create) {
764 synchronized (images) {
765 Image image = images.get(imageId);
766 if (create && (image == null)) {
767 image = new Image(imageId);
768 images.put(imageId, image);
775 * Returns the temporary image with the given ID.
778 * The ID of the temporary image
779 * @return The temporary image, or {@code null} if there is no temporary
780 * image with the given ID
782 public TemporaryImage getTemporaryImage(String imageId) {
783 synchronized (temporaryImages) {
784 return temporaryImages.get(imageId);
793 * Locks the given Sone. A locked Sone will not be inserted by
794 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
800 public void lockSone(Sone sone) {
801 synchronized (lockedSones) {
802 if (lockedSones.add(sone)) {
803 eventBus.post(new SoneLockedEvent(sone));
809 * Unlocks the given Sone.
811 * @see #lockSone(Sone)
815 public void unlockSone(Sone sone) {
816 synchronized (lockedSones) {
817 if (lockedSones.remove(sone)) {
818 eventBus.post(new SoneUnlockedEvent(sone));
824 * Adds a local Sone from the given own identity.
827 * The own identity to create a Sone from
828 * @return The added (or already existing) Sone
830 public Sone addLocalSone(OwnIdentity ownIdentity) {
831 if (ownIdentity == null) {
832 logger.log(Level.WARNING, "Given OwnIdentity is null!");
835 synchronized (sones) {
838 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
839 } catch (MalformedURLException mue1) {
840 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
843 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
844 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
846 /* TODO - load posts ’n stuff */
847 sones.put(ownIdentity.getId(), sone);
848 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
849 soneInserter.addSoneInsertListener(this);
850 soneInserters.put(sone, soneInserter);
851 sone.setStatus(SoneStatus.idle);
853 soneInserter.start();
859 * Creates a new Sone for the given own identity.
862 * The own identity to create a Sone for
863 * @return The created Sone
865 public Sone createSone(OwnIdentity ownIdentity) {
866 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
867 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
870 Sone sone = addLocalSone(ownIdentity);
871 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
872 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
873 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
874 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
875 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
876 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
878 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
879 touchConfiguration();
884 * Adds the Sone of the given identity.
887 * The identity whose Sone to add
888 * @return The added or already existing Sone
890 public Sone addRemoteSone(Identity identity) {
891 if (identity == null) {
892 logger.log(Level.WARNING, "Given Identity is null!");
895 synchronized (sones) {
896 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
897 boolean newSone = sone.getRequestUri() == null;
898 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
899 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
901 synchronized (knownSones) {
902 newSone = !knownSones.contains(sone.getId());
904 sone.setKnown(!newSone);
906 eventBus.post(new NewSoneFoundEvent(sone));
907 for (Sone localSone : getLocalSones()) {
908 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
909 followSone(localSone, sone);
914 soneDownloader.addSone(sone);
915 soneDownloaders.execute(new Runnable() {
918 @SuppressWarnings("synthetic-access")
920 soneDownloader.fetchSone(sone, sone.getRequestUri());
929 * Lets the given local Sone follow the Sone with the given ID.
932 * The local Sone that should follow another Sone
934 * The ID of the Sone to follow
936 public void followSone(Sone sone, String soneId) {
937 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
938 Sone followedSone = getSone(soneId, true);
939 if (followedSone == null) {
940 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
943 followSone(sone, getSone(soneId));
947 * Lets the given local Sone follow the other given Sone. If the given Sone
948 * was not followed by any local Sone before, this will mark all elements of
949 * the followed Sone as read that have been created before the current
953 * The local Sone that should follow the other Sone
954 * @param followedSone
955 * The Sone that should be followed
957 public void followSone(Sone sone, Sone followedSone) {
958 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
959 sone.addFriend(followedSone.getId());
960 synchronized (soneFollowingTimes) {
961 if (!soneFollowingTimes.containsKey(followedSone)) {
962 long now = System.currentTimeMillis();
963 soneFollowingTimes.put(followedSone, now);
964 for (Post post : followedSone.getPosts()) {
965 if (post.getTime() < now) {
969 for (PostReply reply : followedSone.getReplies()) {
970 if (reply.getTime() < now) {
971 markReplyKnown(reply);
976 touchConfiguration();
980 * Lets the given local Sone unfollow the Sone with the given ID.
983 * The local Sone that should unfollow another Sone
985 * The ID of the Sone being unfollowed
987 public void unfollowSone(Sone sone, String soneId) {
988 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
989 unfollowSone(sone, getSone(soneId, false));
993 * Lets the given local Sone unfollow the other given Sone. If the given
994 * local Sone is the last local Sone that followed the given Sone, its
995 * following time will be removed.
998 * The local Sone that should unfollow another Sone
999 * @param unfollowedSone
1000 * The Sone being unfollowed
1002 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1003 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1004 sone.removeFriend(unfollowedSone.getId());
1005 boolean unfollowedSoneStillFollowed = false;
1006 for (Sone localSone : getLocalSones()) {
1007 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1009 if (!unfollowedSoneStillFollowed) {
1010 synchronized (soneFollowingTimes) {
1011 soneFollowingTimes.remove(unfollowedSone);
1014 touchConfiguration();
1018 * Sets the trust value of the given origin Sone for the target Sone.
1025 * The trust value (from {@code -100} to {@code 100})
1027 public void setTrust(Sone origin, Sone target, int trustValue) {
1028 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();
1029 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1033 * Removes any trust assignment for the given target Sone.
1040 public void removeTrust(Sone origin, Sone target) {
1041 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1042 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1046 * Assigns the configured positive trust value for the given target.
1053 public void trustSone(Sone origin, Sone target) {
1054 setTrust(origin, target, preferences.getPositiveTrust());
1058 * Assigns the configured negative trust value for the given target.
1065 public void distrustSone(Sone origin, Sone target) {
1066 setTrust(origin, target, preferences.getNegativeTrust());
1070 * Removes the trust assignment for the given target.
1077 public void untrustSone(Sone origin, Sone target) {
1078 removeTrust(origin, target);
1082 * Updates the stored Sone with the given Sone.
1087 public void updateSone(Sone sone) {
1088 updateSone(sone, false);
1092 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1093 * {@code true}, an older Sone than the current Sone can be given to restore
1097 * The Sone to update
1098 * @param soneRescueMode
1099 * {@code true} if the stored Sone should be updated regardless
1100 * of the age of the given Sone
1102 public void updateSone(Sone sone, boolean soneRescueMode) {
1103 if (hasSone(sone.getId())) {
1104 Sone storedSone = getSone(sone.getId());
1105 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1106 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1109 synchronized (posts) {
1110 if (!soneRescueMode) {
1111 for (Post post : storedSone.getPosts()) {
1112 posts.remove(post.getId());
1113 if (!sone.getPosts().contains(post)) {
1114 eventBus.post(new PostRemovedEvent(post));
1118 List<Post> storedPosts = storedSone.getPosts();
1119 synchronized (knownPosts) {
1120 for (Post post : sone.getPosts()) {
1121 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1122 if (!storedPosts.contains(post)) {
1123 if (post.getTime() < getSoneFollowingTime(sone)) {
1124 knownPosts.add(post.getId());
1125 post.setKnown(true);
1126 } else if (!knownPosts.contains(post.getId())) {
1127 eventBus.post(new NewPostFoundEvent(post));
1130 posts.put(post.getId(), post);
1134 synchronized (replies) {
1135 if (!soneRescueMode) {
1136 for (PostReply reply : storedSone.getReplies()) {
1137 replies.remove(reply.getId());
1138 if (!sone.getReplies().contains(reply)) {
1139 eventBus.post(new PostReplyRemovedEvent(reply));
1143 Set<PostReply> storedReplies = storedSone.getReplies();
1144 synchronized (knownReplies) {
1145 for (PostReply reply : sone.getReplies()) {
1146 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1147 if (!storedReplies.contains(reply)) {
1148 if (reply.getTime() < getSoneFollowingTime(sone)) {
1149 knownReplies.add(reply.getId());
1150 reply.setKnown(true);
1151 } else if (!knownReplies.contains(reply.getId())) {
1152 eventBus.post(new NewPostReplyFoundEvent(reply));
1155 replies.put(reply.getId(), reply);
1159 synchronized (albums) {
1160 synchronized (images) {
1161 for (Album album : storedSone.getAlbums()) {
1162 albums.remove(album.getId());
1163 for (Image image : album.getImages()) {
1164 images.remove(image.getId());
1167 for (Album album : sone.getAlbums()) {
1168 albums.put(album.getId(), album);
1169 for (Image image : album.getImages()) {
1170 images.put(image.getId(), image);
1175 synchronized (storedSone) {
1176 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1177 storedSone.setTime(sone.getTime());
1179 storedSone.setClient(sone.getClient());
1180 storedSone.setProfile(sone.getProfile());
1181 if (soneRescueMode) {
1182 for (Post post : sone.getPosts()) {
1183 storedSone.addPost(post);
1185 for (PostReply reply : sone.getReplies()) {
1186 storedSone.addReply(reply);
1188 for (String likedPostId : sone.getLikedPostIds()) {
1189 storedSone.addLikedPostId(likedPostId);
1191 for (String likedReplyId : sone.getLikedReplyIds()) {
1192 storedSone.addLikedReplyId(likedReplyId);
1194 for (Album album : sone.getAlbums()) {
1195 storedSone.addAlbum(album);
1198 storedSone.setPosts(sone.getPosts());
1199 storedSone.setReplies(sone.getReplies());
1200 storedSone.setLikePostIds(sone.getLikedPostIds());
1201 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1202 storedSone.setAlbums(sone.getAlbums());
1204 storedSone.setLatestEdition(sone.getLatestEdition());
1210 * Deletes the given Sone. This will remove the Sone from the
1211 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1212 * remove the context from its identity.
1215 * The Sone to delete
1217 public void deleteSone(Sone sone) {
1218 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1219 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1222 synchronized (sones) {
1223 if (!getLocalSones().contains(sone)) {
1224 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1227 sones.remove(sone.getId());
1228 SoneInserter soneInserter = soneInserters.remove(sone);
1229 soneInserter.removeSoneInsertListener(this);
1230 soneInserter.stop();
1232 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1233 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1235 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1236 } catch (ConfigurationException ce1) {
1237 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1242 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1243 * known} before, a {@link MarkSoneKnownEvent} is fired.
1246 * The Sone to mark as known
1248 public void markSoneKnown(Sone sone) {
1249 if (!sone.isKnown()) {
1250 sone.setKnown(true);
1251 synchronized (knownSones) {
1252 knownSones.add(sone.getId());
1254 eventBus.post(new MarkSoneKnownEvent(sone));
1255 touchConfiguration();
1260 * Loads and updates the given Sone from the configuration. If any error is
1261 * encountered, loading is aborted and the given Sone is not changed.
1264 * The Sone to load and update
1266 public void loadSone(Sone sone) {
1267 if (!sone.isLocal()) {
1268 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1272 /* initialize options. */
1273 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1274 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1275 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1276 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1277 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1278 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1281 String sonePrefix = "Sone/" + sone.getId();
1282 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1283 if (soneTime == null) {
1284 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1287 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1290 Profile profile = new Profile(sone);
1291 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1292 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1293 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1294 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1295 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1296 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1298 /* load profile fields. */
1300 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1301 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1302 if (fieldName == null) {
1305 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1306 profile.addField(fieldName).setValue(fieldValue);
1310 Set<Post> posts = new HashSet<Post>();
1312 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1313 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1314 if (postId == null) {
1317 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1318 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1319 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1320 if ((postTime == 0) || (postText == null)) {
1321 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1324 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1325 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1326 post.setRecipient(getSone(postRecipientId));
1332 Set<PostReply> replies = new HashSet<PostReply>();
1334 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1335 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1336 if (replyId == null) {
1339 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1340 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1341 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1342 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1343 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1346 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1349 /* load post likes. */
1350 Set<String> likedPostIds = new HashSet<String>();
1352 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1353 if (likedPostId == null) {
1356 likedPostIds.add(likedPostId);
1359 /* load reply likes. */
1360 Set<String> likedReplyIds = new HashSet<String>();
1362 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1363 if (likedReplyId == null) {
1366 likedReplyIds.add(likedReplyId);
1370 Set<String> friends = new HashSet<String>();
1372 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1373 if (friendId == null) {
1376 friends.add(friendId);
1380 List<Album> topLevelAlbums = new ArrayList<Album>();
1381 int albumCounter = 0;
1383 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1384 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1385 if (albumId == null) {
1388 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1389 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1390 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1391 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1392 if ((albumTitle == null) || (albumDescription == null)) {
1393 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1396 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1397 if (albumParentId != null) {
1398 Album parentAlbum = getAlbum(albumParentId, false);
1399 if (parentAlbum == null) {
1400 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1403 parentAlbum.addAlbum(album);
1405 if (!topLevelAlbums.contains(album)) {
1406 topLevelAlbums.add(album);
1412 int imageCounter = 0;
1414 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1415 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1416 if (imageId == null) {
1419 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1420 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1421 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1422 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1423 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1424 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1425 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1426 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1427 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1430 Album album = getAlbum(albumId, false);
1431 if (album == null) {
1432 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1435 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1436 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1437 album.addImage(image);
1441 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1442 if (avatarId != null) {
1443 profile.setAvatar(getImage(avatarId, false));
1447 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1448 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1449 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1450 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1451 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1452 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1454 /* if we’re still here, Sone was loaded successfully. */
1455 synchronized (sone) {
1456 sone.setTime(soneTime);
1457 sone.setProfile(profile);
1458 sone.setPosts(posts);
1459 sone.setReplies(replies);
1460 sone.setLikePostIds(likedPostIds);
1461 sone.setLikeReplyIds(likedReplyIds);
1462 for (String friendId : friends) {
1463 followSone(sone, friendId);
1465 sone.setAlbums(topLevelAlbums);
1466 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1468 synchronized (knownSones) {
1469 for (String friend : friends) {
1470 knownSones.add(friend);
1473 synchronized (knownPosts) {
1474 for (Post post : posts) {
1475 knownPosts.add(post.getId());
1478 synchronized (knownReplies) {
1479 for (PostReply reply : replies) {
1480 knownReplies.add(reply.getId());
1486 * Creates a new post.
1489 * The Sone that creates the post
1491 * The text of the post
1492 * @return The created post
1494 public Post createPost(Sone sone, String text) {
1495 return createPost(sone, System.currentTimeMillis(), text);
1499 * Creates a new post.
1502 * The Sone that creates the post
1504 * The time of the post
1506 * The text of the post
1507 * @return The created post
1509 public Post createPost(Sone sone, long time, String text) {
1510 return createPost(sone, null, time, text);
1514 * Creates a new post.
1517 * The Sone that creates the post
1519 * The recipient Sone, or {@code null} if this post does not have
1522 * The text of the post
1523 * @return The created post
1525 public Post createPost(Sone sone, Sone recipient, String text) {
1526 return createPost(sone, recipient, System.currentTimeMillis(), text);
1530 * Creates a new post.
1533 * The Sone that creates the post
1535 * The recipient Sone, or {@code null} if this post does not have
1538 * The time of the post
1540 * The text of the post
1541 * @return The created post
1543 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1544 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1545 if (!sone.isLocal()) {
1546 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1549 final Post post = new PostImpl(sone, time, text);
1550 if (recipient != null) {
1551 post.setRecipient(recipient);
1553 synchronized (posts) {
1554 posts.put(post.getId(), post);
1556 eventBus.post(new NewPostFoundEvent(post));
1558 touchConfiguration();
1559 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1566 markPostKnown(post);
1568 }, "Mark " + post + " read.");
1573 * Deletes the given post.
1576 * The post to delete
1578 public void deletePost(Post post) {
1579 if (!post.getSone().isLocal()) {
1580 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1583 post.getSone().removePost(post);
1584 synchronized (posts) {
1585 posts.remove(post.getId());
1587 eventBus.post(new PostRemovedEvent(post));
1588 markPostKnown(post);
1589 touchConfiguration();
1593 * Marks the given post as known, if it is currently not a known post
1594 * (according to {@link Post#isKnown()}).
1597 * The post to mark as known
1599 public void markPostKnown(Post post) {
1600 post.setKnown(true);
1601 synchronized (knownPosts) {
1602 eventBus.post(new MarkPostKnownEvent(post));
1603 if (knownPosts.add(post.getId())) {
1604 touchConfiguration();
1607 for (PostReply reply : getReplies(post)) {
1608 markReplyKnown(reply);
1613 * Bookmarks the given post.
1616 * The post to bookmark
1618 public void bookmark(Post post) {
1619 bookmarkPost(post.getId());
1623 * Bookmarks the post with the given ID.
1626 * The ID of the post to bookmark
1628 public void bookmarkPost(String id) {
1629 synchronized (bookmarkedPosts) {
1630 bookmarkedPosts.add(id);
1635 * Removes the given post from the bookmarks.
1638 * The post to unbookmark
1640 public void unbookmark(Post post) {
1641 unbookmarkPost(post.getId());
1645 * Removes the post with the given ID from the bookmarks.
1648 * The ID of the post to unbookmark
1650 public void unbookmarkPost(String id) {
1651 synchronized (bookmarkedPosts) {
1652 bookmarkedPosts.remove(id);
1657 * Creates a new reply.
1660 * The Sone that creates the reply
1662 * The post that this reply refers to
1664 * The text of the reply
1665 * @return The created reply
1667 public PostReply createReply(Sone sone, Post post, String text) {
1668 return createReply(sone, post, System.currentTimeMillis(), text);
1672 * Creates a new reply.
1675 * The Sone that creates the reply
1677 * The post that this reply refers to
1679 * The time of the reply
1681 * The text of the reply
1682 * @return The created reply
1684 public PostReply createReply(Sone sone, Post post, long time, String text) {
1685 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1686 if (!sone.isLocal()) {
1687 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1690 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1691 synchronized (replies) {
1692 replies.put(reply.getId(), reply);
1694 synchronized (knownReplies) {
1695 eventBus.post(new NewPostReplyFoundEvent(reply));
1697 sone.addReply(reply);
1698 touchConfiguration();
1699 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1706 markReplyKnown(reply);
1708 }, "Mark " + reply + " read.");
1713 * Deletes the given reply.
1716 * The reply to delete
1718 public void deleteReply(PostReply reply) {
1719 Sone sone = reply.getSone();
1720 if (!sone.isLocal()) {
1721 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1724 synchronized (replies) {
1725 replies.remove(reply.getId());
1727 synchronized (knownReplies) {
1728 markReplyKnown(reply);
1729 knownReplies.remove(reply.getId());
1731 sone.removeReply(reply);
1732 touchConfiguration();
1736 * Marks the given reply as known, if it is currently not a known reply
1737 * (according to {@link Reply#isKnown()}).
1740 * The reply to mark as known
1742 public void markReplyKnown(PostReply reply) {
1743 reply.setKnown(true);
1744 synchronized (knownReplies) {
1745 eventBus.post(new MarkPostReplyKnownEvent(reply));
1746 if (knownReplies.add(reply.getId())) {
1747 touchConfiguration();
1753 * Creates a new top-level album for the given Sone.
1756 * The Sone to create the album for
1757 * @return The new album
1759 public Album createAlbum(Sone sone) {
1760 return createAlbum(sone, null);
1764 * Creates a new album for the given Sone.
1767 * The Sone to create the album for
1769 * The parent of the album (may be {@code null} to create a
1771 * @return The new album
1773 public Album createAlbum(Sone sone, Album parent) {
1774 Album album = new Album();
1775 synchronized (albums) {
1776 albums.put(album.getId(), album);
1778 album.setSone(sone);
1779 if (parent != null) {
1780 parent.addAlbum(album);
1782 sone.addAlbum(album);
1788 * Deletes the given album. The owner of the album has to be a local Sone,
1789 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1792 * The album to remove
1794 public void deleteAlbum(Album album) {
1795 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1796 if (!album.isEmpty()) {
1799 if (album.getParent() == null) {
1800 album.getSone().removeAlbum(album);
1802 album.getParent().removeAlbum(album);
1804 synchronized (albums) {
1805 albums.remove(album.getId());
1807 touchConfiguration();
1811 * Creates a new image.
1814 * The Sone creating the image
1816 * The album the image will be inserted into
1817 * @param temporaryImage
1818 * The temporary image to create the image from
1819 * @return The newly created image
1821 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1822 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();
1823 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1824 album.addImage(image);
1825 synchronized (images) {
1826 images.put(image.getId(), image);
1828 imageInserter.insertImage(temporaryImage, image);
1833 * Deletes the given image. This method will also delete a matching
1836 * @see #deleteTemporaryImage(TemporaryImage)
1838 * The image to delete
1840 public void deleteImage(Image image) {
1841 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1842 deleteTemporaryImage(image.getId());
1843 image.getAlbum().removeImage(image);
1844 synchronized (images) {
1845 images.remove(image.getId());
1847 touchConfiguration();
1851 * Creates a new temporary image.
1854 * The MIME type of the temporary image
1856 * The encoded data of the image
1857 * @return The temporary image
1859 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1860 TemporaryImage temporaryImage = new TemporaryImage();
1861 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1862 synchronized (temporaryImages) {
1863 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1865 return temporaryImage;
1869 * Deletes the given temporary image.
1871 * @param temporaryImage
1872 * The temporary image to delete
1874 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1875 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1876 deleteTemporaryImage(temporaryImage.getId());
1880 * Deletes the temporary image with the given ID.
1883 * The ID of the temporary image to delete
1885 public void deleteTemporaryImage(String imageId) {
1886 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1887 synchronized (temporaryImages) {
1888 temporaryImages.remove(imageId);
1890 Image image = getImage(imageId, false);
1891 if (image != null) {
1892 imageInserter.cancelImageInsert(image);
1897 * Notifies the core that the configuration, either of the core or of a
1898 * single local Sone, has changed, and that the configuration should be
1901 public void touchConfiguration() {
1902 lastConfigurationUpdate = System.currentTimeMillis();
1913 public void serviceStart() {
1914 loadConfiguration();
1915 updateChecker.addUpdateListener(this);
1916 updateChecker.start();
1917 identityManager.addIdentityListener(this);
1918 identityManager.start();
1919 webOfTrustUpdater.init();
1920 webOfTrustUpdater.start();
1927 public void serviceRun() {
1928 long lastSaved = System.currentTimeMillis();
1929 while (!shouldStop()) {
1931 long now = System.currentTimeMillis();
1932 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1933 for (Sone localSone : getLocalSones()) {
1934 saveSone(localSone);
1936 saveConfiguration();
1946 public void serviceStop() {
1947 synchronized (sones) {
1948 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1949 soneInserter.getValue().removeSoneInsertListener(this);
1950 soneInserter.getValue().stop();
1951 saveSone(soneInserter.getKey());
1954 saveConfiguration();
1955 webOfTrustUpdater.stop();
1956 updateChecker.stop();
1957 updateChecker.removeUpdateListener(this);
1958 soneDownloader.stop();
1959 identityManager.removeIdentityListener(this);
1960 identityManager.stop();
1968 * Saves the given Sone. This will persist all local settings for the given
1969 * Sone, such as the friends list and similar, private options.
1974 private synchronized void saveSone(Sone sone) {
1975 if (!sone.isLocal()) {
1976 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1979 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1980 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1984 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1986 /* save Sone into configuration. */
1987 String sonePrefix = "Sone/" + sone.getId();
1988 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1989 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1992 Profile profile = sone.getProfile();
1993 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1994 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1995 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1996 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1997 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1998 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1999 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2001 /* save profile fields. */
2002 int fieldCounter = 0;
2003 for (Field profileField : profile.getFields()) {
2004 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2005 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2006 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2008 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2011 int postCounter = 0;
2012 for (Post post : sone.getPosts()) {
2013 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2014 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2015 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2016 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2017 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2019 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2022 int replyCounter = 0;
2023 for (PostReply reply : sone.getReplies()) {
2024 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2025 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2026 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2027 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2028 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2030 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2032 /* save post likes. */
2033 int postLikeCounter = 0;
2034 for (String postId : sone.getLikedPostIds()) {
2035 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2037 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2039 /* save reply likes. */
2040 int replyLikeCounter = 0;
2041 for (String replyId : sone.getLikedReplyIds()) {
2042 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2044 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2047 int friendCounter = 0;
2048 for (String friendId : sone.getFriends()) {
2049 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2051 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2053 /* save albums. first, collect in a flat structure, top-level first. */
2054 List<Album> albums = sone.getAllAlbums();
2056 int albumCounter = 0;
2057 for (Album album : albums) {
2058 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2059 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2060 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2061 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2062 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2063 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2065 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2068 int imageCounter = 0;
2069 for (Album album : albums) {
2070 for (Image image : album.getImages()) {
2071 if (!image.isInserted()) {
2074 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2075 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2076 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2077 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2078 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2079 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2080 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2081 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2082 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2085 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2088 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2089 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2090 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2091 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2092 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2093 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2095 configuration.save();
2097 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2099 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2100 } catch (ConfigurationException ce1) {
2101 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2106 * Saves the current options.
2108 private void saveConfiguration() {
2109 synchronized (configuration) {
2110 if (storingConfiguration) {
2111 logger.log(Level.FINE, "Already storing configuration…");
2114 storingConfiguration = true;
2117 /* store the options first. */
2119 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2120 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2121 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2122 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2123 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2124 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2125 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2126 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2127 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2128 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2129 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2130 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2132 /* save known Sones. */
2133 int soneCounter = 0;
2134 synchronized (knownSones) {
2135 for (String knownSoneId : knownSones) {
2136 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2138 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2141 /* save Sone following times. */
2143 synchronized (soneFollowingTimes) {
2144 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2145 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2146 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2149 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2152 /* save known posts. */
2153 int postCounter = 0;
2154 synchronized (knownPosts) {
2155 for (String knownPostId : knownPosts) {
2156 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2158 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2161 /* save known replies. */
2162 int replyCounter = 0;
2163 synchronized (knownReplies) {
2164 for (String knownReplyId : knownReplies) {
2165 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2167 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2170 /* save bookmarked posts. */
2171 int bookmarkedPostCounter = 0;
2172 synchronized (bookmarkedPosts) {
2173 for (String bookmarkedPostId : bookmarkedPosts) {
2174 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2177 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2180 configuration.save();
2182 } catch (ConfigurationException ce1) {
2183 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2185 synchronized (configuration) {
2186 storingConfiguration = false;
2192 * Loads the configuration.
2194 @SuppressWarnings("unchecked")
2195 private void loadConfiguration() {
2196 /* create options. */
2197 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2200 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2201 SoneInserter.setInsertionDelay(newValue);
2205 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2206 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2207 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2208 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2209 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2210 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2211 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2212 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2213 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2216 @SuppressWarnings("synthetic-access")
2217 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2218 fcpInterface.setActive(newValue);
2221 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2224 @SuppressWarnings("synthetic-access")
2225 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2226 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2231 loadConfigurationValue("InsertionDelay");
2232 loadConfigurationValue("PostsPerPage");
2233 loadConfigurationValue("ImagesPerPage");
2234 loadConfigurationValue("CharactersPerPost");
2235 loadConfigurationValue("PostCutOffLength");
2236 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2237 loadConfigurationValue("PositiveTrust");
2238 loadConfigurationValue("NegativeTrust");
2239 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2240 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2241 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2243 /* load known Sones. */
2244 int soneCounter = 0;
2246 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2247 if (knownSoneId == null) {
2250 synchronized (knownSones) {
2251 knownSones.add(knownSoneId);
2255 /* load Sone following times. */
2258 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2259 if (soneId == null) {
2262 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2263 Sone followedSone = getSone(soneId);
2264 if (followedSone == null) {
2265 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2267 synchronized (soneFollowingTimes) {
2268 soneFollowingTimes.put(getSone(soneId), time);
2274 /* load known posts. */
2275 int postCounter = 0;
2277 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2278 if (knownPostId == null) {
2281 synchronized (knownPosts) {
2282 knownPosts.add(knownPostId);
2286 /* load known replies. */
2287 int replyCounter = 0;
2289 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2290 if (knownReplyId == null) {
2293 synchronized (knownReplies) {
2294 knownReplies.add(knownReplyId);
2298 /* load bookmarked posts. */
2299 int bookmarkedPostCounter = 0;
2301 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2302 if (bookmarkedPostId == null) {
2305 synchronized (bookmarkedPosts) {
2306 bookmarkedPosts.add(bookmarkedPostId);
2313 * Loads an {@link Integer} configuration value for the option with the
2314 * given name, logging validation failures.
2317 * The name of the option to load
2319 private void loadConfigurationValue(String optionName) {
2321 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2322 } catch (IllegalArgumentException iae1) {
2323 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2328 * Generate a Sone URI from the given URI and latest edition.
2331 * The URI to derive the Sone URI from
2332 * @return The derived URI
2334 private static FreenetURI getSoneUri(String uriString) {
2336 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2338 } catch (MalformedURLException mue1) {
2339 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2345 // INTERFACE IdentityListener
2352 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2353 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2354 if (ownIdentity.hasContext("Sone")) {
2355 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2356 addLocalSone(ownIdentity);
2364 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2365 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2366 trustedIdentities.remove(ownIdentity);
2373 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2374 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2375 trustedIdentities.get(ownIdentity).add(identity);
2376 addRemoteSone(identity);
2383 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2384 soneDownloaders.execute(new Runnable() {
2387 @SuppressWarnings("synthetic-access")
2389 Sone sone = getRemoteSone(identity.getId(), false);
2390 sone.setIdentity(identity);
2391 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2392 soneDownloader.addSone(sone);
2393 soneDownloader.fetchSone(sone);
2402 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2403 trustedIdentities.get(ownIdentity).remove(identity);
2404 boolean foundIdentity = false;
2405 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2406 if (trustedIdentity.getKey().equals(ownIdentity)) {
2409 if (trustedIdentity.getValue().contains(identity)) {
2410 foundIdentity = true;
2413 if (foundIdentity) {
2414 /* some local identity still trusts this identity, don’t remove. */
2417 Sone sone = getSone(identity.getId(), false);
2419 /* TODO - we don’t have the Sone anymore. should this happen? */
2422 synchronized (posts) {
2423 synchronized (knownPosts) {
2424 for (Post post : sone.getPosts()) {
2425 posts.remove(post.getId());
2426 eventBus.post(new PostRemovedEvent(post));
2430 synchronized (replies) {
2431 synchronized (knownReplies) {
2432 for (PostReply reply : sone.getReplies()) {
2433 replies.remove(reply.getId());
2434 eventBus.post(new PostReplyRemovedEvent(reply));
2438 synchronized (sones) {
2439 sones.remove(identity.getId());
2441 eventBus.post(new SoneRemovedEvent(sone));
2445 // INTERFACE UpdateListener
2452 public void updateFound(Version version, long releaseTime, long latestEdition) {
2453 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2457 // INTERFACE ImageInsertListener
2464 public void insertStarted(Sone sone) {
2465 coreListenerManager.fireSoneInserting(sone);
2472 public void insertFinished(Sone sone, long insertDuration) {
2473 coreListenerManager.fireSoneInserted(sone, insertDuration);
2480 public void insertAborted(Sone sone, Throwable cause) {
2481 coreListenerManager.fireSoneInsertAborted(sone, cause);
2485 // SONEINSERTLISTENER METHODS
2492 public void imageInsertStarted(Image image) {
2493 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2494 coreListenerManager.fireImageInsertStarted(image);
2501 public void imageInsertAborted(Image image) {
2502 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2503 coreListenerManager.fireImageInsertAborted(image);
2510 public void imageInsertFinished(Image image, FreenetURI key) {
2511 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2512 image.setKey(key.toString());
2513 deleteTemporaryImage(image.getId());
2514 touchConfiguration();
2515 coreListenerManager.fireImageInsertFinished(image);
2522 public void imageInsertFailed(Image image, Throwable cause) {
2523 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2524 coreListenerManager.fireImageInsertFailed(image, cause);
2528 * Convenience interface for external classes that want to access the core’s
2531 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2533 public static class Preferences {
2535 /** The wrapped options. */
2536 private final Options options;
2539 * Creates a new preferences object wrapped around the given options.
2542 * The options to wrap
2544 public Preferences(Options options) {
2545 this.options = options;
2549 * Returns the insertion delay.
2551 * @return The insertion delay
2553 public int getInsertionDelay() {
2554 return options.getIntegerOption("InsertionDelay").get();
2558 * Validates the given insertion delay.
2560 * @param insertionDelay
2561 * The insertion delay to validate
2562 * @return {@code true} if the given insertion delay was valid,
2563 * {@code false} otherwise
2565 public boolean validateInsertionDelay(Integer insertionDelay) {
2566 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2570 * Sets the insertion delay
2572 * @param insertionDelay
2573 * The new insertion delay, or {@code null} to restore it to
2575 * @return This preferences
2577 public Preferences setInsertionDelay(Integer insertionDelay) {
2578 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2583 * Returns the number of posts to show per page.
2585 * @return The number of posts to show per page
2587 public int getPostsPerPage() {
2588 return options.getIntegerOption("PostsPerPage").get();
2592 * Validates the number of posts per page.
2594 * @param postsPerPage
2595 * The number of posts per page
2596 * @return {@code true} if the number of posts per page was valid,
2597 * {@code false} otherwise
2599 public boolean validatePostsPerPage(Integer postsPerPage) {
2600 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2604 * Sets the number of posts to show per page.
2606 * @param postsPerPage
2607 * The number of posts to show per page
2608 * @return This preferences object
2610 public Preferences setPostsPerPage(Integer postsPerPage) {
2611 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2616 * Returns the number of images to show per page.
2618 * @return The number of images to show per page
2620 public int getImagesPerPage() {
2621 return options.getIntegerOption("ImagesPerPage").get();
2625 * Validates the number of images per page.
2627 * @param imagesPerPage
2628 * The number of images per page
2629 * @return {@code true} if the number of images per page was valid,
2630 * {@code false} otherwise
2632 public boolean validateImagesPerPage(Integer imagesPerPage) {
2633 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2637 * Sets the number of images per page.
2639 * @param imagesPerPage
2640 * The number of images per page
2641 * @return This preferences object
2643 public Preferences setImagesPerPage(Integer imagesPerPage) {
2644 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2649 * Returns the number of characters per post, or <code>-1</code> if the
2650 * posts should not be cut off.
2652 * @return The numbers of characters per post
2654 public int getCharactersPerPost() {
2655 return options.getIntegerOption("CharactersPerPost").get();
2659 * Validates the number of characters per post.
2661 * @param charactersPerPost
2662 * The number of characters per post
2663 * @return {@code true} if the number of characters per post was valid,
2664 * {@code false} otherwise
2666 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2667 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2671 * Sets the number of characters per post.
2673 * @param charactersPerPost
2674 * The number of characters per post, or <code>-1</code> to
2675 * not cut off the posts
2676 * @return This preferences objects
2678 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2679 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2684 * Returns the number of characters the shortened post should have.
2686 * @return The number of characters of the snippet
2688 public int getPostCutOffLength() {
2689 return options.getIntegerOption("PostCutOffLength").get();
2693 * Validates the number of characters after which to cut off the post.
2695 * @param postCutOffLength
2696 * The number of characters of the snippet
2697 * @return {@code true} if the number of characters of the snippet is
2698 * valid, {@code false} otherwise
2700 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2701 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2705 * Sets the number of characters the shortened post should have.
2707 * @param postCutOffLength
2708 * The number of characters of the snippet
2709 * @return This preferences
2711 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2712 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2717 * Returns whether Sone requires full access to be even visible.
2719 * @return {@code true} if Sone requires full access, {@code false}
2722 public boolean isRequireFullAccess() {
2723 return options.getBooleanOption("RequireFullAccess").get();
2727 * Sets whether Sone requires full access to be even visible.
2729 * @param requireFullAccess
2730 * {@code true} if Sone requires full access, {@code false}
2733 public void setRequireFullAccess(Boolean requireFullAccess) {
2734 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2738 * Returns the positive trust.
2740 * @return The positive trust
2742 public int getPositiveTrust() {
2743 return options.getIntegerOption("PositiveTrust").get();
2747 * Validates the positive trust.
2749 * @param positiveTrust
2750 * The positive trust to validate
2751 * @return {@code true} if the positive trust was valid, {@code false}
2754 public boolean validatePositiveTrust(Integer positiveTrust) {
2755 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2759 * Sets the positive trust.
2761 * @param positiveTrust
2762 * The new positive trust, or {@code null} to restore it to
2764 * @return This preferences
2766 public Preferences setPositiveTrust(Integer positiveTrust) {
2767 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2772 * Returns the negative trust.
2774 * @return The negative trust
2776 public int getNegativeTrust() {
2777 return options.getIntegerOption("NegativeTrust").get();
2781 * Validates the negative trust.
2783 * @param negativeTrust
2784 * The negative trust to validate
2785 * @return {@code true} if the negative trust was valid, {@code false}
2788 public boolean validateNegativeTrust(Integer negativeTrust) {
2789 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2793 * Sets the negative trust.
2795 * @param negativeTrust
2796 * The negative trust, or {@code null} to restore it to the
2798 * @return The preferences
2800 public Preferences setNegativeTrust(Integer negativeTrust) {
2801 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2806 * Returns the trust comment. This is the comment that is set in the web
2807 * of trust when a trust value is assigned to an identity.
2809 * @return The trust comment
2811 public String getTrustComment() {
2812 return options.getStringOption("TrustComment").get();
2816 * Sets the trust comment.
2818 * @param trustComment
2819 * The trust comment, or {@code null} to restore it to the
2821 * @return This preferences
2823 public Preferences setTrustComment(String trustComment) {
2824 options.getStringOption("TrustComment").set(trustComment);
2829 * Returns whether the {@link FcpInterface FCP interface} is currently
2832 * @see FcpInterface#setActive(boolean)
2833 * @return {@code true} if the FCP interface is currently active,
2834 * {@code false} otherwise
2836 public boolean isFcpInterfaceActive() {
2837 return options.getBooleanOption("ActivateFcpInterface").get();
2841 * Sets whether the {@link FcpInterface FCP interface} is currently
2844 * @see FcpInterface#setActive(boolean)
2845 * @param fcpInterfaceActive
2846 * {@code true} to activate the FCP interface, {@code false}
2847 * to deactivate the FCP interface
2848 * @return This preferences object
2850 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2851 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2856 * Returns the action level for which full access to the FCP interface
2859 * @return The action level for which full access to the FCP interface
2862 public FullAccessRequired getFcpFullAccessRequired() {
2863 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2867 * Sets the action level for which full access to the FCP interface is
2870 * @param fcpFullAccessRequired
2872 * @return This preferences
2874 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2875 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);