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.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Profile.Field;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.data.TemporaryImage;
49 import net.pterodactylus.sone.data.impl.PostImpl;
50 import net.pterodactylus.sone.fcp.FcpInterface;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.sone.freenet.wot.IdentityListener;
54 import net.pterodactylus.sone.freenet.wot.IdentityManager;
55 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
56 import net.pterodactylus.sone.freenet.wot.Trust;
57 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
58 import net.pterodactylus.sone.main.SonePlugin;
59 import net.pterodactylus.util.config.Configuration;
60 import net.pterodactylus.util.config.ConfigurationException;
61 import net.pterodactylus.util.logging.Logging;
62 import net.pterodactylus.util.number.Numbers;
63 import net.pterodactylus.util.service.AbstractService;
64 import net.pterodactylus.util.thread.Ticker;
65 import net.pterodactylus.util.validation.EqualityValidator;
66 import net.pterodactylus.util.validation.IntegerRangeValidator;
67 import net.pterodactylus.util.validation.OrValidator;
68 import net.pterodactylus.util.validation.Validation;
69 import net.pterodactylus.util.version.Version;
70 import freenet.keys.FreenetURI;
75 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
80 private static final Logger logger = Logging.getLogger(Core.class);
83 private final Options options = new Options();
85 /** The preferences. */
86 private final Preferences preferences = new Preferences(options);
88 /** The core listener manager. */
89 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
91 /** The configuration. */
92 private Configuration configuration;
94 /** Whether we’re currently saving the configuration. */
95 private boolean storingConfiguration = false;
97 /** The identity manager. */
98 private final IdentityManager identityManager;
100 /** Interface to freenet. */
101 private final FreenetInterface freenetInterface;
103 /** The Sone downloader. */
104 private final SoneDownloader soneDownloader;
106 /** The image inserter. */
107 private final ImageInserter imageInserter;
109 /** Sone downloader thread-pool. */
110 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
112 /** The update checker. */
113 private final UpdateChecker updateChecker;
115 /** The trust updater. */
116 private final WebOfTrustUpdater webOfTrustUpdater;
118 /** The FCP interface. */
119 private volatile FcpInterface fcpInterface;
121 /** The times Sones were followed. */
122 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
124 /** Locked local Sones. */
125 /* synchronize on itself. */
126 private final Set<Sone> lockedSones = new HashSet<Sone>();
128 /** Sone inserters. */
129 /* synchronize access on this on localSones. */
130 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
132 /** Sone rescuers. */
133 /* synchronize access on this on localSones. */
134 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
136 /** All local Sones. */
137 /* synchronize access on this on itself. */
138 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
140 /** All remote Sones. */
141 /* synchronize access on this on itself. */
142 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
144 /** All known Sones. */
145 private final Set<String> knownSones = new HashSet<String>();
148 private final Map<String, Post> posts = new HashMap<String, Post>();
150 /** All known posts. */
151 private final Set<String> knownPosts = new HashSet<String>();
154 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
156 /** All known replies. */
157 private final Set<String> knownReplies = new HashSet<String>();
159 /** All bookmarked posts. */
160 /* synchronize access on itself. */
161 private final Set<String> bookmarkedPosts = new HashSet<String>();
163 /** Trusted identities, sorted by own identities. */
164 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
166 /** All known albums. */
167 private final Map<String, Album> albums = new HashMap<String, Album>();
169 /** All known images. */
170 private final Map<String, Image> images = new HashMap<String, Image>();
172 /** All temporary images. */
173 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
175 /** Ticker for threads that mark own elements as known. */
176 private final Ticker localElementTicker = new Ticker();
178 /** The time the configuration was last touched. */
179 private volatile long lastConfigurationUpdate;
182 * Creates a new core.
184 * @param configuration
185 * The configuration of the core
186 * @param freenetInterface
187 * The freenet interface
188 * @param identityManager
189 * The identity manager
190 * @param webOfTrustUpdater
191 * The WebOfTrust updater
193 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
195 this.configuration = configuration;
196 this.freenetInterface = freenetInterface;
197 this.identityManager = identityManager;
198 this.soneDownloader = new SoneDownloader(this, freenetInterface);
199 this.imageInserter = new ImageInserter(this, freenetInterface);
200 this.updateChecker = new UpdateChecker(freenetInterface);
201 this.webOfTrustUpdater = webOfTrustUpdater;
205 // LISTENER MANAGEMENT
209 * Adds a new core listener.
211 * @param coreListener
212 * The listener to add
214 public void addCoreListener(CoreListener coreListener) {
215 coreListenerManager.addListener(coreListener);
219 * Removes a core listener.
221 * @param coreListener
222 * The listener to remove
224 public void removeCoreListener(CoreListener coreListener) {
225 coreListenerManager.removeListener(coreListener);
233 * Sets the configuration to use. This will automatically save the current
234 * configuration to the given configuration.
236 * @param configuration
237 * The new configuration to use
239 public void setConfiguration(Configuration configuration) {
240 this.configuration = configuration;
241 touchConfiguration();
245 * Returns the options used by the core.
247 * @return The options of the core
249 public Preferences getPreferences() {
254 * Returns the identity manager used by the core.
256 * @return The identity manager
258 public IdentityManager getIdentityManager() {
259 return identityManager;
263 * Returns the update checker.
265 * @return The update checker
267 public UpdateChecker getUpdateChecker() {
268 return updateChecker;
272 * Sets the FCP interface to use.
274 * @param fcpInterface
275 * The FCP interface to use
277 public void setFcpInterface(FcpInterface fcpInterface) {
278 this.fcpInterface = fcpInterface;
282 * Returns the Sone rescuer for the given local Sone.
285 * The local Sone to get the rescuer for
286 * @return The Sone rescuer for the given Sone
288 public SoneRescuer getSoneRescuer(Sone sone) {
289 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
290 synchronized (localSones) {
291 SoneRescuer soneRescuer = soneRescuers.get(sone);
292 if (soneRescuer == null) {
293 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
294 soneRescuers.put(sone, soneRescuer);
302 * Returns whether the given Sone is currently locked.
306 * @return {@code true} if the Sone is locked, {@code false} if it is not
308 public boolean isLocked(Sone sone) {
309 synchronized (lockedSones) {
310 return lockedSones.contains(sone);
315 * Returns all Sones, remote and local.
319 public Set<Sone> getSones() {
320 Set<Sone> allSones = new HashSet<Sone>();
321 allSones.addAll(getLocalSones());
322 allSones.addAll(getRemoteSones());
327 * Returns the Sone with the given ID, regardless whether it’s local or
331 * The ID of the Sone to get
332 * @return The Sone with the given ID, or {@code null} if there is no such
335 public Sone getSone(String id) {
336 return getSone(id, true);
340 * Returns the Sone with the given ID, regardless whether it’s local or
344 * The ID of the Sone to get
346 * {@code true} to create a new Sone if none exists,
347 * {@code false} to return {@code null} if a Sone with the given
349 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Sone getSone(String id, boolean create) {
354 if (isLocalSone(id)) {
355 return getLocalSone(id);
357 return getRemoteSone(id, create);
361 * Checks whether the core knows a Sone with the given ID.
365 * @return {@code true} if there is a Sone with the given ID, {@code false}
368 public boolean hasSone(String id) {
369 return isLocalSone(id) || isRemoteSone(id);
373 * Returns whether the given Sone is a local Sone.
376 * The Sone to check for its locality
377 * @return {@code true} if the given Sone is local, {@code false} otherwise
379 public boolean isLocalSone(Sone sone) {
380 synchronized (localSones) {
381 return localSones.containsKey(sone.getId());
386 * Returns whether the given ID is the ID of a local Sone.
389 * The Sone ID to check for its locality
390 * @return {@code true} if the given ID is a local Sone, {@code false}
393 public boolean isLocalSone(String id) {
394 synchronized (localSones) {
395 return localSones.containsKey(id);
400 * Returns all local Sones.
402 * @return All local Sones
404 public Set<Sone> getLocalSones() {
405 synchronized (localSones) {
406 return new HashSet<Sone>(localSones.values());
411 * Returns the local Sone with the given ID.
414 * The ID of the Sone to get
415 * @return The Sone with the given ID
417 public Sone getLocalSone(String id) {
418 return getLocalSone(id, true);
422 * Returns the local Sone with the given ID, optionally creating a new Sone.
427 * {@code true} to create a new Sone if none exists,
428 * {@code false} to return null if none exists
429 * @return The Sone with the given ID, or {@code null}
431 public Sone getLocalSone(String id, boolean create) {
432 synchronized (localSones) {
433 Sone sone = localSones.get(id);
434 if ((sone == null) && create) {
436 localSones.put(id, sone);
443 * Returns all remote Sones.
445 * @return All remote Sones
447 public Set<Sone> getRemoteSones() {
448 synchronized (remoteSones) {
449 return new HashSet<Sone>(remoteSones.values());
454 * Returns the remote Sone with the given ID.
457 * The ID of the remote Sone to get
459 * {@code true} to always create a Sone, {@code false} to return
460 * {@code null} if no Sone with the given ID exists
461 * @return The Sone with the given ID
463 public Sone getRemoteSone(String id, boolean create) {
464 synchronized (remoteSones) {
465 Sone sone = remoteSones.get(id);
466 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
468 remoteSones.put(id, sone);
475 * Returns whether the given Sone is a remote Sone.
479 * @return {@code true} if the given Sone is a remote Sone, {@code false}
482 public boolean isRemoteSone(Sone sone) {
483 synchronized (remoteSones) {
484 return remoteSones.containsKey(sone.getId());
489 * Returns whether the Sone with the given ID is a remote Sone.
492 * The ID of the Sone to check
493 * @return {@code true} if the Sone with the given ID is a remote Sone,
494 * {@code false} otherwise
496 public boolean isRemoteSone(String id) {
497 synchronized (remoteSones) {
498 return remoteSones.containsKey(id);
503 * Returns whether the given Sone has been modified.
506 * The Sone to check for modifications
507 * @return {@code true} if a modification has been detected in the Sone,
508 * {@code false} otherwise
510 public boolean isModifiedSone(Sone sone) {
511 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
515 * Returns the time when the given was first followed by any local Sone.
518 * The Sone to get the time for
519 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
520 * been followed, or {@link Long#MAX_VALUE}
522 public long getSoneFollowingTime(Sone sone) {
523 synchronized (soneFollowingTimes) {
524 if (soneFollowingTimes.containsKey(sone)) {
525 return soneFollowingTimes.get(sone);
527 return Long.MAX_VALUE;
532 * Returns whether the target Sone is trusted by the origin Sone.
538 * @return {@code true} if the target Sone is trusted by the origin Sone
540 public boolean isSoneTrusted(Sone origin, Sone target) {
541 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
542 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
546 * Returns the post with the given ID.
549 * The ID of the post to get
550 * @return The post with the given ID, or a new post with the given ID
552 public Post getPost(String postId) {
553 return getPost(postId, true);
557 * Returns the post with the given ID, optionally creating a new post.
560 * The ID of the post to get
562 * {@code true} it create a new post if no post with the given ID
563 * exists, {@code false} to return {@code null}
564 * @return The post, or {@code null} if there is no such post
567 public Post getPost(String postId, boolean create) {
568 synchronized (posts) {
569 Post post = posts.get(postId);
570 if ((post == null) && create) {
571 post = new PostImpl(postId);
572 posts.put(postId, post);
579 * Returns all posts that have the given Sone as recipient.
581 * @see Post#getRecipient()
583 * The recipient of the posts
584 * @return All posts that have the given Sone as recipient
586 public Set<Post> getDirectedPosts(Sone recipient) {
587 Validation.begin().isNotNull("Recipient", recipient).check();
588 Set<Post> directedPosts = new HashSet<Post>();
589 synchronized (posts) {
590 for (Post post : posts.values()) {
591 if (recipient.equals(post.getRecipient())) {
592 directedPosts.add(post);
596 return directedPosts;
600 * Returns the reply with the given ID. If there is no reply with the given
601 * ID yet, a new one is created.
604 * The ID of the reply to get
607 public PostReply getReply(String replyId) {
608 return getReply(replyId, true);
612 * Returns the reply with the given ID. If there is no reply with the given
613 * ID yet, a new one is created, unless {@code create} is false in which
614 * case {@code null} is returned.
617 * The ID of the reply to get
619 * {@code true} to always return a {@link Reply}, {@code false}
620 * to return {@code null} if no reply can be found
621 * @return The reply, or {@code null} if there is no such reply
623 public PostReply getReply(String replyId, boolean create) {
624 synchronized (replies) {
625 PostReply reply = replies.get(replyId);
626 if (create && (reply == null)) {
627 reply = new PostReply(replyId);
628 replies.put(replyId, reply);
635 * Returns all replies for the given post, order ascending by time.
638 * The post to get all replies for
639 * @return All replies for the given post
641 public List<PostReply> getReplies(Post post) {
642 Set<Sone> sones = getSones();
643 List<PostReply> replies = new ArrayList<PostReply>();
644 for (Sone sone : sones) {
645 for (PostReply reply : sone.getReplies()) {
646 if (reply.getPost().equals(post)) {
651 Collections.sort(replies, Reply.TIME_COMPARATOR);
656 * Returns all Sones that have liked the given post.
659 * The post to get the liking Sones for
660 * @return The Sones that like the given post
662 public Set<Sone> getLikes(Post post) {
663 Set<Sone> sones = new HashSet<Sone>();
664 for (Sone sone : getSones()) {
665 if (sone.getLikedPostIds().contains(post.getId())) {
673 * Returns all Sones that have liked the given reply.
676 * The reply to get the liking Sones for
677 * @return The Sones that like the given reply
679 public Set<Sone> getLikes(PostReply reply) {
680 Set<Sone> sones = new HashSet<Sone>();
681 for (Sone sone : getSones()) {
682 if (sone.getLikedReplyIds().contains(reply.getId())) {
690 * Returns whether the given post is bookmarked.
694 * @return {@code true} if the given post is bookmarked, {@code false}
697 public boolean isBookmarked(Post post) {
698 return isPostBookmarked(post.getId());
702 * Returns whether the post with the given ID is bookmarked.
705 * The ID of the post to check
706 * @return {@code true} if the post with the given ID is bookmarked,
707 * {@code false} otherwise
709 public boolean isPostBookmarked(String id) {
710 synchronized (bookmarkedPosts) {
711 return bookmarkedPosts.contains(id);
716 * Returns all currently known bookmarked posts.
718 * @return All bookmarked posts
720 public Set<Post> getBookmarkedPosts() {
721 Set<Post> posts = new HashSet<Post>();
722 synchronized (bookmarkedPosts) {
723 for (String bookmarkedPostId : bookmarkedPosts) {
724 Post post = getPost(bookmarkedPostId, false);
734 * Returns the album with the given ID, creating a new album if no album
735 * with the given ID can be found.
738 * The ID of the album
739 * @return The album with the given ID
741 public Album getAlbum(String albumId) {
742 return getAlbum(albumId, true);
746 * Returns the album with the given ID, optionally creating a new album if
747 * an album with the given ID can not be found.
750 * The ID of the album
752 * {@code true} to create a new album if none exists for the
754 * @return The album with the given ID, or {@code null} if no album with the
755 * given ID exists and {@code create} is {@code false}
757 public Album getAlbum(String albumId, boolean create) {
758 synchronized (albums) {
759 Album album = albums.get(albumId);
760 if (create && (album == null)) {
761 album = new Album(albumId);
762 albums.put(albumId, album);
769 * Returns the image with the given ID, creating it if necessary.
772 * The ID of the image
773 * @return The image with the given ID
775 public Image getImage(String imageId) {
776 return getImage(imageId, true);
780 * Returns the image with the given ID, optionally creating it if it does
784 * The ID of the image
786 * {@code true} to create an image if none exists with the given
788 * @return The image with the given ID, or {@code null} if none exists and
791 public Image getImage(String imageId, boolean create) {
792 synchronized (images) {
793 Image image = images.get(imageId);
794 if (create && (image == null)) {
795 image = new Image(imageId);
796 images.put(imageId, image);
803 * Returns the temporary image with the given ID.
806 * The ID of the temporary image
807 * @return The temporary image, or {@code null} if there is no temporary
808 * image with the given ID
810 public TemporaryImage getTemporaryImage(String imageId) {
811 synchronized (temporaryImages) {
812 return temporaryImages.get(imageId);
821 * Locks the given Sone. A locked Sone will not be inserted by
822 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
828 public void lockSone(Sone sone) {
829 synchronized (lockedSones) {
830 if (lockedSones.add(sone)) {
831 coreListenerManager.fireSoneLocked(sone);
837 * Unlocks the given Sone.
839 * @see #lockSone(Sone)
843 public void unlockSone(Sone sone) {
844 synchronized (lockedSones) {
845 if (lockedSones.remove(sone)) {
846 coreListenerManager.fireSoneUnlocked(sone);
852 * Adds a local Sone from the given own identity.
855 * The own identity to create a Sone from
856 * @return The added (or already existing) Sone
858 public Sone addLocalSone(OwnIdentity ownIdentity) {
859 if (ownIdentity == null) {
860 logger.log(Level.WARNING, "Given OwnIdentity is null!");
863 synchronized (localSones) {
866 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
867 } catch (MalformedURLException mue1) {
868 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
871 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
872 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
874 /* TODO - load posts ’n stuff */
875 localSones.put(ownIdentity.getId(), sone);
876 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
877 soneInserter.addSoneInsertListener(this);
878 soneInserters.put(sone, soneInserter);
879 sone.setStatus(SoneStatus.idle);
881 soneInserter.start();
887 * Creates a new Sone for the given own identity.
890 * The own identity to create a Sone for
891 * @return The created Sone
893 public Sone createSone(OwnIdentity ownIdentity) {
895 ownIdentity.addContext("Sone");
896 } catch (WebOfTrustException wote1) {
897 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity), wote1);
900 Sone sone = addLocalSone(ownIdentity);
901 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
902 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
903 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
904 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
905 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
906 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
908 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
909 touchConfiguration();
914 * Adds the Sone of the given identity.
917 * The identity whose Sone to add
918 * @return The added or already existing Sone
920 public Sone addRemoteSone(Identity identity) {
921 if (identity == null) {
922 logger.log(Level.WARNING, "Given Identity is null!");
925 synchronized (remoteSones) {
926 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
927 boolean newSone = sone.getRequestUri() == null;
928 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
929 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
931 synchronized (knownSones) {
932 newSone = !knownSones.contains(sone.getId());
934 sone.setKnown(!newSone);
936 coreListenerManager.fireNewSoneFound(sone);
937 for (Sone localSone : getLocalSones()) {
938 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
939 followSone(localSone, sone);
944 soneDownloader.addSone(sone);
945 soneDownloaders.execute(new Runnable() {
948 @SuppressWarnings("synthetic-access")
950 soneDownloader.fetchSone(sone, sone.getRequestUri());
959 * Lets the given local Sone follow the Sone with the given ID.
962 * The local Sone that should follow another Sone
964 * The ID of the Sone to follow
966 public void followSone(Sone sone, String soneId) {
967 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
968 Sone followedSone = getSone(soneId, true);
969 if (followedSone == null) {
970 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
973 followSone(sone, getSone(soneId));
977 * Lets the given local Sone follow the other given Sone. If the given Sone
978 * was not followed by any local Sone before, this will mark all elements of
979 * the followed Sone as read that have been created before the current
983 * The local Sone that should follow the other Sone
984 * @param followedSone
985 * The Sone that should be followed
987 public void followSone(Sone sone, Sone followedSone) {
988 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
989 sone.addFriend(followedSone.getId());
990 synchronized (soneFollowingTimes) {
991 if (!soneFollowingTimes.containsKey(followedSone)) {
992 long now = System.currentTimeMillis();
993 soneFollowingTimes.put(followedSone, now);
994 for (Post post : followedSone.getPosts()) {
995 if (post.getTime() < now) {
999 for (PostReply reply : followedSone.getReplies()) {
1000 if (reply.getTime() < now) {
1001 markReplyKnown(reply);
1006 touchConfiguration();
1010 * Lets the given local Sone unfollow the Sone with the given ID.
1013 * The local Sone that should unfollow another Sone
1015 * The ID of the Sone being unfollowed
1017 public void unfollowSone(Sone sone, String soneId) {
1018 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1019 unfollowSone(sone, getSone(soneId, false));
1023 * Lets the given local Sone unfollow the other given Sone. If the given
1024 * local Sone is the last local Sone that followed the given Sone, its
1025 * following time will be removed.
1028 * The local Sone that should unfollow another Sone
1029 * @param unfollowedSone
1030 * The Sone being unfollowed
1032 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1033 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1034 sone.removeFriend(unfollowedSone.getId());
1035 boolean unfollowedSoneStillFollowed = false;
1036 for (Sone localSone : getLocalSones()) {
1037 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1039 if (!unfollowedSoneStillFollowed) {
1040 synchronized (soneFollowingTimes) {
1041 soneFollowingTimes.remove(unfollowedSone);
1044 touchConfiguration();
1048 * Retrieves the trust relationship from the origin to the target. If the
1049 * trust relationship can not be retrieved, {@code null} is returned.
1051 * @see Identity#getTrust(OwnIdentity)
1053 * The origin of the trust tree
1055 * The target of the trust
1056 * @return The trust relationship
1058 public Trust getTrust(Sone origin, Sone target) {
1059 if (!isLocalSone(origin)) {
1060 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
1063 webOfTrustUpdater.getTrust((OwnIdentity) origin.getIdentity(), target.getIdentity());
1064 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1068 * Sets the trust value of the given origin Sone for the target Sone.
1075 * The trust value (from {@code -100} to {@code 100})
1077 public void setTrust(Sone origin, Sone target, int trustValue) {
1078 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();
1079 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1083 * Removes any trust assignment for the given target Sone.
1090 public void removeTrust(Sone origin, Sone target) {
1091 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1092 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1096 * Assigns the configured positive trust value for the given target.
1103 public void trustSone(Sone origin, Sone target) {
1104 setTrust(origin, target, preferences.getPositiveTrust());
1108 * Assigns the configured negative trust value for the given target.
1115 public void distrustSone(Sone origin, Sone target) {
1116 setTrust(origin, target, preferences.getNegativeTrust());
1120 * Removes the trust assignment for the given target.
1127 public void untrustSone(Sone origin, Sone target) {
1128 removeTrust(origin, target);
1132 * Updates the stored Sone with the given Sone.
1137 public void updateSone(Sone sone) {
1138 updateSone(sone, false);
1142 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1143 * {@code true}, an older Sone than the current Sone can be given to restore
1147 * The Sone to update
1148 * @param soneRescueMode
1149 * {@code true} if the stored Sone should be updated regardless
1150 * of the age of the given Sone
1152 public void updateSone(Sone sone, boolean soneRescueMode) {
1153 if (hasSone(sone.getId())) {
1154 Sone storedSone = getSone(sone.getId());
1155 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1156 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1159 synchronized (posts) {
1160 if (!soneRescueMode) {
1161 for (Post post : storedSone.getPosts()) {
1162 posts.remove(post.getId());
1163 if (!sone.getPosts().contains(post)) {
1164 coreListenerManager.firePostRemoved(post);
1168 List<Post> storedPosts = storedSone.getPosts();
1169 synchronized (knownPosts) {
1170 for (Post post : sone.getPosts()) {
1171 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1172 if (!storedPosts.contains(post)) {
1173 if (post.getTime() < getSoneFollowingTime(sone)) {
1174 knownPosts.add(post.getId());
1175 } else if (!knownPosts.contains(post.getId())) {
1176 sone.setKnown(false);
1177 coreListenerManager.fireNewPostFound(post);
1180 posts.put(post.getId(), post);
1184 synchronized (replies) {
1185 if (!soneRescueMode) {
1186 for (PostReply reply : storedSone.getReplies()) {
1187 replies.remove(reply.getId());
1188 if (!sone.getReplies().contains(reply)) {
1189 coreListenerManager.fireReplyRemoved(reply);
1193 Set<PostReply> storedReplies = storedSone.getReplies();
1194 synchronized (knownReplies) {
1195 for (PostReply reply : sone.getReplies()) {
1196 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1197 if (!storedReplies.contains(reply)) {
1198 if (reply.getTime() < getSoneFollowingTime(sone)) {
1199 knownReplies.add(reply.getId());
1200 } else if (!knownReplies.contains(reply.getId())) {
1201 reply.setKnown(false);
1202 coreListenerManager.fireNewReplyFound(reply);
1205 replies.put(reply.getId(), reply);
1209 synchronized (albums) {
1210 synchronized (images) {
1211 for (Album album : storedSone.getAlbums()) {
1212 albums.remove(album.getId());
1213 for (Image image : album.getImages()) {
1214 images.remove(image.getId());
1217 for (Album album : sone.getAlbums()) {
1218 albums.put(album.getId(), album);
1219 for (Image image : album.getImages()) {
1220 images.put(image.getId(), image);
1225 synchronized (storedSone) {
1226 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1227 storedSone.setTime(sone.getTime());
1229 storedSone.setClient(sone.getClient());
1230 storedSone.setProfile(sone.getProfile());
1231 if (soneRescueMode) {
1232 for (Post post : sone.getPosts()) {
1233 storedSone.addPost(post);
1235 for (PostReply reply : sone.getReplies()) {
1236 storedSone.addReply(reply);
1238 for (String likedPostId : sone.getLikedPostIds()) {
1239 storedSone.addLikedPostId(likedPostId);
1241 for (String likedReplyId : sone.getLikedReplyIds()) {
1242 storedSone.addLikedReplyId(likedReplyId);
1244 for (Album album : sone.getAlbums()) {
1245 storedSone.addAlbum(album);
1248 storedSone.setPosts(sone.getPosts());
1249 storedSone.setReplies(sone.getReplies());
1250 storedSone.setLikePostIds(sone.getLikedPostIds());
1251 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1252 storedSone.setAlbums(sone.getAlbums());
1254 storedSone.setLatestEdition(sone.getLatestEdition());
1260 * Deletes the given Sone. This will remove the Sone from the
1261 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1262 * and remove the context from its identity.
1265 * The Sone to delete
1267 public void deleteSone(Sone sone) {
1268 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1269 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1272 synchronized (localSones) {
1273 if (!localSones.containsKey(sone.getId())) {
1274 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1277 localSones.remove(sone.getId());
1278 SoneInserter soneInserter = soneInserters.remove(sone);
1279 soneInserter.removeSoneInsertListener(this);
1280 soneInserter.stop();
1283 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1284 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1285 } catch (WebOfTrustException wote1) {
1286 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1289 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1290 } catch (ConfigurationException ce1) {
1291 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1296 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1297 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1300 * The Sone to mark as known
1302 public void markSoneKnown(Sone sone) {
1303 if (!sone.isKnown()) {
1304 sone.setKnown(true);
1305 synchronized (knownSones) {
1306 knownSones.add(sone.getId());
1308 coreListenerManager.fireMarkSoneKnown(sone);
1309 touchConfiguration();
1314 * Loads and updates the given Sone from the configuration. If any error is
1315 * encountered, loading is aborted and the given Sone is not changed.
1318 * The Sone to load and update
1320 public void loadSone(Sone sone) {
1321 if (!isLocalSone(sone)) {
1322 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1326 /* initialize options. */
1327 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1328 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1329 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1330 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1331 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1332 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1335 String sonePrefix = "Sone/" + sone.getId();
1336 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1337 if (soneTime == null) {
1338 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1341 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1344 Profile profile = new Profile(sone);
1345 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1346 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1347 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1348 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1349 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1350 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1352 /* load profile fields. */
1354 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1355 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1356 if (fieldName == null) {
1359 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1360 profile.addField(fieldName).setValue(fieldValue);
1364 Set<Post> posts = new HashSet<Post>();
1366 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1367 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1368 if (postId == null) {
1371 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1372 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1373 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1374 if ((postTime == 0) || (postText == null)) {
1375 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1378 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1379 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1380 post.setRecipient(getSone(postRecipientId));
1386 Set<PostReply> replies = new HashSet<PostReply>();
1388 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1389 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1390 if (replyId == null) {
1393 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1394 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1395 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1396 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1397 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1400 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1403 /* load post likes. */
1404 Set<String> likedPostIds = new HashSet<String>();
1406 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1407 if (likedPostId == null) {
1410 likedPostIds.add(likedPostId);
1413 /* load reply likes. */
1414 Set<String> likedReplyIds = new HashSet<String>();
1416 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1417 if (likedReplyId == null) {
1420 likedReplyIds.add(likedReplyId);
1424 Set<String> friends = new HashSet<String>();
1426 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1427 if (friendId == null) {
1430 friends.add(friendId);
1434 List<Album> topLevelAlbums = new ArrayList<Album>();
1435 int albumCounter = 0;
1437 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1438 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1439 if (albumId == null) {
1442 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1443 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1444 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1445 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1446 if ((albumTitle == null) || (albumDescription == null)) {
1447 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1450 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1451 if (albumParentId != null) {
1452 Album parentAlbum = getAlbum(albumParentId, false);
1453 if (parentAlbum == null) {
1454 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1457 parentAlbum.addAlbum(album);
1459 if (!topLevelAlbums.contains(album)) {
1460 topLevelAlbums.add(album);
1466 int imageCounter = 0;
1468 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1469 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1470 if (imageId == null) {
1473 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1474 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1475 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1476 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1477 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1478 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1479 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1480 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1481 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1484 Album album = getAlbum(albumId, false);
1485 if (album == null) {
1486 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1489 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1490 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1491 album.addImage(image);
1495 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1496 if (avatarId != null) {
1497 profile.setAvatar(getImage(avatarId, false));
1501 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1502 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1503 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1504 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1505 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1506 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1508 /* if we’re still here, Sone was loaded successfully. */
1509 synchronized (sone) {
1510 sone.setTime(soneTime);
1511 sone.setProfile(profile);
1512 sone.setPosts(posts);
1513 sone.setReplies(replies);
1514 sone.setLikePostIds(likedPostIds);
1515 sone.setLikeReplyIds(likedReplyIds);
1516 for (String friendId : friends) {
1517 followSone(sone, friendId);
1519 sone.setAlbums(topLevelAlbums);
1520 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1522 synchronized (knownSones) {
1523 for (String friend : friends) {
1524 knownSones.add(friend);
1527 synchronized (knownPosts) {
1528 for (Post post : posts) {
1529 knownPosts.add(post.getId());
1532 synchronized (knownReplies) {
1533 for (PostReply reply : replies) {
1534 knownReplies.add(reply.getId());
1540 * Creates a new post.
1543 * The Sone that creates the post
1545 * The text of the post
1546 * @return The created post
1548 public Post createPost(Sone sone, String text) {
1549 return createPost(sone, System.currentTimeMillis(), text);
1553 * Creates a new post.
1556 * The Sone that creates the post
1558 * The time of the post
1560 * The text of the post
1561 * @return The created post
1563 public Post createPost(Sone sone, long time, String text) {
1564 return createPost(sone, null, time, text);
1568 * Creates a new post.
1571 * The Sone that creates the post
1573 * The recipient Sone, or {@code null} if this post does not have
1576 * The text of the post
1577 * @return The created post
1579 public Post createPost(Sone sone, Sone recipient, String text) {
1580 return createPost(sone, recipient, System.currentTimeMillis(), text);
1584 * Creates a new post.
1587 * The Sone that creates the post
1589 * The recipient Sone, or {@code null} if this post does not have
1592 * The time of the post
1594 * The text of the post
1595 * @return The created post
1597 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1598 if (!isLocalSone(sone)) {
1599 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1602 final Post post = new PostImpl(sone, time, text);
1603 if (recipient != null) {
1604 post.setRecipient(recipient);
1606 synchronized (posts) {
1607 posts.put(post.getId(), post);
1609 coreListenerManager.fireNewPostFound(post);
1611 touchConfiguration();
1612 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1619 markPostKnown(post);
1621 }, "Mark " + post + " read.");
1626 * Deletes the given post.
1629 * The post to delete
1631 public void deletePost(Post post) {
1632 if (!isLocalSone(post.getSone())) {
1633 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1636 post.getSone().removePost(post);
1637 synchronized (posts) {
1638 posts.remove(post.getId());
1640 coreListenerManager.firePostRemoved(post);
1641 markPostKnown(post);
1642 touchConfiguration();
1646 * Marks the given post as known, if it is currently not a known post
1647 * (according to {@link Post#isKnown()}).
1650 * The post to mark as known
1652 public void markPostKnown(Post post) {
1653 post.setKnown(true);
1654 synchronized (knownPosts) {
1655 coreListenerManager.fireMarkPostKnown(post);
1656 if (knownPosts.add(post.getId())) {
1657 touchConfiguration();
1660 for (PostReply reply : getReplies(post)) {
1661 markReplyKnown(reply);
1666 * Bookmarks the given post.
1669 * The post to bookmark
1671 public void bookmark(Post post) {
1672 bookmarkPost(post.getId());
1676 * Bookmarks the post with the given ID.
1679 * The ID of the post to bookmark
1681 public void bookmarkPost(String id) {
1682 synchronized (bookmarkedPosts) {
1683 bookmarkedPosts.add(id);
1688 * Removes the given post from the bookmarks.
1691 * The post to unbookmark
1693 public void unbookmark(Post post) {
1694 unbookmarkPost(post.getId());
1698 * Removes the post with the given ID from the bookmarks.
1701 * The ID of the post to unbookmark
1703 public void unbookmarkPost(String id) {
1704 synchronized (bookmarkedPosts) {
1705 bookmarkedPosts.remove(id);
1710 * Creates a new reply.
1713 * The Sone that creates the reply
1715 * The post that this reply refers to
1717 * The text of the reply
1718 * @return The created reply
1720 public PostReply createReply(Sone sone, Post post, String text) {
1721 return createReply(sone, post, System.currentTimeMillis(), text);
1725 * Creates a new reply.
1728 * The Sone that creates the reply
1730 * The post that this reply refers to
1732 * The time of the reply
1734 * The text of the reply
1735 * @return The created reply
1737 public PostReply createReply(Sone sone, Post post, long time, String text) {
1738 if (!isLocalSone(sone)) {
1739 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1742 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1743 synchronized (replies) {
1744 replies.put(reply.getId(), reply);
1746 synchronized (knownReplies) {
1747 coreListenerManager.fireNewReplyFound(reply);
1749 sone.addReply(reply);
1750 touchConfiguration();
1751 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1758 markReplyKnown(reply);
1760 }, "Mark " + reply + " read.");
1765 * Deletes the given reply.
1768 * The reply to delete
1770 public void deleteReply(PostReply reply) {
1771 Sone sone = reply.getSone();
1772 if (!isLocalSone(sone)) {
1773 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1776 synchronized (replies) {
1777 replies.remove(reply.getId());
1779 synchronized (knownReplies) {
1780 markReplyKnown(reply);
1781 knownReplies.remove(reply.getId());
1783 sone.removeReply(reply);
1784 touchConfiguration();
1788 * Marks the given reply as known, if it is currently not a known reply
1789 * (according to {@link Reply#isKnown()}).
1792 * The reply to mark as known
1794 public void markReplyKnown(PostReply reply) {
1795 reply.setKnown(true);
1796 synchronized (knownReplies) {
1797 coreListenerManager.fireMarkReplyKnown(reply);
1798 if (knownReplies.add(reply.getId())) {
1799 touchConfiguration();
1805 * Creates a new top-level album for the given Sone.
1808 * The Sone to create the album for
1809 * @return The new album
1811 public Album createAlbum(Sone sone) {
1812 return createAlbum(sone, null);
1816 * Creates a new album for the given Sone.
1819 * The Sone to create the album for
1821 * The parent of the album (may be {@code null} to create a
1823 * @return The new album
1825 public Album createAlbum(Sone sone, Album parent) {
1826 Album album = new Album();
1827 synchronized (albums) {
1828 albums.put(album.getId(), album);
1830 album.setSone(sone);
1831 if (parent != null) {
1832 parent.addAlbum(album);
1834 sone.addAlbum(album);
1840 * Deletes the given album. The owner of the album has to be a local Sone,
1841 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1844 * The album to remove
1846 public void deleteAlbum(Album album) {
1847 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1848 if (!album.isEmpty()) {
1851 if (album.getParent() == null) {
1852 album.getSone().removeAlbum(album);
1854 album.getParent().removeAlbum(album);
1856 synchronized (albums) {
1857 albums.remove(album.getId());
1859 saveSone(album.getSone());
1863 * Creates a new image.
1866 * The Sone creating the image
1868 * The album the image will be inserted into
1869 * @param temporaryImage
1870 * The temporary image to create the image from
1871 * @return The newly created image
1873 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1874 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", isLocalSone(sone)).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1875 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1876 album.addImage(image);
1877 synchronized (images) {
1878 images.put(image.getId(), image);
1880 imageInserter.insertImage(temporaryImage, image);
1885 * Deletes the given image. This method will also delete a matching
1888 * @see #deleteTemporaryImage(TemporaryImage)
1890 * The image to delete
1892 public void deleteImage(Image image) {
1893 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1894 deleteTemporaryImage(image.getId());
1895 image.getAlbum().removeImage(image);
1896 synchronized (images) {
1897 images.remove(image.getId());
1899 saveSone(image.getSone());
1903 * Creates a new temporary image.
1906 * The MIME type of the temporary image
1908 * The encoded data of the image
1909 * @return The temporary image
1911 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1912 TemporaryImage temporaryImage = new TemporaryImage();
1913 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1914 synchronized (temporaryImages) {
1915 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1917 return temporaryImage;
1921 * Deletes the given temporary image.
1923 * @param temporaryImage
1924 * The temporary image to delete
1926 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1927 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1928 deleteTemporaryImage(temporaryImage.getId());
1932 * Deletes the temporary image with the given ID.
1935 * The ID of the temporary image to delete
1937 public void deleteTemporaryImage(String imageId) {
1938 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1939 synchronized (temporaryImages) {
1940 temporaryImages.remove(imageId);
1942 Image image = getImage(imageId, false);
1943 if (image != null) {
1944 imageInserter.cancelImageInsert(image);
1949 * Notifies the core that the configuration, either of the core or of a
1950 * single local Sone, has changed, and that the configuration should be
1953 public void touchConfiguration() {
1954 lastConfigurationUpdate = System.currentTimeMillis();
1965 public void serviceStart() {
1966 loadConfiguration();
1967 updateChecker.addUpdateListener(this);
1968 updateChecker.start();
1969 webOfTrustUpdater.start();
1976 public void serviceRun() {
1977 long lastSaved = System.currentTimeMillis();
1978 while (!shouldStop()) {
1980 long now = System.currentTimeMillis();
1981 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1982 for (Sone localSone : getLocalSones()) {
1983 saveSone(localSone);
1985 saveConfiguration();
1995 public void serviceStop() {
1996 synchronized (localSones) {
1997 for (SoneInserter soneInserter : soneInserters.values()) {
1998 soneInserter.removeSoneInsertListener(this);
1999 soneInserter.stop();
2002 webOfTrustUpdater.stop();
2003 updateChecker.stop();
2004 updateChecker.removeUpdateListener(this);
2005 soneDownloader.stop();
2013 * Saves the given Sone. This will persist all local settings for the given
2014 * Sone, such as the friends list and similar, private options.
2019 private synchronized void saveSone(Sone sone) {
2020 if (!isLocalSone(sone)) {
2021 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2024 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2025 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2029 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2031 /* save Sone into configuration. */
2032 String sonePrefix = "Sone/" + sone.getId();
2033 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2034 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2037 Profile profile = sone.getProfile();
2038 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2039 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2040 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2041 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2042 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2043 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2044 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2046 /* save profile fields. */
2047 int fieldCounter = 0;
2048 for (Field profileField : profile.getFields()) {
2049 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2050 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2051 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2053 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2056 int postCounter = 0;
2057 for (Post post : sone.getPosts()) {
2058 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2059 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2060 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2061 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2062 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2064 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2067 int replyCounter = 0;
2068 for (PostReply reply : sone.getReplies()) {
2069 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2070 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2071 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2072 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2073 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2075 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2077 /* save post likes. */
2078 int postLikeCounter = 0;
2079 for (String postId : sone.getLikedPostIds()) {
2080 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2082 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2084 /* save reply likes. */
2085 int replyLikeCounter = 0;
2086 for (String replyId : sone.getLikedReplyIds()) {
2087 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2089 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2092 int friendCounter = 0;
2093 for (String friendId : sone.getFriends()) {
2094 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2096 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2098 /* save albums. first, collect in a flat structure, top-level first. */
2099 List<Album> albums = sone.getAllAlbums();
2101 int albumCounter = 0;
2102 for (Album album : albums) {
2103 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2104 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2105 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2106 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2107 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2108 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2110 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2113 int imageCounter = 0;
2114 for (Album album : albums) {
2115 for (Image image : album.getImages()) {
2116 if (!image.isInserted()) {
2119 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2120 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2121 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2122 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2123 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2124 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2125 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2126 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2127 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2130 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2133 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2134 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2135 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2136 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2137 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2138 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2140 configuration.save();
2142 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2144 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2145 } catch (ConfigurationException ce1) {
2146 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2147 } catch (WebOfTrustException wote1) {
2148 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2153 * Saves the current options.
2155 private void saveConfiguration() {
2156 synchronized (configuration) {
2157 if (storingConfiguration) {
2158 logger.log(Level.FINE, "Already storing configuration…");
2161 storingConfiguration = true;
2164 /* store the options first. */
2166 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2167 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2168 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2169 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2170 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2171 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2172 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2173 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2174 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2175 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2176 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2177 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2179 /* save known Sones. */
2180 int soneCounter = 0;
2181 synchronized (knownSones) {
2182 for (String knownSoneId : knownSones) {
2183 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2185 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2188 /* save Sone following times. */
2190 synchronized (soneFollowingTimes) {
2191 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2192 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2193 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2196 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2199 /* save known posts. */
2200 int postCounter = 0;
2201 synchronized (knownPosts) {
2202 for (String knownPostId : knownPosts) {
2203 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2205 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2208 /* save known replies. */
2209 int replyCounter = 0;
2210 synchronized (knownReplies) {
2211 for (String knownReplyId : knownReplies) {
2212 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2214 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2217 /* save bookmarked posts. */
2218 int bookmarkedPostCounter = 0;
2219 synchronized (bookmarkedPosts) {
2220 for (String bookmarkedPostId : bookmarkedPosts) {
2221 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2224 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2227 configuration.save();
2229 } catch (ConfigurationException ce1) {
2230 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2232 synchronized (configuration) {
2233 storingConfiguration = false;
2239 * Loads the configuration.
2241 @SuppressWarnings("unchecked")
2242 private void loadConfiguration() {
2243 /* create options. */
2244 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2247 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2248 SoneInserter.setInsertionDelay(newValue);
2252 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2253 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2254 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2255 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2256 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2257 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2258 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2259 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2260 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2263 @SuppressWarnings("synthetic-access")
2264 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2265 fcpInterface.setActive(newValue);
2268 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2271 @SuppressWarnings("synthetic-access")
2272 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2273 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2278 loadConfigurationValue("InsertionDelay");
2279 loadConfigurationValue("PostsPerPage");
2280 loadConfigurationValue("ImagesPerPage");
2281 loadConfigurationValue("CharactersPerPost");
2282 loadConfigurationValue("PostCutOffLength");
2283 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2284 loadConfigurationValue("PositiveTrust");
2285 loadConfigurationValue("NegativeTrust");
2286 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2287 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2288 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2290 /* load known Sones. */
2291 int soneCounter = 0;
2293 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2294 if (knownSoneId == null) {
2297 synchronized (knownSones) {
2298 knownSones.add(knownSoneId);
2302 /* load Sone following times. */
2305 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2306 if (soneId == null) {
2309 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2310 Sone followedSone = getSone(soneId);
2311 if (followedSone == null) {
2312 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2314 synchronized (soneFollowingTimes) {
2315 soneFollowingTimes.put(getSone(soneId), time);
2321 /* load known posts. */
2322 int postCounter = 0;
2324 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2325 if (knownPostId == null) {
2328 synchronized (knownPosts) {
2329 knownPosts.add(knownPostId);
2333 /* load known replies. */
2334 int replyCounter = 0;
2336 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2337 if (knownReplyId == null) {
2340 synchronized (knownReplies) {
2341 knownReplies.add(knownReplyId);
2345 /* load bookmarked posts. */
2346 int bookmarkedPostCounter = 0;
2348 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2349 if (bookmarkedPostId == null) {
2352 synchronized (bookmarkedPosts) {
2353 bookmarkedPosts.add(bookmarkedPostId);
2360 * Loads an {@link Integer} configuration value for the option with the
2361 * given name, logging validation failures.
2364 * The name of the option to load
2366 private void loadConfigurationValue(String optionName) {
2368 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2369 } catch (IllegalArgumentException iae1) {
2370 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2375 * Generate a Sone URI from the given URI and latest edition.
2378 * The URI to derive the Sone URI from
2379 * @return The derived URI
2381 private FreenetURI getSoneUri(String uriString) {
2383 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2385 } catch (MalformedURLException mue1) {
2386 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2392 // INTERFACE IdentityListener
2399 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2400 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2401 if (ownIdentity.hasContext("Sone")) {
2402 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2403 addLocalSone(ownIdentity);
2411 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2412 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2413 trustedIdentities.remove(ownIdentity);
2420 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2421 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2422 trustedIdentities.get(ownIdentity).add(identity);
2423 addRemoteSone(identity);
2430 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2431 new Thread(new Runnable() {
2434 @SuppressWarnings("synthetic-access")
2436 Sone sone = getRemoteSone(identity.getId(), false);
2437 sone.setIdentity(identity);
2438 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2439 soneDownloader.addSone(sone);
2440 soneDownloader.fetchSone(sone);
2449 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2450 trustedIdentities.get(ownIdentity).remove(identity);
2451 boolean foundIdentity = false;
2452 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2453 if (trustedIdentity.getKey().equals(ownIdentity)) {
2456 if (trustedIdentity.getValue().contains(identity)) {
2457 foundIdentity = true;
2460 if (foundIdentity) {
2461 /* some local identity still trusts this identity, don’t remove. */
2464 Sone sone = getSone(identity.getId(), false);
2466 /* TODO - we don’t have the Sone anymore. should this happen? */
2469 synchronized (posts) {
2470 synchronized (knownPosts) {
2471 for (Post post : sone.getPosts()) {
2472 posts.remove(post.getId());
2473 coreListenerManager.firePostRemoved(post);
2477 synchronized (replies) {
2478 synchronized (knownReplies) {
2479 for (PostReply reply : sone.getReplies()) {
2480 replies.remove(reply.getId());
2481 coreListenerManager.fireReplyRemoved(reply);
2485 synchronized (remoteSones) {
2486 remoteSones.remove(identity.getId());
2488 coreListenerManager.fireSoneRemoved(sone);
2492 // INTERFACE UpdateListener
2499 public void updateFound(Version version, long releaseTime, long latestEdition) {
2500 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2504 // INTERFACE ImageInsertListener
2511 public void insertStarted(Sone sone) {
2512 coreListenerManager.fireSoneInserting(sone);
2519 public void insertFinished(Sone sone, long insertDuration) {
2520 coreListenerManager.fireSoneInserted(sone, insertDuration);
2527 public void insertAborted(Sone sone, Throwable cause) {
2528 coreListenerManager.fireSoneInsertAborted(sone, cause);
2532 // SONEINSERTLISTENER METHODS
2539 public void imageInsertStarted(Image image) {
2540 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2541 coreListenerManager.fireImageInsertStarted(image);
2548 public void imageInsertAborted(Image image) {
2549 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2550 coreListenerManager.fireImageInsertAborted(image);
2557 public void imageInsertFinished(Image image, FreenetURI key) {
2558 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2559 image.setKey(key.toString());
2560 deleteTemporaryImage(image.getId());
2561 saveSone(image.getSone());
2562 coreListenerManager.fireImageInsertFinished(image);
2569 public void imageInsertFailed(Image image, Throwable cause) {
2570 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2571 coreListenerManager.fireImageInsertFailed(image, cause);
2575 * Convenience interface for external classes that want to access the core’s
2578 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2580 public static class Preferences {
2582 /** The wrapped options. */
2583 private final Options options;
2586 * Creates a new preferences object wrapped around the given options.
2589 * The options to wrap
2591 public Preferences(Options options) {
2592 this.options = options;
2596 * Returns the insertion delay.
2598 * @return The insertion delay
2600 public int getInsertionDelay() {
2601 return options.getIntegerOption("InsertionDelay").get();
2605 * Validates the given insertion delay.
2607 * @param insertionDelay
2608 * The insertion delay to validate
2609 * @return {@code true} if the given insertion delay was valid,
2610 * {@code false} otherwise
2612 public boolean validateInsertionDelay(Integer insertionDelay) {
2613 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2617 * Sets the insertion delay
2619 * @param insertionDelay
2620 * The new insertion delay, or {@code null} to restore it to
2622 * @return This preferences
2624 public Preferences setInsertionDelay(Integer insertionDelay) {
2625 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2630 * Returns the number of posts to show per page.
2632 * @return The number of posts to show per page
2634 public int getPostsPerPage() {
2635 return options.getIntegerOption("PostsPerPage").get();
2639 * Validates the number of posts per page.
2641 * @param postsPerPage
2642 * The number of posts per page
2643 * @return {@code true} if the number of posts per page was valid,
2644 * {@code false} otherwise
2646 public boolean validatePostsPerPage(Integer postsPerPage) {
2647 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2651 * Sets the number of posts to show per page.
2653 * @param postsPerPage
2654 * The number of posts to show per page
2655 * @return This preferences object
2657 public Preferences setPostsPerPage(Integer postsPerPage) {
2658 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2663 * Returns the number of images to show per page.
2665 * @return The number of images to show per page
2667 public int getImagesPerPage() {
2668 return options.getIntegerOption("ImagesPerPage").get();
2672 * Validates the number of images per page.
2674 * @param imagesPerPage
2675 * The number of images per page
2676 * @return {@code true} if the number of images per page was valid,
2677 * {@code false} otherwise
2679 public boolean validateImagesPerPage(Integer imagesPerPage) {
2680 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2684 * Sets the number of images per page.
2686 * @param imagesPerPage
2687 * The number of images per page
2688 * @return This preferences object
2690 public Preferences setImagesPerPage(Integer imagesPerPage) {
2691 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2696 * Returns the number of characters per post, or <code>-1</code> if the
2697 * posts should not be cut off.
2699 * @return The numbers of characters per post
2701 public int getCharactersPerPost() {
2702 return options.getIntegerOption("CharactersPerPost").get();
2706 * Validates the number of characters per post.
2708 * @param charactersPerPost
2709 * The number of characters per post
2710 * @return {@code true} if the number of characters per post was valid,
2711 * {@code false} otherwise
2713 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2714 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2718 * Sets the number of characters per post.
2720 * @param charactersPerPost
2721 * The number of characters per post, or <code>-1</code> to
2722 * not cut off the posts
2723 * @return This preferences objects
2725 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2726 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2731 * Returns the number of characters the shortened post should have.
2733 * @return The number of characters of the snippet
2735 public int getPostCutOffLength() {
2736 return options.getIntegerOption("PostCutOffLength").get();
2740 * Validates the number of characters after which to cut off the post.
2742 * @param postCutOffLength
2743 * The number of characters of the snippet
2744 * @return {@code true} if the number of characters of the snippet is
2745 * valid, {@code false} otherwise
2747 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2748 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2752 * Sets the number of characters the shortened post should have.
2754 * @param postCutOffLength
2755 * The number of characters of the snippet
2756 * @return This preferences
2758 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2759 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2764 * Returns whether Sone requires full access to be even visible.
2766 * @return {@code true} if Sone requires full access, {@code false}
2769 public boolean isRequireFullAccess() {
2770 return options.getBooleanOption("RequireFullAccess").get();
2774 * Sets whether Sone requires full access to be even visible.
2776 * @param requireFullAccess
2777 * {@code true} if Sone requires full access, {@code false}
2780 public void setRequireFullAccess(Boolean requireFullAccess) {
2781 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2785 * Returns the positive trust.
2787 * @return The positive trust
2789 public int getPositiveTrust() {
2790 return options.getIntegerOption("PositiveTrust").get();
2794 * Validates the positive trust.
2796 * @param positiveTrust
2797 * The positive trust to validate
2798 * @return {@code true} if the positive trust was valid, {@code false}
2801 public boolean validatePositiveTrust(Integer positiveTrust) {
2802 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2806 * Sets the positive trust.
2808 * @param positiveTrust
2809 * The new positive trust, or {@code null} to restore it to
2811 * @return This preferences
2813 public Preferences setPositiveTrust(Integer positiveTrust) {
2814 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2819 * Returns the negative trust.
2821 * @return The negative trust
2823 public int getNegativeTrust() {
2824 return options.getIntegerOption("NegativeTrust").get();
2828 * Validates the negative trust.
2830 * @param negativeTrust
2831 * The negative trust to validate
2832 * @return {@code true} if the negative trust was valid, {@code false}
2835 public boolean validateNegativeTrust(Integer negativeTrust) {
2836 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2840 * Sets the negative trust.
2842 * @param negativeTrust
2843 * The negative trust, or {@code null} to restore it to the
2845 * @return The preferences
2847 public Preferences setNegativeTrust(Integer negativeTrust) {
2848 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2853 * Returns the trust comment. This is the comment that is set in the web
2854 * of trust when a trust value is assigned to an identity.
2856 * @return The trust comment
2858 public String getTrustComment() {
2859 return options.getStringOption("TrustComment").get();
2863 * Sets the trust comment.
2865 * @param trustComment
2866 * The trust comment, or {@code null} to restore it to the
2868 * @return This preferences
2870 public Preferences setTrustComment(String trustComment) {
2871 options.getStringOption("TrustComment").set(trustComment);
2876 * Returns whether the {@link FcpInterface FCP interface} is currently
2879 * @see FcpInterface#setActive(boolean)
2880 * @return {@code true} if the FCP interface is currently active,
2881 * {@code false} otherwise
2883 public boolean isFcpInterfaceActive() {
2884 return options.getBooleanOption("ActivateFcpInterface").get();
2888 * Sets whether the {@link FcpInterface FCP interface} is currently
2891 * @see FcpInterface#setActive(boolean)
2892 * @param fcpInterfaceActive
2893 * {@code true} to activate the FCP interface, {@code false}
2894 * to deactivate the FCP interface
2895 * @return This preferences object
2897 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2898 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2903 * Returns the action level for which full access to the FCP interface
2906 * @return The action level for which full access to the FCP interface
2909 public FullAccessRequired getFcpFullAccessRequired() {
2910 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2914 * Sets the action level for which full access to the FCP interface is
2917 * @param fcpFullAccessRequired
2919 * @return This preferences
2921 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2922 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);