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.
615 * The ID of the reply to get
618 public PostReply getReply(String replyId) {
619 return getReply(replyId, true);
623 * Returns the reply with the given ID. If there is no reply with the given
624 * ID yet, a new one is created, unless {@code create} is false in which
625 * case {@code null} is returned.
628 * The ID of the reply to get
630 * {@code true} to always return a {@link Reply}, {@code false}
631 * to return {@code null} if no reply can be found
632 * @return The reply, or {@code null} if there is no such reply
634 public PostReply getReply(String replyId, boolean create) {
635 synchronized (replies) {
636 PostReply reply = replies.get(replyId);
637 if (create && (reply == null)) {
638 reply = new PostReply(replyId);
639 replies.put(replyId, reply);
646 * Returns all replies for the given post, order ascending by time.
649 * The post to get all replies for
650 * @return All replies for the given post
652 public List<PostReply> getReplies(Post post) {
653 Set<Sone> sones = getSones();
654 List<PostReply> replies = new ArrayList<PostReply>();
655 for (Sone sone : sones) {
656 for (PostReply reply : sone.getReplies()) {
657 if (reply.getPost().equals(post)) {
662 Collections.sort(replies, Reply.TIME_COMPARATOR);
667 * Returns all Sones that have liked the given post.
670 * The post to get the liking Sones for
671 * @return The Sones that like the given post
673 public Set<Sone> getLikes(Post post) {
674 Set<Sone> sones = new HashSet<Sone>();
675 for (Sone sone : getSones()) {
676 if (sone.getLikedPostIds().contains(post.getId())) {
684 * Returns all Sones that have liked the given reply.
687 * The reply to get the liking Sones for
688 * @return The Sones that like the given reply
690 public Set<Sone> getLikes(PostReply reply) {
691 Set<Sone> sones = new HashSet<Sone>();
692 for (Sone sone : getSones()) {
693 if (sone.getLikedReplyIds().contains(reply.getId())) {
701 * Returns whether the given post is bookmarked.
705 * @return {@code true} if the given post is bookmarked, {@code false}
708 public boolean isBookmarked(Post post) {
709 return isPostBookmarked(post.getId());
713 * Returns whether the post with the given ID is bookmarked.
716 * The ID of the post to check
717 * @return {@code true} if the post with the given ID is bookmarked,
718 * {@code false} otherwise
720 public boolean isPostBookmarked(String id) {
721 synchronized (bookmarkedPosts) {
722 return bookmarkedPosts.contains(id);
727 * Returns all currently known bookmarked posts.
729 * @return All bookmarked posts
731 public Set<Post> getBookmarkedPosts() {
732 Set<Post> posts = new HashSet<Post>();
733 synchronized (bookmarkedPosts) {
734 for (String bookmarkedPostId : bookmarkedPosts) {
735 Post post = getPost(bookmarkedPostId, false);
745 * Returns the album with the given ID, creating a new album if no album
746 * with the given ID can be found.
749 * The ID of the album
750 * @return The album with the given ID
752 public Album getAlbum(String albumId) {
753 return getAlbum(albumId, true);
757 * Returns the album with the given ID, optionally creating a new album if
758 * an album with the given ID can not be found.
761 * The ID of the album
763 * {@code true} to create a new album if none exists for the
765 * @return The album with the given ID, or {@code null} if no album with the
766 * given ID exists and {@code create} is {@code false}
768 public Album getAlbum(String albumId, boolean create) {
769 synchronized (albums) {
770 Album album = albums.get(albumId);
771 if (create && (album == null)) {
772 album = new Album(albumId);
773 albums.put(albumId, album);
780 * Returns the image with the given ID, creating it if necessary.
783 * The ID of the image
784 * @return The image with the given ID
786 public Image getImage(String imageId) {
787 return getImage(imageId, true);
791 * Returns the image with the given ID, optionally creating it if it does
795 * The ID of the image
797 * {@code true} to create an image if none exists with the given
799 * @return The image with the given ID, or {@code null} if none exists and
802 public Image getImage(String imageId, boolean create) {
803 synchronized (images) {
804 Image image = images.get(imageId);
805 if (create && (image == null)) {
806 image = new Image(imageId);
807 images.put(imageId, image);
814 * Returns the temporary image with the given ID.
817 * The ID of the temporary image
818 * @return The temporary image, or {@code null} if there is no temporary
819 * image with the given ID
821 public TemporaryImage getTemporaryImage(String imageId) {
822 synchronized (temporaryImages) {
823 return temporaryImages.get(imageId);
832 * Locks the given Sone. A locked Sone will not be inserted by
833 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
839 public void lockSone(Sone sone) {
840 synchronized (lockedSones) {
841 if (lockedSones.add(sone)) {
842 coreListenerManager.fireSoneLocked(sone);
848 * Unlocks the given Sone.
850 * @see #lockSone(Sone)
854 public void unlockSone(Sone sone) {
855 synchronized (lockedSones) {
856 if (lockedSones.remove(sone)) {
857 coreListenerManager.fireSoneUnlocked(sone);
863 * Adds a local Sone from the given own identity.
866 * The own identity to create a Sone from
867 * @return The added (or already existing) Sone
869 public Sone addLocalSone(OwnIdentity ownIdentity) {
870 if (ownIdentity == null) {
871 logger.log(Level.WARNING, "Given OwnIdentity is null!");
874 synchronized (localSones) {
877 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
878 } catch (MalformedURLException mue1) {
879 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
882 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
883 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
885 /* TODO - load posts ’n stuff */
886 localSones.put(ownIdentity.getId(), sone);
887 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
888 soneInserter.addSoneInsertListener(this);
889 soneInserters.put(sone, soneInserter);
890 sone.setStatus(SoneStatus.idle);
892 soneInserter.start();
898 * Creates a new Sone for the given own identity.
901 * The own identity to create a Sone for
902 * @return The created Sone
904 public Sone createSone(OwnIdentity ownIdentity) {
905 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
906 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
909 Sone sone = addLocalSone(ownIdentity);
910 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
911 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
912 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
913 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
914 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
915 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
917 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
918 touchConfiguration();
923 * Adds the Sone of the given identity.
926 * The identity whose Sone to add
927 * @return The added or already existing Sone
929 public Sone addRemoteSone(Identity identity) {
930 if (identity == null) {
931 logger.log(Level.WARNING, "Given Identity is null!");
934 synchronized (remoteSones) {
935 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
936 boolean newSone = sone.getRequestUri() == null;
937 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
938 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
940 synchronized (knownSones) {
941 newSone = !knownSones.contains(sone.getId());
943 sone.setKnown(!newSone);
945 coreListenerManager.fireNewSoneFound(sone);
946 for (Sone localSone : getLocalSones()) {
947 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
948 followSone(localSone, sone);
953 soneDownloader.addSone(sone);
954 soneDownloaders.execute(new Runnable() {
957 @SuppressWarnings("synthetic-access")
959 soneDownloader.fetchSone(sone, sone.getRequestUri());
968 * Lets the given local Sone follow the Sone with the given ID.
971 * The local Sone that should follow another Sone
973 * The ID of the Sone to follow
975 public void followSone(Sone sone, String soneId) {
976 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
977 Sone followedSone = getSone(soneId, true);
978 if (followedSone == null) {
979 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
982 followSone(sone, getSone(soneId));
986 * Lets the given local Sone follow the other given Sone. If the given Sone
987 * was not followed by any local Sone before, this will mark all elements of
988 * the followed Sone as read that have been created before the current
992 * The local Sone that should follow the other Sone
993 * @param followedSone
994 * The Sone that should be followed
996 public void followSone(Sone sone, Sone followedSone) {
997 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
998 sone.addFriend(followedSone.getId());
999 synchronized (soneFollowingTimes) {
1000 if (!soneFollowingTimes.containsKey(followedSone)) {
1001 long now = System.currentTimeMillis();
1002 soneFollowingTimes.put(followedSone, now);
1003 for (Post post : followedSone.getPosts()) {
1004 if (post.getTime() < now) {
1005 markPostKnown(post);
1008 for (PostReply reply : followedSone.getReplies()) {
1009 if (reply.getTime() < now) {
1010 markReplyKnown(reply);
1015 touchConfiguration();
1019 * Lets the given local Sone unfollow the Sone with the given ID.
1022 * The local Sone that should unfollow another Sone
1024 * The ID of the Sone being unfollowed
1026 public void unfollowSone(Sone sone, String soneId) {
1027 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1028 unfollowSone(sone, getSone(soneId, false));
1032 * Lets the given local Sone unfollow the other given Sone. If the given
1033 * local Sone is the last local Sone that followed the given Sone, its
1034 * following time will be removed.
1037 * The local Sone that should unfollow another Sone
1038 * @param unfollowedSone
1039 * The Sone being unfollowed
1041 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1042 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1043 sone.removeFriend(unfollowedSone.getId());
1044 boolean unfollowedSoneStillFollowed = false;
1045 for (Sone localSone : getLocalSones()) {
1046 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1048 if (!unfollowedSoneStillFollowed) {
1049 synchronized (soneFollowingTimes) {
1050 soneFollowingTimes.remove(unfollowedSone);
1053 touchConfiguration();
1057 * Sets the trust value of the given origin Sone for the target Sone.
1064 * The trust value (from {@code -100} to {@code 100})
1066 public void setTrust(Sone origin, Sone target, int trustValue) {
1067 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();
1068 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1072 * Removes any trust assignment for the given target Sone.
1079 public void removeTrust(Sone origin, Sone target) {
1080 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1081 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1085 * Assigns the configured positive trust value for the given target.
1092 public void trustSone(Sone origin, Sone target) {
1093 setTrust(origin, target, preferences.getPositiveTrust());
1097 * Assigns the configured negative trust value for the given target.
1104 public void distrustSone(Sone origin, Sone target) {
1105 setTrust(origin, target, preferences.getNegativeTrust());
1109 * Removes the trust assignment for the given target.
1116 public void untrustSone(Sone origin, Sone target) {
1117 removeTrust(origin, target);
1121 * Updates the stored Sone with the given Sone.
1126 public void updateSone(Sone sone) {
1127 updateSone(sone, false);
1131 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1132 * {@code true}, an older Sone than the current Sone can be given to restore
1136 * The Sone to update
1137 * @param soneRescueMode
1138 * {@code true} if the stored Sone should be updated regardless
1139 * of the age of the given Sone
1141 public void updateSone(Sone sone, boolean soneRescueMode) {
1142 if (hasSone(sone.getId())) {
1143 Sone storedSone = getSone(sone.getId());
1144 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1145 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1148 synchronized (posts) {
1149 if (!soneRescueMode) {
1150 for (Post post : storedSone.getPosts()) {
1151 posts.remove(post.getId());
1152 if (!sone.getPosts().contains(post)) {
1153 coreListenerManager.firePostRemoved(post);
1157 List<Post> storedPosts = storedSone.getPosts();
1158 synchronized (knownPosts) {
1159 for (Post post : sone.getPosts()) {
1160 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1161 if (!storedPosts.contains(post)) {
1162 if (post.getTime() < getSoneFollowingTime(sone)) {
1163 knownPosts.add(post.getId());
1164 post.setKnown(true);
1165 } else if (!knownPosts.contains(post.getId())) {
1166 coreListenerManager.fireNewPostFound(post);
1169 posts.put(post.getId(), post);
1173 synchronized (replies) {
1174 if (!soneRescueMode) {
1175 for (PostReply reply : storedSone.getReplies()) {
1176 replies.remove(reply.getId());
1177 if (!sone.getReplies().contains(reply)) {
1178 coreListenerManager.fireReplyRemoved(reply);
1182 Set<PostReply> storedReplies = storedSone.getReplies();
1183 synchronized (knownReplies) {
1184 for (PostReply reply : sone.getReplies()) {
1185 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1186 if (!storedReplies.contains(reply)) {
1187 if (reply.getTime() < getSoneFollowingTime(sone)) {
1188 knownReplies.add(reply.getId());
1189 reply.setKnown(true);
1190 } else if (!knownReplies.contains(reply.getId())) {
1191 coreListenerManager.fireNewReplyFound(reply);
1194 replies.put(reply.getId(), reply);
1198 synchronized (albums) {
1199 synchronized (images) {
1200 for (Album album : storedSone.getAlbums()) {
1201 albums.remove(album.getId());
1202 for (Image image : album.getImages()) {
1203 images.remove(image.getId());
1206 for (Album album : sone.getAlbums()) {
1207 albums.put(album.getId(), album);
1208 for (Image image : album.getImages()) {
1209 images.put(image.getId(), image);
1214 synchronized (storedSone) {
1215 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1216 storedSone.setTime(sone.getTime());
1218 storedSone.setClient(sone.getClient());
1219 storedSone.setProfile(sone.getProfile());
1220 if (soneRescueMode) {
1221 for (Post post : sone.getPosts()) {
1222 storedSone.addPost(post);
1224 for (PostReply reply : sone.getReplies()) {
1225 storedSone.addReply(reply);
1227 for (String likedPostId : sone.getLikedPostIds()) {
1228 storedSone.addLikedPostId(likedPostId);
1230 for (String likedReplyId : sone.getLikedReplyIds()) {
1231 storedSone.addLikedReplyId(likedReplyId);
1233 for (Album album : sone.getAlbums()) {
1234 storedSone.addAlbum(album);
1237 storedSone.setPosts(sone.getPosts());
1238 storedSone.setReplies(sone.getReplies());
1239 storedSone.setLikePostIds(sone.getLikedPostIds());
1240 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1241 storedSone.setAlbums(sone.getAlbums());
1243 storedSone.setLatestEdition(sone.getLatestEdition());
1249 * Deletes the given Sone. This will remove the Sone from the
1250 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1251 * and remove the context from its identity.
1254 * The Sone to delete
1256 public void deleteSone(Sone sone) {
1257 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1258 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1261 synchronized (localSones) {
1262 if (!localSones.containsKey(sone.getId())) {
1263 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1266 localSones.remove(sone.getId());
1267 SoneInserter soneInserter = soneInserters.remove(sone);
1268 soneInserter.removeSoneInsertListener(this);
1269 soneInserter.stop();
1271 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1272 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1274 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1275 } catch (ConfigurationException ce1) {
1276 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1281 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1282 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1285 * The Sone to mark as known
1287 public void markSoneKnown(Sone sone) {
1288 if (!sone.isKnown()) {
1289 sone.setKnown(true);
1290 synchronized (knownSones) {
1291 knownSones.add(sone.getId());
1293 coreListenerManager.fireMarkSoneKnown(sone);
1294 touchConfiguration();
1299 * Loads and updates the given Sone from the configuration. If any error is
1300 * encountered, loading is aborted and the given Sone is not changed.
1303 * The Sone to load and update
1305 public void loadSone(Sone sone) {
1306 if (!isLocalSone(sone)) {
1307 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1311 /* initialize options. */
1312 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1313 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1314 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1315 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1316 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1317 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1320 String sonePrefix = "Sone/" + sone.getId();
1321 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1322 if (soneTime == null) {
1323 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1326 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1329 Profile profile = new Profile(sone);
1330 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1331 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1332 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1333 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1334 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1335 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1337 /* load profile fields. */
1339 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1340 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1341 if (fieldName == null) {
1344 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1345 profile.addField(fieldName).setValue(fieldValue);
1349 Set<Post> posts = new HashSet<Post>();
1351 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1352 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1353 if (postId == null) {
1356 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1357 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1358 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1359 if ((postTime == 0) || (postText == null)) {
1360 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1363 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1364 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1365 post.setRecipient(getSone(postRecipientId));
1371 Set<PostReply> replies = new HashSet<PostReply>();
1373 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1374 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1375 if (replyId == null) {
1378 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1379 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1380 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1381 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1382 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1385 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1388 /* load post likes. */
1389 Set<String> likedPostIds = new HashSet<String>();
1391 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1392 if (likedPostId == null) {
1395 likedPostIds.add(likedPostId);
1398 /* load reply likes. */
1399 Set<String> likedReplyIds = new HashSet<String>();
1401 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1402 if (likedReplyId == null) {
1405 likedReplyIds.add(likedReplyId);
1409 Set<String> friends = new HashSet<String>();
1411 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1412 if (friendId == null) {
1415 friends.add(friendId);
1419 List<Album> topLevelAlbums = new ArrayList<Album>();
1420 int albumCounter = 0;
1422 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1423 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1424 if (albumId == null) {
1427 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1428 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1429 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1430 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1431 if ((albumTitle == null) || (albumDescription == null)) {
1432 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1435 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1436 if (albumParentId != null) {
1437 Album parentAlbum = getAlbum(albumParentId, false);
1438 if (parentAlbum == null) {
1439 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1442 parentAlbum.addAlbum(album);
1444 if (!topLevelAlbums.contains(album)) {
1445 topLevelAlbums.add(album);
1451 int imageCounter = 0;
1453 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1454 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1455 if (imageId == null) {
1458 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1459 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1460 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1461 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1462 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1463 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1464 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1465 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1466 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1469 Album album = getAlbum(albumId, false);
1470 if (album == null) {
1471 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1474 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1475 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1476 album.addImage(image);
1480 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1481 if (avatarId != null) {
1482 profile.setAvatar(getImage(avatarId, false));
1486 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1487 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1488 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1489 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1490 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1491 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1493 /* if we’re still here, Sone was loaded successfully. */
1494 synchronized (sone) {
1495 sone.setTime(soneTime);
1496 sone.setProfile(profile);
1497 sone.setPosts(posts);
1498 sone.setReplies(replies);
1499 sone.setLikePostIds(likedPostIds);
1500 sone.setLikeReplyIds(likedReplyIds);
1501 for (String friendId : friends) {
1502 followSone(sone, friendId);
1504 sone.setAlbums(topLevelAlbums);
1505 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1507 synchronized (knownSones) {
1508 for (String friend : friends) {
1509 knownSones.add(friend);
1512 synchronized (knownPosts) {
1513 for (Post post : posts) {
1514 knownPosts.add(post.getId());
1517 synchronized (knownReplies) {
1518 for (PostReply reply : replies) {
1519 knownReplies.add(reply.getId());
1525 * Creates a new post.
1528 * The Sone that creates the post
1530 * The text of the post
1531 * @return The created post
1533 public Post createPost(Sone sone, String text) {
1534 return createPost(sone, System.currentTimeMillis(), text);
1538 * Creates a new post.
1541 * The Sone that creates the post
1543 * The time of the post
1545 * The text of the post
1546 * @return The created post
1548 public Post createPost(Sone sone, long time, String text) {
1549 return createPost(sone, null, time, text);
1553 * Creates a new post.
1556 * The Sone that creates the post
1558 * The recipient Sone, or {@code null} if this post does not have
1561 * The text of the post
1562 * @return The created post
1564 public Post createPost(Sone sone, Sone recipient, String text) {
1565 return createPost(sone, recipient, System.currentTimeMillis(), text);
1569 * Creates a new post.
1572 * The Sone that creates the post
1574 * The recipient Sone, or {@code null} if this post does not have
1577 * The time of the post
1579 * The text of the post
1580 * @return The created post
1582 public Post createPost(Sone sone, Sone recipient, long time, String text) {
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 if (!isLocalSone(sone)) {
1724 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1727 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1728 synchronized (replies) {
1729 replies.put(reply.getId(), reply);
1731 synchronized (knownReplies) {
1732 coreListenerManager.fireNewReplyFound(reply);
1734 sone.addReply(reply);
1735 touchConfiguration();
1736 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1743 markReplyKnown(reply);
1745 }, "Mark " + reply + " read.");
1750 * Deletes the given reply.
1753 * The reply to delete
1755 public void deleteReply(PostReply reply) {
1756 Sone sone = reply.getSone();
1757 if (!isLocalSone(sone)) {
1758 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1761 synchronized (replies) {
1762 replies.remove(reply.getId());
1764 synchronized (knownReplies) {
1765 markReplyKnown(reply);
1766 knownReplies.remove(reply.getId());
1768 sone.removeReply(reply);
1769 touchConfiguration();
1773 * Marks the given reply as known, if it is currently not a known reply
1774 * (according to {@link Reply#isKnown()}).
1777 * The reply to mark as known
1779 public void markReplyKnown(PostReply reply) {
1780 reply.setKnown(true);
1781 synchronized (knownReplies) {
1782 coreListenerManager.fireMarkReplyKnown(reply);
1783 if (knownReplies.add(reply.getId())) {
1784 touchConfiguration();
1790 * Creates a new top-level album for the given Sone.
1793 * The Sone to create the album for
1794 * @return The new album
1796 public Album createAlbum(Sone sone) {
1797 return createAlbum(sone, null);
1801 * Creates a new album for the given Sone.
1804 * The Sone to create the album for
1806 * The parent of the album (may be {@code null} to create a
1808 * @return The new album
1810 public Album createAlbum(Sone sone, Album parent) {
1811 Album album = new Album();
1812 synchronized (albums) {
1813 albums.put(album.getId(), album);
1815 album.setSone(sone);
1816 if (parent != null) {
1817 parent.addAlbum(album);
1819 sone.addAlbum(album);
1825 * Deletes the given album. The owner of the album has to be a local Sone,
1826 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1829 * The album to remove
1831 public void deleteAlbum(Album album) {
1832 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1833 if (!album.isEmpty()) {
1836 if (album.getParent() == null) {
1837 album.getSone().removeAlbum(album);
1839 album.getParent().removeAlbum(album);
1841 synchronized (albums) {
1842 albums.remove(album.getId());
1844 touchConfiguration();
1848 * Creates a new image.
1851 * The Sone creating the image
1853 * The album the image will be inserted into
1854 * @param temporaryImage
1855 * The temporary image to create the image from
1856 * @return The newly created image
1858 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1859 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();
1860 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1861 album.addImage(image);
1862 synchronized (images) {
1863 images.put(image.getId(), image);
1865 imageInserter.insertImage(temporaryImage, image);
1870 * Deletes the given image. This method will also delete a matching
1873 * @see #deleteTemporaryImage(TemporaryImage)
1875 * The image to delete
1877 public void deleteImage(Image image) {
1878 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1879 deleteTemporaryImage(image.getId());
1880 image.getAlbum().removeImage(image);
1881 synchronized (images) {
1882 images.remove(image.getId());
1884 touchConfiguration();
1888 * Creates a new temporary image.
1891 * The MIME type of the temporary image
1893 * The encoded data of the image
1894 * @return The temporary image
1896 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1897 TemporaryImage temporaryImage = new TemporaryImage();
1898 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1899 synchronized (temporaryImages) {
1900 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1902 return temporaryImage;
1906 * Deletes the given temporary image.
1908 * @param temporaryImage
1909 * The temporary image to delete
1911 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1912 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1913 deleteTemporaryImage(temporaryImage.getId());
1917 * Deletes the temporary image with the given ID.
1920 * The ID of the temporary image to delete
1922 public void deleteTemporaryImage(String imageId) {
1923 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1924 synchronized (temporaryImages) {
1925 temporaryImages.remove(imageId);
1927 Image image = getImage(imageId, false);
1928 if (image != null) {
1929 imageInserter.cancelImageInsert(image);
1934 * Notifies the core that the configuration, either of the core or of a
1935 * single local Sone, has changed, and that the configuration should be
1938 public void touchConfiguration() {
1939 lastConfigurationUpdate = System.currentTimeMillis();
1950 public void serviceStart() {
1951 loadConfiguration();
1952 updateChecker.addUpdateListener(this);
1953 updateChecker.start();
1954 webOfTrustUpdater.start();
1961 public void serviceRun() {
1962 long lastSaved = System.currentTimeMillis();
1963 while (!shouldStop()) {
1965 long now = System.currentTimeMillis();
1966 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1967 for (Sone localSone : getLocalSones()) {
1968 saveSone(localSone);
1970 saveConfiguration();
1980 public void serviceStop() {
1981 synchronized (localSones) {
1982 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1983 soneInserter.getValue().removeSoneInsertListener(this);
1984 soneInserter.getValue().stop();
1985 saveSone(soneInserter.getKey());
1988 saveConfiguration();
1989 webOfTrustUpdater.stop();
1990 updateChecker.stop();
1991 updateChecker.removeUpdateListener(this);
1992 soneDownloader.stop();
2000 * Saves the given Sone. This will persist all local settings for the given
2001 * Sone, such as the friends list and similar, private options.
2006 private synchronized void saveSone(Sone sone) {
2007 if (!isLocalSone(sone)) {
2008 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2011 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2012 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2016 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2018 /* save Sone into configuration. */
2019 String sonePrefix = "Sone/" + sone.getId();
2020 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2021 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2024 Profile profile = sone.getProfile();
2025 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2026 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2027 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2028 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2029 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2030 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2031 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2033 /* save profile fields. */
2034 int fieldCounter = 0;
2035 for (Field profileField : profile.getFields()) {
2036 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2037 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2038 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2040 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2043 int postCounter = 0;
2044 for (Post post : sone.getPosts()) {
2045 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2046 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2047 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2048 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2049 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2051 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2054 int replyCounter = 0;
2055 for (PostReply reply : sone.getReplies()) {
2056 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2057 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2058 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2059 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2060 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2062 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2064 /* save post likes. */
2065 int postLikeCounter = 0;
2066 for (String postId : sone.getLikedPostIds()) {
2067 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2069 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2071 /* save reply likes. */
2072 int replyLikeCounter = 0;
2073 for (String replyId : sone.getLikedReplyIds()) {
2074 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2076 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2079 int friendCounter = 0;
2080 for (String friendId : sone.getFriends()) {
2081 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2083 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2085 /* save albums. first, collect in a flat structure, top-level first. */
2086 List<Album> albums = sone.getAllAlbums();
2088 int albumCounter = 0;
2089 for (Album album : albums) {
2090 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2091 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2092 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2093 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2094 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2095 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2097 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2100 int imageCounter = 0;
2101 for (Album album : albums) {
2102 for (Image image : album.getImages()) {
2103 if (!image.isInserted()) {
2106 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2107 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2108 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2109 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2110 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2111 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2112 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2113 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2114 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2117 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2120 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2121 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2122 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2123 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2124 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2125 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2127 configuration.save();
2129 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2131 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2132 } catch (ConfigurationException ce1) {
2133 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2138 * Saves the current options.
2140 private void saveConfiguration() {
2141 synchronized (configuration) {
2142 if (storingConfiguration) {
2143 logger.log(Level.FINE, "Already storing configuration…");
2146 storingConfiguration = true;
2149 /* store the options first. */
2151 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2152 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2153 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2154 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2155 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2156 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2157 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2158 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2159 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2160 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2161 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2162 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2164 /* save known Sones. */
2165 int soneCounter = 0;
2166 synchronized (knownSones) {
2167 for (String knownSoneId : knownSones) {
2168 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2170 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2173 /* save Sone following times. */
2175 synchronized (soneFollowingTimes) {
2176 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2177 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2178 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2181 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2184 /* save known posts. */
2185 int postCounter = 0;
2186 synchronized (knownPosts) {
2187 for (String knownPostId : knownPosts) {
2188 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2190 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2193 /* save known replies. */
2194 int replyCounter = 0;
2195 synchronized (knownReplies) {
2196 for (String knownReplyId : knownReplies) {
2197 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2199 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2202 /* save bookmarked posts. */
2203 int bookmarkedPostCounter = 0;
2204 synchronized (bookmarkedPosts) {
2205 for (String bookmarkedPostId : bookmarkedPosts) {
2206 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2209 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2212 configuration.save();
2214 } catch (ConfigurationException ce1) {
2215 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2217 synchronized (configuration) {
2218 storingConfiguration = false;
2224 * Loads the configuration.
2226 @SuppressWarnings("unchecked")
2227 private void loadConfiguration() {
2228 /* create options. */
2229 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2232 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2233 SoneInserter.setInsertionDelay(newValue);
2237 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2238 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2239 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2240 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2241 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2242 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2243 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2244 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2245 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2248 @SuppressWarnings("synthetic-access")
2249 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2250 fcpInterface.setActive(newValue);
2253 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2256 @SuppressWarnings("synthetic-access")
2257 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2258 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2263 loadConfigurationValue("InsertionDelay");
2264 loadConfigurationValue("PostsPerPage");
2265 loadConfigurationValue("ImagesPerPage");
2266 loadConfigurationValue("CharactersPerPost");
2267 loadConfigurationValue("PostCutOffLength");
2268 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2269 loadConfigurationValue("PositiveTrust");
2270 loadConfigurationValue("NegativeTrust");
2271 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2272 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2273 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2275 /* load known Sones. */
2276 int soneCounter = 0;
2278 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2279 if (knownSoneId == null) {
2282 synchronized (knownSones) {
2283 knownSones.add(knownSoneId);
2287 /* load Sone following times. */
2290 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2291 if (soneId == null) {
2294 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2295 Sone followedSone = getSone(soneId);
2296 if (followedSone == null) {
2297 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2299 synchronized (soneFollowingTimes) {
2300 soneFollowingTimes.put(getSone(soneId), time);
2306 /* load known posts. */
2307 int postCounter = 0;
2309 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2310 if (knownPostId == null) {
2313 synchronized (knownPosts) {
2314 knownPosts.add(knownPostId);
2318 /* load known replies. */
2319 int replyCounter = 0;
2321 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2322 if (knownReplyId == null) {
2325 synchronized (knownReplies) {
2326 knownReplies.add(knownReplyId);
2330 /* load bookmarked posts. */
2331 int bookmarkedPostCounter = 0;
2333 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2334 if (bookmarkedPostId == null) {
2337 synchronized (bookmarkedPosts) {
2338 bookmarkedPosts.add(bookmarkedPostId);
2345 * Loads an {@link Integer} configuration value for the option with the
2346 * given name, logging validation failures.
2349 * The name of the option to load
2351 private void loadConfigurationValue(String optionName) {
2353 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2354 } catch (IllegalArgumentException iae1) {
2355 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2360 * Generate a Sone URI from the given URI and latest edition.
2363 * The URI to derive the Sone URI from
2364 * @return The derived URI
2366 private static FreenetURI getSoneUri(String uriString) {
2368 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2370 } catch (MalformedURLException mue1) {
2371 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2377 // INTERFACE IdentityListener
2384 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2385 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2386 if (ownIdentity.hasContext("Sone")) {
2387 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2388 addLocalSone(ownIdentity);
2396 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2397 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2398 trustedIdentities.remove(ownIdentity);
2405 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2406 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2407 trustedIdentities.get(ownIdentity).add(identity);
2408 addRemoteSone(identity);
2415 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2416 new Thread(new Runnable() {
2419 @SuppressWarnings("synthetic-access")
2421 Sone sone = getRemoteSone(identity.getId(), false);
2422 sone.setIdentity(identity);
2423 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2424 soneDownloader.addSone(sone);
2425 soneDownloader.fetchSone(sone);
2434 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2435 trustedIdentities.get(ownIdentity).remove(identity);
2436 boolean foundIdentity = false;
2437 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2438 if (trustedIdentity.getKey().equals(ownIdentity)) {
2441 if (trustedIdentity.getValue().contains(identity)) {
2442 foundIdentity = true;
2445 if (foundIdentity) {
2446 /* some local identity still trusts this identity, don’t remove. */
2449 Sone sone = getSone(identity.getId(), false);
2451 /* TODO - we don’t have the Sone anymore. should this happen? */
2454 synchronized (posts) {
2455 synchronized (knownPosts) {
2456 for (Post post : sone.getPosts()) {
2457 posts.remove(post.getId());
2458 coreListenerManager.firePostRemoved(post);
2462 synchronized (replies) {
2463 synchronized (knownReplies) {
2464 for (PostReply reply : sone.getReplies()) {
2465 replies.remove(reply.getId());
2466 coreListenerManager.fireReplyRemoved(reply);
2470 synchronized (remoteSones) {
2471 remoteSones.remove(identity.getId());
2473 coreListenerManager.fireSoneRemoved(sone);
2477 // INTERFACE UpdateListener
2484 public void updateFound(Version version, long releaseTime, long latestEdition) {
2485 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2489 // INTERFACE ImageInsertListener
2496 public void insertStarted(Sone sone) {
2497 coreListenerManager.fireSoneInserting(sone);
2504 public void insertFinished(Sone sone, long insertDuration) {
2505 coreListenerManager.fireSoneInserted(sone, insertDuration);
2512 public void insertAborted(Sone sone, Throwable cause) {
2513 coreListenerManager.fireSoneInsertAborted(sone, cause);
2517 // SONEINSERTLISTENER METHODS
2524 public void imageInsertStarted(Image image) {
2525 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2526 coreListenerManager.fireImageInsertStarted(image);
2533 public void imageInsertAborted(Image image) {
2534 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2535 coreListenerManager.fireImageInsertAborted(image);
2542 public void imageInsertFinished(Image image, FreenetURI key) {
2543 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2544 image.setKey(key.toString());
2545 deleteTemporaryImage(image.getId());
2546 touchConfiguration();
2547 coreListenerManager.fireImageInsertFinished(image);
2554 public void imageInsertFailed(Image image, Throwable cause) {
2555 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2556 coreListenerManager.fireImageInsertFailed(image, cause);
2560 * Convenience interface for external classes that want to access the core’s
2563 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2565 public static class Preferences {
2567 /** The wrapped options. */
2568 private final Options options;
2571 * Creates a new preferences object wrapped around the given options.
2574 * The options to wrap
2576 public Preferences(Options options) {
2577 this.options = options;
2581 * Returns the insertion delay.
2583 * @return The insertion delay
2585 public int getInsertionDelay() {
2586 return options.getIntegerOption("InsertionDelay").get();
2590 * Validates the given insertion delay.
2592 * @param insertionDelay
2593 * The insertion delay to validate
2594 * @return {@code true} if the given insertion delay was valid,
2595 * {@code false} otherwise
2597 public boolean validateInsertionDelay(Integer insertionDelay) {
2598 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2602 * Sets the insertion delay
2604 * @param insertionDelay
2605 * The new insertion delay, or {@code null} to restore it to
2607 * @return This preferences
2609 public Preferences setInsertionDelay(Integer insertionDelay) {
2610 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2615 * Returns the number of posts to show per page.
2617 * @return The number of posts to show per page
2619 public int getPostsPerPage() {
2620 return options.getIntegerOption("PostsPerPage").get();
2624 * Validates the number of posts per page.
2626 * @param postsPerPage
2627 * The number of posts per page
2628 * @return {@code true} if the number of posts per page was valid,
2629 * {@code false} otherwise
2631 public boolean validatePostsPerPage(Integer postsPerPage) {
2632 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2636 * Sets the number of posts to show per page.
2638 * @param postsPerPage
2639 * The number of posts to show per page
2640 * @return This preferences object
2642 public Preferences setPostsPerPage(Integer postsPerPage) {
2643 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2648 * Returns the number of images to show per page.
2650 * @return The number of images to show per page
2652 public int getImagesPerPage() {
2653 return options.getIntegerOption("ImagesPerPage").get();
2657 * Validates the number of images per page.
2659 * @param imagesPerPage
2660 * The number of images per page
2661 * @return {@code true} if the number of images per page was valid,
2662 * {@code false} otherwise
2664 public boolean validateImagesPerPage(Integer imagesPerPage) {
2665 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2669 * Sets the number of images per page.
2671 * @param imagesPerPage
2672 * The number of images per page
2673 * @return This preferences object
2675 public Preferences setImagesPerPage(Integer imagesPerPage) {
2676 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2681 * Returns the number of characters per post, or <code>-1</code> if the
2682 * posts should not be cut off.
2684 * @return The numbers of characters per post
2686 public int getCharactersPerPost() {
2687 return options.getIntegerOption("CharactersPerPost").get();
2691 * Validates the number of characters per post.
2693 * @param charactersPerPost
2694 * The number of characters per post
2695 * @return {@code true} if the number of characters per post was valid,
2696 * {@code false} otherwise
2698 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2699 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2703 * Sets the number of characters per post.
2705 * @param charactersPerPost
2706 * The number of characters per post, or <code>-1</code> to
2707 * not cut off the posts
2708 * @return This preferences objects
2710 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2711 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2716 * Returns the number of characters the shortened post should have.
2718 * @return The number of characters of the snippet
2720 public int getPostCutOffLength() {
2721 return options.getIntegerOption("PostCutOffLength").get();
2725 * Validates the number of characters after which to cut off the post.
2727 * @param postCutOffLength
2728 * The number of characters of the snippet
2729 * @return {@code true} if the number of characters of the snippet is
2730 * valid, {@code false} otherwise
2732 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2733 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2737 * Sets the number of characters the shortened post should have.
2739 * @param postCutOffLength
2740 * The number of characters of the snippet
2741 * @return This preferences
2743 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2744 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2749 * Returns whether Sone requires full access to be even visible.
2751 * @return {@code true} if Sone requires full access, {@code false}
2754 public boolean isRequireFullAccess() {
2755 return options.getBooleanOption("RequireFullAccess").get();
2759 * Sets whether Sone requires full access to be even visible.
2761 * @param requireFullAccess
2762 * {@code true} if Sone requires full access, {@code false}
2765 public void setRequireFullAccess(Boolean requireFullAccess) {
2766 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2770 * Returns the positive trust.
2772 * @return The positive trust
2774 public int getPositiveTrust() {
2775 return options.getIntegerOption("PositiveTrust").get();
2779 * Validates the positive trust.
2781 * @param positiveTrust
2782 * The positive trust to validate
2783 * @return {@code true} if the positive trust was valid, {@code false}
2786 public boolean validatePositiveTrust(Integer positiveTrust) {
2787 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2791 * Sets the positive trust.
2793 * @param positiveTrust
2794 * The new positive trust, or {@code null} to restore it to
2796 * @return This preferences
2798 public Preferences setPositiveTrust(Integer positiveTrust) {
2799 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2804 * Returns the negative trust.
2806 * @return The negative trust
2808 public int getNegativeTrust() {
2809 return options.getIntegerOption("NegativeTrust").get();
2813 * Validates the negative trust.
2815 * @param negativeTrust
2816 * The negative trust to validate
2817 * @return {@code true} if the negative trust was valid, {@code false}
2820 public boolean validateNegativeTrust(Integer negativeTrust) {
2821 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2825 * Sets the negative trust.
2827 * @param negativeTrust
2828 * The negative trust, or {@code null} to restore it to the
2830 * @return The preferences
2832 public Preferences setNegativeTrust(Integer negativeTrust) {
2833 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2838 * Returns the trust comment. This is the comment that is set in the web
2839 * of trust when a trust value is assigned to an identity.
2841 * @return The trust comment
2843 public String getTrustComment() {
2844 return options.getStringOption("TrustComment").get();
2848 * Sets the trust comment.
2850 * @param trustComment
2851 * The trust comment, or {@code null} to restore it to the
2853 * @return This preferences
2855 public Preferences setTrustComment(String trustComment) {
2856 options.getStringOption("TrustComment").set(trustComment);
2861 * Returns whether the {@link FcpInterface FCP interface} is currently
2864 * @see FcpInterface#setActive(boolean)
2865 * @return {@code true} if the FCP interface is currently active,
2866 * {@code false} otherwise
2868 public boolean isFcpInterfaceActive() {
2869 return options.getBooleanOption("ActivateFcpInterface").get();
2873 * Sets whether the {@link FcpInterface FCP interface} is currently
2876 * @see FcpInterface#setActive(boolean)
2877 * @param fcpInterfaceActive
2878 * {@code true} to activate the FCP interface, {@code false}
2879 * to deactivate the FCP interface
2880 * @return This preferences object
2882 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2883 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2888 * Returns the action level for which full access to the FCP interface
2891 * @return The action level for which full access to the FCP interface
2894 public FullAccessRequired getFcpFullAccessRequired() {
2895 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2899 * Sets the action level for which full access to the FCP interface is
2902 * @param fcpFullAccessRequired
2904 * @return This preferences
2906 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2907 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);