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.SoneRemovedEvent;
46 import net.pterodactylus.sone.data.Album;
47 import net.pterodactylus.sone.data.Client;
48 import net.pterodactylus.sone.data.Image;
49 import net.pterodactylus.sone.data.Post;
50 import net.pterodactylus.sone.data.PostReply;
51 import net.pterodactylus.sone.data.Profile;
52 import net.pterodactylus.sone.data.Profile.Field;
53 import net.pterodactylus.sone.data.Reply;
54 import net.pterodactylus.sone.data.Sone;
55 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
56 import net.pterodactylus.sone.data.Sone.SoneStatus;
57 import net.pterodactylus.sone.data.TemporaryImage;
58 import net.pterodactylus.sone.data.impl.PostImpl;
59 import net.pterodactylus.sone.fcp.FcpInterface;
60 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
61 import net.pterodactylus.sone.freenet.wot.Identity;
62 import net.pterodactylus.sone.freenet.wot.IdentityListener;
63 import net.pterodactylus.sone.freenet.wot.IdentityManager;
64 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
65 import net.pterodactylus.sone.main.SonePlugin;
66 import net.pterodactylus.util.config.Configuration;
67 import net.pterodactylus.util.config.ConfigurationException;
68 import net.pterodactylus.util.logging.Logging;
69 import net.pterodactylus.util.number.Numbers;
70 import net.pterodactylus.util.service.AbstractService;
71 import net.pterodactylus.util.thread.NamedThreadFactory;
72 import net.pterodactylus.util.thread.Ticker;
73 import net.pterodactylus.util.validation.EqualityValidator;
74 import net.pterodactylus.util.validation.IntegerRangeValidator;
75 import net.pterodactylus.util.validation.OrValidator;
76 import net.pterodactylus.util.validation.Validation;
77 import net.pterodactylus.util.version.Version;
79 import com.google.common.base.Predicate;
80 import com.google.common.collect.Collections2;
81 import com.google.common.eventbus.EventBus;
82 import com.google.inject.Inject;
84 import freenet.keys.FreenetURI;
89 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
91 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
94 private static final Logger logger = Logging.getLogger(Core.class);
96 /** The start time. */
97 private final long startupTime = System.currentTimeMillis();
100 private final Options options = new Options();
102 /** The preferences. */
103 private final Preferences preferences = new Preferences(options);
105 /** The core listener manager. */
106 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
108 /** The event bus. */
109 private final EventBus eventBus;
111 /** The configuration. */
112 private Configuration configuration;
114 /** Whether we’re currently saving the configuration. */
115 private boolean storingConfiguration = false;
117 /** The identity manager. */
118 private final IdentityManager identityManager;
120 /** Interface to freenet. */
121 private final FreenetInterface freenetInterface;
123 /** The Sone downloader. */
124 private final SoneDownloader soneDownloader;
126 /** The image inserter. */
127 private final ImageInserter imageInserter;
129 /** Sone downloader thread-pool. */
130 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
132 /** The update checker. */
133 private final UpdateChecker updateChecker;
135 /** The trust updater. */
136 private final WebOfTrustUpdater webOfTrustUpdater;
138 /** The FCP interface. */
139 private volatile FcpInterface fcpInterface;
141 /** The times Sones were followed. */
142 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
144 /** Locked local Sones. */
145 /* synchronize on itself. */
146 private final Set<Sone> lockedSones = new HashSet<Sone>();
148 /** Sone inserters. */
149 /* synchronize access on this on sones. */
150 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
152 /** Sone rescuers. */
153 /* synchronize access on this on sones. */
154 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
157 /* synchronize access on this on itself. */
158 private final Map<String, Sone> sones = new HashMap<String, Sone>();
160 /** All known Sones. */
161 private final Set<String> knownSones = new HashSet<String>();
164 private final Map<String, Post> posts = new HashMap<String, Post>();
166 /** All known posts. */
167 private final Set<String> knownPosts = new HashSet<String>();
170 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
172 /** All known replies. */
173 private final Set<String> knownReplies = new HashSet<String>();
175 /** All bookmarked posts. */
176 /* synchronize access on itself. */
177 private final Set<String> bookmarkedPosts = new HashSet<String>();
179 /** Trusted identities, sorted by own identities. */
180 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
182 /** All known albums. */
183 private final Map<String, Album> albums = new HashMap<String, Album>();
185 /** All known images. */
186 private final Map<String, Image> images = new HashMap<String, Image>();
188 /** All temporary images. */
189 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
191 /** Ticker for threads that mark own elements as known. */
192 private final Ticker localElementTicker = new Ticker();
194 /** The time the configuration was last touched. */
195 private volatile long lastConfigurationUpdate;
198 * Creates a new core.
200 * @param configuration
201 * The configuration of the core
202 * @param freenetInterface
203 * The freenet interface
204 * @param identityManager
205 * The identity manager
206 * @param webOfTrustUpdater
207 * The WebOfTrust updater
212 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
214 this.configuration = configuration;
215 this.freenetInterface = freenetInterface;
216 this.identityManager = identityManager;
217 this.soneDownloader = new SoneDownloader(this, freenetInterface);
218 this.imageInserter = new ImageInserter(this, freenetInterface);
219 this.updateChecker = new UpdateChecker(freenetInterface);
220 this.webOfTrustUpdater = webOfTrustUpdater;
221 this.eventBus = eventBus;
225 // LISTENER MANAGEMENT
229 * Adds a new core listener.
231 * @param coreListener
232 * The listener to add
234 public void addCoreListener(CoreListener coreListener) {
235 coreListenerManager.addListener(coreListener);
239 * Removes a core listener.
241 * @param coreListener
242 * The listener to remove
244 public void removeCoreListener(CoreListener coreListener) {
245 coreListenerManager.removeListener(coreListener);
253 * Returns the time Sone was started.
255 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
257 public long getStartupTime() {
262 * Sets the configuration to use. This will automatically save the current
263 * configuration to the given configuration.
265 * @param configuration
266 * The new configuration to use
268 public void setConfiguration(Configuration configuration) {
269 this.configuration = configuration;
270 touchConfiguration();
274 * Returns the options used by the core.
276 * @return The options of the core
278 public Preferences getPreferences() {
283 * Returns the identity manager used by the core.
285 * @return The identity manager
287 public IdentityManager getIdentityManager() {
288 return identityManager;
292 * Returns the update checker.
294 * @return The update checker
296 public UpdateChecker getUpdateChecker() {
297 return updateChecker;
301 * Sets the FCP interface to use.
303 * @param fcpInterface
304 * The FCP interface to use
306 public void setFcpInterface(FcpInterface fcpInterface) {
307 this.fcpInterface = fcpInterface;
311 * Returns the Sone rescuer for the given local Sone.
314 * The local Sone to get the rescuer for
315 * @return The Sone rescuer for the given Sone
317 public SoneRescuer getSoneRescuer(Sone sone) {
318 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
319 synchronized (sones) {
320 SoneRescuer soneRescuer = soneRescuers.get(sone);
321 if (soneRescuer == null) {
322 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
323 soneRescuers.put(sone, soneRescuer);
331 * Returns whether the given Sone is currently locked.
335 * @return {@code true} if the Sone is locked, {@code false} if it is not
337 public boolean isLocked(Sone sone) {
338 synchronized (lockedSones) {
339 return lockedSones.contains(sone);
344 * Returns all Sones, remote and local.
348 public Set<Sone> getSones() {
349 return new HashSet<Sone>(sones.values());
353 * Returns the Sone with the given ID, regardless whether it’s local or
357 * The ID of the Sone to get
358 * @return The Sone with the given ID, or {@code null} if there is no such
361 public Sone getSone(String id) {
362 return getSone(id, true);
366 * Returns the Sone with the given ID, regardless whether it’s local or
370 * The ID of the Sone to get
372 * {@code true} to create a new Sone if none exists,
373 * {@code false} to return {@code null} if a Sone with the given
375 * @return The Sone with the given ID, or {@code null} if there is no such
379 public Sone getSone(String id, boolean create) {
380 synchronized (sones) {
381 if (!sones.containsKey(id)) {
382 Sone sone = new Sone(id, false);
385 return sones.get(id);
390 * Checks whether the core knows a Sone with the given ID.
394 * @return {@code true} if there is a Sone with the given ID, {@code false}
397 public boolean hasSone(String id) {
398 synchronized (sones) {
399 return sones.containsKey(id);
404 * Returns all local Sones.
406 * @return All local Sones
408 public Collection<Sone> getLocalSones() {
409 synchronized (sones) {
410 return Collections2.filter(sones.values(), new Predicate<Sone>() {
413 public boolean apply(Sone sone) {
414 return sone.isLocal();
421 * Returns the local Sone with the given ID, optionally creating a new Sone.
426 * {@code true} to create a new Sone if none exists,
427 * {@code false} to return null if none exists
428 * @return The Sone with the given ID, or {@code null}
430 public Sone getLocalSone(String id, boolean create) {
431 synchronized (sones) {
432 Sone sone = sones.get(id);
433 if ((sone == null) && create) {
434 sone = new Sone(id, true);
437 if ((sone != null) && !sone.isLocal()) {
438 sone = new Sone(id, true);
446 * Returns all remote Sones.
448 * @return All remote Sones
450 public Collection<Sone> getRemoteSones() {
451 synchronized (sones) {
452 return Collections2.filter(sones.values(), new Predicate<Sone>() {
455 public boolean apply(Sone sone) {
456 return !sone.isLocal();
463 * Returns the remote Sone with the given ID.
466 * The ID of the remote Sone to get
468 * {@code true} to always create a Sone, {@code false} to return
469 * {@code null} if no Sone with the given ID exists
470 * @return The Sone with the given ID
472 public Sone getRemoteSone(String id, boolean create) {
473 synchronized (sones) {
474 Sone sone = sones.get(id);
475 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
476 sone = new Sone(id, false);
484 * Returns whether the given Sone has been modified.
487 * The Sone to check for modifications
488 * @return {@code true} if a modification has been detected in the Sone,
489 * {@code false} otherwise
491 public boolean isModifiedSone(Sone sone) {
492 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
496 * Returns the time when the given was first followed by any local Sone.
499 * The Sone to get the time for
500 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
501 * been followed, or {@link Long#MAX_VALUE}
503 public long getSoneFollowingTime(Sone sone) {
504 synchronized (soneFollowingTimes) {
505 if (soneFollowingTimes.containsKey(sone)) {
506 return soneFollowingTimes.get(sone);
508 return Long.MAX_VALUE;
513 * Returns whether the target Sone is trusted by the origin Sone.
519 * @return {@code true} if the target Sone is trusted by the origin Sone
521 public boolean isSoneTrusted(Sone origin, Sone target) {
522 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
523 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
527 * Returns the post with the given ID.
530 * The ID of the post to get
531 * @return The post with the given ID, or a new post with the given ID
533 public Post getPost(String postId) {
534 return getPost(postId, true);
538 * Returns the post with the given ID, optionally creating a new post.
541 * The ID of the post to get
543 * {@code true} it create a new post if no post with the given ID
544 * exists, {@code false} to return {@code null}
545 * @return The post, or {@code null} if there is no such post
548 public Post getPost(String postId, boolean create) {
549 synchronized (posts) {
550 Post post = posts.get(postId);
551 if ((post == null) && create) {
552 post = new PostImpl(postId);
553 posts.put(postId, post);
560 * Returns all posts that have the given Sone as recipient.
562 * @see Post#getRecipient()
564 * The recipient of the posts
565 * @return All posts that have the given Sone as recipient
567 public Set<Post> getDirectedPosts(Sone recipient) {
568 Validation.begin().isNotNull("Recipient", recipient).check();
569 Set<Post> directedPosts = new HashSet<Post>();
570 synchronized (posts) {
571 for (Post post : posts.values()) {
572 if (recipient.equals(post.getRecipient())) {
573 directedPosts.add(post);
577 return directedPosts;
581 * Returns the reply with the given ID. If there is no reply with the given
582 * ID yet, a new one is created, unless {@code create} is false in which
583 * case {@code null} is returned.
586 * The ID of the reply to get
588 * {@code true} to always return a {@link Reply}, {@code false}
589 * to return {@code null} if no reply can be found
590 * @return The reply, or {@code null} if there is no such reply
592 public PostReply getPostReply(String replyId, boolean create) {
593 synchronized (replies) {
594 PostReply reply = replies.get(replyId);
595 if (create && (reply == null)) {
596 reply = new PostReply(replyId);
597 replies.put(replyId, reply);
604 * Returns all replies for the given post, order ascending by time.
607 * The post to get all replies for
608 * @return All replies for the given post
610 public List<PostReply> getReplies(Post post) {
611 Set<Sone> sones = getSones();
612 List<PostReply> replies = new ArrayList<PostReply>();
613 for (Sone sone : sones) {
614 for (PostReply reply : sone.getReplies()) {
615 if (reply.getPost().equals(post)) {
620 Collections.sort(replies, Reply.TIME_COMPARATOR);
625 * Returns all Sones that have liked the given post.
628 * The post to get the liking Sones for
629 * @return The Sones that like the given post
631 public Set<Sone> getLikes(Post post) {
632 Set<Sone> sones = new HashSet<Sone>();
633 for (Sone sone : getSones()) {
634 if (sone.getLikedPostIds().contains(post.getId())) {
642 * Returns all Sones that have liked the given reply.
645 * The reply to get the liking Sones for
646 * @return The Sones that like the given reply
648 public Set<Sone> getLikes(PostReply reply) {
649 Set<Sone> sones = new HashSet<Sone>();
650 for (Sone sone : getSones()) {
651 if (sone.getLikedReplyIds().contains(reply.getId())) {
659 * Returns whether the given post is bookmarked.
663 * @return {@code true} if the given post is bookmarked, {@code false}
666 public boolean isBookmarked(Post post) {
667 return isPostBookmarked(post.getId());
671 * Returns whether the post with the given ID is bookmarked.
674 * The ID of the post to check
675 * @return {@code true} if the post with the given ID is bookmarked,
676 * {@code false} otherwise
678 public boolean isPostBookmarked(String id) {
679 synchronized (bookmarkedPosts) {
680 return bookmarkedPosts.contains(id);
685 * Returns all currently known bookmarked posts.
687 * @return All bookmarked posts
689 public Set<Post> getBookmarkedPosts() {
690 Set<Post> posts = new HashSet<Post>();
691 synchronized (bookmarkedPosts) {
692 for (String bookmarkedPostId : bookmarkedPosts) {
693 Post post = getPost(bookmarkedPostId, false);
703 * Returns the album with the given ID, creating a new album if no album
704 * with the given ID can be found.
707 * The ID of the album
708 * @return The album with the given ID
710 public Album getAlbum(String albumId) {
711 return getAlbum(albumId, true);
715 * Returns the album with the given ID, optionally creating a new album if
716 * an album with the given ID can not be found.
719 * The ID of the album
721 * {@code true} to create a new album if none exists for the
723 * @return The album with the given ID, or {@code null} if no album with the
724 * given ID exists and {@code create} is {@code false}
726 public Album getAlbum(String albumId, boolean create) {
727 synchronized (albums) {
728 Album album = albums.get(albumId);
729 if (create && (album == null)) {
730 album = new Album(albumId);
731 albums.put(albumId, album);
738 * Returns the image with the given ID, creating it if necessary.
741 * The ID of the image
742 * @return The image with the given ID
744 public Image getImage(String imageId) {
745 return getImage(imageId, true);
749 * Returns the image with the given ID, optionally creating it if it does
753 * The ID of the image
755 * {@code true} to create an image if none exists with the given
757 * @return The image with the given ID, or {@code null} if none exists and
760 public Image getImage(String imageId, boolean create) {
761 synchronized (images) {
762 Image image = images.get(imageId);
763 if (create && (image == null)) {
764 image = new Image(imageId);
765 images.put(imageId, image);
772 * Returns the temporary image with the given ID.
775 * The ID of the temporary image
776 * @return The temporary image, or {@code null} if there is no temporary
777 * image with the given ID
779 public TemporaryImage getTemporaryImage(String imageId) {
780 synchronized (temporaryImages) {
781 return temporaryImages.get(imageId);
790 * Locks the given Sone. A locked Sone will not be inserted by
791 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
797 public void lockSone(Sone sone) {
798 synchronized (lockedSones) {
799 if (lockedSones.add(sone)) {
800 coreListenerManager.fireSoneLocked(sone);
806 * Unlocks the given Sone.
808 * @see #lockSone(Sone)
812 public void unlockSone(Sone sone) {
813 synchronized (lockedSones) {
814 if (lockedSones.remove(sone)) {
815 coreListenerManager.fireSoneUnlocked(sone);
821 * Adds a local Sone from the given own identity.
824 * The own identity to create a Sone from
825 * @return The added (or already existing) Sone
827 public Sone addLocalSone(OwnIdentity ownIdentity) {
828 if (ownIdentity == null) {
829 logger.log(Level.WARNING, "Given OwnIdentity is null!");
832 synchronized (sones) {
835 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
836 } catch (MalformedURLException mue1) {
837 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
840 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
841 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
843 /* TODO - load posts ’n stuff */
844 sones.put(ownIdentity.getId(), sone);
845 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
846 soneInserter.addSoneInsertListener(this);
847 soneInserters.put(sone, soneInserter);
848 sone.setStatus(SoneStatus.idle);
850 soneInserter.start();
856 * Creates a new Sone for the given own identity.
859 * The own identity to create a Sone for
860 * @return The created Sone
862 public Sone createSone(OwnIdentity ownIdentity) {
863 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
864 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
867 Sone sone = addLocalSone(ownIdentity);
868 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
869 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
870 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
871 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
872 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
873 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
875 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
876 touchConfiguration();
881 * Adds the Sone of the given identity.
884 * The identity whose Sone to add
885 * @return The added or already existing Sone
887 public Sone addRemoteSone(Identity identity) {
888 if (identity == null) {
889 logger.log(Level.WARNING, "Given Identity is null!");
892 synchronized (sones) {
893 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
894 boolean newSone = sone.getRequestUri() == null;
895 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
896 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
898 synchronized (knownSones) {
899 newSone = !knownSones.contains(sone.getId());
901 sone.setKnown(!newSone);
903 eventBus.post(new NewSoneFoundEvent(sone));
904 for (Sone localSone : getLocalSones()) {
905 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
906 followSone(localSone, sone);
911 soneDownloader.addSone(sone);
912 soneDownloaders.execute(new Runnable() {
915 @SuppressWarnings("synthetic-access")
917 soneDownloader.fetchSone(sone, sone.getRequestUri());
926 * Lets the given local Sone follow the Sone with the given ID.
929 * The local Sone that should follow another Sone
931 * The ID of the Sone to follow
933 public void followSone(Sone sone, String soneId) {
934 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
935 Sone followedSone = getSone(soneId, true);
936 if (followedSone == null) {
937 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
940 followSone(sone, getSone(soneId));
944 * Lets the given local Sone follow the other given Sone. If the given Sone
945 * was not followed by any local Sone before, this will mark all elements of
946 * the followed Sone as read that have been created before the current
950 * The local Sone that should follow the other Sone
951 * @param followedSone
952 * The Sone that should be followed
954 public void followSone(Sone sone, Sone followedSone) {
955 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
956 sone.addFriend(followedSone.getId());
957 synchronized (soneFollowingTimes) {
958 if (!soneFollowingTimes.containsKey(followedSone)) {
959 long now = System.currentTimeMillis();
960 soneFollowingTimes.put(followedSone, now);
961 for (Post post : followedSone.getPosts()) {
962 if (post.getTime() < now) {
966 for (PostReply reply : followedSone.getReplies()) {
967 if (reply.getTime() < now) {
968 markReplyKnown(reply);
973 touchConfiguration();
977 * Lets the given local Sone unfollow the Sone with the given ID.
980 * The local Sone that should unfollow another Sone
982 * The ID of the Sone being unfollowed
984 public void unfollowSone(Sone sone, String soneId) {
985 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
986 unfollowSone(sone, getSone(soneId, false));
990 * Lets the given local Sone unfollow the other given Sone. If the given
991 * local Sone is the last local Sone that followed the given Sone, its
992 * following time will be removed.
995 * The local Sone that should unfollow another Sone
996 * @param unfollowedSone
997 * The Sone being unfollowed
999 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1000 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1001 sone.removeFriend(unfollowedSone.getId());
1002 boolean unfollowedSoneStillFollowed = false;
1003 for (Sone localSone : getLocalSones()) {
1004 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1006 if (!unfollowedSoneStillFollowed) {
1007 synchronized (soneFollowingTimes) {
1008 soneFollowingTimes.remove(unfollowedSone);
1011 touchConfiguration();
1015 * Sets the trust value of the given origin Sone for the target Sone.
1022 * The trust value (from {@code -100} to {@code 100})
1024 public void setTrust(Sone origin, Sone target, int trustValue) {
1025 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();
1026 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1030 * Removes any trust assignment for the given target Sone.
1037 public void removeTrust(Sone origin, Sone target) {
1038 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1039 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1043 * Assigns the configured positive trust value for the given target.
1050 public void trustSone(Sone origin, Sone target) {
1051 setTrust(origin, target, preferences.getPositiveTrust());
1055 * Assigns the configured negative trust value for the given target.
1062 public void distrustSone(Sone origin, Sone target) {
1063 setTrust(origin, target, preferences.getNegativeTrust());
1067 * Removes the trust assignment for the given target.
1074 public void untrustSone(Sone origin, Sone target) {
1075 removeTrust(origin, target);
1079 * Updates the stored Sone with the given Sone.
1084 public void updateSone(Sone sone) {
1085 updateSone(sone, false);
1089 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1090 * {@code true}, an older Sone than the current Sone can be given to restore
1094 * The Sone to update
1095 * @param soneRescueMode
1096 * {@code true} if the stored Sone should be updated regardless
1097 * of the age of the given Sone
1099 public void updateSone(Sone sone, boolean soneRescueMode) {
1100 if (hasSone(sone.getId())) {
1101 Sone storedSone = getSone(sone.getId());
1102 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1103 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1106 synchronized (posts) {
1107 if (!soneRescueMode) {
1108 for (Post post : storedSone.getPosts()) {
1109 posts.remove(post.getId());
1110 if (!sone.getPosts().contains(post)) {
1111 eventBus.post(new PostRemovedEvent(post));
1115 List<Post> storedPosts = storedSone.getPosts();
1116 synchronized (knownPosts) {
1117 for (Post post : sone.getPosts()) {
1118 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1119 if (!storedPosts.contains(post)) {
1120 if (post.getTime() < getSoneFollowingTime(sone)) {
1121 knownPosts.add(post.getId());
1122 post.setKnown(true);
1123 } else if (!knownPosts.contains(post.getId())) {
1124 eventBus.post(new NewPostFoundEvent(post));
1127 posts.put(post.getId(), post);
1131 synchronized (replies) {
1132 if (!soneRescueMode) {
1133 for (PostReply reply : storedSone.getReplies()) {
1134 replies.remove(reply.getId());
1135 if (!sone.getReplies().contains(reply)) {
1136 coreListenerManager.fireReplyRemoved(reply);
1140 Set<PostReply> storedReplies = storedSone.getReplies();
1141 synchronized (knownReplies) {
1142 for (PostReply reply : sone.getReplies()) {
1143 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1144 if (!storedReplies.contains(reply)) {
1145 if (reply.getTime() < getSoneFollowingTime(sone)) {
1146 knownReplies.add(reply.getId());
1147 reply.setKnown(true);
1148 } else if (!knownReplies.contains(reply.getId())) {
1149 eventBus.post(new NewPostReplyFoundEvent(reply));
1152 replies.put(reply.getId(), reply);
1156 synchronized (albums) {
1157 synchronized (images) {
1158 for (Album album : storedSone.getAlbums()) {
1159 albums.remove(album.getId());
1160 for (Image image : album.getImages()) {
1161 images.remove(image.getId());
1164 for (Album album : sone.getAlbums()) {
1165 albums.put(album.getId(), album);
1166 for (Image image : album.getImages()) {
1167 images.put(image.getId(), image);
1172 synchronized (storedSone) {
1173 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1174 storedSone.setTime(sone.getTime());
1176 storedSone.setClient(sone.getClient());
1177 storedSone.setProfile(sone.getProfile());
1178 if (soneRescueMode) {
1179 for (Post post : sone.getPosts()) {
1180 storedSone.addPost(post);
1182 for (PostReply reply : sone.getReplies()) {
1183 storedSone.addReply(reply);
1185 for (String likedPostId : sone.getLikedPostIds()) {
1186 storedSone.addLikedPostId(likedPostId);
1188 for (String likedReplyId : sone.getLikedReplyIds()) {
1189 storedSone.addLikedReplyId(likedReplyId);
1191 for (Album album : sone.getAlbums()) {
1192 storedSone.addAlbum(album);
1195 storedSone.setPosts(sone.getPosts());
1196 storedSone.setReplies(sone.getReplies());
1197 storedSone.setLikePostIds(sone.getLikedPostIds());
1198 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1199 storedSone.setAlbums(sone.getAlbums());
1201 storedSone.setLatestEdition(sone.getLatestEdition());
1207 * Deletes the given Sone. This will remove the Sone from the
1208 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1209 * remove the context from its identity.
1212 * The Sone to delete
1214 public void deleteSone(Sone sone) {
1215 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1216 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1219 synchronized (sones) {
1220 if (!getLocalSones().contains(sone)) {
1221 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1224 sones.remove(sone.getId());
1225 SoneInserter soneInserter = soneInserters.remove(sone);
1226 soneInserter.removeSoneInsertListener(this);
1227 soneInserter.stop();
1229 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1230 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1232 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1233 } catch (ConfigurationException ce1) {
1234 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1239 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1240 * known} before, a {@link MarkSoneKnownEvent} is fired.
1243 * The Sone to mark as known
1245 public void markSoneKnown(Sone sone) {
1246 if (!sone.isKnown()) {
1247 sone.setKnown(true);
1248 synchronized (knownSones) {
1249 knownSones.add(sone.getId());
1251 eventBus.post(new MarkSoneKnownEvent(sone));
1252 touchConfiguration();
1257 * Loads and updates the given Sone from the configuration. If any error is
1258 * encountered, loading is aborted and the given Sone is not changed.
1261 * The Sone to load and update
1263 public void loadSone(Sone sone) {
1264 if (!sone.isLocal()) {
1265 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1269 /* initialize options. */
1270 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1271 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1272 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1273 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1274 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1275 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1278 String sonePrefix = "Sone/" + sone.getId();
1279 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1280 if (soneTime == null) {
1281 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1284 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1287 Profile profile = new Profile(sone);
1288 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1289 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1290 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1291 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1292 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1293 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1295 /* load profile fields. */
1297 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1298 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1299 if (fieldName == null) {
1302 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1303 profile.addField(fieldName).setValue(fieldValue);
1307 Set<Post> posts = new HashSet<Post>();
1309 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1310 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1311 if (postId == null) {
1314 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1315 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1316 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1317 if ((postTime == 0) || (postText == null)) {
1318 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1321 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1322 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1323 post.setRecipient(getSone(postRecipientId));
1329 Set<PostReply> replies = new HashSet<PostReply>();
1331 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1332 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1333 if (replyId == null) {
1336 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1337 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1338 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1339 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1340 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1343 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1346 /* load post likes. */
1347 Set<String> likedPostIds = new HashSet<String>();
1349 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1350 if (likedPostId == null) {
1353 likedPostIds.add(likedPostId);
1356 /* load reply likes. */
1357 Set<String> likedReplyIds = new HashSet<String>();
1359 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1360 if (likedReplyId == null) {
1363 likedReplyIds.add(likedReplyId);
1367 Set<String> friends = new HashSet<String>();
1369 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1370 if (friendId == null) {
1373 friends.add(friendId);
1377 List<Album> topLevelAlbums = new ArrayList<Album>();
1378 int albumCounter = 0;
1380 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1381 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1382 if (albumId == null) {
1385 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1386 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1387 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1388 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1389 if ((albumTitle == null) || (albumDescription == null)) {
1390 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1393 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1394 if (albumParentId != null) {
1395 Album parentAlbum = getAlbum(albumParentId, false);
1396 if (parentAlbum == null) {
1397 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1400 parentAlbum.addAlbum(album);
1402 if (!topLevelAlbums.contains(album)) {
1403 topLevelAlbums.add(album);
1409 int imageCounter = 0;
1411 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1412 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1413 if (imageId == null) {
1416 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1417 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1418 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1419 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1420 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1421 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1422 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1423 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1424 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1427 Album album = getAlbum(albumId, false);
1428 if (album == null) {
1429 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1432 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1433 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1434 album.addImage(image);
1438 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1439 if (avatarId != null) {
1440 profile.setAvatar(getImage(avatarId, false));
1444 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1445 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1446 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1447 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1448 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1449 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1451 /* if we’re still here, Sone was loaded successfully. */
1452 synchronized (sone) {
1453 sone.setTime(soneTime);
1454 sone.setProfile(profile);
1455 sone.setPosts(posts);
1456 sone.setReplies(replies);
1457 sone.setLikePostIds(likedPostIds);
1458 sone.setLikeReplyIds(likedReplyIds);
1459 for (String friendId : friends) {
1460 followSone(sone, friendId);
1462 sone.setAlbums(topLevelAlbums);
1463 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1465 synchronized (knownSones) {
1466 for (String friend : friends) {
1467 knownSones.add(friend);
1470 synchronized (knownPosts) {
1471 for (Post post : posts) {
1472 knownPosts.add(post.getId());
1475 synchronized (knownReplies) {
1476 for (PostReply reply : replies) {
1477 knownReplies.add(reply.getId());
1483 * Creates a new post.
1486 * The Sone that creates the post
1488 * The text of the post
1489 * @return The created post
1491 public Post createPost(Sone sone, String text) {
1492 return createPost(sone, System.currentTimeMillis(), text);
1496 * Creates a new post.
1499 * The Sone that creates the post
1501 * The time of the post
1503 * The text of the post
1504 * @return The created post
1506 public Post createPost(Sone sone, long time, String text) {
1507 return createPost(sone, null, time, text);
1511 * Creates a new post.
1514 * The Sone that creates the post
1516 * The recipient Sone, or {@code null} if this post does not have
1519 * The text of the post
1520 * @return The created post
1522 public Post createPost(Sone sone, Sone recipient, String text) {
1523 return createPost(sone, recipient, System.currentTimeMillis(), text);
1527 * Creates a new post.
1530 * The Sone that creates the post
1532 * The recipient Sone, or {@code null} if this post does not have
1535 * The time of the post
1537 * The text of the post
1538 * @return The created post
1540 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1541 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1542 if (!sone.isLocal()) {
1543 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1546 final Post post = new PostImpl(sone, time, text);
1547 if (recipient != null) {
1548 post.setRecipient(recipient);
1550 synchronized (posts) {
1551 posts.put(post.getId(), post);
1553 eventBus.post(new NewPostFoundEvent(post));
1555 touchConfiguration();
1556 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1563 markPostKnown(post);
1565 }, "Mark " + post + " read.");
1570 * Deletes the given post.
1573 * The post to delete
1575 public void deletePost(Post post) {
1576 if (!post.getSone().isLocal()) {
1577 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1580 post.getSone().removePost(post);
1581 synchronized (posts) {
1582 posts.remove(post.getId());
1584 eventBus.post(new PostRemovedEvent(post));
1585 markPostKnown(post);
1586 touchConfiguration();
1590 * Marks the given post as known, if it is currently not a known post
1591 * (according to {@link Post#isKnown()}).
1594 * The post to mark as known
1596 public void markPostKnown(Post post) {
1597 post.setKnown(true);
1598 synchronized (knownPosts) {
1599 eventBus.post(new MarkPostKnownEvent(post));
1600 if (knownPosts.add(post.getId())) {
1601 touchConfiguration();
1604 for (PostReply reply : getReplies(post)) {
1605 markReplyKnown(reply);
1610 * Bookmarks the given post.
1613 * The post to bookmark
1615 public void bookmark(Post post) {
1616 bookmarkPost(post.getId());
1620 * Bookmarks the post with the given ID.
1623 * The ID of the post to bookmark
1625 public void bookmarkPost(String id) {
1626 synchronized (bookmarkedPosts) {
1627 bookmarkedPosts.add(id);
1632 * Removes the given post from the bookmarks.
1635 * The post to unbookmark
1637 public void unbookmark(Post post) {
1638 unbookmarkPost(post.getId());
1642 * Removes the post with the given ID from the bookmarks.
1645 * The ID of the post to unbookmark
1647 public void unbookmarkPost(String id) {
1648 synchronized (bookmarkedPosts) {
1649 bookmarkedPosts.remove(id);
1654 * Creates a new reply.
1657 * The Sone that creates the reply
1659 * The post that this reply refers to
1661 * The text of the reply
1662 * @return The created reply
1664 public PostReply createReply(Sone sone, Post post, String text) {
1665 return createReply(sone, post, System.currentTimeMillis(), text);
1669 * Creates a new reply.
1672 * The Sone that creates the reply
1674 * The post that this reply refers to
1676 * The time of the reply
1678 * The text of the reply
1679 * @return The created reply
1681 public PostReply createReply(Sone sone, Post post, long time, String text) {
1682 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1683 if (!sone.isLocal()) {
1684 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1687 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1688 synchronized (replies) {
1689 replies.put(reply.getId(), reply);
1691 synchronized (knownReplies) {
1692 eventBus.post(new NewPostReplyFoundEvent(reply));
1694 sone.addReply(reply);
1695 touchConfiguration();
1696 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1703 markReplyKnown(reply);
1705 }, "Mark " + reply + " read.");
1710 * Deletes the given reply.
1713 * The reply to delete
1715 public void deleteReply(PostReply reply) {
1716 Sone sone = reply.getSone();
1717 if (!sone.isLocal()) {
1718 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1721 synchronized (replies) {
1722 replies.remove(reply.getId());
1724 synchronized (knownReplies) {
1725 markReplyKnown(reply);
1726 knownReplies.remove(reply.getId());
1728 sone.removeReply(reply);
1729 touchConfiguration();
1733 * Marks the given reply as known, if it is currently not a known reply
1734 * (according to {@link Reply#isKnown()}).
1737 * The reply to mark as known
1739 public void markReplyKnown(PostReply reply) {
1740 reply.setKnown(true);
1741 synchronized (knownReplies) {
1742 eventBus.post(new MarkPostReplyKnownEvent(reply));
1743 if (knownReplies.add(reply.getId())) {
1744 touchConfiguration();
1750 * Creates a new top-level album for the given Sone.
1753 * The Sone to create the album for
1754 * @return The new album
1756 public Album createAlbum(Sone sone) {
1757 return createAlbum(sone, null);
1761 * Creates a new album for the given Sone.
1764 * The Sone to create the album for
1766 * The parent of the album (may be {@code null} to create a
1768 * @return The new album
1770 public Album createAlbum(Sone sone, Album parent) {
1771 Album album = new Album();
1772 synchronized (albums) {
1773 albums.put(album.getId(), album);
1775 album.setSone(sone);
1776 if (parent != null) {
1777 parent.addAlbum(album);
1779 sone.addAlbum(album);
1785 * Deletes the given album. The owner of the album has to be a local Sone,
1786 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1789 * The album to remove
1791 public void deleteAlbum(Album album) {
1792 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1793 if (!album.isEmpty()) {
1796 if (album.getParent() == null) {
1797 album.getSone().removeAlbum(album);
1799 album.getParent().removeAlbum(album);
1801 synchronized (albums) {
1802 albums.remove(album.getId());
1804 touchConfiguration();
1808 * Creates a new image.
1811 * The Sone creating the image
1813 * The album the image will be inserted into
1814 * @param temporaryImage
1815 * The temporary image to create the image from
1816 * @return The newly created image
1818 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1819 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();
1820 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1821 album.addImage(image);
1822 synchronized (images) {
1823 images.put(image.getId(), image);
1825 imageInserter.insertImage(temporaryImage, image);
1830 * Deletes the given image. This method will also delete a matching
1833 * @see #deleteTemporaryImage(TemporaryImage)
1835 * The image to delete
1837 public void deleteImage(Image image) {
1838 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1839 deleteTemporaryImage(image.getId());
1840 image.getAlbum().removeImage(image);
1841 synchronized (images) {
1842 images.remove(image.getId());
1844 touchConfiguration();
1848 * Creates a new temporary image.
1851 * The MIME type of the temporary image
1853 * The encoded data of the image
1854 * @return The temporary image
1856 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1857 TemporaryImage temporaryImage = new TemporaryImage();
1858 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1859 synchronized (temporaryImages) {
1860 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1862 return temporaryImage;
1866 * Deletes the given temporary image.
1868 * @param temporaryImage
1869 * The temporary image to delete
1871 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1872 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1873 deleteTemporaryImage(temporaryImage.getId());
1877 * Deletes the temporary image with the given ID.
1880 * The ID of the temporary image to delete
1882 public void deleteTemporaryImage(String imageId) {
1883 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1884 synchronized (temporaryImages) {
1885 temporaryImages.remove(imageId);
1887 Image image = getImage(imageId, false);
1888 if (image != null) {
1889 imageInserter.cancelImageInsert(image);
1894 * Notifies the core that the configuration, either of the core or of a
1895 * single local Sone, has changed, and that the configuration should be
1898 public void touchConfiguration() {
1899 lastConfigurationUpdate = System.currentTimeMillis();
1910 public void serviceStart() {
1911 loadConfiguration();
1912 updateChecker.addUpdateListener(this);
1913 updateChecker.start();
1914 identityManager.addIdentityListener(this);
1915 identityManager.start();
1916 webOfTrustUpdater.init();
1917 webOfTrustUpdater.start();
1924 public void serviceRun() {
1925 long lastSaved = System.currentTimeMillis();
1926 while (!shouldStop()) {
1928 long now = System.currentTimeMillis();
1929 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1930 for (Sone localSone : getLocalSones()) {
1931 saveSone(localSone);
1933 saveConfiguration();
1943 public void serviceStop() {
1944 synchronized (sones) {
1945 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1946 soneInserter.getValue().removeSoneInsertListener(this);
1947 soneInserter.getValue().stop();
1948 saveSone(soneInserter.getKey());
1951 saveConfiguration();
1952 webOfTrustUpdater.stop();
1953 updateChecker.stop();
1954 updateChecker.removeUpdateListener(this);
1955 soneDownloader.stop();
1956 identityManager.removeIdentityListener(this);
1957 identityManager.stop();
1965 * Saves the given Sone. This will persist all local settings for the given
1966 * Sone, such as the friends list and similar, private options.
1971 private synchronized void saveSone(Sone sone) {
1972 if (!sone.isLocal()) {
1973 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1976 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1977 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1981 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1983 /* save Sone into configuration. */
1984 String sonePrefix = "Sone/" + sone.getId();
1985 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1986 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1989 Profile profile = sone.getProfile();
1990 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1991 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1992 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1993 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1994 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1995 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1996 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1998 /* save profile fields. */
1999 int fieldCounter = 0;
2000 for (Field profileField : profile.getFields()) {
2001 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2002 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2003 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2005 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2008 int postCounter = 0;
2009 for (Post post : sone.getPosts()) {
2010 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2011 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2012 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2013 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2014 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2016 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2019 int replyCounter = 0;
2020 for (PostReply reply : sone.getReplies()) {
2021 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2022 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2023 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2024 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2025 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2027 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2029 /* save post likes. */
2030 int postLikeCounter = 0;
2031 for (String postId : sone.getLikedPostIds()) {
2032 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2034 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2036 /* save reply likes. */
2037 int replyLikeCounter = 0;
2038 for (String replyId : sone.getLikedReplyIds()) {
2039 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2041 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2044 int friendCounter = 0;
2045 for (String friendId : sone.getFriends()) {
2046 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2048 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2050 /* save albums. first, collect in a flat structure, top-level first. */
2051 List<Album> albums = sone.getAllAlbums();
2053 int albumCounter = 0;
2054 for (Album album : albums) {
2055 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2056 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2057 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2058 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2059 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2060 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2062 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2065 int imageCounter = 0;
2066 for (Album album : albums) {
2067 for (Image image : album.getImages()) {
2068 if (!image.isInserted()) {
2071 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2072 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2073 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2074 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2075 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2076 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2077 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2078 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2079 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2082 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2085 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2086 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2087 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2088 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2089 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2090 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2092 configuration.save();
2094 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2096 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2097 } catch (ConfigurationException ce1) {
2098 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2103 * Saves the current options.
2105 private void saveConfiguration() {
2106 synchronized (configuration) {
2107 if (storingConfiguration) {
2108 logger.log(Level.FINE, "Already storing configuration…");
2111 storingConfiguration = true;
2114 /* store the options first. */
2116 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2117 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2118 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2119 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2120 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2121 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2122 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2123 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2124 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2125 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2126 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2127 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2129 /* save known Sones. */
2130 int soneCounter = 0;
2131 synchronized (knownSones) {
2132 for (String knownSoneId : knownSones) {
2133 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2135 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2138 /* save Sone following times. */
2140 synchronized (soneFollowingTimes) {
2141 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2142 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2143 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2146 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2149 /* save known posts. */
2150 int postCounter = 0;
2151 synchronized (knownPosts) {
2152 for (String knownPostId : knownPosts) {
2153 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2155 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2158 /* save known replies. */
2159 int replyCounter = 0;
2160 synchronized (knownReplies) {
2161 for (String knownReplyId : knownReplies) {
2162 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2164 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2167 /* save bookmarked posts. */
2168 int bookmarkedPostCounter = 0;
2169 synchronized (bookmarkedPosts) {
2170 for (String bookmarkedPostId : bookmarkedPosts) {
2171 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2174 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2177 configuration.save();
2179 } catch (ConfigurationException ce1) {
2180 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2182 synchronized (configuration) {
2183 storingConfiguration = false;
2189 * Loads the configuration.
2191 @SuppressWarnings("unchecked")
2192 private void loadConfiguration() {
2193 /* create options. */
2194 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2197 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2198 SoneInserter.setInsertionDelay(newValue);
2202 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2203 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2204 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2205 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2206 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2207 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2208 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2209 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2210 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2213 @SuppressWarnings("synthetic-access")
2214 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2215 fcpInterface.setActive(newValue);
2218 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2221 @SuppressWarnings("synthetic-access")
2222 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2223 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2228 loadConfigurationValue("InsertionDelay");
2229 loadConfigurationValue("PostsPerPage");
2230 loadConfigurationValue("ImagesPerPage");
2231 loadConfigurationValue("CharactersPerPost");
2232 loadConfigurationValue("PostCutOffLength");
2233 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2234 loadConfigurationValue("PositiveTrust");
2235 loadConfigurationValue("NegativeTrust");
2236 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2237 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2238 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2240 /* load known Sones. */
2241 int soneCounter = 0;
2243 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2244 if (knownSoneId == null) {
2247 synchronized (knownSones) {
2248 knownSones.add(knownSoneId);
2252 /* load Sone following times. */
2255 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2256 if (soneId == null) {
2259 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2260 Sone followedSone = getSone(soneId);
2261 if (followedSone == null) {
2262 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2264 synchronized (soneFollowingTimes) {
2265 soneFollowingTimes.put(getSone(soneId), time);
2271 /* load known posts. */
2272 int postCounter = 0;
2274 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2275 if (knownPostId == null) {
2278 synchronized (knownPosts) {
2279 knownPosts.add(knownPostId);
2283 /* load known replies. */
2284 int replyCounter = 0;
2286 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2287 if (knownReplyId == null) {
2290 synchronized (knownReplies) {
2291 knownReplies.add(knownReplyId);
2295 /* load bookmarked posts. */
2296 int bookmarkedPostCounter = 0;
2298 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2299 if (bookmarkedPostId == null) {
2302 synchronized (bookmarkedPosts) {
2303 bookmarkedPosts.add(bookmarkedPostId);
2310 * Loads an {@link Integer} configuration value for the option with the
2311 * given name, logging validation failures.
2314 * The name of the option to load
2316 private void loadConfigurationValue(String optionName) {
2318 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2319 } catch (IllegalArgumentException iae1) {
2320 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2325 * Generate a Sone URI from the given URI and latest edition.
2328 * The URI to derive the Sone URI from
2329 * @return The derived URI
2331 private static FreenetURI getSoneUri(String uriString) {
2333 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2335 } catch (MalformedURLException mue1) {
2336 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2342 // INTERFACE IdentityListener
2349 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2350 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2351 if (ownIdentity.hasContext("Sone")) {
2352 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2353 addLocalSone(ownIdentity);
2361 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2362 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2363 trustedIdentities.remove(ownIdentity);
2370 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2371 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2372 trustedIdentities.get(ownIdentity).add(identity);
2373 addRemoteSone(identity);
2380 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2381 soneDownloaders.execute(new Runnable() {
2384 @SuppressWarnings("synthetic-access")
2386 Sone sone = getRemoteSone(identity.getId(), false);
2387 sone.setIdentity(identity);
2388 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2389 soneDownloader.addSone(sone);
2390 soneDownloader.fetchSone(sone);
2399 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2400 trustedIdentities.get(ownIdentity).remove(identity);
2401 boolean foundIdentity = false;
2402 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2403 if (trustedIdentity.getKey().equals(ownIdentity)) {
2406 if (trustedIdentity.getValue().contains(identity)) {
2407 foundIdentity = true;
2410 if (foundIdentity) {
2411 /* some local identity still trusts this identity, don’t remove. */
2414 Sone sone = getSone(identity.getId(), false);
2416 /* TODO - we don’t have the Sone anymore. should this happen? */
2419 synchronized (posts) {
2420 synchronized (knownPosts) {
2421 for (Post post : sone.getPosts()) {
2422 posts.remove(post.getId());
2423 eventBus.post(new PostRemovedEvent(post));
2427 synchronized (replies) {
2428 synchronized (knownReplies) {
2429 for (PostReply reply : sone.getReplies()) {
2430 replies.remove(reply.getId());
2431 coreListenerManager.fireReplyRemoved(reply);
2435 synchronized (sones) {
2436 sones.remove(identity.getId());
2438 eventBus.post(new SoneRemovedEvent(sone));
2442 // INTERFACE UpdateListener
2449 public void updateFound(Version version, long releaseTime, long latestEdition) {
2450 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2454 // INTERFACE ImageInsertListener
2461 public void insertStarted(Sone sone) {
2462 coreListenerManager.fireSoneInserting(sone);
2469 public void insertFinished(Sone sone, long insertDuration) {
2470 coreListenerManager.fireSoneInserted(sone, insertDuration);
2477 public void insertAborted(Sone sone, Throwable cause) {
2478 coreListenerManager.fireSoneInsertAborted(sone, cause);
2482 // SONEINSERTLISTENER METHODS
2489 public void imageInsertStarted(Image image) {
2490 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2491 coreListenerManager.fireImageInsertStarted(image);
2498 public void imageInsertAborted(Image image) {
2499 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2500 coreListenerManager.fireImageInsertAborted(image);
2507 public void imageInsertFinished(Image image, FreenetURI key) {
2508 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2509 image.setKey(key.toString());
2510 deleteTemporaryImage(image.getId());
2511 touchConfiguration();
2512 coreListenerManager.fireImageInsertFinished(image);
2519 public void imageInsertFailed(Image image, Throwable cause) {
2520 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2521 coreListenerManager.fireImageInsertFailed(image, cause);
2525 * Convenience interface for external classes that want to access the core’s
2528 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2530 public static class Preferences {
2532 /** The wrapped options. */
2533 private final Options options;
2536 * Creates a new preferences object wrapped around the given options.
2539 * The options to wrap
2541 public Preferences(Options options) {
2542 this.options = options;
2546 * Returns the insertion delay.
2548 * @return The insertion delay
2550 public int getInsertionDelay() {
2551 return options.getIntegerOption("InsertionDelay").get();
2555 * Validates the given insertion delay.
2557 * @param insertionDelay
2558 * The insertion delay to validate
2559 * @return {@code true} if the given insertion delay was valid,
2560 * {@code false} otherwise
2562 public boolean validateInsertionDelay(Integer insertionDelay) {
2563 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2567 * Sets the insertion delay
2569 * @param insertionDelay
2570 * The new insertion delay, or {@code null} to restore it to
2572 * @return This preferences
2574 public Preferences setInsertionDelay(Integer insertionDelay) {
2575 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2580 * Returns the number of posts to show per page.
2582 * @return The number of posts to show per page
2584 public int getPostsPerPage() {
2585 return options.getIntegerOption("PostsPerPage").get();
2589 * Validates the number of posts per page.
2591 * @param postsPerPage
2592 * The number of posts per page
2593 * @return {@code true} if the number of posts per page was valid,
2594 * {@code false} otherwise
2596 public boolean validatePostsPerPage(Integer postsPerPage) {
2597 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2601 * Sets the number of posts to show per page.
2603 * @param postsPerPage
2604 * The number of posts to show per page
2605 * @return This preferences object
2607 public Preferences setPostsPerPage(Integer postsPerPage) {
2608 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2613 * Returns the number of images to show per page.
2615 * @return The number of images to show per page
2617 public int getImagesPerPage() {
2618 return options.getIntegerOption("ImagesPerPage").get();
2622 * Validates the number of images per page.
2624 * @param imagesPerPage
2625 * The number of images per page
2626 * @return {@code true} if the number of images per page was valid,
2627 * {@code false} otherwise
2629 public boolean validateImagesPerPage(Integer imagesPerPage) {
2630 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2634 * Sets the number of images per page.
2636 * @param imagesPerPage
2637 * The number of images per page
2638 * @return This preferences object
2640 public Preferences setImagesPerPage(Integer imagesPerPage) {
2641 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2646 * Returns the number of characters per post, or <code>-1</code> if the
2647 * posts should not be cut off.
2649 * @return The numbers of characters per post
2651 public int getCharactersPerPost() {
2652 return options.getIntegerOption("CharactersPerPost").get();
2656 * Validates the number of characters per post.
2658 * @param charactersPerPost
2659 * The number of characters per post
2660 * @return {@code true} if the number of characters per post was valid,
2661 * {@code false} otherwise
2663 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2664 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2668 * Sets the number of characters per post.
2670 * @param charactersPerPost
2671 * The number of characters per post, or <code>-1</code> to
2672 * not cut off the posts
2673 * @return This preferences objects
2675 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2676 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2681 * Returns the number of characters the shortened post should have.
2683 * @return The number of characters of the snippet
2685 public int getPostCutOffLength() {
2686 return options.getIntegerOption("PostCutOffLength").get();
2690 * Validates the number of characters after which to cut off the post.
2692 * @param postCutOffLength
2693 * The number of characters of the snippet
2694 * @return {@code true} if the number of characters of the snippet is
2695 * valid, {@code false} otherwise
2697 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2698 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2702 * Sets the number of characters the shortened post should have.
2704 * @param postCutOffLength
2705 * The number of characters of the snippet
2706 * @return This preferences
2708 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2709 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2714 * Returns whether Sone requires full access to be even visible.
2716 * @return {@code true} if Sone requires full access, {@code false}
2719 public boolean isRequireFullAccess() {
2720 return options.getBooleanOption("RequireFullAccess").get();
2724 * Sets whether Sone requires full access to be even visible.
2726 * @param requireFullAccess
2727 * {@code true} if Sone requires full access, {@code false}
2730 public void setRequireFullAccess(Boolean requireFullAccess) {
2731 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2735 * Returns the positive trust.
2737 * @return The positive trust
2739 public int getPositiveTrust() {
2740 return options.getIntegerOption("PositiveTrust").get();
2744 * Validates the positive trust.
2746 * @param positiveTrust
2747 * The positive trust to validate
2748 * @return {@code true} if the positive trust was valid, {@code false}
2751 public boolean validatePositiveTrust(Integer positiveTrust) {
2752 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2756 * Sets the positive trust.
2758 * @param positiveTrust
2759 * The new positive trust, or {@code null} to restore it to
2761 * @return This preferences
2763 public Preferences setPositiveTrust(Integer positiveTrust) {
2764 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2769 * Returns the negative trust.
2771 * @return The negative trust
2773 public int getNegativeTrust() {
2774 return options.getIntegerOption("NegativeTrust").get();
2778 * Validates the negative trust.
2780 * @param negativeTrust
2781 * The negative trust to validate
2782 * @return {@code true} if the negative trust was valid, {@code false}
2785 public boolean validateNegativeTrust(Integer negativeTrust) {
2786 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2790 * Sets the negative trust.
2792 * @param negativeTrust
2793 * The negative trust, or {@code null} to restore it to the
2795 * @return The preferences
2797 public Preferences setNegativeTrust(Integer negativeTrust) {
2798 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2803 * Returns the trust comment. This is the comment that is set in the web
2804 * of trust when a trust value is assigned to an identity.
2806 * @return The trust comment
2808 public String getTrustComment() {
2809 return options.getStringOption("TrustComment").get();
2813 * Sets the trust comment.
2815 * @param trustComment
2816 * The trust comment, or {@code null} to restore it to the
2818 * @return This preferences
2820 public Preferences setTrustComment(String trustComment) {
2821 options.getStringOption("TrustComment").set(trustComment);
2826 * Returns whether the {@link FcpInterface FCP interface} is currently
2829 * @see FcpInterface#setActive(boolean)
2830 * @return {@code true} if the FCP interface is currently active,
2831 * {@code false} otherwise
2833 public boolean isFcpInterfaceActive() {
2834 return options.getBooleanOption("ActivateFcpInterface").get();
2838 * Sets whether the {@link FcpInterface FCP interface} is currently
2841 * @see FcpInterface#setActive(boolean)
2842 * @param fcpInterfaceActive
2843 * {@code true} to activate the FCP interface, {@code false}
2844 * to deactivate the FCP interface
2845 * @return This preferences object
2847 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2848 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2853 * Returns the action level for which full access to the FCP interface
2856 * @return The action level for which full access to the FCP interface
2859 public FullAccessRequired getFcpFullAccessRequired() {
2860 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2864 * Sets the action level for which full access to the FCP interface is
2867 * @param fcpFullAccessRequired
2869 * @return This preferences
2871 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2872 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);