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.data.Album;
49 import net.pterodactylus.sone.data.Client;
50 import net.pterodactylus.sone.data.Image;
51 import net.pterodactylus.sone.data.Post;
52 import net.pterodactylus.sone.data.PostReply;
53 import net.pterodactylus.sone.data.Profile;
54 import net.pterodactylus.sone.data.Profile.Field;
55 import net.pterodactylus.sone.data.Reply;
56 import net.pterodactylus.sone.data.Sone;
57 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
58 import net.pterodactylus.sone.data.Sone.SoneStatus;
59 import net.pterodactylus.sone.data.TemporaryImage;
60 import net.pterodactylus.sone.data.impl.PostImpl;
61 import net.pterodactylus.sone.fcp.FcpInterface;
62 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
63 import net.pterodactylus.sone.freenet.wot.Identity;
64 import net.pterodactylus.sone.freenet.wot.IdentityListener;
65 import net.pterodactylus.sone.freenet.wot.IdentityManager;
66 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
67 import net.pterodactylus.sone.main.SonePlugin;
68 import net.pterodactylus.util.config.Configuration;
69 import net.pterodactylus.util.config.ConfigurationException;
70 import net.pterodactylus.util.logging.Logging;
71 import net.pterodactylus.util.number.Numbers;
72 import net.pterodactylus.util.service.AbstractService;
73 import net.pterodactylus.util.thread.NamedThreadFactory;
74 import net.pterodactylus.util.thread.Ticker;
75 import net.pterodactylus.util.validation.EqualityValidator;
76 import net.pterodactylus.util.validation.IntegerRangeValidator;
77 import net.pterodactylus.util.validation.OrValidator;
78 import net.pterodactylus.util.validation.Validation;
79 import net.pterodactylus.util.version.Version;
81 import com.google.common.base.Predicate;
82 import com.google.common.collect.Collections2;
83 import com.google.common.eventbus.EventBus;
84 import com.google.inject.Inject;
86 import freenet.keys.FreenetURI;
91 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
93 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
96 private static final Logger logger = Logging.getLogger(Core.class);
98 /** The start time. */
99 private final long startupTime = System.currentTimeMillis();
102 private final Options options = new Options();
104 /** The preferences. */
105 private final Preferences preferences = new Preferences(options);
107 /** The core listener manager. */
108 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
110 /** The event bus. */
111 private final EventBus eventBus;
113 /** The configuration. */
114 private Configuration configuration;
116 /** Whether we’re currently saving the configuration. */
117 private boolean storingConfiguration = false;
119 /** The identity manager. */
120 private final IdentityManager identityManager;
122 /** Interface to freenet. */
123 private final FreenetInterface freenetInterface;
125 /** The Sone downloader. */
126 private final SoneDownloader soneDownloader;
128 /** The image inserter. */
129 private final ImageInserter imageInserter;
131 /** Sone downloader thread-pool. */
132 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
134 /** The update checker. */
135 private final UpdateChecker updateChecker;
137 /** The trust updater. */
138 private final WebOfTrustUpdater webOfTrustUpdater;
140 /** The FCP interface. */
141 private volatile FcpInterface fcpInterface;
143 /** The times Sones were followed. */
144 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
146 /** Locked local Sones. */
147 /* synchronize on itself. */
148 private final Set<Sone> lockedSones = new HashSet<Sone>();
150 /** Sone inserters. */
151 /* synchronize access on this on sones. */
152 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
154 /** Sone rescuers. */
155 /* synchronize access on this on sones. */
156 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
159 /* synchronize access on this on itself. */
160 private final Map<String, Sone> sones = new HashMap<String, Sone>();
162 /** All known Sones. */
163 private final Set<String> knownSones = new HashSet<String>();
166 private final Map<String, Post> posts = new HashMap<String, Post>();
168 /** All known posts. */
169 private final Set<String> knownPosts = new HashSet<String>();
172 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
174 /** All known replies. */
175 private final Set<String> knownReplies = new HashSet<String>();
177 /** All bookmarked posts. */
178 /* synchronize access on itself. */
179 private final Set<String> bookmarkedPosts = new HashSet<String>();
181 /** Trusted identities, sorted by own identities. */
182 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
184 /** All known albums. */
185 private final Map<String, Album> albums = new HashMap<String, Album>();
187 /** All known images. */
188 private final Map<String, Image> images = new HashMap<String, Image>();
190 /** All temporary images. */
191 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
193 /** Ticker for threads that mark own elements as known. */
194 private final Ticker localElementTicker = new Ticker();
196 /** The time the configuration was last touched. */
197 private volatile long lastConfigurationUpdate;
200 * Creates a new core.
202 * @param configuration
203 * The configuration of the core
204 * @param freenetInterface
205 * The freenet interface
206 * @param identityManager
207 * The identity manager
208 * @param webOfTrustUpdater
209 * The WebOfTrust updater
214 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
216 this.configuration = configuration;
217 this.freenetInterface = freenetInterface;
218 this.identityManager = identityManager;
219 this.soneDownloader = new SoneDownloader(this, freenetInterface);
220 this.imageInserter = new ImageInserter(this, freenetInterface);
221 this.updateChecker = new UpdateChecker(freenetInterface);
222 this.webOfTrustUpdater = webOfTrustUpdater;
223 this.eventBus = eventBus;
227 // LISTENER MANAGEMENT
231 * Adds a new core listener.
233 * @param coreListener
234 * The listener to add
236 public void addCoreListener(CoreListener coreListener) {
237 coreListenerManager.addListener(coreListener);
241 * Removes a core listener.
243 * @param coreListener
244 * The listener to remove
246 public void removeCoreListener(CoreListener coreListener) {
247 coreListenerManager.removeListener(coreListener);
255 * Returns the time Sone was started.
257 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
259 public long getStartupTime() {
264 * Sets the configuration to use. This will automatically save the current
265 * configuration to the given configuration.
267 * @param configuration
268 * The new configuration to use
270 public void setConfiguration(Configuration configuration) {
271 this.configuration = configuration;
272 touchConfiguration();
276 * Returns the options used by the core.
278 * @return The options of the core
280 public Preferences getPreferences() {
285 * Returns the identity manager used by the core.
287 * @return The identity manager
289 public IdentityManager getIdentityManager() {
290 return identityManager;
294 * Returns the update checker.
296 * @return The update checker
298 public UpdateChecker getUpdateChecker() {
299 return updateChecker;
303 * Sets the FCP interface to use.
305 * @param fcpInterface
306 * The FCP interface to use
308 public void setFcpInterface(FcpInterface fcpInterface) {
309 this.fcpInterface = fcpInterface;
313 * Returns the Sone rescuer for the given local Sone.
316 * The local Sone to get the rescuer for
317 * @return The Sone rescuer for the given Sone
319 public SoneRescuer getSoneRescuer(Sone sone) {
320 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
321 synchronized (sones) {
322 SoneRescuer soneRescuer = soneRescuers.get(sone);
323 if (soneRescuer == null) {
324 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
325 soneRescuers.put(sone, soneRescuer);
333 * Returns whether the given Sone is currently locked.
337 * @return {@code true} if the Sone is locked, {@code false} if it is not
339 public boolean isLocked(Sone sone) {
340 synchronized (lockedSones) {
341 return lockedSones.contains(sone);
346 * Returns all Sones, remote and local.
350 public Set<Sone> getSones() {
351 return new HashSet<Sone>(sones.values());
355 * Returns the Sone with the given ID, regardless whether it’s local or
359 * The ID of the Sone to get
360 * @return The Sone with the given ID, or {@code null} if there is no such
363 public Sone getSone(String id) {
364 return getSone(id, true);
368 * Returns the Sone with the given ID, regardless whether it’s local or
372 * The ID of the Sone to get
374 * {@code true} to create a new Sone if none exists,
375 * {@code false} to return {@code null} if a Sone with the given
377 * @return The Sone with the given ID, or {@code null} if there is no such
381 public Sone getSone(String id, boolean create) {
382 synchronized (sones) {
383 if (!sones.containsKey(id)) {
384 Sone sone = new Sone(id, false);
387 return sones.get(id);
392 * Checks whether the core knows a Sone with the given ID.
396 * @return {@code true} if there is a Sone with the given ID, {@code false}
399 public boolean hasSone(String id) {
400 synchronized (sones) {
401 return sones.containsKey(id);
406 * Returns all local Sones.
408 * @return All local Sones
410 public Collection<Sone> getLocalSones() {
411 synchronized (sones) {
412 return Collections2.filter(sones.values(), new Predicate<Sone>() {
415 public boolean apply(Sone sone) {
416 return sone.isLocal();
423 * Returns the local Sone with the given ID, optionally creating a new Sone.
428 * {@code true} to create a new Sone if none exists,
429 * {@code false} to return null if none exists
430 * @return The Sone with the given ID, or {@code null}
432 public Sone getLocalSone(String id, boolean create) {
433 synchronized (sones) {
434 Sone sone = sones.get(id);
435 if ((sone == null) && create) {
436 sone = new Sone(id, true);
439 if ((sone != null) && !sone.isLocal()) {
440 sone = new Sone(id, true);
448 * Returns all remote Sones.
450 * @return All remote Sones
452 public Collection<Sone> getRemoteSones() {
453 synchronized (sones) {
454 return Collections2.filter(sones.values(), new Predicate<Sone>() {
457 public boolean apply(Sone sone) {
458 return !sone.isLocal();
465 * Returns the remote Sone with the given ID.
468 * The ID of the remote Sone to get
470 * {@code true} to always create a Sone, {@code false} to return
471 * {@code null} if no Sone with the given ID exists
472 * @return The Sone with the given ID
474 public Sone getRemoteSone(String id, boolean create) {
475 synchronized (sones) {
476 Sone sone = sones.get(id);
477 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
478 sone = new Sone(id, false);
486 * Returns whether the given Sone has been modified.
489 * The Sone to check for modifications
490 * @return {@code true} if a modification has been detected in the Sone,
491 * {@code false} otherwise
493 public boolean isModifiedSone(Sone sone) {
494 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
498 * Returns the time when the given was first followed by any local Sone.
501 * The Sone to get the time for
502 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
503 * been followed, or {@link Long#MAX_VALUE}
505 public long getSoneFollowingTime(Sone sone) {
506 synchronized (soneFollowingTimes) {
507 if (soneFollowingTimes.containsKey(sone)) {
508 return soneFollowingTimes.get(sone);
510 return Long.MAX_VALUE;
515 * Returns whether the target Sone is trusted by the origin Sone.
521 * @return {@code true} if the target Sone is trusted by the origin Sone
523 public boolean isSoneTrusted(Sone origin, Sone target) {
524 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
525 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
529 * Returns the post with the given ID.
532 * The ID of the post to get
533 * @return The post with the given ID, or a new post with the given ID
535 public Post getPost(String postId) {
536 return getPost(postId, true);
540 * Returns the post with the given ID, optionally creating a new post.
543 * The ID of the post to get
545 * {@code true} it create a new post if no post with the given ID
546 * exists, {@code false} to return {@code null}
547 * @return The post, or {@code null} if there is no such post
550 public Post getPost(String postId, boolean create) {
551 synchronized (posts) {
552 Post post = posts.get(postId);
553 if ((post == null) && create) {
554 post = new PostImpl(postId);
555 posts.put(postId, post);
562 * Returns all posts that have the given Sone as recipient.
564 * @see Post#getRecipient()
566 * The recipient of the posts
567 * @return All posts that have the given Sone as recipient
569 public Set<Post> getDirectedPosts(Sone recipient) {
570 Validation.begin().isNotNull("Recipient", recipient).check();
571 Set<Post> directedPosts = new HashSet<Post>();
572 synchronized (posts) {
573 for (Post post : posts.values()) {
574 if (recipient.equals(post.getRecipient())) {
575 directedPosts.add(post);
579 return directedPosts;
583 * Returns the reply with the given ID. If there is no reply with the given
584 * ID yet, a new one is created, unless {@code create} is false in which
585 * case {@code null} is returned.
588 * The ID of the reply to get
590 * {@code true} to always return a {@link Reply}, {@code false}
591 * to return {@code null} if no reply can be found
592 * @return The reply, or {@code null} if there is no such reply
594 public PostReply getPostReply(String replyId, boolean create) {
595 synchronized (replies) {
596 PostReply reply = replies.get(replyId);
597 if (create && (reply == null)) {
598 reply = new PostReply(replyId);
599 replies.put(replyId, reply);
606 * Returns all replies for the given post, order ascending by time.
609 * The post to get all replies for
610 * @return All replies for the given post
612 public List<PostReply> getReplies(Post post) {
613 Set<Sone> sones = getSones();
614 List<PostReply> replies = new ArrayList<PostReply>();
615 for (Sone sone : sones) {
616 for (PostReply reply : sone.getReplies()) {
617 if (reply.getPost().equals(post)) {
622 Collections.sort(replies, Reply.TIME_COMPARATOR);
627 * Returns all Sones that have liked the given post.
630 * The post to get the liking Sones for
631 * @return The Sones that like the given post
633 public Set<Sone> getLikes(Post post) {
634 Set<Sone> sones = new HashSet<Sone>();
635 for (Sone sone : getSones()) {
636 if (sone.getLikedPostIds().contains(post.getId())) {
644 * Returns all Sones that have liked the given reply.
647 * The reply to get the liking Sones for
648 * @return The Sones that like the given reply
650 public Set<Sone> getLikes(PostReply reply) {
651 Set<Sone> sones = new HashSet<Sone>();
652 for (Sone sone : getSones()) {
653 if (sone.getLikedReplyIds().contains(reply.getId())) {
661 * Returns whether the given post is bookmarked.
665 * @return {@code true} if the given post is bookmarked, {@code false}
668 public boolean isBookmarked(Post post) {
669 return isPostBookmarked(post.getId());
673 * Returns whether the post with the given ID is bookmarked.
676 * The ID of the post to check
677 * @return {@code true} if the post with the given ID is bookmarked,
678 * {@code false} otherwise
680 public boolean isPostBookmarked(String id) {
681 synchronized (bookmarkedPosts) {
682 return bookmarkedPosts.contains(id);
687 * Returns all currently known bookmarked posts.
689 * @return All bookmarked posts
691 public Set<Post> getBookmarkedPosts() {
692 Set<Post> posts = new HashSet<Post>();
693 synchronized (bookmarkedPosts) {
694 for (String bookmarkedPostId : bookmarkedPosts) {
695 Post post = getPost(bookmarkedPostId, false);
705 * Returns the album with the given ID, creating a new album if no album
706 * with the given ID can be found.
709 * The ID of the album
710 * @return The album with the given ID
712 public Album getAlbum(String albumId) {
713 return getAlbum(albumId, true);
717 * Returns the album with the given ID, optionally creating a new album if
718 * an album with the given ID can not be found.
721 * The ID of the album
723 * {@code true} to create a new album if none exists for the
725 * @return The album with the given ID, or {@code null} if no album with the
726 * given ID exists and {@code create} is {@code false}
728 public Album getAlbum(String albumId, boolean create) {
729 synchronized (albums) {
730 Album album = albums.get(albumId);
731 if (create && (album == null)) {
732 album = new Album(albumId);
733 albums.put(albumId, album);
740 * Returns the image with the given ID, creating it if necessary.
743 * The ID of the image
744 * @return The image with the given ID
746 public Image getImage(String imageId) {
747 return getImage(imageId, true);
751 * Returns the image with the given ID, optionally creating it if it does
755 * The ID of the image
757 * {@code true} to create an image if none exists with the given
759 * @return The image with the given ID, or {@code null} if none exists and
762 public Image getImage(String imageId, boolean create) {
763 synchronized (images) {
764 Image image = images.get(imageId);
765 if (create && (image == null)) {
766 image = new Image(imageId);
767 images.put(imageId, image);
774 * Returns the temporary image with the given ID.
777 * The ID of the temporary image
778 * @return The temporary image, or {@code null} if there is no temporary
779 * image with the given ID
781 public TemporaryImage getTemporaryImage(String imageId) {
782 synchronized (temporaryImages) {
783 return temporaryImages.get(imageId);
792 * Locks the given Sone. A locked Sone will not be inserted by
793 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
799 public void lockSone(Sone sone) {
800 synchronized (lockedSones) {
801 if (lockedSones.add(sone)) {
802 eventBus.post(new SoneLockedEvent(sone));
808 * Unlocks the given Sone.
810 * @see #lockSone(Sone)
814 public void unlockSone(Sone sone) {
815 synchronized (lockedSones) {
816 if (lockedSones.remove(sone)) {
817 coreListenerManager.fireSoneUnlocked(sone);
823 * Adds a local Sone from the given own identity.
826 * The own identity to create a Sone from
827 * @return The added (or already existing) Sone
829 public Sone addLocalSone(OwnIdentity ownIdentity) {
830 if (ownIdentity == null) {
831 logger.log(Level.WARNING, "Given OwnIdentity is null!");
834 synchronized (sones) {
837 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
838 } catch (MalformedURLException mue1) {
839 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
842 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
843 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
845 /* TODO - load posts ’n stuff */
846 sones.put(ownIdentity.getId(), sone);
847 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
848 soneInserter.addSoneInsertListener(this);
849 soneInserters.put(sone, soneInserter);
850 sone.setStatus(SoneStatus.idle);
852 soneInserter.start();
858 * Creates a new Sone for the given own identity.
861 * The own identity to create a Sone for
862 * @return The created Sone
864 public Sone createSone(OwnIdentity ownIdentity) {
865 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
866 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
869 Sone sone = addLocalSone(ownIdentity);
870 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
871 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
872 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
873 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
874 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
875 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
877 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
878 touchConfiguration();
883 * Adds the Sone of the given identity.
886 * The identity whose Sone to add
887 * @return The added or already existing Sone
889 public Sone addRemoteSone(Identity identity) {
890 if (identity == null) {
891 logger.log(Level.WARNING, "Given Identity is null!");
894 synchronized (sones) {
895 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
896 boolean newSone = sone.getRequestUri() == null;
897 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
898 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
900 synchronized (knownSones) {
901 newSone = !knownSones.contains(sone.getId());
903 sone.setKnown(!newSone);
905 eventBus.post(new NewSoneFoundEvent(sone));
906 for (Sone localSone : getLocalSones()) {
907 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
908 followSone(localSone, sone);
913 soneDownloader.addSone(sone);
914 soneDownloaders.execute(new Runnable() {
917 @SuppressWarnings("synthetic-access")
919 soneDownloader.fetchSone(sone, sone.getRequestUri());
928 * Lets the given local Sone follow the Sone with the given ID.
931 * The local Sone that should follow another Sone
933 * The ID of the Sone to follow
935 public void followSone(Sone sone, String soneId) {
936 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
937 Sone followedSone = getSone(soneId, true);
938 if (followedSone == null) {
939 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
942 followSone(sone, getSone(soneId));
946 * Lets the given local Sone follow the other given Sone. If the given Sone
947 * was not followed by any local Sone before, this will mark all elements of
948 * the followed Sone as read that have been created before the current
952 * The local Sone that should follow the other Sone
953 * @param followedSone
954 * The Sone that should be followed
956 public void followSone(Sone sone, Sone followedSone) {
957 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
958 sone.addFriend(followedSone.getId());
959 synchronized (soneFollowingTimes) {
960 if (!soneFollowingTimes.containsKey(followedSone)) {
961 long now = System.currentTimeMillis();
962 soneFollowingTimes.put(followedSone, now);
963 for (Post post : followedSone.getPosts()) {
964 if (post.getTime() < now) {
968 for (PostReply reply : followedSone.getReplies()) {
969 if (reply.getTime() < now) {
970 markReplyKnown(reply);
975 touchConfiguration();
979 * Lets the given local Sone unfollow the Sone with the given ID.
982 * The local Sone that should unfollow another Sone
984 * The ID of the Sone being unfollowed
986 public void unfollowSone(Sone sone, String soneId) {
987 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
988 unfollowSone(sone, getSone(soneId, false));
992 * Lets the given local Sone unfollow the other given Sone. If the given
993 * local Sone is the last local Sone that followed the given Sone, its
994 * following time will be removed.
997 * The local Sone that should unfollow another Sone
998 * @param unfollowedSone
999 * The Sone being unfollowed
1001 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1002 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1003 sone.removeFriend(unfollowedSone.getId());
1004 boolean unfollowedSoneStillFollowed = false;
1005 for (Sone localSone : getLocalSones()) {
1006 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1008 if (!unfollowedSoneStillFollowed) {
1009 synchronized (soneFollowingTimes) {
1010 soneFollowingTimes.remove(unfollowedSone);
1013 touchConfiguration();
1017 * Sets the trust value of the given origin Sone for the target Sone.
1024 * The trust value (from {@code -100} to {@code 100})
1026 public void setTrust(Sone origin, Sone target, int trustValue) {
1027 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();
1028 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1032 * Removes any trust assignment for the given target Sone.
1039 public void removeTrust(Sone origin, Sone target) {
1040 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1041 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1045 * Assigns the configured positive trust value for the given target.
1052 public void trustSone(Sone origin, Sone target) {
1053 setTrust(origin, target, preferences.getPositiveTrust());
1057 * Assigns the configured negative trust value for the given target.
1064 public void distrustSone(Sone origin, Sone target) {
1065 setTrust(origin, target, preferences.getNegativeTrust());
1069 * Removes the trust assignment for the given target.
1076 public void untrustSone(Sone origin, Sone target) {
1077 removeTrust(origin, target);
1081 * Updates the stored Sone with the given Sone.
1086 public void updateSone(Sone sone) {
1087 updateSone(sone, false);
1091 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1092 * {@code true}, an older Sone than the current Sone can be given to restore
1096 * The Sone to update
1097 * @param soneRescueMode
1098 * {@code true} if the stored Sone should be updated regardless
1099 * of the age of the given Sone
1101 public void updateSone(Sone sone, boolean soneRescueMode) {
1102 if (hasSone(sone.getId())) {
1103 Sone storedSone = getSone(sone.getId());
1104 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1105 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1108 synchronized (posts) {
1109 if (!soneRescueMode) {
1110 for (Post post : storedSone.getPosts()) {
1111 posts.remove(post.getId());
1112 if (!sone.getPosts().contains(post)) {
1113 eventBus.post(new PostRemovedEvent(post));
1117 List<Post> storedPosts = storedSone.getPosts();
1118 synchronized (knownPosts) {
1119 for (Post post : sone.getPosts()) {
1120 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1121 if (!storedPosts.contains(post)) {
1122 if (post.getTime() < getSoneFollowingTime(sone)) {
1123 knownPosts.add(post.getId());
1124 post.setKnown(true);
1125 } else if (!knownPosts.contains(post.getId())) {
1126 eventBus.post(new NewPostFoundEvent(post));
1129 posts.put(post.getId(), post);
1133 synchronized (replies) {
1134 if (!soneRescueMode) {
1135 for (PostReply reply : storedSone.getReplies()) {
1136 replies.remove(reply.getId());
1137 if (!sone.getReplies().contains(reply)) {
1138 eventBus.post(new PostReplyRemovedEvent(reply));
1142 Set<PostReply> storedReplies = storedSone.getReplies();
1143 synchronized (knownReplies) {
1144 for (PostReply reply : sone.getReplies()) {
1145 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1146 if (!storedReplies.contains(reply)) {
1147 if (reply.getTime() < getSoneFollowingTime(sone)) {
1148 knownReplies.add(reply.getId());
1149 reply.setKnown(true);
1150 } else if (!knownReplies.contains(reply.getId())) {
1151 eventBus.post(new NewPostReplyFoundEvent(reply));
1154 replies.put(reply.getId(), reply);
1158 synchronized (albums) {
1159 synchronized (images) {
1160 for (Album album : storedSone.getAlbums()) {
1161 albums.remove(album.getId());
1162 for (Image image : album.getImages()) {
1163 images.remove(image.getId());
1166 for (Album album : sone.getAlbums()) {
1167 albums.put(album.getId(), album);
1168 for (Image image : album.getImages()) {
1169 images.put(image.getId(), image);
1174 synchronized (storedSone) {
1175 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1176 storedSone.setTime(sone.getTime());
1178 storedSone.setClient(sone.getClient());
1179 storedSone.setProfile(sone.getProfile());
1180 if (soneRescueMode) {
1181 for (Post post : sone.getPosts()) {
1182 storedSone.addPost(post);
1184 for (PostReply reply : sone.getReplies()) {
1185 storedSone.addReply(reply);
1187 for (String likedPostId : sone.getLikedPostIds()) {
1188 storedSone.addLikedPostId(likedPostId);
1190 for (String likedReplyId : sone.getLikedReplyIds()) {
1191 storedSone.addLikedReplyId(likedReplyId);
1193 for (Album album : sone.getAlbums()) {
1194 storedSone.addAlbum(album);
1197 storedSone.setPosts(sone.getPosts());
1198 storedSone.setReplies(sone.getReplies());
1199 storedSone.setLikePostIds(sone.getLikedPostIds());
1200 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1201 storedSone.setAlbums(sone.getAlbums());
1203 storedSone.setLatestEdition(sone.getLatestEdition());
1209 * Deletes the given Sone. This will remove the Sone from the
1210 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1211 * remove the context from its identity.
1214 * The Sone to delete
1216 public void deleteSone(Sone sone) {
1217 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1218 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1221 synchronized (sones) {
1222 if (!getLocalSones().contains(sone)) {
1223 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1226 sones.remove(sone.getId());
1227 SoneInserter soneInserter = soneInserters.remove(sone);
1228 soneInserter.removeSoneInsertListener(this);
1229 soneInserter.stop();
1231 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1232 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1234 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1235 } catch (ConfigurationException ce1) {
1236 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1241 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1242 * known} before, a {@link MarkSoneKnownEvent} is fired.
1245 * The Sone to mark as known
1247 public void markSoneKnown(Sone sone) {
1248 if (!sone.isKnown()) {
1249 sone.setKnown(true);
1250 synchronized (knownSones) {
1251 knownSones.add(sone.getId());
1253 eventBus.post(new MarkSoneKnownEvent(sone));
1254 touchConfiguration();
1259 * Loads and updates the given Sone from the configuration. If any error is
1260 * encountered, loading is aborted and the given Sone is not changed.
1263 * The Sone to load and update
1265 public void loadSone(Sone sone) {
1266 if (!sone.isLocal()) {
1267 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1271 /* initialize options. */
1272 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1273 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1274 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1275 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1276 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1277 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1280 String sonePrefix = "Sone/" + sone.getId();
1281 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1282 if (soneTime == null) {
1283 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1286 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1289 Profile profile = new Profile(sone);
1290 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1291 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1292 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1293 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1294 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1295 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1297 /* load profile fields. */
1299 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1300 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1301 if (fieldName == null) {
1304 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1305 profile.addField(fieldName).setValue(fieldValue);
1309 Set<Post> posts = new HashSet<Post>();
1311 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1312 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1313 if (postId == null) {
1316 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1317 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1318 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1319 if ((postTime == 0) || (postText == null)) {
1320 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1323 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1324 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1325 post.setRecipient(getSone(postRecipientId));
1331 Set<PostReply> replies = new HashSet<PostReply>();
1333 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1334 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1335 if (replyId == null) {
1338 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1339 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1340 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1341 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1342 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1345 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1348 /* load post likes. */
1349 Set<String> likedPostIds = new HashSet<String>();
1351 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1352 if (likedPostId == null) {
1355 likedPostIds.add(likedPostId);
1358 /* load reply likes. */
1359 Set<String> likedReplyIds = new HashSet<String>();
1361 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1362 if (likedReplyId == null) {
1365 likedReplyIds.add(likedReplyId);
1369 Set<String> friends = new HashSet<String>();
1371 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1372 if (friendId == null) {
1375 friends.add(friendId);
1379 List<Album> topLevelAlbums = new ArrayList<Album>();
1380 int albumCounter = 0;
1382 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1383 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1384 if (albumId == null) {
1387 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1388 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1389 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1390 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1391 if ((albumTitle == null) || (albumDescription == null)) {
1392 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1395 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1396 if (albumParentId != null) {
1397 Album parentAlbum = getAlbum(albumParentId, false);
1398 if (parentAlbum == null) {
1399 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1402 parentAlbum.addAlbum(album);
1404 if (!topLevelAlbums.contains(album)) {
1405 topLevelAlbums.add(album);
1411 int imageCounter = 0;
1413 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1414 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1415 if (imageId == null) {
1418 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1419 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1420 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1421 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1422 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1423 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1424 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1425 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1426 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1429 Album album = getAlbum(albumId, false);
1430 if (album == null) {
1431 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1434 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1435 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1436 album.addImage(image);
1440 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1441 if (avatarId != null) {
1442 profile.setAvatar(getImage(avatarId, false));
1446 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1447 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1448 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1449 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1450 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1451 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1453 /* if we’re still here, Sone was loaded successfully. */
1454 synchronized (sone) {
1455 sone.setTime(soneTime);
1456 sone.setProfile(profile);
1457 sone.setPosts(posts);
1458 sone.setReplies(replies);
1459 sone.setLikePostIds(likedPostIds);
1460 sone.setLikeReplyIds(likedReplyIds);
1461 for (String friendId : friends) {
1462 followSone(sone, friendId);
1464 sone.setAlbums(topLevelAlbums);
1465 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1467 synchronized (knownSones) {
1468 for (String friend : friends) {
1469 knownSones.add(friend);
1472 synchronized (knownPosts) {
1473 for (Post post : posts) {
1474 knownPosts.add(post.getId());
1477 synchronized (knownReplies) {
1478 for (PostReply reply : replies) {
1479 knownReplies.add(reply.getId());
1485 * Creates a new post.
1488 * The Sone that creates the post
1490 * The text of the post
1491 * @return The created post
1493 public Post createPost(Sone sone, String text) {
1494 return createPost(sone, System.currentTimeMillis(), text);
1498 * Creates a new post.
1501 * The Sone that creates the post
1503 * The time of the post
1505 * The text of the post
1506 * @return The created post
1508 public Post createPost(Sone sone, long time, String text) {
1509 return createPost(sone, null, time, text);
1513 * Creates a new post.
1516 * The Sone that creates the post
1518 * The recipient Sone, or {@code null} if this post does not have
1521 * The text of the post
1522 * @return The created post
1524 public Post createPost(Sone sone, Sone recipient, String text) {
1525 return createPost(sone, recipient, System.currentTimeMillis(), text);
1529 * Creates a new post.
1532 * The Sone that creates the post
1534 * The recipient Sone, or {@code null} if this post does not have
1537 * The time of the post
1539 * The text of the post
1540 * @return The created post
1542 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1543 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1544 if (!sone.isLocal()) {
1545 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1548 final Post post = new PostImpl(sone, time, text);
1549 if (recipient != null) {
1550 post.setRecipient(recipient);
1552 synchronized (posts) {
1553 posts.put(post.getId(), post);
1555 eventBus.post(new NewPostFoundEvent(post));
1557 touchConfiguration();
1558 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1565 markPostKnown(post);
1567 }, "Mark " + post + " read.");
1572 * Deletes the given post.
1575 * The post to delete
1577 public void deletePost(Post post) {
1578 if (!post.getSone().isLocal()) {
1579 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1582 post.getSone().removePost(post);
1583 synchronized (posts) {
1584 posts.remove(post.getId());
1586 eventBus.post(new PostRemovedEvent(post));
1587 markPostKnown(post);
1588 touchConfiguration();
1592 * Marks the given post as known, if it is currently not a known post
1593 * (according to {@link Post#isKnown()}).
1596 * The post to mark as known
1598 public void markPostKnown(Post post) {
1599 post.setKnown(true);
1600 synchronized (knownPosts) {
1601 eventBus.post(new MarkPostKnownEvent(post));
1602 if (knownPosts.add(post.getId())) {
1603 touchConfiguration();
1606 for (PostReply reply : getReplies(post)) {
1607 markReplyKnown(reply);
1612 * Bookmarks the given post.
1615 * The post to bookmark
1617 public void bookmark(Post post) {
1618 bookmarkPost(post.getId());
1622 * Bookmarks the post with the given ID.
1625 * The ID of the post to bookmark
1627 public void bookmarkPost(String id) {
1628 synchronized (bookmarkedPosts) {
1629 bookmarkedPosts.add(id);
1634 * Removes the given post from the bookmarks.
1637 * The post to unbookmark
1639 public void unbookmark(Post post) {
1640 unbookmarkPost(post.getId());
1644 * Removes the post with the given ID from the bookmarks.
1647 * The ID of the post to unbookmark
1649 public void unbookmarkPost(String id) {
1650 synchronized (bookmarkedPosts) {
1651 bookmarkedPosts.remove(id);
1656 * Creates a new reply.
1659 * The Sone that creates the reply
1661 * The post that this reply refers to
1663 * The text of the reply
1664 * @return The created reply
1666 public PostReply createReply(Sone sone, Post post, String text) {
1667 return createReply(sone, post, System.currentTimeMillis(), text);
1671 * Creates a new reply.
1674 * The Sone that creates the reply
1676 * The post that this reply refers to
1678 * The time of the reply
1680 * The text of the reply
1681 * @return The created reply
1683 public PostReply createReply(Sone sone, Post post, long time, String text) {
1684 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1685 if (!sone.isLocal()) {
1686 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1689 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1690 synchronized (replies) {
1691 replies.put(reply.getId(), reply);
1693 synchronized (knownReplies) {
1694 eventBus.post(new NewPostReplyFoundEvent(reply));
1696 sone.addReply(reply);
1697 touchConfiguration();
1698 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1705 markReplyKnown(reply);
1707 }, "Mark " + reply + " read.");
1712 * Deletes the given reply.
1715 * The reply to delete
1717 public void deleteReply(PostReply reply) {
1718 Sone sone = reply.getSone();
1719 if (!sone.isLocal()) {
1720 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1723 synchronized (replies) {
1724 replies.remove(reply.getId());
1726 synchronized (knownReplies) {
1727 markReplyKnown(reply);
1728 knownReplies.remove(reply.getId());
1730 sone.removeReply(reply);
1731 touchConfiguration();
1735 * Marks the given reply as known, if it is currently not a known reply
1736 * (according to {@link Reply#isKnown()}).
1739 * The reply to mark as known
1741 public void markReplyKnown(PostReply reply) {
1742 reply.setKnown(true);
1743 synchronized (knownReplies) {
1744 eventBus.post(new MarkPostReplyKnownEvent(reply));
1745 if (knownReplies.add(reply.getId())) {
1746 touchConfiguration();
1752 * Creates a new top-level album for the given Sone.
1755 * The Sone to create the album for
1756 * @return The new album
1758 public Album createAlbum(Sone sone) {
1759 return createAlbum(sone, null);
1763 * Creates a new album for the given Sone.
1766 * The Sone to create the album for
1768 * The parent of the album (may be {@code null} to create a
1770 * @return The new album
1772 public Album createAlbum(Sone sone, Album parent) {
1773 Album album = new Album();
1774 synchronized (albums) {
1775 albums.put(album.getId(), album);
1777 album.setSone(sone);
1778 if (parent != null) {
1779 parent.addAlbum(album);
1781 sone.addAlbum(album);
1787 * Deletes the given album. The owner of the album has to be a local Sone,
1788 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1791 * The album to remove
1793 public void deleteAlbum(Album album) {
1794 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1795 if (!album.isEmpty()) {
1798 if (album.getParent() == null) {
1799 album.getSone().removeAlbum(album);
1801 album.getParent().removeAlbum(album);
1803 synchronized (albums) {
1804 albums.remove(album.getId());
1806 touchConfiguration();
1810 * Creates a new image.
1813 * The Sone creating the image
1815 * The album the image will be inserted into
1816 * @param temporaryImage
1817 * The temporary image to create the image from
1818 * @return The newly created image
1820 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1821 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();
1822 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1823 album.addImage(image);
1824 synchronized (images) {
1825 images.put(image.getId(), image);
1827 imageInserter.insertImage(temporaryImage, image);
1832 * Deletes the given image. This method will also delete a matching
1835 * @see #deleteTemporaryImage(TemporaryImage)
1837 * The image to delete
1839 public void deleteImage(Image image) {
1840 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1841 deleteTemporaryImage(image.getId());
1842 image.getAlbum().removeImage(image);
1843 synchronized (images) {
1844 images.remove(image.getId());
1846 touchConfiguration();
1850 * Creates a new temporary image.
1853 * The MIME type of the temporary image
1855 * The encoded data of the image
1856 * @return The temporary image
1858 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1859 TemporaryImage temporaryImage = new TemporaryImage();
1860 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1861 synchronized (temporaryImages) {
1862 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1864 return temporaryImage;
1868 * Deletes the given temporary image.
1870 * @param temporaryImage
1871 * The temporary image to delete
1873 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1874 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1875 deleteTemporaryImage(temporaryImage.getId());
1879 * Deletes the temporary image with the given ID.
1882 * The ID of the temporary image to delete
1884 public void deleteTemporaryImage(String imageId) {
1885 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1886 synchronized (temporaryImages) {
1887 temporaryImages.remove(imageId);
1889 Image image = getImage(imageId, false);
1890 if (image != null) {
1891 imageInserter.cancelImageInsert(image);
1896 * Notifies the core that the configuration, either of the core or of a
1897 * single local Sone, has changed, and that the configuration should be
1900 public void touchConfiguration() {
1901 lastConfigurationUpdate = System.currentTimeMillis();
1912 public void serviceStart() {
1913 loadConfiguration();
1914 updateChecker.addUpdateListener(this);
1915 updateChecker.start();
1916 identityManager.addIdentityListener(this);
1917 identityManager.start();
1918 webOfTrustUpdater.init();
1919 webOfTrustUpdater.start();
1926 public void serviceRun() {
1927 long lastSaved = System.currentTimeMillis();
1928 while (!shouldStop()) {
1930 long now = System.currentTimeMillis();
1931 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1932 for (Sone localSone : getLocalSones()) {
1933 saveSone(localSone);
1935 saveConfiguration();
1945 public void serviceStop() {
1946 synchronized (sones) {
1947 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1948 soneInserter.getValue().removeSoneInsertListener(this);
1949 soneInserter.getValue().stop();
1950 saveSone(soneInserter.getKey());
1953 saveConfiguration();
1954 webOfTrustUpdater.stop();
1955 updateChecker.stop();
1956 updateChecker.removeUpdateListener(this);
1957 soneDownloader.stop();
1958 identityManager.removeIdentityListener(this);
1959 identityManager.stop();
1967 * Saves the given Sone. This will persist all local settings for the given
1968 * Sone, such as the friends list and similar, private options.
1973 private synchronized void saveSone(Sone sone) {
1974 if (!sone.isLocal()) {
1975 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1978 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1979 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1983 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1985 /* save Sone into configuration. */
1986 String sonePrefix = "Sone/" + sone.getId();
1987 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1988 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1991 Profile profile = sone.getProfile();
1992 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1993 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1994 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1995 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1996 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1997 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1998 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2000 /* save profile fields. */
2001 int fieldCounter = 0;
2002 for (Field profileField : profile.getFields()) {
2003 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2004 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2005 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2007 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2010 int postCounter = 0;
2011 for (Post post : sone.getPosts()) {
2012 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2013 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2014 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2015 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2016 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2018 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2021 int replyCounter = 0;
2022 for (PostReply reply : sone.getReplies()) {
2023 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2024 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2025 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2026 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2027 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2029 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2031 /* save post likes. */
2032 int postLikeCounter = 0;
2033 for (String postId : sone.getLikedPostIds()) {
2034 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2036 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2038 /* save reply likes. */
2039 int replyLikeCounter = 0;
2040 for (String replyId : sone.getLikedReplyIds()) {
2041 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2043 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2046 int friendCounter = 0;
2047 for (String friendId : sone.getFriends()) {
2048 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2050 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2052 /* save albums. first, collect in a flat structure, top-level first. */
2053 List<Album> albums = sone.getAllAlbums();
2055 int albumCounter = 0;
2056 for (Album album : albums) {
2057 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2058 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2059 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2060 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2061 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2062 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2064 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2067 int imageCounter = 0;
2068 for (Album album : albums) {
2069 for (Image image : album.getImages()) {
2070 if (!image.isInserted()) {
2073 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2074 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2075 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2076 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2077 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2078 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2079 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2080 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2081 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2084 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2087 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2088 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2089 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2090 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2091 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2092 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2094 configuration.save();
2096 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2098 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2099 } catch (ConfigurationException ce1) {
2100 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2105 * Saves the current options.
2107 private void saveConfiguration() {
2108 synchronized (configuration) {
2109 if (storingConfiguration) {
2110 logger.log(Level.FINE, "Already storing configuration…");
2113 storingConfiguration = true;
2116 /* store the options first. */
2118 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2119 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2120 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2121 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2122 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2123 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2124 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2125 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2126 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2127 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2128 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2129 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2131 /* save known Sones. */
2132 int soneCounter = 0;
2133 synchronized (knownSones) {
2134 for (String knownSoneId : knownSones) {
2135 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2137 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2140 /* save Sone following times. */
2142 synchronized (soneFollowingTimes) {
2143 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2144 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2145 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2148 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2151 /* save known posts. */
2152 int postCounter = 0;
2153 synchronized (knownPosts) {
2154 for (String knownPostId : knownPosts) {
2155 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2157 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2160 /* save known replies. */
2161 int replyCounter = 0;
2162 synchronized (knownReplies) {
2163 for (String knownReplyId : knownReplies) {
2164 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2166 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2169 /* save bookmarked posts. */
2170 int bookmarkedPostCounter = 0;
2171 synchronized (bookmarkedPosts) {
2172 for (String bookmarkedPostId : bookmarkedPosts) {
2173 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2176 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2179 configuration.save();
2181 } catch (ConfigurationException ce1) {
2182 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2184 synchronized (configuration) {
2185 storingConfiguration = false;
2191 * Loads the configuration.
2193 @SuppressWarnings("unchecked")
2194 private void loadConfiguration() {
2195 /* create options. */
2196 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2199 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2200 SoneInserter.setInsertionDelay(newValue);
2204 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2205 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2206 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2207 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2208 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2209 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2210 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2211 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2212 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2215 @SuppressWarnings("synthetic-access")
2216 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2217 fcpInterface.setActive(newValue);
2220 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2223 @SuppressWarnings("synthetic-access")
2224 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2225 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2230 loadConfigurationValue("InsertionDelay");
2231 loadConfigurationValue("PostsPerPage");
2232 loadConfigurationValue("ImagesPerPage");
2233 loadConfigurationValue("CharactersPerPost");
2234 loadConfigurationValue("PostCutOffLength");
2235 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2236 loadConfigurationValue("PositiveTrust");
2237 loadConfigurationValue("NegativeTrust");
2238 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2239 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2240 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2242 /* load known Sones. */
2243 int soneCounter = 0;
2245 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2246 if (knownSoneId == null) {
2249 synchronized (knownSones) {
2250 knownSones.add(knownSoneId);
2254 /* load Sone following times. */
2257 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2258 if (soneId == null) {
2261 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2262 Sone followedSone = getSone(soneId);
2263 if (followedSone == null) {
2264 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2266 synchronized (soneFollowingTimes) {
2267 soneFollowingTimes.put(getSone(soneId), time);
2273 /* load known posts. */
2274 int postCounter = 0;
2276 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2277 if (knownPostId == null) {
2280 synchronized (knownPosts) {
2281 knownPosts.add(knownPostId);
2285 /* load known replies. */
2286 int replyCounter = 0;
2288 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2289 if (knownReplyId == null) {
2292 synchronized (knownReplies) {
2293 knownReplies.add(knownReplyId);
2297 /* load bookmarked posts. */
2298 int bookmarkedPostCounter = 0;
2300 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2301 if (bookmarkedPostId == null) {
2304 synchronized (bookmarkedPosts) {
2305 bookmarkedPosts.add(bookmarkedPostId);
2312 * Loads an {@link Integer} configuration value for the option with the
2313 * given name, logging validation failures.
2316 * The name of the option to load
2318 private void loadConfigurationValue(String optionName) {
2320 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2321 } catch (IllegalArgumentException iae1) {
2322 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2327 * Generate a Sone URI from the given URI and latest edition.
2330 * The URI to derive the Sone URI from
2331 * @return The derived URI
2333 private static FreenetURI getSoneUri(String uriString) {
2335 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2337 } catch (MalformedURLException mue1) {
2338 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2344 // INTERFACE IdentityListener
2351 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2352 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2353 if (ownIdentity.hasContext("Sone")) {
2354 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2355 addLocalSone(ownIdentity);
2363 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2364 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2365 trustedIdentities.remove(ownIdentity);
2372 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2373 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2374 trustedIdentities.get(ownIdentity).add(identity);
2375 addRemoteSone(identity);
2382 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2383 soneDownloaders.execute(new Runnable() {
2386 @SuppressWarnings("synthetic-access")
2388 Sone sone = getRemoteSone(identity.getId(), false);
2389 sone.setIdentity(identity);
2390 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2391 soneDownloader.addSone(sone);
2392 soneDownloader.fetchSone(sone);
2401 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2402 trustedIdentities.get(ownIdentity).remove(identity);
2403 boolean foundIdentity = false;
2404 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2405 if (trustedIdentity.getKey().equals(ownIdentity)) {
2408 if (trustedIdentity.getValue().contains(identity)) {
2409 foundIdentity = true;
2412 if (foundIdentity) {
2413 /* some local identity still trusts this identity, don’t remove. */
2416 Sone sone = getSone(identity.getId(), false);
2418 /* TODO - we don’t have the Sone anymore. should this happen? */
2421 synchronized (posts) {
2422 synchronized (knownPosts) {
2423 for (Post post : sone.getPosts()) {
2424 posts.remove(post.getId());
2425 eventBus.post(new PostRemovedEvent(post));
2429 synchronized (replies) {
2430 synchronized (knownReplies) {
2431 for (PostReply reply : sone.getReplies()) {
2432 replies.remove(reply.getId());
2433 eventBus.post(new PostReplyRemovedEvent(reply));
2437 synchronized (sones) {
2438 sones.remove(identity.getId());
2440 eventBus.post(new SoneRemovedEvent(sone));
2444 // INTERFACE UpdateListener
2451 public void updateFound(Version version, long releaseTime, long latestEdition) {
2452 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2456 // INTERFACE ImageInsertListener
2463 public void insertStarted(Sone sone) {
2464 coreListenerManager.fireSoneInserting(sone);
2471 public void insertFinished(Sone sone, long insertDuration) {
2472 coreListenerManager.fireSoneInserted(sone, insertDuration);
2479 public void insertAborted(Sone sone, Throwable cause) {
2480 coreListenerManager.fireSoneInsertAborted(sone, cause);
2484 // SONEINSERTLISTENER METHODS
2491 public void imageInsertStarted(Image image) {
2492 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2493 coreListenerManager.fireImageInsertStarted(image);
2500 public void imageInsertAborted(Image image) {
2501 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2502 coreListenerManager.fireImageInsertAborted(image);
2509 public void imageInsertFinished(Image image, FreenetURI key) {
2510 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2511 image.setKey(key.toString());
2512 deleteTemporaryImage(image.getId());
2513 touchConfiguration();
2514 coreListenerManager.fireImageInsertFinished(image);
2521 public void imageInsertFailed(Image image, Throwable cause) {
2522 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2523 coreListenerManager.fireImageInsertFailed(image, cause);
2527 * Convenience interface for external classes that want to access the core’s
2530 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2532 public static class Preferences {
2534 /** The wrapped options. */
2535 private final Options options;
2538 * Creates a new preferences object wrapped around the given options.
2541 * The options to wrap
2543 public Preferences(Options options) {
2544 this.options = options;
2548 * Returns the insertion delay.
2550 * @return The insertion delay
2552 public int getInsertionDelay() {
2553 return options.getIntegerOption("InsertionDelay").get();
2557 * Validates the given insertion delay.
2559 * @param insertionDelay
2560 * The insertion delay to validate
2561 * @return {@code true} if the given insertion delay was valid,
2562 * {@code false} otherwise
2564 public boolean validateInsertionDelay(Integer insertionDelay) {
2565 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2569 * Sets the insertion delay
2571 * @param insertionDelay
2572 * The new insertion delay, or {@code null} to restore it to
2574 * @return This preferences
2576 public Preferences setInsertionDelay(Integer insertionDelay) {
2577 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2582 * Returns the number of posts to show per page.
2584 * @return The number of posts to show per page
2586 public int getPostsPerPage() {
2587 return options.getIntegerOption("PostsPerPage").get();
2591 * Validates the number of posts per page.
2593 * @param postsPerPage
2594 * The number of posts per page
2595 * @return {@code true} if the number of posts per page was valid,
2596 * {@code false} otherwise
2598 public boolean validatePostsPerPage(Integer postsPerPage) {
2599 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2603 * Sets the number of posts to show per page.
2605 * @param postsPerPage
2606 * The number of posts to show per page
2607 * @return This preferences object
2609 public Preferences setPostsPerPage(Integer postsPerPage) {
2610 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2615 * Returns the number of images to show per page.
2617 * @return The number of images to show per page
2619 public int getImagesPerPage() {
2620 return options.getIntegerOption("ImagesPerPage").get();
2624 * Validates the number of images per page.
2626 * @param imagesPerPage
2627 * The number of images per page
2628 * @return {@code true} if the number of images per page was valid,
2629 * {@code false} otherwise
2631 public boolean validateImagesPerPage(Integer imagesPerPage) {
2632 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2636 * Sets the number of images per page.
2638 * @param imagesPerPage
2639 * The number of images per page
2640 * @return This preferences object
2642 public Preferences setImagesPerPage(Integer imagesPerPage) {
2643 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2648 * Returns the number of characters per post, or <code>-1</code> if the
2649 * posts should not be cut off.
2651 * @return The numbers of characters per post
2653 public int getCharactersPerPost() {
2654 return options.getIntegerOption("CharactersPerPost").get();
2658 * Validates the number of characters per post.
2660 * @param charactersPerPost
2661 * The number of characters per post
2662 * @return {@code true} if the number of characters per post was valid,
2663 * {@code false} otherwise
2665 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2666 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2670 * Sets the number of characters per post.
2672 * @param charactersPerPost
2673 * The number of characters per post, or <code>-1</code> to
2674 * not cut off the posts
2675 * @return This preferences objects
2677 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2678 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2683 * Returns the number of characters the shortened post should have.
2685 * @return The number of characters of the snippet
2687 public int getPostCutOffLength() {
2688 return options.getIntegerOption("PostCutOffLength").get();
2692 * Validates the number of characters after which to cut off the post.
2694 * @param postCutOffLength
2695 * The number of characters of the snippet
2696 * @return {@code true} if the number of characters of the snippet is
2697 * valid, {@code false} otherwise
2699 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2700 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2704 * Sets the number of characters the shortened post should have.
2706 * @param postCutOffLength
2707 * The number of characters of the snippet
2708 * @return This preferences
2710 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2711 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2716 * Returns whether Sone requires full access to be even visible.
2718 * @return {@code true} if Sone requires full access, {@code false}
2721 public boolean isRequireFullAccess() {
2722 return options.getBooleanOption("RequireFullAccess").get();
2726 * Sets whether Sone requires full access to be even visible.
2728 * @param requireFullAccess
2729 * {@code true} if Sone requires full access, {@code false}
2732 public void setRequireFullAccess(Boolean requireFullAccess) {
2733 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2737 * Returns the positive trust.
2739 * @return The positive trust
2741 public int getPositiveTrust() {
2742 return options.getIntegerOption("PositiveTrust").get();
2746 * Validates the positive trust.
2748 * @param positiveTrust
2749 * The positive trust to validate
2750 * @return {@code true} if the positive trust was valid, {@code false}
2753 public boolean validatePositiveTrust(Integer positiveTrust) {
2754 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2758 * Sets the positive trust.
2760 * @param positiveTrust
2761 * The new positive trust, or {@code null} to restore it to
2763 * @return This preferences
2765 public Preferences setPositiveTrust(Integer positiveTrust) {
2766 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2771 * Returns the negative trust.
2773 * @return The negative trust
2775 public int getNegativeTrust() {
2776 return options.getIntegerOption("NegativeTrust").get();
2780 * Validates the negative trust.
2782 * @param negativeTrust
2783 * The negative trust to validate
2784 * @return {@code true} if the negative trust was valid, {@code false}
2787 public boolean validateNegativeTrust(Integer negativeTrust) {
2788 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2792 * Sets the negative trust.
2794 * @param negativeTrust
2795 * The negative trust, or {@code null} to restore it to the
2797 * @return The preferences
2799 public Preferences setNegativeTrust(Integer negativeTrust) {
2800 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2805 * Returns the trust comment. This is the comment that is set in the web
2806 * of trust when a trust value is assigned to an identity.
2808 * @return The trust comment
2810 public String getTrustComment() {
2811 return options.getStringOption("TrustComment").get();
2815 * Sets the trust comment.
2817 * @param trustComment
2818 * The trust comment, or {@code null} to restore it to the
2820 * @return This preferences
2822 public Preferences setTrustComment(String trustComment) {
2823 options.getStringOption("TrustComment").set(trustComment);
2828 * Returns whether the {@link FcpInterface FCP interface} is currently
2831 * @see FcpInterface#setActive(boolean)
2832 * @return {@code true} if the FCP interface is currently active,
2833 * {@code false} otherwise
2835 public boolean isFcpInterfaceActive() {
2836 return options.getBooleanOption("ActivateFcpInterface").get();
2840 * Sets whether the {@link FcpInterface FCP interface} is currently
2843 * @see FcpInterface#setActive(boolean)
2844 * @param fcpInterfaceActive
2845 * {@code true} to activate the FCP interface, {@code false}
2846 * to deactivate the FCP interface
2847 * @return This preferences object
2849 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2850 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2855 * Returns the action level for which full access to the FCP interface
2858 * @return The action level for which full access to the FCP interface
2861 public FullAccessRequired getFcpFullAccessRequired() {
2862 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2866 * Sets the action level for which full access to the FCP interface is
2869 * @param fcpFullAccessRequired
2871 * @return This preferences
2873 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2874 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);