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.main.SonePlugin;
57 import net.pterodactylus.util.config.Configuration;
58 import net.pterodactylus.util.config.ConfigurationException;
59 import net.pterodactylus.util.logging.Logging;
60 import net.pterodactylus.util.number.Numbers;
61 import net.pterodactylus.util.service.AbstractService;
62 import net.pterodactylus.util.thread.NamedThreadFactory;
63 import net.pterodactylus.util.thread.Ticker;
64 import net.pterodactylus.util.validation.EqualityValidator;
65 import net.pterodactylus.util.validation.IntegerRangeValidator;
66 import net.pterodactylus.util.validation.OrValidator;
67 import net.pterodactylus.util.validation.Validation;
68 import net.pterodactylus.util.version.Version;
69 import freenet.keys.FreenetURI;
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
79 private static final Logger logger = Logging.getLogger(Core.class);
81 /** The start time. */
82 private final long startupTime = System.currentTimeMillis();
85 private final Options options = new Options();
87 /** The preferences. */
88 private final Preferences preferences = new Preferences(options);
90 /** The core listener manager. */
91 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
93 /** The configuration. */
94 private Configuration configuration;
96 /** Whether we’re currently saving the configuration. */
97 private boolean storingConfiguration = false;
99 /** The identity manager. */
100 private final IdentityManager identityManager;
102 /** Interface to freenet. */
103 private final FreenetInterface freenetInterface;
105 /** The Sone downloader. */
106 private final SoneDownloader soneDownloader;
108 /** The image inserter. */
109 private final ImageInserter imageInserter;
111 /** Sone downloader thread-pool. */
112 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
114 /** The update checker. */
115 private final UpdateChecker updateChecker;
117 /** The trust updater. */
118 private final WebOfTrustUpdater webOfTrustUpdater;
120 /** The FCP interface. */
121 private volatile FcpInterface fcpInterface;
123 /** The times Sones were followed. */
124 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
126 /** Locked local Sones. */
127 /* synchronize on itself. */
128 private final Set<Sone> lockedSones = new HashSet<Sone>();
130 /** Sone inserters. */
131 /* synchronize access on this on localSones. */
132 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
134 /** Sone rescuers. */
135 /* synchronize access on this on localSones. */
136 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
138 /** All local Sones. */
139 /* synchronize access on this on itself. */
140 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
142 /** All remote Sones. */
143 /* synchronize access on this on itself. */
144 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
146 /** All known Sones. */
147 private final Set<String> knownSones = new HashSet<String>();
150 private final Map<String, Post> posts = new HashMap<String, Post>();
152 /** All known posts. */
153 private final Set<String> knownPosts = new HashSet<String>();
156 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
158 /** All known replies. */
159 private final Set<String> knownReplies = new HashSet<String>();
161 /** All bookmarked posts. */
162 /* synchronize access on itself. */
163 private final Set<String> bookmarkedPosts = new HashSet<String>();
165 /** Trusted identities, sorted by own identities. */
166 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
168 /** All known albums. */
169 private final Map<String, Album> albums = new HashMap<String, Album>();
171 /** All known images. */
172 private final Map<String, Image> images = new HashMap<String, Image>();
174 /** All temporary images. */
175 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
177 /** Ticker for threads that mark own elements as known. */
178 private final Ticker localElementTicker = new Ticker();
180 /** The time the configuration was last touched. */
181 private volatile long lastConfigurationUpdate;
184 * Creates a new core.
186 * @param configuration
187 * The configuration of the core
188 * @param freenetInterface
189 * The freenet interface
190 * @param identityManager
191 * The identity manager
192 * @param webOfTrustUpdater
193 * The WebOfTrust updater
195 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
197 this.configuration = configuration;
198 this.freenetInterface = freenetInterface;
199 this.identityManager = identityManager;
200 this.soneDownloader = new SoneDownloader(this, freenetInterface);
201 this.imageInserter = new ImageInserter(this, freenetInterface);
202 this.updateChecker = new UpdateChecker(freenetInterface);
203 this.webOfTrustUpdater = webOfTrustUpdater;
207 // LISTENER MANAGEMENT
211 * Adds a new core listener.
213 * @param coreListener
214 * The listener to add
216 public void addCoreListener(CoreListener coreListener) {
217 coreListenerManager.addListener(coreListener);
221 * Removes a core listener.
223 * @param coreListener
224 * The listener to remove
226 public void removeCoreListener(CoreListener coreListener) {
227 coreListenerManager.removeListener(coreListener);
235 * Returns the time Sone was started.
237 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
239 public long getStartupTime() {
244 * Sets the configuration to use. This will automatically save the current
245 * configuration to the given configuration.
247 * @param configuration
248 * The new configuration to use
250 public void setConfiguration(Configuration configuration) {
251 this.configuration = configuration;
252 touchConfiguration();
256 * Returns the options used by the core.
258 * @return The options of the core
260 public Preferences getPreferences() {
265 * Returns the identity manager used by the core.
267 * @return The identity manager
269 public IdentityManager getIdentityManager() {
270 return identityManager;
274 * Returns the update checker.
276 * @return The update checker
278 public UpdateChecker getUpdateChecker() {
279 return updateChecker;
283 * Sets the FCP interface to use.
285 * @param fcpInterface
286 * The FCP interface to use
288 public void setFcpInterface(FcpInterface fcpInterface) {
289 this.fcpInterface = fcpInterface;
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
301 synchronized (localSones) {
302 SoneRescuer soneRescuer = soneRescuers.get(sone);
303 if (soneRescuer == null) {
304 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
305 soneRescuers.put(sone, soneRescuer);
313 * Returns whether the given Sone is currently locked.
317 * @return {@code true} if the Sone is locked, {@code false} if it is not
319 public boolean isLocked(Sone sone) {
320 synchronized (lockedSones) {
321 return lockedSones.contains(sone);
326 * Returns all Sones, remote and local.
330 public Set<Sone> getSones() {
331 Set<Sone> allSones = new HashSet<Sone>();
332 allSones.addAll(getLocalSones());
333 allSones.addAll(getRemoteSones());
338 * Returns the Sone with the given ID, regardless whether it’s local or
342 * The ID of the Sone to get
343 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Sone getSone(String id) {
347 return getSone(id, true);
351 * Returns the Sone with the given ID, regardless whether it’s local or
355 * The ID of the Sone to get
357 * {@code true} to create a new Sone if none exists,
358 * {@code false} to return {@code null} if a Sone with the given
360 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Sone getSone(String id, boolean create) {
365 if (isLocalSone(id)) {
366 return getLocalSone(id);
368 return getRemoteSone(id, create);
372 * Checks whether the core knows a Sone with the given ID.
376 * @return {@code true} if there is a Sone with the given ID, {@code false}
379 public boolean hasSone(String id) {
380 return isLocalSone(id) || isRemoteSone(id);
384 * Returns whether the given Sone is a local Sone.
387 * The Sone to check for its locality
388 * @return {@code true} if the given Sone is local, {@code false} otherwise
390 public boolean isLocalSone(Sone sone) {
391 synchronized (localSones) {
392 return localSones.containsKey(sone.getId());
397 * Returns whether the given ID is the ID of a local Sone.
400 * The Sone ID to check for its locality
401 * @return {@code true} if the given ID is a local Sone, {@code false}
404 public boolean isLocalSone(String id) {
405 synchronized (localSones) {
406 return localSones.containsKey(id);
411 * Returns all local Sones.
413 * @return All local Sones
415 public Set<Sone> getLocalSones() {
416 synchronized (localSones) {
417 return new HashSet<Sone>(localSones.values());
422 * Returns the local Sone with the given ID.
425 * The ID of the Sone to get
426 * @return The Sone with the given ID
428 public Sone getLocalSone(String id) {
429 return getLocalSone(id, true);
433 * Returns the local Sone with the given ID, optionally creating a new Sone.
438 * {@code true} to create a new Sone if none exists,
439 * {@code false} to return null if none exists
440 * @return The Sone with the given ID, or {@code null}
442 public Sone getLocalSone(String id, boolean create) {
443 synchronized (localSones) {
444 Sone sone = localSones.get(id);
445 if ((sone == null) && create) {
447 localSones.put(id, sone);
454 * Returns all remote Sones.
456 * @return All remote Sones
458 public Set<Sone> getRemoteSones() {
459 synchronized (remoteSones) {
460 return new HashSet<Sone>(remoteSones.values());
465 * Returns the remote Sone with the given ID.
468 * The ID of the remote Sone to get
470 * {@code true} to always create a Sone, {@code false} to return
471 * {@code null} if no Sone with the given ID exists
472 * @return The Sone with the given ID
474 public Sone getRemoteSone(String id, boolean create) {
475 synchronized (remoteSones) {
476 Sone sone = remoteSones.get(id);
477 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
479 remoteSones.put(id, sone);
486 * Returns whether the given Sone is a remote Sone.
490 * @return {@code true} if the given Sone is a remote Sone, {@code false}
493 public boolean isRemoteSone(Sone sone) {
494 synchronized (remoteSones) {
495 return remoteSones.containsKey(sone.getId());
500 * Returns whether the Sone with the given ID is a remote Sone.
503 * The ID of the Sone to check
504 * @return {@code true} if the Sone with the given ID is a remote Sone,
505 * {@code false} otherwise
507 public boolean isRemoteSone(String id) {
508 synchronized (remoteSones) {
509 return remoteSones.containsKey(id);
514 * Returns whether the given Sone has been modified.
517 * The Sone to check for modifications
518 * @return {@code true} if a modification has been detected in the Sone,
519 * {@code false} otherwise
521 public boolean isModifiedSone(Sone sone) {
522 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
526 * Returns the time when the given was first followed by any local Sone.
529 * The Sone to get the time for
530 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
531 * been followed, or {@link Long#MAX_VALUE}
533 public long getSoneFollowingTime(Sone sone) {
534 synchronized (soneFollowingTimes) {
535 if (soneFollowingTimes.containsKey(sone)) {
536 return soneFollowingTimes.get(sone);
538 return Long.MAX_VALUE;
543 * Returns whether the target Sone is trusted by the origin Sone.
549 * @return {@code true} if the target Sone is trusted by the origin Sone
551 public boolean isSoneTrusted(Sone origin, Sone target) {
552 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
553 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
557 * Returns the post with the given ID.
560 * The ID of the post to get
561 * @return The post with the given ID, or a new post with the given ID
563 public Post getPost(String postId) {
564 return getPost(postId, true);
568 * Returns the post with the given ID, optionally creating a new post.
571 * The ID of the post to get
573 * {@code true} it create a new post if no post with the given ID
574 * exists, {@code false} to return {@code null}
575 * @return The post, or {@code null} if there is no such post
578 public Post getPost(String postId, boolean create) {
579 synchronized (posts) {
580 Post post = posts.get(postId);
581 if ((post == null) && create) {
582 post = new PostImpl(postId);
583 posts.put(postId, post);
590 * Returns all posts that have the given Sone as recipient.
592 * @see Post#getRecipient()
594 * The recipient of the posts
595 * @return All posts that have the given Sone as recipient
597 public Set<Post> getDirectedPosts(Sone recipient) {
598 Validation.begin().isNotNull("Recipient", recipient).check();
599 Set<Post> directedPosts = new HashSet<Post>();
600 synchronized (posts) {
601 for (Post post : posts.values()) {
602 if (recipient.equals(post.getRecipient())) {
603 directedPosts.add(post);
607 return directedPosts;
611 * Returns the reply with the given ID. If there is no reply with the given
612 * ID yet, a new one is created, unless {@code create} is false in which
613 * case {@code null} is returned.
616 * The ID of the reply to get
618 * {@code true} to always return a {@link Reply}, {@code false}
619 * to return {@code null} if no reply can be found
620 * @return The reply, or {@code null} if there is no such reply
622 public PostReply getPostReply(String replyId, boolean create) {
623 synchronized (replies) {
624 PostReply reply = replies.get(replyId);
625 if (create && (reply == null)) {
626 reply = new PostReply(replyId);
627 replies.put(replyId, reply);
634 * Returns all replies for the given post, order ascending by time.
637 * The post to get all replies for
638 * @return All replies for the given post
640 public List<PostReply> getReplies(Post post) {
641 Set<Sone> sones = getSones();
642 List<PostReply> replies = new ArrayList<PostReply>();
643 for (Sone sone : sones) {
644 for (PostReply reply : sone.getReplies()) {
645 if (reply.getPost().equals(post)) {
650 Collections.sort(replies, Reply.TIME_COMPARATOR);
655 * Returns all Sones that have liked the given post.
658 * The post to get the liking Sones for
659 * @return The Sones that like the given post
661 public Set<Sone> getLikes(Post post) {
662 Set<Sone> sones = new HashSet<Sone>();
663 for (Sone sone : getSones()) {
664 if (sone.getLikedPostIds().contains(post.getId())) {
672 * Returns all Sones that have liked the given reply.
675 * The reply to get the liking Sones for
676 * @return The Sones that like the given reply
678 public Set<Sone> getLikes(PostReply reply) {
679 Set<Sone> sones = new HashSet<Sone>();
680 for (Sone sone : getSones()) {
681 if (sone.getLikedReplyIds().contains(reply.getId())) {
689 * Returns whether the given post is bookmarked.
693 * @return {@code true} if the given post is bookmarked, {@code false}
696 public boolean isBookmarked(Post post) {
697 return isPostBookmarked(post.getId());
701 * Returns whether the post with the given ID is bookmarked.
704 * The ID of the post to check
705 * @return {@code true} if the post with the given ID is bookmarked,
706 * {@code false} otherwise
708 public boolean isPostBookmarked(String id) {
709 synchronized (bookmarkedPosts) {
710 return bookmarkedPosts.contains(id);
715 * Returns all currently known bookmarked posts.
717 * @return All bookmarked posts
719 public Set<Post> getBookmarkedPosts() {
720 Set<Post> posts = new HashSet<Post>();
721 synchronized (bookmarkedPosts) {
722 for (String bookmarkedPostId : bookmarkedPosts) {
723 Post post = getPost(bookmarkedPostId, false);
733 * Returns the album with the given ID, creating a new album if no album
734 * with the given ID can be found.
737 * The ID of the album
738 * @return The album with the given ID
740 public Album getAlbum(String albumId) {
741 return getAlbum(albumId, true);
745 * Returns the album with the given ID, optionally creating a new album if
746 * an album with the given ID can not be found.
749 * The ID of the album
751 * {@code true} to create a new album if none exists for the
753 * @return The album with the given ID, or {@code null} if no album with the
754 * given ID exists and {@code create} is {@code false}
756 public Album getAlbum(String albumId, boolean create) {
757 synchronized (albums) {
758 Album album = albums.get(albumId);
759 if (create && (album == null)) {
760 album = new Album(albumId);
761 albums.put(albumId, album);
768 * Returns the image with the given ID, creating it if necessary.
771 * The ID of the image
772 * @return The image with the given ID
774 public Image getImage(String imageId) {
775 return getImage(imageId, true);
779 * Returns the image with the given ID, optionally creating it if it does
783 * The ID of the image
785 * {@code true} to create an image if none exists with the given
787 * @return The image with the given ID, or {@code null} if none exists and
790 public Image getImage(String imageId, boolean create) {
791 synchronized (images) {
792 Image image = images.get(imageId);
793 if (create && (image == null)) {
794 image = new Image(imageId);
795 images.put(imageId, image);
802 * Returns the temporary image with the given ID.
805 * The ID of the temporary image
806 * @return The temporary image, or {@code null} if there is no temporary
807 * image with the given ID
809 public TemporaryImage getTemporaryImage(String imageId) {
810 synchronized (temporaryImages) {
811 return temporaryImages.get(imageId);
820 * Locks the given Sone. A locked Sone will not be inserted by
821 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
827 public void lockSone(Sone sone) {
828 synchronized (lockedSones) {
829 if (lockedSones.add(sone)) {
830 coreListenerManager.fireSoneLocked(sone);
836 * Unlocks the given Sone.
838 * @see #lockSone(Sone)
842 public void unlockSone(Sone sone) {
843 synchronized (lockedSones) {
844 if (lockedSones.remove(sone)) {
845 coreListenerManager.fireSoneUnlocked(sone);
851 * Adds a local Sone from the given own identity.
854 * The own identity to create a Sone from
855 * @return The added (or already existing) Sone
857 public Sone addLocalSone(OwnIdentity ownIdentity) {
858 if (ownIdentity == null) {
859 logger.log(Level.WARNING, "Given OwnIdentity is null!");
862 synchronized (localSones) {
865 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
866 } catch (MalformedURLException mue1) {
867 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
870 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
871 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
873 /* TODO - load posts ’n stuff */
874 localSones.put(ownIdentity.getId(), sone);
875 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
876 soneInserter.addSoneInsertListener(this);
877 soneInserters.put(sone, soneInserter);
878 sone.setStatus(SoneStatus.idle);
880 soneInserter.start();
886 * Creates a new Sone for the given own identity.
889 * The own identity to create a Sone for
890 * @return The created Sone
892 public Sone createSone(OwnIdentity ownIdentity) {
893 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
894 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
897 Sone sone = addLocalSone(ownIdentity);
898 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
899 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
900 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
901 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
902 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
903 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
905 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
906 touchConfiguration();
911 * Adds the Sone of the given identity.
914 * The identity whose Sone to add
915 * @return The added or already existing Sone
917 public Sone addRemoteSone(Identity identity) {
918 if (identity == null) {
919 logger.log(Level.WARNING, "Given Identity is null!");
922 synchronized (remoteSones) {
923 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
924 boolean newSone = sone.getRequestUri() == null;
925 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
926 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
928 synchronized (knownSones) {
929 newSone = !knownSones.contains(sone.getId());
931 sone.setKnown(!newSone);
933 coreListenerManager.fireNewSoneFound(sone);
934 for (Sone localSone : getLocalSones()) {
935 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
936 followSone(localSone, sone);
941 soneDownloader.addSone(sone);
942 soneDownloaders.execute(new Runnable() {
945 @SuppressWarnings("synthetic-access")
947 soneDownloader.fetchSone(sone, sone.getRequestUri());
956 * Lets the given local Sone follow the Sone with the given ID.
959 * The local Sone that should follow another Sone
961 * The ID of the Sone to follow
963 public void followSone(Sone sone, String soneId) {
964 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
965 Sone followedSone = getSone(soneId, true);
966 if (followedSone == null) {
967 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
970 followSone(sone, getSone(soneId));
974 * Lets the given local Sone follow the other given Sone. If the given Sone
975 * was not followed by any local Sone before, this will mark all elements of
976 * the followed Sone as read that have been created before the current
980 * The local Sone that should follow the other Sone
981 * @param followedSone
982 * The Sone that should be followed
984 public void followSone(Sone sone, Sone followedSone) {
985 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
986 sone.addFriend(followedSone.getId());
987 synchronized (soneFollowingTimes) {
988 if (!soneFollowingTimes.containsKey(followedSone)) {
989 long now = System.currentTimeMillis();
990 soneFollowingTimes.put(followedSone, now);
991 for (Post post : followedSone.getPosts()) {
992 if (post.getTime() < now) {
996 for (PostReply reply : followedSone.getReplies()) {
997 if (reply.getTime() < now) {
998 markReplyKnown(reply);
1003 touchConfiguration();
1007 * Lets the given local Sone unfollow the Sone with the given ID.
1010 * The local Sone that should unfollow another Sone
1012 * The ID of the Sone being unfollowed
1014 public void unfollowSone(Sone sone, String soneId) {
1015 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1016 unfollowSone(sone, getSone(soneId, false));
1020 * Lets the given local Sone unfollow the other given Sone. If the given
1021 * local Sone is the last local Sone that followed the given Sone, its
1022 * following time will be removed.
1025 * The local Sone that should unfollow another Sone
1026 * @param unfollowedSone
1027 * The Sone being unfollowed
1029 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1030 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1031 sone.removeFriend(unfollowedSone.getId());
1032 boolean unfollowedSoneStillFollowed = false;
1033 for (Sone localSone : getLocalSones()) {
1034 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1036 if (!unfollowedSoneStillFollowed) {
1037 synchronized (soneFollowingTimes) {
1038 soneFollowingTimes.remove(unfollowedSone);
1041 touchConfiguration();
1045 * Sets the trust value of the given origin Sone for the target Sone.
1052 * The trust value (from {@code -100} to {@code 100})
1054 public void setTrust(Sone origin, Sone target, int trustValue) {
1055 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();
1056 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1060 * Removes any trust assignment for the given target Sone.
1067 public void removeTrust(Sone origin, Sone target) {
1068 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1069 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1073 * Assigns the configured positive trust value for the given target.
1080 public void trustSone(Sone origin, Sone target) {
1081 setTrust(origin, target, preferences.getPositiveTrust());
1085 * Assigns the configured negative trust value for the given target.
1092 public void distrustSone(Sone origin, Sone target) {
1093 setTrust(origin, target, preferences.getNegativeTrust());
1097 * Removes the trust assignment for the given target.
1104 public void untrustSone(Sone origin, Sone target) {
1105 removeTrust(origin, target);
1109 * Updates the stored Sone with the given Sone.
1114 public void updateSone(Sone sone) {
1115 updateSone(sone, false);
1119 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1120 * {@code true}, an older Sone than the current Sone can be given to restore
1124 * The Sone to update
1125 * @param soneRescueMode
1126 * {@code true} if the stored Sone should be updated regardless
1127 * of the age of the given Sone
1129 public void updateSone(Sone sone, boolean soneRescueMode) {
1130 if (hasSone(sone.getId())) {
1131 Sone storedSone = getSone(sone.getId());
1132 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1133 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1136 synchronized (posts) {
1137 if (!soneRescueMode) {
1138 for (Post post : storedSone.getPosts()) {
1139 posts.remove(post.getId());
1140 if (!sone.getPosts().contains(post)) {
1141 coreListenerManager.firePostRemoved(post);
1145 List<Post> storedPosts = storedSone.getPosts();
1146 synchronized (knownPosts) {
1147 for (Post post : sone.getPosts()) {
1148 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1149 if (!storedPosts.contains(post)) {
1150 if (post.getTime() < getSoneFollowingTime(sone)) {
1151 knownPosts.add(post.getId());
1152 post.setKnown(true);
1153 } else if (!knownPosts.contains(post.getId())) {
1154 coreListenerManager.fireNewPostFound(post);
1157 posts.put(post.getId(), post);
1161 synchronized (replies) {
1162 if (!soneRescueMode) {
1163 for (PostReply reply : storedSone.getReplies()) {
1164 replies.remove(reply.getId());
1165 if (!sone.getReplies().contains(reply)) {
1166 coreListenerManager.fireReplyRemoved(reply);
1170 Set<PostReply> storedReplies = storedSone.getReplies();
1171 synchronized (knownReplies) {
1172 for (PostReply reply : sone.getReplies()) {
1173 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1174 if (!storedReplies.contains(reply)) {
1175 if (reply.getTime() < getSoneFollowingTime(sone)) {
1176 knownReplies.add(reply.getId());
1177 reply.setKnown(true);
1178 } else if (!knownReplies.contains(reply.getId())) {
1179 coreListenerManager.fireNewReplyFound(reply);
1182 replies.put(reply.getId(), reply);
1186 synchronized (albums) {
1187 synchronized (images) {
1188 for (Album album : storedSone.getAlbums()) {
1189 albums.remove(album.getId());
1190 for (Image image : album.getImages()) {
1191 images.remove(image.getId());
1194 for (Album album : sone.getAlbums()) {
1195 albums.put(album.getId(), album);
1196 for (Image image : album.getImages()) {
1197 images.put(image.getId(), image);
1202 synchronized (storedSone) {
1203 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1204 storedSone.setTime(sone.getTime());
1206 storedSone.setClient(sone.getClient());
1207 storedSone.setProfile(sone.getProfile());
1208 if (soneRescueMode) {
1209 for (Post post : sone.getPosts()) {
1210 storedSone.addPost(post);
1212 for (PostReply reply : sone.getReplies()) {
1213 storedSone.addReply(reply);
1215 for (String likedPostId : sone.getLikedPostIds()) {
1216 storedSone.addLikedPostId(likedPostId);
1218 for (String likedReplyId : sone.getLikedReplyIds()) {
1219 storedSone.addLikedReplyId(likedReplyId);
1221 for (Album album : sone.getAlbums()) {
1222 storedSone.addAlbum(album);
1225 storedSone.setPosts(sone.getPosts());
1226 storedSone.setReplies(sone.getReplies());
1227 storedSone.setLikePostIds(sone.getLikedPostIds());
1228 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1229 storedSone.setAlbums(sone.getAlbums());
1231 storedSone.setLatestEdition(sone.getLatestEdition());
1237 * Deletes the given Sone. This will remove the Sone from the
1238 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1239 * and remove the context from its identity.
1242 * The Sone to delete
1244 public void deleteSone(Sone sone) {
1245 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1246 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1249 synchronized (localSones) {
1250 if (!localSones.containsKey(sone.getId())) {
1251 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1254 localSones.remove(sone.getId());
1255 SoneInserter soneInserter = soneInserters.remove(sone);
1256 soneInserter.removeSoneInsertListener(this);
1257 soneInserter.stop();
1259 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1260 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1262 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1263 } catch (ConfigurationException ce1) {
1264 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1269 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1270 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1273 * The Sone to mark as known
1275 public void markSoneKnown(Sone sone) {
1276 if (!sone.isKnown()) {
1277 sone.setKnown(true);
1278 synchronized (knownSones) {
1279 knownSones.add(sone.getId());
1281 coreListenerManager.fireMarkSoneKnown(sone);
1282 touchConfiguration();
1287 * Loads and updates the given Sone from the configuration. If any error is
1288 * encountered, loading is aborted and the given Sone is not changed.
1291 * The Sone to load and update
1293 public void loadSone(Sone sone) {
1294 if (!isLocalSone(sone)) {
1295 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1299 /* initialize options. */
1300 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1301 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1302 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1303 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1304 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1305 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1308 String sonePrefix = "Sone/" + sone.getId();
1309 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1310 if (soneTime == null) {
1311 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1314 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1317 Profile profile = new Profile(sone);
1318 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1319 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1320 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1321 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1322 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1323 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1325 /* load profile fields. */
1327 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1328 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1329 if (fieldName == null) {
1332 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1333 profile.addField(fieldName).setValue(fieldValue);
1337 Set<Post> posts = new HashSet<Post>();
1339 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1340 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1341 if (postId == null) {
1344 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1345 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1346 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1347 if ((postTime == 0) || (postText == null)) {
1348 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1351 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1352 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1353 post.setRecipient(getSone(postRecipientId));
1359 Set<PostReply> replies = new HashSet<PostReply>();
1361 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1362 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1363 if (replyId == null) {
1366 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1367 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1368 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1369 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1370 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1373 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1376 /* load post likes. */
1377 Set<String> likedPostIds = new HashSet<String>();
1379 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1380 if (likedPostId == null) {
1383 likedPostIds.add(likedPostId);
1386 /* load reply likes. */
1387 Set<String> likedReplyIds = new HashSet<String>();
1389 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1390 if (likedReplyId == null) {
1393 likedReplyIds.add(likedReplyId);
1397 Set<String> friends = new HashSet<String>();
1399 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1400 if (friendId == null) {
1403 friends.add(friendId);
1407 List<Album> topLevelAlbums = new ArrayList<Album>();
1408 int albumCounter = 0;
1410 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1411 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1412 if (albumId == null) {
1415 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1416 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1417 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1418 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1419 if ((albumTitle == null) || (albumDescription == null)) {
1420 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1423 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1424 if (albumParentId != null) {
1425 Album parentAlbum = getAlbum(albumParentId, false);
1426 if (parentAlbum == null) {
1427 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1430 parentAlbum.addAlbum(album);
1432 if (!topLevelAlbums.contains(album)) {
1433 topLevelAlbums.add(album);
1439 int imageCounter = 0;
1441 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1442 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1443 if (imageId == null) {
1446 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1447 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1448 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1449 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1450 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1451 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1452 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1453 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1454 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1457 Album album = getAlbum(albumId, false);
1458 if (album == null) {
1459 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1462 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1463 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1464 album.addImage(image);
1468 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1469 if (avatarId != null) {
1470 profile.setAvatar(getImage(avatarId, false));
1474 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1475 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1476 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1477 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1478 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1479 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1481 /* if we’re still here, Sone was loaded successfully. */
1482 synchronized (sone) {
1483 sone.setTime(soneTime);
1484 sone.setProfile(profile);
1485 sone.setPosts(posts);
1486 sone.setReplies(replies);
1487 sone.setLikePostIds(likedPostIds);
1488 sone.setLikeReplyIds(likedReplyIds);
1489 for (String friendId : friends) {
1490 followSone(sone, friendId);
1492 sone.setAlbums(topLevelAlbums);
1493 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1495 synchronized (knownSones) {
1496 for (String friend : friends) {
1497 knownSones.add(friend);
1500 synchronized (knownPosts) {
1501 for (Post post : posts) {
1502 knownPosts.add(post.getId());
1505 synchronized (knownReplies) {
1506 for (PostReply reply : replies) {
1507 knownReplies.add(reply.getId());
1513 * Creates a new post.
1516 * The Sone that creates the post
1518 * The text of the post
1519 * @return The created post
1521 public Post createPost(Sone sone, String text) {
1522 return createPost(sone, System.currentTimeMillis(), text);
1526 * Creates a new post.
1529 * The Sone that creates the post
1531 * The time of the post
1533 * The text of the post
1534 * @return The created post
1536 public Post createPost(Sone sone, long time, String text) {
1537 return createPost(sone, null, time, text);
1541 * Creates a new post.
1544 * The Sone that creates the post
1546 * The recipient Sone, or {@code null} if this post does not have
1549 * The text of the post
1550 * @return The created post
1552 public Post createPost(Sone sone, Sone recipient, String text) {
1553 return createPost(sone, recipient, System.currentTimeMillis(), text);
1557 * Creates a new post.
1560 * The Sone that creates the post
1562 * The recipient Sone, or {@code null} if this post does not have
1565 * The time of the post
1567 * The text of the post
1568 * @return The created post
1570 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1571 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1572 if (!isLocalSone(sone)) {
1573 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1576 final Post post = new PostImpl(sone, time, text);
1577 if (recipient != null) {
1578 post.setRecipient(recipient);
1580 synchronized (posts) {
1581 posts.put(post.getId(), post);
1583 coreListenerManager.fireNewPostFound(post);
1585 touchConfiguration();
1586 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1593 markPostKnown(post);
1595 }, "Mark " + post + " read.");
1600 * Deletes the given post.
1603 * The post to delete
1605 public void deletePost(Post post) {
1606 if (!isLocalSone(post.getSone())) {
1607 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1610 post.getSone().removePost(post);
1611 synchronized (posts) {
1612 posts.remove(post.getId());
1614 coreListenerManager.firePostRemoved(post);
1615 markPostKnown(post);
1616 touchConfiguration();
1620 * Marks the given post as known, if it is currently not a known post
1621 * (according to {@link Post#isKnown()}).
1624 * The post to mark as known
1626 public void markPostKnown(Post post) {
1627 post.setKnown(true);
1628 synchronized (knownPosts) {
1629 coreListenerManager.fireMarkPostKnown(post);
1630 if (knownPosts.add(post.getId())) {
1631 touchConfiguration();
1634 for (PostReply reply : getReplies(post)) {
1635 markReplyKnown(reply);
1640 * Bookmarks the given post.
1643 * The post to bookmark
1645 public void bookmark(Post post) {
1646 bookmarkPost(post.getId());
1650 * Bookmarks the post with the given ID.
1653 * The ID of the post to bookmark
1655 public void bookmarkPost(String id) {
1656 synchronized (bookmarkedPosts) {
1657 bookmarkedPosts.add(id);
1662 * Removes the given post from the bookmarks.
1665 * The post to unbookmark
1667 public void unbookmark(Post post) {
1668 unbookmarkPost(post.getId());
1672 * Removes the post with the given ID from the bookmarks.
1675 * The ID of the post to unbookmark
1677 public void unbookmarkPost(String id) {
1678 synchronized (bookmarkedPosts) {
1679 bookmarkedPosts.remove(id);
1684 * Creates a new reply.
1687 * The Sone that creates the reply
1689 * The post that this reply refers to
1691 * The text of the reply
1692 * @return The created reply
1694 public PostReply createReply(Sone sone, Post post, String text) {
1695 return createReply(sone, post, System.currentTimeMillis(), text);
1699 * Creates a new reply.
1702 * The Sone that creates the reply
1704 * The post that this reply refers to
1706 * The time of the reply
1708 * The text of the reply
1709 * @return The created reply
1711 public PostReply createReply(Sone sone, Post post, long time, String text) {
1712 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1713 if (!isLocalSone(sone)) {
1714 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1717 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1718 synchronized (replies) {
1719 replies.put(reply.getId(), reply);
1721 synchronized (knownReplies) {
1722 coreListenerManager.fireNewReplyFound(reply);
1724 sone.addReply(reply);
1725 touchConfiguration();
1726 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1733 markReplyKnown(reply);
1735 }, "Mark " + reply + " read.");
1740 * Deletes the given reply.
1743 * The reply to delete
1745 public void deleteReply(PostReply reply) {
1746 Sone sone = reply.getSone();
1747 if (!isLocalSone(sone)) {
1748 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1751 synchronized (replies) {
1752 replies.remove(reply.getId());
1754 synchronized (knownReplies) {
1755 markReplyKnown(reply);
1756 knownReplies.remove(reply.getId());
1758 sone.removeReply(reply);
1759 touchConfiguration();
1763 * Marks the given reply as known, if it is currently not a known reply
1764 * (according to {@link Reply#isKnown()}).
1767 * The reply to mark as known
1769 public void markReplyKnown(PostReply reply) {
1770 reply.setKnown(true);
1771 synchronized (knownReplies) {
1772 coreListenerManager.fireMarkReplyKnown(reply);
1773 if (knownReplies.add(reply.getId())) {
1774 touchConfiguration();
1780 * Creates a new top-level album for the given Sone.
1783 * The Sone to create the album for
1784 * @return The new album
1786 public Album createAlbum(Sone sone) {
1787 return createAlbum(sone, null);
1791 * Creates a new album for the given Sone.
1794 * The Sone to create the album for
1796 * The parent of the album (may be {@code null} to create a
1798 * @return The new album
1800 public Album createAlbum(Sone sone, Album parent) {
1801 Album album = new Album();
1802 synchronized (albums) {
1803 albums.put(album.getId(), album);
1805 album.setSone(sone);
1806 if (parent != null) {
1807 parent.addAlbum(album);
1809 sone.addAlbum(album);
1815 * Deletes the given album. The owner of the album has to be a local Sone,
1816 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1819 * The album to remove
1821 public void deleteAlbum(Album album) {
1822 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1823 if (!album.isEmpty()) {
1826 if (album.getParent() == null) {
1827 album.getSone().removeAlbum(album);
1829 album.getParent().removeAlbum(album);
1831 synchronized (albums) {
1832 albums.remove(album.getId());
1834 touchConfiguration();
1838 * Creates a new image.
1841 * The Sone creating the image
1843 * The album the image will be inserted into
1844 * @param temporaryImage
1845 * The temporary image to create the image from
1846 * @return The newly created image
1848 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1849 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();
1850 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1851 album.addImage(image);
1852 synchronized (images) {
1853 images.put(image.getId(), image);
1855 imageInserter.insertImage(temporaryImage, image);
1860 * Deletes the given image. This method will also delete a matching
1863 * @see #deleteTemporaryImage(TemporaryImage)
1865 * The image to delete
1867 public void deleteImage(Image image) {
1868 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1869 deleteTemporaryImage(image.getId());
1870 image.getAlbum().removeImage(image);
1871 synchronized (images) {
1872 images.remove(image.getId());
1874 touchConfiguration();
1878 * Creates a new temporary image.
1881 * The MIME type of the temporary image
1883 * The encoded data of the image
1884 * @return The temporary image
1886 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1887 TemporaryImage temporaryImage = new TemporaryImage();
1888 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1889 synchronized (temporaryImages) {
1890 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1892 return temporaryImage;
1896 * Deletes the given temporary image.
1898 * @param temporaryImage
1899 * The temporary image to delete
1901 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1902 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1903 deleteTemporaryImage(temporaryImage.getId());
1907 * Deletes the temporary image with the given ID.
1910 * The ID of the temporary image to delete
1912 public void deleteTemporaryImage(String imageId) {
1913 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1914 synchronized (temporaryImages) {
1915 temporaryImages.remove(imageId);
1917 Image image = getImage(imageId, false);
1918 if (image != null) {
1919 imageInserter.cancelImageInsert(image);
1924 * Notifies the core that the configuration, either of the core or of a
1925 * single local Sone, has changed, and that the configuration should be
1928 public void touchConfiguration() {
1929 lastConfigurationUpdate = System.currentTimeMillis();
1940 public void serviceStart() {
1941 loadConfiguration();
1942 updateChecker.addUpdateListener(this);
1943 updateChecker.start();
1944 webOfTrustUpdater.start();
1951 public void serviceRun() {
1952 long lastSaved = System.currentTimeMillis();
1953 while (!shouldStop()) {
1955 long now = System.currentTimeMillis();
1956 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1957 for (Sone localSone : getLocalSones()) {
1958 saveSone(localSone);
1960 saveConfiguration();
1970 public void serviceStop() {
1971 synchronized (localSones) {
1972 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1973 soneInserter.getValue().removeSoneInsertListener(this);
1974 soneInserter.getValue().stop();
1975 saveSone(soneInserter.getKey());
1978 saveConfiguration();
1979 webOfTrustUpdater.stop();
1980 updateChecker.stop();
1981 updateChecker.removeUpdateListener(this);
1982 soneDownloader.stop();
1990 * Saves the given Sone. This will persist all local settings for the given
1991 * Sone, such as the friends list and similar, private options.
1996 private synchronized void saveSone(Sone sone) {
1997 if (!isLocalSone(sone)) {
1998 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2001 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2002 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2006 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2008 /* save Sone into configuration. */
2009 String sonePrefix = "Sone/" + sone.getId();
2010 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2011 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2014 Profile profile = sone.getProfile();
2015 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2016 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2017 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2018 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2019 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2020 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2021 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2023 /* save profile fields. */
2024 int fieldCounter = 0;
2025 for (Field profileField : profile.getFields()) {
2026 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2027 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2028 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2030 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2033 int postCounter = 0;
2034 for (Post post : sone.getPosts()) {
2035 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2036 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2037 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2038 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2039 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2041 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2044 int replyCounter = 0;
2045 for (PostReply reply : sone.getReplies()) {
2046 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2047 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2048 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2049 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2050 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2052 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2054 /* save post likes. */
2055 int postLikeCounter = 0;
2056 for (String postId : sone.getLikedPostIds()) {
2057 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2059 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2061 /* save reply likes. */
2062 int replyLikeCounter = 0;
2063 for (String replyId : sone.getLikedReplyIds()) {
2064 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2066 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2069 int friendCounter = 0;
2070 for (String friendId : sone.getFriends()) {
2071 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2073 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2075 /* save albums. first, collect in a flat structure, top-level first. */
2076 List<Album> albums = sone.getAllAlbums();
2078 int albumCounter = 0;
2079 for (Album album : albums) {
2080 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2081 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2082 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2083 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2084 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2085 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2087 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2090 int imageCounter = 0;
2091 for (Album album : albums) {
2092 for (Image image : album.getImages()) {
2093 if (!image.isInserted()) {
2096 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2097 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2098 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2099 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2100 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2101 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2102 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2103 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2104 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2107 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2110 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2111 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2112 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2113 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2114 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2115 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2117 configuration.save();
2119 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2121 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2122 } catch (ConfigurationException ce1) {
2123 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2128 * Saves the current options.
2130 private void saveConfiguration() {
2131 synchronized (configuration) {
2132 if (storingConfiguration) {
2133 logger.log(Level.FINE, "Already storing configuration…");
2136 storingConfiguration = true;
2139 /* store the options first. */
2141 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2142 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2143 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2144 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2145 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2146 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2147 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2148 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2149 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2150 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2151 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2152 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2154 /* save known Sones. */
2155 int soneCounter = 0;
2156 synchronized (knownSones) {
2157 for (String knownSoneId : knownSones) {
2158 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2160 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2163 /* save Sone following times. */
2165 synchronized (soneFollowingTimes) {
2166 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2167 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2168 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2171 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2174 /* save known posts. */
2175 int postCounter = 0;
2176 synchronized (knownPosts) {
2177 for (String knownPostId : knownPosts) {
2178 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2180 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2183 /* save known replies. */
2184 int replyCounter = 0;
2185 synchronized (knownReplies) {
2186 for (String knownReplyId : knownReplies) {
2187 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2189 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2192 /* save bookmarked posts. */
2193 int bookmarkedPostCounter = 0;
2194 synchronized (bookmarkedPosts) {
2195 for (String bookmarkedPostId : bookmarkedPosts) {
2196 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2199 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2202 configuration.save();
2204 } catch (ConfigurationException ce1) {
2205 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2207 synchronized (configuration) {
2208 storingConfiguration = false;
2214 * Loads the configuration.
2216 @SuppressWarnings("unchecked")
2217 private void loadConfiguration() {
2218 /* create options. */
2219 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2222 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2223 SoneInserter.setInsertionDelay(newValue);
2227 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2228 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2229 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2230 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2231 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2232 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2233 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2234 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2235 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2238 @SuppressWarnings("synthetic-access")
2239 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2240 fcpInterface.setActive(newValue);
2243 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2246 @SuppressWarnings("synthetic-access")
2247 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2248 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2253 loadConfigurationValue("InsertionDelay");
2254 loadConfigurationValue("PostsPerPage");
2255 loadConfigurationValue("ImagesPerPage");
2256 loadConfigurationValue("CharactersPerPost");
2257 loadConfigurationValue("PostCutOffLength");
2258 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2259 loadConfigurationValue("PositiveTrust");
2260 loadConfigurationValue("NegativeTrust");
2261 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2262 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2263 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2265 /* load known Sones. */
2266 int soneCounter = 0;
2268 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2269 if (knownSoneId == null) {
2272 synchronized (knownSones) {
2273 knownSones.add(knownSoneId);
2277 /* load Sone following times. */
2280 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2281 if (soneId == null) {
2284 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2285 Sone followedSone = getSone(soneId);
2286 if (followedSone == null) {
2287 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2289 synchronized (soneFollowingTimes) {
2290 soneFollowingTimes.put(getSone(soneId), time);
2296 /* load known posts. */
2297 int postCounter = 0;
2299 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2300 if (knownPostId == null) {
2303 synchronized (knownPosts) {
2304 knownPosts.add(knownPostId);
2308 /* load known replies. */
2309 int replyCounter = 0;
2311 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2312 if (knownReplyId == null) {
2315 synchronized (knownReplies) {
2316 knownReplies.add(knownReplyId);
2320 /* load bookmarked posts. */
2321 int bookmarkedPostCounter = 0;
2323 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2324 if (bookmarkedPostId == null) {
2327 synchronized (bookmarkedPosts) {
2328 bookmarkedPosts.add(bookmarkedPostId);
2335 * Loads an {@link Integer} configuration value for the option with the
2336 * given name, logging validation failures.
2339 * The name of the option to load
2341 private void loadConfigurationValue(String optionName) {
2343 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2344 } catch (IllegalArgumentException iae1) {
2345 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2350 * Generate a Sone URI from the given URI and latest edition.
2353 * The URI to derive the Sone URI from
2354 * @return The derived URI
2356 private static FreenetURI getSoneUri(String uriString) {
2358 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2360 } catch (MalformedURLException mue1) {
2361 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2367 // INTERFACE IdentityListener
2374 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2375 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2376 if (ownIdentity.hasContext("Sone")) {
2377 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2378 addLocalSone(ownIdentity);
2386 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2387 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2388 trustedIdentities.remove(ownIdentity);
2395 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2396 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2397 trustedIdentities.get(ownIdentity).add(identity);
2398 addRemoteSone(identity);
2405 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2406 soneDownloaders.execute(new Runnable() {
2409 @SuppressWarnings("synthetic-access")
2411 Sone sone = getRemoteSone(identity.getId(), false);
2412 sone.setIdentity(identity);
2413 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2414 soneDownloader.addSone(sone);
2415 soneDownloader.fetchSone(sone);
2424 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2425 trustedIdentities.get(ownIdentity).remove(identity);
2426 boolean foundIdentity = false;
2427 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2428 if (trustedIdentity.getKey().equals(ownIdentity)) {
2431 if (trustedIdentity.getValue().contains(identity)) {
2432 foundIdentity = true;
2435 if (foundIdentity) {
2436 /* some local identity still trusts this identity, don’t remove. */
2439 Sone sone = getSone(identity.getId(), false);
2441 /* TODO - we don’t have the Sone anymore. should this happen? */
2444 synchronized (posts) {
2445 synchronized (knownPosts) {
2446 for (Post post : sone.getPosts()) {
2447 posts.remove(post.getId());
2448 coreListenerManager.firePostRemoved(post);
2452 synchronized (replies) {
2453 synchronized (knownReplies) {
2454 for (PostReply reply : sone.getReplies()) {
2455 replies.remove(reply.getId());
2456 coreListenerManager.fireReplyRemoved(reply);
2460 synchronized (remoteSones) {
2461 remoteSones.remove(identity.getId());
2463 coreListenerManager.fireSoneRemoved(sone);
2467 // INTERFACE UpdateListener
2474 public void updateFound(Version version, long releaseTime, long latestEdition) {
2475 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2479 // INTERFACE ImageInsertListener
2486 public void insertStarted(Sone sone) {
2487 coreListenerManager.fireSoneInserting(sone);
2494 public void insertFinished(Sone sone, long insertDuration) {
2495 coreListenerManager.fireSoneInserted(sone, insertDuration);
2502 public void insertAborted(Sone sone, Throwable cause) {
2503 coreListenerManager.fireSoneInsertAborted(sone, cause);
2507 // SONEINSERTLISTENER METHODS
2514 public void imageInsertStarted(Image image) {
2515 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2516 coreListenerManager.fireImageInsertStarted(image);
2523 public void imageInsertAborted(Image image) {
2524 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2525 coreListenerManager.fireImageInsertAborted(image);
2532 public void imageInsertFinished(Image image, FreenetURI key) {
2533 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2534 image.setKey(key.toString());
2535 deleteTemporaryImage(image.getId());
2536 touchConfiguration();
2537 coreListenerManager.fireImageInsertFinished(image);
2544 public void imageInsertFailed(Image image, Throwable cause) {
2545 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2546 coreListenerManager.fireImageInsertFailed(image, cause);
2550 * Convenience interface for external classes that want to access the core’s
2553 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2555 public static class Preferences {
2557 /** The wrapped options. */
2558 private final Options options;
2561 * Creates a new preferences object wrapped around the given options.
2564 * The options to wrap
2566 public Preferences(Options options) {
2567 this.options = options;
2571 * Returns the insertion delay.
2573 * @return The insertion delay
2575 public int getInsertionDelay() {
2576 return options.getIntegerOption("InsertionDelay").get();
2580 * Validates the given insertion delay.
2582 * @param insertionDelay
2583 * The insertion delay to validate
2584 * @return {@code true} if the given insertion delay was valid,
2585 * {@code false} otherwise
2587 public boolean validateInsertionDelay(Integer insertionDelay) {
2588 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2592 * Sets the insertion delay
2594 * @param insertionDelay
2595 * The new insertion delay, or {@code null} to restore it to
2597 * @return This preferences
2599 public Preferences setInsertionDelay(Integer insertionDelay) {
2600 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2605 * Returns the number of posts to show per page.
2607 * @return The number of posts to show per page
2609 public int getPostsPerPage() {
2610 return options.getIntegerOption("PostsPerPage").get();
2614 * Validates the number of posts per page.
2616 * @param postsPerPage
2617 * The number of posts per page
2618 * @return {@code true} if the number of posts per page was valid,
2619 * {@code false} otherwise
2621 public boolean validatePostsPerPage(Integer postsPerPage) {
2622 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2626 * Sets the number of posts to show per page.
2628 * @param postsPerPage
2629 * The number of posts to show per page
2630 * @return This preferences object
2632 public Preferences setPostsPerPage(Integer postsPerPage) {
2633 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2638 * Returns the number of images to show per page.
2640 * @return The number of images to show per page
2642 public int getImagesPerPage() {
2643 return options.getIntegerOption("ImagesPerPage").get();
2647 * Validates the number of images per page.
2649 * @param imagesPerPage
2650 * The number of images per page
2651 * @return {@code true} if the number of images per page was valid,
2652 * {@code false} otherwise
2654 public boolean validateImagesPerPage(Integer imagesPerPage) {
2655 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2659 * Sets the number of images per page.
2661 * @param imagesPerPage
2662 * The number of images per page
2663 * @return This preferences object
2665 public Preferences setImagesPerPage(Integer imagesPerPage) {
2666 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2671 * Returns the number of characters per post, or <code>-1</code> if the
2672 * posts should not be cut off.
2674 * @return The numbers of characters per post
2676 public int getCharactersPerPost() {
2677 return options.getIntegerOption("CharactersPerPost").get();
2681 * Validates the number of characters per post.
2683 * @param charactersPerPost
2684 * The number of characters per post
2685 * @return {@code true} if the number of characters per post was valid,
2686 * {@code false} otherwise
2688 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2689 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2693 * Sets the number of characters per post.
2695 * @param charactersPerPost
2696 * The number of characters per post, or <code>-1</code> to
2697 * not cut off the posts
2698 * @return This preferences objects
2700 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2701 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2706 * Returns the number of characters the shortened post should have.
2708 * @return The number of characters of the snippet
2710 public int getPostCutOffLength() {
2711 return options.getIntegerOption("PostCutOffLength").get();
2715 * Validates the number of characters after which to cut off the post.
2717 * @param postCutOffLength
2718 * The number of characters of the snippet
2719 * @return {@code true} if the number of characters of the snippet is
2720 * valid, {@code false} otherwise
2722 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2723 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2727 * Sets the number of characters the shortened post should have.
2729 * @param postCutOffLength
2730 * The number of characters of the snippet
2731 * @return This preferences
2733 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2734 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2739 * Returns whether Sone requires full access to be even visible.
2741 * @return {@code true} if Sone requires full access, {@code false}
2744 public boolean isRequireFullAccess() {
2745 return options.getBooleanOption("RequireFullAccess").get();
2749 * Sets whether Sone requires full access to be even visible.
2751 * @param requireFullAccess
2752 * {@code true} if Sone requires full access, {@code false}
2755 public void setRequireFullAccess(Boolean requireFullAccess) {
2756 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2760 * Returns the positive trust.
2762 * @return The positive trust
2764 public int getPositiveTrust() {
2765 return options.getIntegerOption("PositiveTrust").get();
2769 * Validates the positive trust.
2771 * @param positiveTrust
2772 * The positive trust to validate
2773 * @return {@code true} if the positive trust was valid, {@code false}
2776 public boolean validatePositiveTrust(Integer positiveTrust) {
2777 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2781 * Sets the positive trust.
2783 * @param positiveTrust
2784 * The new positive trust, or {@code null} to restore it to
2786 * @return This preferences
2788 public Preferences setPositiveTrust(Integer positiveTrust) {
2789 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2794 * Returns the negative trust.
2796 * @return The negative trust
2798 public int getNegativeTrust() {
2799 return options.getIntegerOption("NegativeTrust").get();
2803 * Validates the negative trust.
2805 * @param negativeTrust
2806 * The negative trust to validate
2807 * @return {@code true} if the negative trust was valid, {@code false}
2810 public boolean validateNegativeTrust(Integer negativeTrust) {
2811 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2815 * Sets the negative trust.
2817 * @param negativeTrust
2818 * The negative trust, or {@code null} to restore it to the
2820 * @return The preferences
2822 public Preferences setNegativeTrust(Integer negativeTrust) {
2823 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2828 * Returns the trust comment. This is the comment that is set in the web
2829 * of trust when a trust value is assigned to an identity.
2831 * @return The trust comment
2833 public String getTrustComment() {
2834 return options.getStringOption("TrustComment").get();
2838 * Sets the trust comment.
2840 * @param trustComment
2841 * The trust comment, or {@code null} to restore it to the
2843 * @return This preferences
2845 public Preferences setTrustComment(String trustComment) {
2846 options.getStringOption("TrustComment").set(trustComment);
2851 * Returns whether the {@link FcpInterface FCP interface} is currently
2854 * @see FcpInterface#setActive(boolean)
2855 * @return {@code true} if the FCP interface is currently active,
2856 * {@code false} otherwise
2858 public boolean isFcpInterfaceActive() {
2859 return options.getBooleanOption("ActivateFcpInterface").get();
2863 * Sets whether the {@link FcpInterface FCP interface} is currently
2866 * @see FcpInterface#setActive(boolean)
2867 * @param fcpInterfaceActive
2868 * {@code true} to activate the FCP interface, {@code false}
2869 * to deactivate the FCP interface
2870 * @return This preferences object
2872 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2873 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2878 * Returns the action level for which full access to the FCP interface
2881 * @return The action level for which full access to the FCP interface
2884 public FullAccessRequired getFcpFullAccessRequired() {
2885 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2889 * Sets the action level for which full access to the FCP interface is
2892 * @param fcpFullAccessRequired
2894 * @return This preferences
2896 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2897 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);