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.Ticker;
63 import net.pterodactylus.util.validation.EqualityValidator;
64 import net.pterodactylus.util.validation.IntegerRangeValidator;
65 import net.pterodactylus.util.validation.OrValidator;
66 import net.pterodactylus.util.validation.Validation;
67 import net.pterodactylus.util.version.Version;
68 import freenet.keys.FreenetURI;
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
78 private static final Logger logger = Logging.getLogger(Core.class);
80 /** The start time. */
81 private final long startupTime = System.currentTimeMillis();
84 private final Options options = new Options();
86 /** The preferences. */
87 private final Preferences preferences = new Preferences(options);
89 /** The core listener manager. */
90 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
92 /** The configuration. */
93 private Configuration configuration;
95 /** Whether we’re currently saving the configuration. */
96 private boolean storingConfiguration = false;
98 /** The identity manager. */
99 private final IdentityManager identityManager;
101 /** Interface to freenet. */
102 private final FreenetInterface freenetInterface;
104 /** The Sone downloader. */
105 private final SoneDownloader soneDownloader;
107 /** The image inserter. */
108 private final ImageInserter imageInserter;
110 /** Sone downloader thread-pool. */
111 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
113 /** The update checker. */
114 private final UpdateChecker updateChecker;
116 /** The trust updater. */
117 private final WebOfTrustUpdater webOfTrustUpdater;
119 /** The FCP interface. */
120 private volatile FcpInterface fcpInterface;
122 /** The times Sones were followed. */
123 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
125 /** Locked local Sones. */
126 /* synchronize on itself. */
127 private final Set<Sone> lockedSones = new HashSet<Sone>();
129 /** Sone inserters. */
130 /* synchronize access on this on localSones. */
131 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
133 /** Sone rescuers. */
134 /* synchronize access on this on localSones. */
135 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
137 /** All local Sones. */
138 /* synchronize access on this on itself. */
139 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
141 /** All remote Sones. */
142 /* synchronize access on this on itself. */
143 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
145 /** All known Sones. */
146 private final Set<String> knownSones = new HashSet<String>();
149 private final Map<String, Post> posts = new HashMap<String, Post>();
151 /** All known posts. */
152 private final Set<String> knownPosts = new HashSet<String>();
155 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
157 /** All known replies. */
158 private final Set<String> knownReplies = new HashSet<String>();
160 /** All bookmarked posts. */
161 /* synchronize access on itself. */
162 private final Set<String> bookmarkedPosts = new HashSet<String>();
164 /** Trusted identities, sorted by own identities. */
165 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
167 /** All known albums. */
168 private final Map<String, Album> albums = new HashMap<String, Album>();
170 /** All known images. */
171 private final Map<String, Image> images = new HashMap<String, Image>();
173 /** All temporary images. */
174 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
176 /** Ticker for threads that mark own elements as known. */
177 private final Ticker localElementTicker = new Ticker();
179 /** The time the configuration was last touched. */
180 private volatile long lastConfigurationUpdate;
183 * Creates a new core.
185 * @param configuration
186 * The configuration of the core
187 * @param freenetInterface
188 * The freenet interface
189 * @param identityManager
190 * The identity manager
191 * @param webOfTrustUpdater
192 * The WebOfTrust updater
194 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
196 this.configuration = configuration;
197 this.freenetInterface = freenetInterface;
198 this.identityManager = identityManager;
199 this.soneDownloader = new SoneDownloader(this, freenetInterface);
200 this.imageInserter = new ImageInserter(this, freenetInterface);
201 this.updateChecker = new UpdateChecker(freenetInterface);
202 this.webOfTrustUpdater = webOfTrustUpdater;
206 // LISTENER MANAGEMENT
210 * Adds a new core listener.
212 * @param coreListener
213 * The listener to add
215 public void addCoreListener(CoreListener coreListener) {
216 coreListenerManager.addListener(coreListener);
220 * Removes a core listener.
222 * @param coreListener
223 * The listener to remove
225 public void removeCoreListener(CoreListener coreListener) {
226 coreListenerManager.removeListener(coreListener);
234 * Returns the time Sone was started.
236 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
238 public long getStartupTime() {
243 * Sets the configuration to use. This will automatically save the current
244 * configuration to the given configuration.
246 * @param configuration
247 * The new configuration to use
249 public void setConfiguration(Configuration configuration) {
250 this.configuration = configuration;
251 touchConfiguration();
255 * Returns the options used by the core.
257 * @return The options of the core
259 public Preferences getPreferences() {
264 * Returns the identity manager used by the core.
266 * @return The identity manager
268 public IdentityManager getIdentityManager() {
269 return identityManager;
273 * Returns the update checker.
275 * @return The update checker
277 public UpdateChecker getUpdateChecker() {
278 return updateChecker;
282 * Sets the FCP interface to use.
284 * @param fcpInterface
285 * The FCP interface to use
287 public void setFcpInterface(FcpInterface fcpInterface) {
288 this.fcpInterface = fcpInterface;
292 * Returns the Sone rescuer for the given local Sone.
295 * The local Sone to get the rescuer for
296 * @return The Sone rescuer for the given Sone
298 public SoneRescuer getSoneRescuer(Sone sone) {
299 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
300 synchronized (localSones) {
301 SoneRescuer soneRescuer = soneRescuers.get(sone);
302 if (soneRescuer == null) {
303 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
304 soneRescuers.put(sone, soneRescuer);
312 * Returns whether the given Sone is currently locked.
316 * @return {@code true} if the Sone is locked, {@code false} if it is not
318 public boolean isLocked(Sone sone) {
319 synchronized (lockedSones) {
320 return lockedSones.contains(sone);
325 * Returns all Sones, remote and local.
329 public Set<Sone> getSones() {
330 Set<Sone> allSones = new HashSet<Sone>();
331 allSones.addAll(getLocalSones());
332 allSones.addAll(getRemoteSones());
337 * Returns the Sone with the given ID, regardless whether it’s local or
341 * The ID of the Sone to get
342 * @return The Sone with the given ID, or {@code null} if there is no such
345 public Sone getSone(String id) {
346 return getSone(id, true);
350 * Returns the Sone with the given ID, regardless whether it’s local or
354 * The ID of the Sone to get
356 * {@code true} to create a new Sone if none exists,
357 * {@code false} to return {@code null} if a Sone with the given
359 * @return The Sone with the given ID, or {@code null} if there is no such
363 public Sone getSone(String id, boolean create) {
364 if (isLocalSone(id)) {
365 return getLocalSone(id);
367 return getRemoteSone(id, create);
371 * Checks whether the core knows a Sone with the given ID.
375 * @return {@code true} if there is a Sone with the given ID, {@code false}
378 public boolean hasSone(String id) {
379 return isLocalSone(id) || isRemoteSone(id);
383 * Returns whether the given Sone is a local Sone.
386 * The Sone to check for its locality
387 * @return {@code true} if the given Sone is local, {@code false} otherwise
389 public boolean isLocalSone(Sone sone) {
390 synchronized (localSones) {
391 return localSones.containsKey(sone.getId());
396 * Returns whether the given ID is the ID of a local Sone.
399 * The Sone ID to check for its locality
400 * @return {@code true} if the given ID is a local Sone, {@code false}
403 public boolean isLocalSone(String id) {
404 synchronized (localSones) {
405 return localSones.containsKey(id);
410 * Returns all local Sones.
412 * @return All local Sones
414 public Set<Sone> getLocalSones() {
415 synchronized (localSones) {
416 return new HashSet<Sone>(localSones.values());
421 * Returns the local Sone with the given ID.
424 * The ID of the Sone to get
425 * @return The Sone with the given ID
427 public Sone getLocalSone(String id) {
428 return getLocalSone(id, true);
432 * Returns the local Sone with the given ID, optionally creating a new Sone.
437 * {@code true} to create a new Sone if none exists,
438 * {@code false} to return null if none exists
439 * @return The Sone with the given ID, or {@code null}
441 public Sone getLocalSone(String id, boolean create) {
442 synchronized (localSones) {
443 Sone sone = localSones.get(id);
444 if ((sone == null) && create) {
446 localSones.put(id, sone);
453 * Returns all remote Sones.
455 * @return All remote Sones
457 public Set<Sone> getRemoteSones() {
458 synchronized (remoteSones) {
459 return new HashSet<Sone>(remoteSones.values());
464 * Returns the remote Sone with the given ID.
467 * The ID of the remote Sone to get
469 * {@code true} to always create a Sone, {@code false} to return
470 * {@code null} if no Sone with the given ID exists
471 * @return The Sone with the given ID
473 public Sone getRemoteSone(String id, boolean create) {
474 synchronized (remoteSones) {
475 Sone sone = remoteSones.get(id);
476 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
478 remoteSones.put(id, sone);
485 * Returns whether the given Sone is a remote Sone.
489 * @return {@code true} if the given Sone is a remote Sone, {@code false}
492 public boolean isRemoteSone(Sone sone) {
493 synchronized (remoteSones) {
494 return remoteSones.containsKey(sone.getId());
499 * Returns whether the Sone with the given ID is a remote Sone.
502 * The ID of the Sone to check
503 * @return {@code true} if the Sone with the given ID is a remote Sone,
504 * {@code false} otherwise
506 public boolean isRemoteSone(String id) {
507 synchronized (remoteSones) {
508 return remoteSones.containsKey(id);
513 * Returns whether the given Sone has been modified.
516 * The Sone to check for modifications
517 * @return {@code true} if a modification has been detected in the Sone,
518 * {@code false} otherwise
520 public boolean isModifiedSone(Sone sone) {
521 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
525 * Returns the time when the given was first followed by any local Sone.
528 * The Sone to get the time for
529 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
530 * been followed, or {@link Long#MAX_VALUE}
532 public long getSoneFollowingTime(Sone sone) {
533 synchronized (soneFollowingTimes) {
534 if (soneFollowingTimes.containsKey(sone)) {
535 return soneFollowingTimes.get(sone);
537 return Long.MAX_VALUE;
542 * Returns whether the target Sone is trusted by the origin Sone.
548 * @return {@code true} if the target Sone is trusted by the origin Sone
550 public boolean isSoneTrusted(Sone origin, Sone target) {
551 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
552 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
556 * Returns the post with the given ID.
559 * The ID of the post to get
560 * @return The post with the given ID, or a new post with the given ID
562 public Post getPost(String postId) {
563 return getPost(postId, true);
567 * Returns the post with the given ID, optionally creating a new post.
570 * The ID of the post to get
572 * {@code true} it create a new post if no post with the given ID
573 * exists, {@code false} to return {@code null}
574 * @return The post, or {@code null} if there is no such post
577 public Post getPost(String postId, boolean create) {
578 synchronized (posts) {
579 Post post = posts.get(postId);
580 if ((post == null) && create) {
581 post = new PostImpl(postId);
582 posts.put(postId, post);
589 * Returns all posts that have the given Sone as recipient.
591 * @see Post#getRecipient()
593 * The recipient of the posts
594 * @return All posts that have the given Sone as recipient
596 public Set<Post> getDirectedPosts(Sone recipient) {
597 Validation.begin().isNotNull("Recipient", recipient).check();
598 Set<Post> directedPosts = new HashSet<Post>();
599 synchronized (posts) {
600 for (Post post : posts.values()) {
601 if (recipient.equals(post.getRecipient())) {
602 directedPosts.add(post);
606 return directedPosts;
610 * Returns the reply with the given ID. If there is no reply with the given
611 * ID yet, a new one is created.
614 * The ID of the reply to get
617 public PostReply getReply(String replyId) {
618 return getReply(replyId, true);
622 * Returns the reply with the given ID. If there is no reply with the given
623 * ID yet, a new one is created, unless {@code create} is false in which
624 * case {@code null} is returned.
627 * The ID of the reply to get
629 * {@code true} to always return a {@link Reply}, {@code false}
630 * to return {@code null} if no reply can be found
631 * @return The reply, or {@code null} if there is no such reply
633 public PostReply getReply(String replyId, boolean create) {
634 synchronized (replies) {
635 PostReply reply = replies.get(replyId);
636 if (create && (reply == null)) {
637 reply = new PostReply(replyId);
638 replies.put(replyId, reply);
645 * Returns all replies for the given post, order ascending by time.
648 * The post to get all replies for
649 * @return All replies for the given post
651 public List<PostReply> getReplies(Post post) {
652 Set<Sone> sones = getSones();
653 List<PostReply> replies = new ArrayList<PostReply>();
654 for (Sone sone : sones) {
655 for (PostReply reply : sone.getReplies()) {
656 if (reply.getPost().equals(post)) {
661 Collections.sort(replies, Reply.TIME_COMPARATOR);
666 * Returns all Sones that have liked the given post.
669 * The post to get the liking Sones for
670 * @return The Sones that like the given post
672 public Set<Sone> getLikes(Post post) {
673 Set<Sone> sones = new HashSet<Sone>();
674 for (Sone sone : getSones()) {
675 if (sone.getLikedPostIds().contains(post.getId())) {
683 * Returns all Sones that have liked the given reply.
686 * The reply to get the liking Sones for
687 * @return The Sones that like the given reply
689 public Set<Sone> getLikes(PostReply reply) {
690 Set<Sone> sones = new HashSet<Sone>();
691 for (Sone sone : getSones()) {
692 if (sone.getLikedReplyIds().contains(reply.getId())) {
700 * Returns whether the given post is bookmarked.
704 * @return {@code true} if the given post is bookmarked, {@code false}
707 public boolean isBookmarked(Post post) {
708 return isPostBookmarked(post.getId());
712 * Returns whether the post with the given ID is bookmarked.
715 * The ID of the post to check
716 * @return {@code true} if the post with the given ID is bookmarked,
717 * {@code false} otherwise
719 public boolean isPostBookmarked(String id) {
720 synchronized (bookmarkedPosts) {
721 return bookmarkedPosts.contains(id);
726 * Returns all currently known bookmarked posts.
728 * @return All bookmarked posts
730 public Set<Post> getBookmarkedPosts() {
731 Set<Post> posts = new HashSet<Post>();
732 synchronized (bookmarkedPosts) {
733 for (String bookmarkedPostId : bookmarkedPosts) {
734 Post post = getPost(bookmarkedPostId, false);
744 * Returns the album with the given ID, creating a new album if no album
745 * with the given ID can be found.
748 * The ID of the album
749 * @return The album with the given ID
751 public Album getAlbum(String albumId) {
752 return getAlbum(albumId, true);
756 * Returns the album with the given ID, optionally creating a new album if
757 * an album with the given ID can not be found.
760 * The ID of the album
762 * {@code true} to create a new album if none exists for the
764 * @return The album with the given ID, or {@code null} if no album with the
765 * given ID exists and {@code create} is {@code false}
767 public Album getAlbum(String albumId, boolean create) {
768 synchronized (albums) {
769 Album album = albums.get(albumId);
770 if (create && (album == null)) {
771 album = new Album(albumId);
772 albums.put(albumId, album);
779 * Returns the image with the given ID, creating it if necessary.
782 * The ID of the image
783 * @return The image with the given ID
785 public Image getImage(String imageId) {
786 return getImage(imageId, true);
790 * Returns the image with the given ID, optionally creating it if it does
794 * The ID of the image
796 * {@code true} to create an image if none exists with the given
798 * @return The image with the given ID, or {@code null} if none exists and
801 public Image getImage(String imageId, boolean create) {
802 synchronized (images) {
803 Image image = images.get(imageId);
804 if (create && (image == null)) {
805 image = new Image(imageId);
806 images.put(imageId, image);
813 * Returns the temporary image with the given ID.
816 * The ID of the temporary image
817 * @return The temporary image, or {@code null} if there is no temporary
818 * image with the given ID
820 public TemporaryImage getTemporaryImage(String imageId) {
821 synchronized (temporaryImages) {
822 return temporaryImages.get(imageId);
831 * Locks the given Sone. A locked Sone will not be inserted by
832 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
838 public void lockSone(Sone sone) {
839 synchronized (lockedSones) {
840 if (lockedSones.add(sone)) {
841 coreListenerManager.fireSoneLocked(sone);
847 * Unlocks the given Sone.
849 * @see #lockSone(Sone)
853 public void unlockSone(Sone sone) {
854 synchronized (lockedSones) {
855 if (lockedSones.remove(sone)) {
856 coreListenerManager.fireSoneUnlocked(sone);
862 * Adds a local Sone from the given own identity.
865 * The own identity to create a Sone from
866 * @return The added (or already existing) Sone
868 public Sone addLocalSone(OwnIdentity ownIdentity) {
869 if (ownIdentity == null) {
870 logger.log(Level.WARNING, "Given OwnIdentity is null!");
873 synchronized (localSones) {
876 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
877 } catch (MalformedURLException mue1) {
878 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
881 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
882 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
884 /* TODO - load posts ’n stuff */
885 localSones.put(ownIdentity.getId(), sone);
886 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
887 soneInserter.addSoneInsertListener(this);
888 soneInserters.put(sone, soneInserter);
889 sone.setStatus(SoneStatus.idle);
891 soneInserter.start();
897 * Creates a new Sone for the given own identity.
900 * The own identity to create a Sone for
901 * @return The created Sone
903 public Sone createSone(OwnIdentity ownIdentity) {
904 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
905 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
908 Sone sone = addLocalSone(ownIdentity);
909 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
910 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
911 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
912 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
913 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
914 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
916 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
917 touchConfiguration();
922 * Adds the Sone of the given identity.
925 * The identity whose Sone to add
926 * @return The added or already existing Sone
928 public Sone addRemoteSone(Identity identity) {
929 if (identity == null) {
930 logger.log(Level.WARNING, "Given Identity is null!");
933 synchronized (remoteSones) {
934 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
935 boolean newSone = sone.getRequestUri() == null;
936 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
937 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
939 synchronized (knownSones) {
940 newSone = !knownSones.contains(sone.getId());
942 sone.setKnown(!newSone);
944 coreListenerManager.fireNewSoneFound(sone);
945 for (Sone localSone : getLocalSones()) {
946 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
947 followSone(localSone, sone);
952 soneDownloader.addSone(sone);
953 soneDownloaders.execute(new Runnable() {
956 @SuppressWarnings("synthetic-access")
958 soneDownloader.fetchSone(sone, sone.getRequestUri());
967 * Lets the given local Sone follow the Sone with the given ID.
970 * The local Sone that should follow another Sone
972 * The ID of the Sone to follow
974 public void followSone(Sone sone, String soneId) {
975 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
976 Sone followedSone = getSone(soneId, true);
977 if (followedSone == null) {
978 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
981 followSone(sone, getSone(soneId));
985 * Lets the given local Sone follow the other given Sone. If the given Sone
986 * was not followed by any local Sone before, this will mark all elements of
987 * the followed Sone as read that have been created before the current
991 * The local Sone that should follow the other Sone
992 * @param followedSone
993 * The Sone that should be followed
995 public void followSone(Sone sone, Sone followedSone) {
996 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
997 sone.addFriend(followedSone.getId());
998 synchronized (soneFollowingTimes) {
999 if (!soneFollowingTimes.containsKey(followedSone)) {
1000 long now = System.currentTimeMillis();
1001 soneFollowingTimes.put(followedSone, now);
1002 for (Post post : followedSone.getPosts()) {
1003 if (post.getTime() < now) {
1004 markPostKnown(post);
1007 for (PostReply reply : followedSone.getReplies()) {
1008 if (reply.getTime() < now) {
1009 markReplyKnown(reply);
1014 touchConfiguration();
1018 * Lets the given local Sone unfollow the Sone with the given ID.
1021 * The local Sone that should unfollow another Sone
1023 * The ID of the Sone being unfollowed
1025 public void unfollowSone(Sone sone, String soneId) {
1026 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1027 unfollowSone(sone, getSone(soneId, false));
1031 * Lets the given local Sone unfollow the other given Sone. If the given
1032 * local Sone is the last local Sone that followed the given Sone, its
1033 * following time will be removed.
1036 * The local Sone that should unfollow another Sone
1037 * @param unfollowedSone
1038 * The Sone being unfollowed
1040 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1041 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1042 sone.removeFriend(unfollowedSone.getId());
1043 boolean unfollowedSoneStillFollowed = false;
1044 for (Sone localSone : getLocalSones()) {
1045 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1047 if (!unfollowedSoneStillFollowed) {
1048 synchronized (soneFollowingTimes) {
1049 soneFollowingTimes.remove(unfollowedSone);
1052 touchConfiguration();
1056 * Sets the trust value of the given origin Sone for the target Sone.
1063 * The trust value (from {@code -100} to {@code 100})
1065 public void setTrust(Sone origin, Sone target, int trustValue) {
1066 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();
1067 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1071 * Removes any trust assignment for the given target Sone.
1078 public void removeTrust(Sone origin, Sone target) {
1079 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1080 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1084 * Assigns the configured positive trust value for the given target.
1091 public void trustSone(Sone origin, Sone target) {
1092 setTrust(origin, target, preferences.getPositiveTrust());
1096 * Assigns the configured negative trust value for the given target.
1103 public void distrustSone(Sone origin, Sone target) {
1104 setTrust(origin, target, preferences.getNegativeTrust());
1108 * Removes the trust assignment for the given target.
1115 public void untrustSone(Sone origin, Sone target) {
1116 removeTrust(origin, target);
1120 * Updates the stored Sone with the given Sone.
1125 public void updateSone(Sone sone) {
1126 updateSone(sone, false);
1130 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1131 * {@code true}, an older Sone than the current Sone can be given to restore
1135 * The Sone to update
1136 * @param soneRescueMode
1137 * {@code true} if the stored Sone should be updated regardless
1138 * of the age of the given Sone
1140 public void updateSone(Sone sone, boolean soneRescueMode) {
1141 if (hasSone(sone.getId())) {
1142 Sone storedSone = getSone(sone.getId());
1143 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1144 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1147 synchronized (posts) {
1148 if (!soneRescueMode) {
1149 for (Post post : storedSone.getPosts()) {
1150 posts.remove(post.getId());
1151 if (!sone.getPosts().contains(post)) {
1152 coreListenerManager.firePostRemoved(post);
1156 List<Post> storedPosts = storedSone.getPosts();
1157 synchronized (knownPosts) {
1158 for (Post post : sone.getPosts()) {
1159 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1160 if (!storedPosts.contains(post)) {
1161 if (post.getTime() < getSoneFollowingTime(sone)) {
1162 knownPosts.add(post.getId());
1163 post.setKnown(true);
1164 } else if (!knownPosts.contains(post.getId())) {
1165 coreListenerManager.fireNewPostFound(post);
1168 posts.put(post.getId(), post);
1172 synchronized (replies) {
1173 if (!soneRescueMode) {
1174 for (PostReply reply : storedSone.getReplies()) {
1175 replies.remove(reply.getId());
1176 if (!sone.getReplies().contains(reply)) {
1177 coreListenerManager.fireReplyRemoved(reply);
1181 Set<PostReply> storedReplies = storedSone.getReplies();
1182 synchronized (knownReplies) {
1183 for (PostReply reply : sone.getReplies()) {
1184 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1185 if (!storedReplies.contains(reply)) {
1186 if (reply.getTime() < getSoneFollowingTime(sone)) {
1187 knownReplies.add(reply.getId());
1188 reply.setKnown(true);
1189 } else if (!knownReplies.contains(reply.getId())) {
1190 coreListenerManager.fireNewReplyFound(reply);
1193 replies.put(reply.getId(), reply);
1197 synchronized (albums) {
1198 synchronized (images) {
1199 for (Album album : storedSone.getAlbums()) {
1200 albums.remove(album.getId());
1201 for (Image image : album.getImages()) {
1202 images.remove(image.getId());
1205 for (Album album : sone.getAlbums()) {
1206 albums.put(album.getId(), album);
1207 for (Image image : album.getImages()) {
1208 images.put(image.getId(), image);
1213 synchronized (storedSone) {
1214 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1215 storedSone.setTime(sone.getTime());
1217 storedSone.setClient(sone.getClient());
1218 storedSone.setProfile(sone.getProfile());
1219 if (soneRescueMode) {
1220 for (Post post : sone.getPosts()) {
1221 storedSone.addPost(post);
1223 for (PostReply reply : sone.getReplies()) {
1224 storedSone.addReply(reply);
1226 for (String likedPostId : sone.getLikedPostIds()) {
1227 storedSone.addLikedPostId(likedPostId);
1229 for (String likedReplyId : sone.getLikedReplyIds()) {
1230 storedSone.addLikedReplyId(likedReplyId);
1232 for (Album album : sone.getAlbums()) {
1233 storedSone.addAlbum(album);
1236 storedSone.setPosts(sone.getPosts());
1237 storedSone.setReplies(sone.getReplies());
1238 storedSone.setLikePostIds(sone.getLikedPostIds());
1239 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1240 storedSone.setAlbums(sone.getAlbums());
1242 storedSone.setLatestEdition(sone.getLatestEdition());
1248 * Deletes the given Sone. This will remove the Sone from the
1249 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1250 * and remove the context from its identity.
1253 * The Sone to delete
1255 public void deleteSone(Sone sone) {
1256 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1257 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1260 synchronized (localSones) {
1261 if (!localSones.containsKey(sone.getId())) {
1262 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1265 localSones.remove(sone.getId());
1266 SoneInserter soneInserter = soneInserters.remove(sone);
1267 soneInserter.removeSoneInsertListener(this);
1268 soneInserter.stop();
1270 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1271 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1273 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1274 } catch (ConfigurationException ce1) {
1275 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1280 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1281 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1284 * The Sone to mark as known
1286 public void markSoneKnown(Sone sone) {
1287 if (!sone.isKnown()) {
1288 sone.setKnown(true);
1289 synchronized (knownSones) {
1290 knownSones.add(sone.getId());
1292 coreListenerManager.fireMarkSoneKnown(sone);
1293 touchConfiguration();
1298 * Loads and updates the given Sone from the configuration. If any error is
1299 * encountered, loading is aborted and the given Sone is not changed.
1302 * The Sone to load and update
1304 public void loadSone(Sone sone) {
1305 if (!isLocalSone(sone)) {
1306 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1310 /* initialize options. */
1311 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1312 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1313 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1314 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1315 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1316 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1319 String sonePrefix = "Sone/" + sone.getId();
1320 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1321 if (soneTime == null) {
1322 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1325 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1328 Profile profile = new Profile(sone);
1329 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1330 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1331 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1332 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1333 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1334 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1336 /* load profile fields. */
1338 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1339 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1340 if (fieldName == null) {
1343 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1344 profile.addField(fieldName).setValue(fieldValue);
1348 Set<Post> posts = new HashSet<Post>();
1350 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1351 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1352 if (postId == null) {
1355 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1356 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1357 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1358 if ((postTime == 0) || (postText == null)) {
1359 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1362 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1363 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1364 post.setRecipient(getSone(postRecipientId));
1370 Set<PostReply> replies = new HashSet<PostReply>();
1372 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1373 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1374 if (replyId == null) {
1377 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1378 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1379 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1380 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1381 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1384 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1387 /* load post likes. */
1388 Set<String> likedPostIds = new HashSet<String>();
1390 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1391 if (likedPostId == null) {
1394 likedPostIds.add(likedPostId);
1397 /* load reply likes. */
1398 Set<String> likedReplyIds = new HashSet<String>();
1400 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1401 if (likedReplyId == null) {
1404 likedReplyIds.add(likedReplyId);
1408 Set<String> friends = new HashSet<String>();
1410 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1411 if (friendId == null) {
1414 friends.add(friendId);
1418 List<Album> topLevelAlbums = new ArrayList<Album>();
1419 int albumCounter = 0;
1421 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1422 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1423 if (albumId == null) {
1426 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1427 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1428 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1429 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1430 if ((albumTitle == null) || (albumDescription == null)) {
1431 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1434 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1435 if (albumParentId != null) {
1436 Album parentAlbum = getAlbum(albumParentId, false);
1437 if (parentAlbum == null) {
1438 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1441 parentAlbum.addAlbum(album);
1443 if (!topLevelAlbums.contains(album)) {
1444 topLevelAlbums.add(album);
1450 int imageCounter = 0;
1452 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1453 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1454 if (imageId == null) {
1457 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1458 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1459 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1460 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1461 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1462 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1463 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1464 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1465 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1468 Album album = getAlbum(albumId, false);
1469 if (album == null) {
1470 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1473 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1474 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1475 album.addImage(image);
1479 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1480 if (avatarId != null) {
1481 profile.setAvatar(getImage(avatarId, false));
1485 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1486 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1487 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1488 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1489 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1490 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1492 /* if we’re still here, Sone was loaded successfully. */
1493 synchronized (sone) {
1494 sone.setTime(soneTime);
1495 sone.setProfile(profile);
1496 sone.setPosts(posts);
1497 sone.setReplies(replies);
1498 sone.setLikePostIds(likedPostIds);
1499 sone.setLikeReplyIds(likedReplyIds);
1500 for (String friendId : friends) {
1501 followSone(sone, friendId);
1503 sone.setAlbums(topLevelAlbums);
1504 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1506 synchronized (knownSones) {
1507 for (String friend : friends) {
1508 knownSones.add(friend);
1511 synchronized (knownPosts) {
1512 for (Post post : posts) {
1513 knownPosts.add(post.getId());
1516 synchronized (knownReplies) {
1517 for (PostReply reply : replies) {
1518 knownReplies.add(reply.getId());
1524 * Creates a new post.
1527 * The Sone that creates the post
1529 * The text of the post
1530 * @return The created post
1532 public Post createPost(Sone sone, String text) {
1533 return createPost(sone, System.currentTimeMillis(), text);
1537 * Creates a new post.
1540 * The Sone that creates the post
1542 * The time of the post
1544 * The text of the post
1545 * @return The created post
1547 public Post createPost(Sone sone, long time, String text) {
1548 return createPost(sone, null, time, text);
1552 * Creates a new post.
1555 * The Sone that creates the post
1557 * The recipient Sone, or {@code null} if this post does not have
1560 * The text of the post
1561 * @return The created post
1563 public Post createPost(Sone sone, Sone recipient, String text) {
1564 return createPost(sone, recipient, System.currentTimeMillis(), 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 time of the post
1578 * The text of the post
1579 * @return The created post
1581 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1582 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1583 if (!isLocalSone(sone)) {
1584 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1587 final Post post = new PostImpl(sone, time, text);
1588 if (recipient != null) {
1589 post.setRecipient(recipient);
1591 synchronized (posts) {
1592 posts.put(post.getId(), post);
1594 coreListenerManager.fireNewPostFound(post);
1596 touchConfiguration();
1597 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1604 markPostKnown(post);
1606 }, "Mark " + post + " read.");
1611 * Deletes the given post.
1614 * The post to delete
1616 public void deletePost(Post post) {
1617 if (!isLocalSone(post.getSone())) {
1618 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1621 post.getSone().removePost(post);
1622 synchronized (posts) {
1623 posts.remove(post.getId());
1625 coreListenerManager.firePostRemoved(post);
1626 markPostKnown(post);
1627 touchConfiguration();
1631 * Marks the given post as known, if it is currently not a known post
1632 * (according to {@link Post#isKnown()}).
1635 * The post to mark as known
1637 public void markPostKnown(Post post) {
1638 post.setKnown(true);
1639 synchronized (knownPosts) {
1640 coreListenerManager.fireMarkPostKnown(post);
1641 if (knownPosts.add(post.getId())) {
1642 touchConfiguration();
1645 for (PostReply reply : getReplies(post)) {
1646 markReplyKnown(reply);
1651 * Bookmarks the given post.
1654 * The post to bookmark
1656 public void bookmark(Post post) {
1657 bookmarkPost(post.getId());
1661 * Bookmarks the post with the given ID.
1664 * The ID of the post to bookmark
1666 public void bookmarkPost(String id) {
1667 synchronized (bookmarkedPosts) {
1668 bookmarkedPosts.add(id);
1673 * Removes the given post from the bookmarks.
1676 * The post to unbookmark
1678 public void unbookmark(Post post) {
1679 unbookmarkPost(post.getId());
1683 * Removes the post with the given ID from the bookmarks.
1686 * The ID of the post to unbookmark
1688 public void unbookmarkPost(String id) {
1689 synchronized (bookmarkedPosts) {
1690 bookmarkedPosts.remove(id);
1695 * Creates a new reply.
1698 * The Sone that creates the reply
1700 * The post that this reply refers to
1702 * The text of the reply
1703 * @return The created reply
1705 public PostReply createReply(Sone sone, Post post, String text) {
1706 return createReply(sone, post, System.currentTimeMillis(), text);
1710 * Creates a new reply.
1713 * The Sone that creates the reply
1715 * The post that this reply refers to
1717 * The time of the reply
1719 * The text of the reply
1720 * @return The created reply
1722 public PostReply createReply(Sone sone, Post post, long time, String text) {
1723 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1724 if (!isLocalSone(sone)) {
1725 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1728 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1729 synchronized (replies) {
1730 replies.put(reply.getId(), reply);
1732 synchronized (knownReplies) {
1733 coreListenerManager.fireNewReplyFound(reply);
1735 sone.addReply(reply);
1736 touchConfiguration();
1737 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1744 markReplyKnown(reply);
1746 }, "Mark " + reply + " read.");
1751 * Deletes the given reply.
1754 * The reply to delete
1756 public void deleteReply(PostReply reply) {
1757 Sone sone = reply.getSone();
1758 if (!isLocalSone(sone)) {
1759 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1762 synchronized (replies) {
1763 replies.remove(reply.getId());
1765 synchronized (knownReplies) {
1766 markReplyKnown(reply);
1767 knownReplies.remove(reply.getId());
1769 sone.removeReply(reply);
1770 touchConfiguration();
1774 * Marks the given reply as known, if it is currently not a known reply
1775 * (according to {@link Reply#isKnown()}).
1778 * The reply to mark as known
1780 public void markReplyKnown(PostReply reply) {
1781 reply.setKnown(true);
1782 synchronized (knownReplies) {
1783 coreListenerManager.fireMarkReplyKnown(reply);
1784 if (knownReplies.add(reply.getId())) {
1785 touchConfiguration();
1791 * Creates a new top-level album for the given Sone.
1794 * The Sone to create the album for
1795 * @return The new album
1797 public Album createAlbum(Sone sone) {
1798 return createAlbum(sone, null);
1802 * Creates a new album for the given Sone.
1805 * The Sone to create the album for
1807 * The parent of the album (may be {@code null} to create a
1809 * @return The new album
1811 public Album createAlbum(Sone sone, Album parent) {
1812 Album album = new Album();
1813 synchronized (albums) {
1814 albums.put(album.getId(), album);
1816 album.setSone(sone);
1817 if (parent != null) {
1818 parent.addAlbum(album);
1820 sone.addAlbum(album);
1826 * Deletes the given album. The owner of the album has to be a local Sone,
1827 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1830 * The album to remove
1832 public void deleteAlbum(Album album) {
1833 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1834 if (!album.isEmpty()) {
1837 if (album.getParent() == null) {
1838 album.getSone().removeAlbum(album);
1840 album.getParent().removeAlbum(album);
1842 synchronized (albums) {
1843 albums.remove(album.getId());
1845 touchConfiguration();
1849 * Creates a new image.
1852 * The Sone creating the image
1854 * The album the image will be inserted into
1855 * @param temporaryImage
1856 * The temporary image to create the image from
1857 * @return The newly created image
1859 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1860 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();
1861 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1862 album.addImage(image);
1863 synchronized (images) {
1864 images.put(image.getId(), image);
1866 imageInserter.insertImage(temporaryImage, image);
1871 * Deletes the given image. This method will also delete a matching
1874 * @see #deleteTemporaryImage(TemporaryImage)
1876 * The image to delete
1878 public void deleteImage(Image image) {
1879 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1880 deleteTemporaryImage(image.getId());
1881 image.getAlbum().removeImage(image);
1882 synchronized (images) {
1883 images.remove(image.getId());
1885 touchConfiguration();
1889 * Creates a new temporary image.
1892 * The MIME type of the temporary image
1894 * The encoded data of the image
1895 * @return The temporary image
1897 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1898 TemporaryImage temporaryImage = new TemporaryImage();
1899 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1900 synchronized (temporaryImages) {
1901 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1903 return temporaryImage;
1907 * Deletes the given temporary image.
1909 * @param temporaryImage
1910 * The temporary image to delete
1912 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1913 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1914 deleteTemporaryImage(temporaryImage.getId());
1918 * Deletes the temporary image with the given ID.
1921 * The ID of the temporary image to delete
1923 public void deleteTemporaryImage(String imageId) {
1924 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1925 synchronized (temporaryImages) {
1926 temporaryImages.remove(imageId);
1928 Image image = getImage(imageId, false);
1929 if (image != null) {
1930 imageInserter.cancelImageInsert(image);
1935 * Notifies the core that the configuration, either of the core or of a
1936 * single local Sone, has changed, and that the configuration should be
1939 public void touchConfiguration() {
1940 lastConfigurationUpdate = System.currentTimeMillis();
1951 public void serviceStart() {
1952 loadConfiguration();
1953 updateChecker.addUpdateListener(this);
1954 updateChecker.start();
1955 webOfTrustUpdater.start();
1962 public void serviceRun() {
1963 long lastSaved = System.currentTimeMillis();
1964 while (!shouldStop()) {
1966 long now = System.currentTimeMillis();
1967 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1968 for (Sone localSone : getLocalSones()) {
1969 saveSone(localSone);
1971 saveConfiguration();
1981 public void serviceStop() {
1982 synchronized (localSones) {
1983 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1984 soneInserter.getValue().removeSoneInsertListener(this);
1985 soneInserter.getValue().stop();
1986 saveSone(soneInserter.getKey());
1989 saveConfiguration();
1990 webOfTrustUpdater.stop();
1991 updateChecker.stop();
1992 updateChecker.removeUpdateListener(this);
1993 soneDownloader.stop();
2001 * Saves the given Sone. This will persist all local settings for the given
2002 * Sone, such as the friends list and similar, private options.
2007 private synchronized void saveSone(Sone sone) {
2008 if (!isLocalSone(sone)) {
2009 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2012 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2013 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2017 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2019 /* save Sone into configuration. */
2020 String sonePrefix = "Sone/" + sone.getId();
2021 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2022 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2025 Profile profile = sone.getProfile();
2026 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2027 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2028 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2029 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2030 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2031 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2032 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2034 /* save profile fields. */
2035 int fieldCounter = 0;
2036 for (Field profileField : profile.getFields()) {
2037 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2038 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2039 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2041 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2044 int postCounter = 0;
2045 for (Post post : sone.getPosts()) {
2046 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2047 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2048 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2049 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2050 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2052 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2055 int replyCounter = 0;
2056 for (PostReply reply : sone.getReplies()) {
2057 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2058 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2059 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2060 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2061 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2063 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2065 /* save post likes. */
2066 int postLikeCounter = 0;
2067 for (String postId : sone.getLikedPostIds()) {
2068 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2070 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2072 /* save reply likes. */
2073 int replyLikeCounter = 0;
2074 for (String replyId : sone.getLikedReplyIds()) {
2075 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2077 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2080 int friendCounter = 0;
2081 for (String friendId : sone.getFriends()) {
2082 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2084 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2086 /* save albums. first, collect in a flat structure, top-level first. */
2087 List<Album> albums = sone.getAllAlbums();
2089 int albumCounter = 0;
2090 for (Album album : albums) {
2091 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2092 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2093 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2094 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2095 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2096 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2098 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2101 int imageCounter = 0;
2102 for (Album album : albums) {
2103 for (Image image : album.getImages()) {
2104 if (!image.isInserted()) {
2107 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2108 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2109 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2110 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2111 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2112 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2113 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2114 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2115 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2118 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2121 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2122 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2123 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2124 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2125 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2126 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2128 configuration.save();
2130 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2132 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2133 } catch (ConfigurationException ce1) {
2134 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2139 * Saves the current options.
2141 private void saveConfiguration() {
2142 synchronized (configuration) {
2143 if (storingConfiguration) {
2144 logger.log(Level.FINE, "Already storing configuration…");
2147 storingConfiguration = true;
2150 /* store the options first. */
2152 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2153 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2154 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2155 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2156 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2157 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2158 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2159 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2160 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2161 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2162 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2163 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2165 /* save known Sones. */
2166 int soneCounter = 0;
2167 synchronized (knownSones) {
2168 for (String knownSoneId : knownSones) {
2169 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2171 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2174 /* save Sone following times. */
2176 synchronized (soneFollowingTimes) {
2177 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2178 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2179 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2182 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2185 /* save known posts. */
2186 int postCounter = 0;
2187 synchronized (knownPosts) {
2188 for (String knownPostId : knownPosts) {
2189 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2191 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2194 /* save known replies. */
2195 int replyCounter = 0;
2196 synchronized (knownReplies) {
2197 for (String knownReplyId : knownReplies) {
2198 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2200 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2203 /* save bookmarked posts. */
2204 int bookmarkedPostCounter = 0;
2205 synchronized (bookmarkedPosts) {
2206 for (String bookmarkedPostId : bookmarkedPosts) {
2207 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2210 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2213 configuration.save();
2215 } catch (ConfigurationException ce1) {
2216 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2218 synchronized (configuration) {
2219 storingConfiguration = false;
2225 * Loads the configuration.
2227 @SuppressWarnings("unchecked")
2228 private void loadConfiguration() {
2229 /* create options. */
2230 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2233 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2234 SoneInserter.setInsertionDelay(newValue);
2238 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2239 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2240 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2241 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2242 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2243 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2244 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2245 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2246 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2249 @SuppressWarnings("synthetic-access")
2250 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2251 fcpInterface.setActive(newValue);
2254 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2257 @SuppressWarnings("synthetic-access")
2258 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2259 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2264 loadConfigurationValue("InsertionDelay");
2265 loadConfigurationValue("PostsPerPage");
2266 loadConfigurationValue("ImagesPerPage");
2267 loadConfigurationValue("CharactersPerPost");
2268 loadConfigurationValue("PostCutOffLength");
2269 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2270 loadConfigurationValue("PositiveTrust");
2271 loadConfigurationValue("NegativeTrust");
2272 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2273 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2274 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2276 /* load known Sones. */
2277 int soneCounter = 0;
2279 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2280 if (knownSoneId == null) {
2283 synchronized (knownSones) {
2284 knownSones.add(knownSoneId);
2288 /* load Sone following times. */
2291 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2292 if (soneId == null) {
2295 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2296 Sone followedSone = getSone(soneId);
2297 if (followedSone == null) {
2298 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2300 synchronized (soneFollowingTimes) {
2301 soneFollowingTimes.put(getSone(soneId), time);
2307 /* load known posts. */
2308 int postCounter = 0;
2310 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2311 if (knownPostId == null) {
2314 synchronized (knownPosts) {
2315 knownPosts.add(knownPostId);
2319 /* load known replies. */
2320 int replyCounter = 0;
2322 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2323 if (knownReplyId == null) {
2326 synchronized (knownReplies) {
2327 knownReplies.add(knownReplyId);
2331 /* load bookmarked posts. */
2332 int bookmarkedPostCounter = 0;
2334 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2335 if (bookmarkedPostId == null) {
2338 synchronized (bookmarkedPosts) {
2339 bookmarkedPosts.add(bookmarkedPostId);
2346 * Loads an {@link Integer} configuration value for the option with the
2347 * given name, logging validation failures.
2350 * The name of the option to load
2352 private void loadConfigurationValue(String optionName) {
2354 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2355 } catch (IllegalArgumentException iae1) {
2356 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2361 * Generate a Sone URI from the given URI and latest edition.
2364 * The URI to derive the Sone URI from
2365 * @return The derived URI
2367 private static FreenetURI getSoneUri(String uriString) {
2369 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2371 } catch (MalformedURLException mue1) {
2372 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2378 // INTERFACE IdentityListener
2385 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2386 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2387 if (ownIdentity.hasContext("Sone")) {
2388 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2389 addLocalSone(ownIdentity);
2397 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2398 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2399 trustedIdentities.remove(ownIdentity);
2406 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2407 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2408 trustedIdentities.get(ownIdentity).add(identity);
2409 addRemoteSone(identity);
2416 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2417 new Thread(new Runnable() {
2420 @SuppressWarnings("synthetic-access")
2422 Sone sone = getRemoteSone(identity.getId(), false);
2423 sone.setIdentity(identity);
2424 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2425 soneDownloader.addSone(sone);
2426 soneDownloader.fetchSone(sone);
2435 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2436 trustedIdentities.get(ownIdentity).remove(identity);
2437 boolean foundIdentity = false;
2438 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2439 if (trustedIdentity.getKey().equals(ownIdentity)) {
2442 if (trustedIdentity.getValue().contains(identity)) {
2443 foundIdentity = true;
2446 if (foundIdentity) {
2447 /* some local identity still trusts this identity, don’t remove. */
2450 Sone sone = getSone(identity.getId(), false);
2452 /* TODO - we don’t have the Sone anymore. should this happen? */
2455 synchronized (posts) {
2456 synchronized (knownPosts) {
2457 for (Post post : sone.getPosts()) {
2458 posts.remove(post.getId());
2459 coreListenerManager.firePostRemoved(post);
2463 synchronized (replies) {
2464 synchronized (knownReplies) {
2465 for (PostReply reply : sone.getReplies()) {
2466 replies.remove(reply.getId());
2467 coreListenerManager.fireReplyRemoved(reply);
2471 synchronized (remoteSones) {
2472 remoteSones.remove(identity.getId());
2474 coreListenerManager.fireSoneRemoved(sone);
2478 // INTERFACE UpdateListener
2485 public void updateFound(Version version, long releaseTime, long latestEdition) {
2486 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2490 // INTERFACE ImageInsertListener
2497 public void insertStarted(Sone sone) {
2498 coreListenerManager.fireSoneInserting(sone);
2505 public void insertFinished(Sone sone, long insertDuration) {
2506 coreListenerManager.fireSoneInserted(sone, insertDuration);
2513 public void insertAborted(Sone sone, Throwable cause) {
2514 coreListenerManager.fireSoneInsertAborted(sone, cause);
2518 // SONEINSERTLISTENER METHODS
2525 public void imageInsertStarted(Image image) {
2526 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2527 coreListenerManager.fireImageInsertStarted(image);
2534 public void imageInsertAborted(Image image) {
2535 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2536 coreListenerManager.fireImageInsertAborted(image);
2543 public void imageInsertFinished(Image image, FreenetURI key) {
2544 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2545 image.setKey(key.toString());
2546 deleteTemporaryImage(image.getId());
2547 touchConfiguration();
2548 coreListenerManager.fireImageInsertFinished(image);
2555 public void imageInsertFailed(Image image, Throwable cause) {
2556 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2557 coreListenerManager.fireImageInsertFailed(image, cause);
2561 * Convenience interface for external classes that want to access the core’s
2564 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2566 public static class Preferences {
2568 /** The wrapped options. */
2569 private final Options options;
2572 * Creates a new preferences object wrapped around the given options.
2575 * The options to wrap
2577 public Preferences(Options options) {
2578 this.options = options;
2582 * Returns the insertion delay.
2584 * @return The insertion delay
2586 public int getInsertionDelay() {
2587 return options.getIntegerOption("InsertionDelay").get();
2591 * Validates the given insertion delay.
2593 * @param insertionDelay
2594 * The insertion delay to validate
2595 * @return {@code true} if the given insertion delay was valid,
2596 * {@code false} otherwise
2598 public boolean validateInsertionDelay(Integer insertionDelay) {
2599 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2603 * Sets the insertion delay
2605 * @param insertionDelay
2606 * The new insertion delay, or {@code null} to restore it to
2608 * @return This preferences
2610 public Preferences setInsertionDelay(Integer insertionDelay) {
2611 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2616 * Returns the number of posts to show per page.
2618 * @return The number of posts to show per page
2620 public int getPostsPerPage() {
2621 return options.getIntegerOption("PostsPerPage").get();
2625 * Validates the number of posts per page.
2627 * @param postsPerPage
2628 * The number of posts per page
2629 * @return {@code true} if the number of posts per page was valid,
2630 * {@code false} otherwise
2632 public boolean validatePostsPerPage(Integer postsPerPage) {
2633 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2637 * Sets the number of posts to show per page.
2639 * @param postsPerPage
2640 * The number of posts to show per page
2641 * @return This preferences object
2643 public Preferences setPostsPerPage(Integer postsPerPage) {
2644 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2649 * Returns the number of images to show per page.
2651 * @return The number of images to show per page
2653 public int getImagesPerPage() {
2654 return options.getIntegerOption("ImagesPerPage").get();
2658 * Validates the number of images per page.
2660 * @param imagesPerPage
2661 * The number of images per page
2662 * @return {@code true} if the number of images per page was valid,
2663 * {@code false} otherwise
2665 public boolean validateImagesPerPage(Integer imagesPerPage) {
2666 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2670 * Sets the number of images per page.
2672 * @param imagesPerPage
2673 * The number of images per page
2674 * @return This preferences object
2676 public Preferences setImagesPerPage(Integer imagesPerPage) {
2677 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2682 * Returns the number of characters per post, or <code>-1</code> if the
2683 * posts should not be cut off.
2685 * @return The numbers of characters per post
2687 public int getCharactersPerPost() {
2688 return options.getIntegerOption("CharactersPerPost").get();
2692 * Validates the number of characters per post.
2694 * @param charactersPerPost
2695 * The number of characters per post
2696 * @return {@code true} if the number of characters per post was valid,
2697 * {@code false} otherwise
2699 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2700 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2704 * Sets the number of characters per post.
2706 * @param charactersPerPost
2707 * The number of characters per post, or <code>-1</code> to
2708 * not cut off the posts
2709 * @return This preferences objects
2711 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2712 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2717 * Returns the number of characters the shortened post should have.
2719 * @return The number of characters of the snippet
2721 public int getPostCutOffLength() {
2722 return options.getIntegerOption("PostCutOffLength").get();
2726 * Validates the number of characters after which to cut off the post.
2728 * @param postCutOffLength
2729 * The number of characters of the snippet
2730 * @return {@code true} if the number of characters of the snippet is
2731 * valid, {@code false} otherwise
2733 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2734 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2738 * Sets the number of characters the shortened post should have.
2740 * @param postCutOffLength
2741 * The number of characters of the snippet
2742 * @return This preferences
2744 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2745 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2750 * Returns whether Sone requires full access to be even visible.
2752 * @return {@code true} if Sone requires full access, {@code false}
2755 public boolean isRequireFullAccess() {
2756 return options.getBooleanOption("RequireFullAccess").get();
2760 * Sets whether Sone requires full access to be even visible.
2762 * @param requireFullAccess
2763 * {@code true} if Sone requires full access, {@code false}
2766 public void setRequireFullAccess(Boolean requireFullAccess) {
2767 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2771 * Returns the positive trust.
2773 * @return The positive trust
2775 public int getPositiveTrust() {
2776 return options.getIntegerOption("PositiveTrust").get();
2780 * Validates the positive trust.
2782 * @param positiveTrust
2783 * The positive trust to validate
2784 * @return {@code true} if the positive trust was valid, {@code false}
2787 public boolean validatePositiveTrust(Integer positiveTrust) {
2788 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2792 * Sets the positive trust.
2794 * @param positiveTrust
2795 * The new positive trust, or {@code null} to restore it to
2797 * @return This preferences
2799 public Preferences setPositiveTrust(Integer positiveTrust) {
2800 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2805 * Returns the negative trust.
2807 * @return The negative trust
2809 public int getNegativeTrust() {
2810 return options.getIntegerOption("NegativeTrust").get();
2814 * Validates the negative trust.
2816 * @param negativeTrust
2817 * The negative trust to validate
2818 * @return {@code true} if the negative trust was valid, {@code false}
2821 public boolean validateNegativeTrust(Integer negativeTrust) {
2822 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2826 * Sets the negative trust.
2828 * @param negativeTrust
2829 * The negative trust, or {@code null} to restore it to the
2831 * @return The preferences
2833 public Preferences setNegativeTrust(Integer negativeTrust) {
2834 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2839 * Returns the trust comment. This is the comment that is set in the web
2840 * of trust when a trust value is assigned to an identity.
2842 * @return The trust comment
2844 public String getTrustComment() {
2845 return options.getStringOption("TrustComment").get();
2849 * Sets the trust comment.
2851 * @param trustComment
2852 * The trust comment, or {@code null} to restore it to the
2854 * @return This preferences
2856 public Preferences setTrustComment(String trustComment) {
2857 options.getStringOption("TrustComment").set(trustComment);
2862 * Returns whether the {@link FcpInterface FCP interface} is currently
2865 * @see FcpInterface#setActive(boolean)
2866 * @return {@code true} if the FCP interface is currently active,
2867 * {@code false} otherwise
2869 public boolean isFcpInterfaceActive() {
2870 return options.getBooleanOption("ActivateFcpInterface").get();
2874 * Sets whether the {@link FcpInterface FCP interface} is currently
2877 * @see FcpInterface#setActive(boolean)
2878 * @param fcpInterfaceActive
2879 * {@code true} to activate the FCP interface, {@code false}
2880 * to deactivate the FCP interface
2881 * @return This preferences object
2883 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2884 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2889 * Returns the action level for which full access to the FCP interface
2892 * @return The action level for which full access to the FCP interface
2895 public FullAccessRequired getFcpFullAccessRequired() {
2896 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2900 * Sets the action level for which full access to the FCP interface is
2903 * @param fcpFullAccessRequired
2905 * @return This preferences
2907 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2908 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);