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 } else if (!knownPosts.contains(post.getId())) {
1164 sone.setKnown(false);
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 } else if (!knownReplies.contains(reply.getId())) {
1189 reply.setKnown(false);
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 if (!isLocalSone(sone)) {
1583 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1586 final Post post = new PostImpl(sone, time, text);
1587 if (recipient != null) {
1588 post.setRecipient(recipient);
1590 synchronized (posts) {
1591 posts.put(post.getId(), post);
1593 coreListenerManager.fireNewPostFound(post);
1595 touchConfiguration();
1596 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1603 markPostKnown(post);
1605 }, "Mark " + post + " read.");
1610 * Deletes the given post.
1613 * The post to delete
1615 public void deletePost(Post post) {
1616 if (!isLocalSone(post.getSone())) {
1617 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1620 post.getSone().removePost(post);
1621 synchronized (posts) {
1622 posts.remove(post.getId());
1624 coreListenerManager.firePostRemoved(post);
1625 markPostKnown(post);
1626 touchConfiguration();
1630 * Marks the given post as known, if it is currently not a known post
1631 * (according to {@link Post#isKnown()}).
1634 * The post to mark as known
1636 public void markPostKnown(Post post) {
1637 post.setKnown(true);
1638 synchronized (knownPosts) {
1639 coreListenerManager.fireMarkPostKnown(post);
1640 if (knownPosts.add(post.getId())) {
1641 touchConfiguration();
1644 for (PostReply reply : getReplies(post)) {
1645 markReplyKnown(reply);
1650 * Bookmarks the given post.
1653 * The post to bookmark
1655 public void bookmark(Post post) {
1656 bookmarkPost(post.getId());
1660 * Bookmarks the post with the given ID.
1663 * The ID of the post to bookmark
1665 public void bookmarkPost(String id) {
1666 synchronized (bookmarkedPosts) {
1667 bookmarkedPosts.add(id);
1672 * Removes the given post from the bookmarks.
1675 * The post to unbookmark
1677 public void unbookmark(Post post) {
1678 unbookmarkPost(post.getId());
1682 * Removes the post with the given ID from the bookmarks.
1685 * The ID of the post to unbookmark
1687 public void unbookmarkPost(String id) {
1688 synchronized (bookmarkedPosts) {
1689 bookmarkedPosts.remove(id);
1694 * Creates a new reply.
1697 * The Sone that creates the reply
1699 * The post that this reply refers to
1701 * The text of the reply
1702 * @return The created reply
1704 public PostReply createReply(Sone sone, Post post, String text) {
1705 return createReply(sone, post, System.currentTimeMillis(), text);
1709 * Creates a new reply.
1712 * The Sone that creates the reply
1714 * The post that this reply refers to
1716 * The time of the reply
1718 * The text of the reply
1719 * @return The created reply
1721 public PostReply createReply(Sone sone, Post post, long time, String text) {
1722 if (!isLocalSone(sone)) {
1723 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1726 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1727 synchronized (replies) {
1728 replies.put(reply.getId(), reply);
1730 synchronized (knownReplies) {
1731 coreListenerManager.fireNewReplyFound(reply);
1733 sone.addReply(reply);
1734 touchConfiguration();
1735 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1742 markReplyKnown(reply);
1744 }, "Mark " + reply + " read.");
1749 * Deletes the given reply.
1752 * The reply to delete
1754 public void deleteReply(PostReply reply) {
1755 Sone sone = reply.getSone();
1756 if (!isLocalSone(sone)) {
1757 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1760 synchronized (replies) {
1761 replies.remove(reply.getId());
1763 synchronized (knownReplies) {
1764 markReplyKnown(reply);
1765 knownReplies.remove(reply.getId());
1767 sone.removeReply(reply);
1768 touchConfiguration();
1772 * Marks the given reply as known, if it is currently not a known reply
1773 * (according to {@link Reply#isKnown()}).
1776 * The reply to mark as known
1778 public void markReplyKnown(PostReply reply) {
1779 reply.setKnown(true);
1780 synchronized (knownReplies) {
1781 coreListenerManager.fireMarkReplyKnown(reply);
1782 if (knownReplies.add(reply.getId())) {
1783 touchConfiguration();
1789 * Creates a new top-level album for the given Sone.
1792 * The Sone to create the album for
1793 * @return The new album
1795 public Album createAlbum(Sone sone) {
1796 return createAlbum(sone, null);
1800 * Creates a new album for the given Sone.
1803 * The Sone to create the album for
1805 * The parent of the album (may be {@code null} to create a
1807 * @return The new album
1809 public Album createAlbum(Sone sone, Album parent) {
1810 Album album = new Album();
1811 synchronized (albums) {
1812 albums.put(album.getId(), album);
1814 album.setSone(sone);
1815 if (parent != null) {
1816 parent.addAlbum(album);
1818 sone.addAlbum(album);
1824 * Deletes the given album. The owner of the album has to be a local Sone,
1825 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1828 * The album to remove
1830 public void deleteAlbum(Album album) {
1831 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1832 if (!album.isEmpty()) {
1835 if (album.getParent() == null) {
1836 album.getSone().removeAlbum(album);
1838 album.getParent().removeAlbum(album);
1840 synchronized (albums) {
1841 albums.remove(album.getId());
1843 touchConfiguration();
1847 * Creates a new image.
1850 * The Sone creating the image
1852 * The album the image will be inserted into
1853 * @param temporaryImage
1854 * The temporary image to create the image from
1855 * @return The newly created image
1857 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1858 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();
1859 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1860 album.addImage(image);
1861 synchronized (images) {
1862 images.put(image.getId(), image);
1864 imageInserter.insertImage(temporaryImage, image);
1869 * Deletes the given image. This method will also delete a matching
1872 * @see #deleteTemporaryImage(TemporaryImage)
1874 * The image to delete
1876 public void deleteImage(Image image) {
1877 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1878 deleteTemporaryImage(image.getId());
1879 image.getAlbum().removeImage(image);
1880 synchronized (images) {
1881 images.remove(image.getId());
1883 touchConfiguration();
1887 * Creates a new temporary image.
1890 * The MIME type of the temporary image
1892 * The encoded data of the image
1893 * @return The temporary image
1895 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1896 TemporaryImage temporaryImage = new TemporaryImage();
1897 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1898 synchronized (temporaryImages) {
1899 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1901 return temporaryImage;
1905 * Deletes the given temporary image.
1907 * @param temporaryImage
1908 * The temporary image to delete
1910 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1911 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1912 deleteTemporaryImage(temporaryImage.getId());
1916 * Deletes the temporary image with the given ID.
1919 * The ID of the temporary image to delete
1921 public void deleteTemporaryImage(String imageId) {
1922 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1923 synchronized (temporaryImages) {
1924 temporaryImages.remove(imageId);
1926 Image image = getImage(imageId, false);
1927 if (image != null) {
1928 imageInserter.cancelImageInsert(image);
1933 * Notifies the core that the configuration, either of the core or of a
1934 * single local Sone, has changed, and that the configuration should be
1937 public void touchConfiguration() {
1938 lastConfigurationUpdate = System.currentTimeMillis();
1949 public void serviceStart() {
1950 loadConfiguration();
1951 updateChecker.addUpdateListener(this);
1952 updateChecker.start();
1953 webOfTrustUpdater.start();
1960 public void serviceRun() {
1961 long lastSaved = System.currentTimeMillis();
1962 while (!shouldStop()) {
1964 long now = System.currentTimeMillis();
1965 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1966 for (Sone localSone : getLocalSones()) {
1967 saveSone(localSone);
1969 saveConfiguration();
1979 public void serviceStop() {
1980 synchronized (localSones) {
1981 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1982 soneInserter.getValue().removeSoneInsertListener(this);
1983 soneInserter.getValue().stop();
1984 saveSone(soneInserter.getKey());
1987 saveConfiguration();
1988 webOfTrustUpdater.stop();
1989 updateChecker.stop();
1990 updateChecker.removeUpdateListener(this);
1991 soneDownloader.stop();
1999 * Saves the given Sone. This will persist all local settings for the given
2000 * Sone, such as the friends list and similar, private options.
2005 private synchronized void saveSone(Sone sone) {
2006 if (!isLocalSone(sone)) {
2007 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2010 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2011 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2015 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2017 /* save Sone into configuration. */
2018 String sonePrefix = "Sone/" + sone.getId();
2019 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2020 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2023 Profile profile = sone.getProfile();
2024 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2025 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2026 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2027 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2028 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2029 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2030 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2032 /* save profile fields. */
2033 int fieldCounter = 0;
2034 for (Field profileField : profile.getFields()) {
2035 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2036 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2037 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2039 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2042 int postCounter = 0;
2043 for (Post post : sone.getPosts()) {
2044 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2045 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2046 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2047 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2048 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2050 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2053 int replyCounter = 0;
2054 for (PostReply reply : sone.getReplies()) {
2055 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2056 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2057 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2058 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2059 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2061 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2063 /* save post likes. */
2064 int postLikeCounter = 0;
2065 for (String postId : sone.getLikedPostIds()) {
2066 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2068 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2070 /* save reply likes. */
2071 int replyLikeCounter = 0;
2072 for (String replyId : sone.getLikedReplyIds()) {
2073 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2075 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2078 int friendCounter = 0;
2079 for (String friendId : sone.getFriends()) {
2080 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2082 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2084 /* save albums. first, collect in a flat structure, top-level first. */
2085 List<Album> albums = sone.getAllAlbums();
2087 int albumCounter = 0;
2088 for (Album album : albums) {
2089 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2090 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2091 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2092 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2093 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2094 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2096 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2099 int imageCounter = 0;
2100 for (Album album : albums) {
2101 for (Image image : album.getImages()) {
2102 if (!image.isInserted()) {
2105 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2106 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2107 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2108 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2109 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2110 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2111 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2112 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2113 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2116 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2119 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2120 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2121 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2122 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2123 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2124 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2126 configuration.save();
2128 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2130 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2131 } catch (ConfigurationException ce1) {
2132 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2137 * Saves the current options.
2139 private void saveConfiguration() {
2140 synchronized (configuration) {
2141 if (storingConfiguration) {
2142 logger.log(Level.FINE, "Already storing configuration…");
2145 storingConfiguration = true;
2148 /* store the options first. */
2150 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2151 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2152 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2153 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2154 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2155 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2156 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2157 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2158 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2159 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2160 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2161 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2163 /* save known Sones. */
2164 int soneCounter = 0;
2165 synchronized (knownSones) {
2166 for (String knownSoneId : knownSones) {
2167 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2169 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2172 /* save Sone following times. */
2174 synchronized (soneFollowingTimes) {
2175 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2176 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2177 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2180 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2183 /* save known posts. */
2184 int postCounter = 0;
2185 synchronized (knownPosts) {
2186 for (String knownPostId : knownPosts) {
2187 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2189 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2192 /* save known replies. */
2193 int replyCounter = 0;
2194 synchronized (knownReplies) {
2195 for (String knownReplyId : knownReplies) {
2196 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2198 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2201 /* save bookmarked posts. */
2202 int bookmarkedPostCounter = 0;
2203 synchronized (bookmarkedPosts) {
2204 for (String bookmarkedPostId : bookmarkedPosts) {
2205 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2208 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2211 configuration.save();
2213 } catch (ConfigurationException ce1) {
2214 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2216 synchronized (configuration) {
2217 storingConfiguration = false;
2223 * Loads the configuration.
2225 @SuppressWarnings("unchecked")
2226 private void loadConfiguration() {
2227 /* create options. */
2228 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2231 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2232 SoneInserter.setInsertionDelay(newValue);
2236 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2237 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2238 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2239 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2240 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2241 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2242 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2243 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2244 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2247 @SuppressWarnings("synthetic-access")
2248 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2249 fcpInterface.setActive(newValue);
2252 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2255 @SuppressWarnings("synthetic-access")
2256 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2257 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2262 loadConfigurationValue("InsertionDelay");
2263 loadConfigurationValue("PostsPerPage");
2264 loadConfigurationValue("ImagesPerPage");
2265 loadConfigurationValue("CharactersPerPost");
2266 loadConfigurationValue("PostCutOffLength");
2267 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2268 loadConfigurationValue("PositiveTrust");
2269 loadConfigurationValue("NegativeTrust");
2270 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2271 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2272 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2274 /* load known Sones. */
2275 int soneCounter = 0;
2277 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2278 if (knownSoneId == null) {
2281 synchronized (knownSones) {
2282 knownSones.add(knownSoneId);
2286 /* load Sone following times. */
2289 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2290 if (soneId == null) {
2293 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2294 Sone followedSone = getSone(soneId);
2295 if (followedSone == null) {
2296 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2298 synchronized (soneFollowingTimes) {
2299 soneFollowingTimes.put(getSone(soneId), time);
2305 /* load known posts. */
2306 int postCounter = 0;
2308 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2309 if (knownPostId == null) {
2312 synchronized (knownPosts) {
2313 knownPosts.add(knownPostId);
2317 /* load known replies. */
2318 int replyCounter = 0;
2320 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2321 if (knownReplyId == null) {
2324 synchronized (knownReplies) {
2325 knownReplies.add(knownReplyId);
2329 /* load bookmarked posts. */
2330 int bookmarkedPostCounter = 0;
2332 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2333 if (bookmarkedPostId == null) {
2336 synchronized (bookmarkedPosts) {
2337 bookmarkedPosts.add(bookmarkedPostId);
2344 * Loads an {@link Integer} configuration value for the option with the
2345 * given name, logging validation failures.
2348 * The name of the option to load
2350 private void loadConfigurationValue(String optionName) {
2352 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2353 } catch (IllegalArgumentException iae1) {
2354 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2359 * Generate a Sone URI from the given URI and latest edition.
2362 * The URI to derive the Sone URI from
2363 * @return The derived URI
2365 private static FreenetURI getSoneUri(String uriString) {
2367 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2369 } catch (MalformedURLException mue1) {
2370 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2376 // INTERFACE IdentityListener
2383 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2384 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2385 if (ownIdentity.hasContext("Sone")) {
2386 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2387 addLocalSone(ownIdentity);
2395 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2396 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2397 trustedIdentities.remove(ownIdentity);
2404 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2405 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2406 trustedIdentities.get(ownIdentity).add(identity);
2407 addRemoteSone(identity);
2414 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2415 new Thread(new Runnable() {
2418 @SuppressWarnings("synthetic-access")
2420 Sone sone = getRemoteSone(identity.getId(), false);
2421 sone.setIdentity(identity);
2422 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2423 soneDownloader.addSone(sone);
2424 soneDownloader.fetchSone(sone);
2433 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2434 trustedIdentities.get(ownIdentity).remove(identity);
2435 boolean foundIdentity = false;
2436 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2437 if (trustedIdentity.getKey().equals(ownIdentity)) {
2440 if (trustedIdentity.getValue().contains(identity)) {
2441 foundIdentity = true;
2444 if (foundIdentity) {
2445 /* some local identity still trusts this identity, don’t remove. */
2448 Sone sone = getSone(identity.getId(), false);
2450 /* TODO - we don’t have the Sone anymore. should this happen? */
2453 synchronized (posts) {
2454 synchronized (knownPosts) {
2455 for (Post post : sone.getPosts()) {
2456 posts.remove(post.getId());
2457 coreListenerManager.firePostRemoved(post);
2461 synchronized (replies) {
2462 synchronized (knownReplies) {
2463 for (PostReply reply : sone.getReplies()) {
2464 replies.remove(reply.getId());
2465 coreListenerManager.fireReplyRemoved(reply);
2469 synchronized (remoteSones) {
2470 remoteSones.remove(identity.getId());
2472 coreListenerManager.fireSoneRemoved(sone);
2476 // INTERFACE UpdateListener
2483 public void updateFound(Version version, long releaseTime, long latestEdition) {
2484 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2488 // INTERFACE ImageInsertListener
2495 public void insertStarted(Sone sone) {
2496 coreListenerManager.fireSoneInserting(sone);
2503 public void insertFinished(Sone sone, long insertDuration) {
2504 coreListenerManager.fireSoneInserted(sone, insertDuration);
2511 public void insertAborted(Sone sone, Throwable cause) {
2512 coreListenerManager.fireSoneInsertAborted(sone, cause);
2516 // SONEINSERTLISTENER METHODS
2523 public void imageInsertStarted(Image image) {
2524 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2525 coreListenerManager.fireImageInsertStarted(image);
2532 public void imageInsertAborted(Image image) {
2533 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2534 coreListenerManager.fireImageInsertAborted(image);
2541 public void imageInsertFinished(Image image, FreenetURI key) {
2542 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2543 image.setKey(key.toString());
2544 deleteTemporaryImage(image.getId());
2545 touchConfiguration();
2546 coreListenerManager.fireImageInsertFinished(image);
2553 public void imageInsertFailed(Image image, Throwable cause) {
2554 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2555 coreListenerManager.fireImageInsertFailed(image, cause);
2559 * Convenience interface for external classes that want to access the core’s
2562 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2564 public static class Preferences {
2566 /** The wrapped options. */
2567 private final Options options;
2570 * Creates a new preferences object wrapped around the given options.
2573 * The options to wrap
2575 public Preferences(Options options) {
2576 this.options = options;
2580 * Returns the insertion delay.
2582 * @return The insertion delay
2584 public int getInsertionDelay() {
2585 return options.getIntegerOption("InsertionDelay").get();
2589 * Validates the given insertion delay.
2591 * @param insertionDelay
2592 * The insertion delay to validate
2593 * @return {@code true} if the given insertion delay was valid,
2594 * {@code false} otherwise
2596 public boolean validateInsertionDelay(Integer insertionDelay) {
2597 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2601 * Sets the insertion delay
2603 * @param insertionDelay
2604 * The new insertion delay, or {@code null} to restore it to
2606 * @return This preferences
2608 public Preferences setInsertionDelay(Integer insertionDelay) {
2609 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2614 * Returns the number of posts to show per page.
2616 * @return The number of posts to show per page
2618 public int getPostsPerPage() {
2619 return options.getIntegerOption("PostsPerPage").get();
2623 * Validates the number of posts per page.
2625 * @param postsPerPage
2626 * The number of posts per page
2627 * @return {@code true} if the number of posts per page was valid,
2628 * {@code false} otherwise
2630 public boolean validatePostsPerPage(Integer postsPerPage) {
2631 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2635 * Sets the number of posts to show per page.
2637 * @param postsPerPage
2638 * The number of posts to show per page
2639 * @return This preferences object
2641 public Preferences setPostsPerPage(Integer postsPerPage) {
2642 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2647 * Returns the number of images to show per page.
2649 * @return The number of images to show per page
2651 public int getImagesPerPage() {
2652 return options.getIntegerOption("ImagesPerPage").get();
2656 * Validates the number of images per page.
2658 * @param imagesPerPage
2659 * The number of images per page
2660 * @return {@code true} if the number of images per page was valid,
2661 * {@code false} otherwise
2663 public boolean validateImagesPerPage(Integer imagesPerPage) {
2664 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2668 * Sets the number of images per page.
2670 * @param imagesPerPage
2671 * The number of images per page
2672 * @return This preferences object
2674 public Preferences setImagesPerPage(Integer imagesPerPage) {
2675 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2680 * Returns the number of characters per post, or <code>-1</code> if the
2681 * posts should not be cut off.
2683 * @return The numbers of characters per post
2685 public int getCharactersPerPost() {
2686 return options.getIntegerOption("CharactersPerPost").get();
2690 * Validates the number of characters per post.
2692 * @param charactersPerPost
2693 * The number of characters per post
2694 * @return {@code true} if the number of characters per post was valid,
2695 * {@code false} otherwise
2697 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2698 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2702 * Sets the number of characters per post.
2704 * @param charactersPerPost
2705 * The number of characters per post, or <code>-1</code> to
2706 * not cut off the posts
2707 * @return This preferences objects
2709 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2710 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2715 * Returns the number of characters the shortened post should have.
2717 * @return The number of characters of the snippet
2719 public int getPostCutOffLength() {
2720 return options.getIntegerOption("PostCutOffLength").get();
2724 * Validates the number of characters after which to cut off the post.
2726 * @param postCutOffLength
2727 * The number of characters of the snippet
2728 * @return {@code true} if the number of characters of the snippet is
2729 * valid, {@code false} otherwise
2731 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2732 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2736 * Sets the number of characters the shortened post should have.
2738 * @param postCutOffLength
2739 * The number of characters of the snippet
2740 * @return This preferences
2742 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2743 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2748 * Returns whether Sone requires full access to be even visible.
2750 * @return {@code true} if Sone requires full access, {@code false}
2753 public boolean isRequireFullAccess() {
2754 return options.getBooleanOption("RequireFullAccess").get();
2758 * Sets whether Sone requires full access to be even visible.
2760 * @param requireFullAccess
2761 * {@code true} if Sone requires full access, {@code false}
2764 public void setRequireFullAccess(Boolean requireFullAccess) {
2765 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2769 * Returns the positive trust.
2771 * @return The positive trust
2773 public int getPositiveTrust() {
2774 return options.getIntegerOption("PositiveTrust").get();
2778 * Validates the positive trust.
2780 * @param positiveTrust
2781 * The positive trust to validate
2782 * @return {@code true} if the positive trust was valid, {@code false}
2785 public boolean validatePositiveTrust(Integer positiveTrust) {
2786 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2790 * Sets the positive trust.
2792 * @param positiveTrust
2793 * The new positive trust, or {@code null} to restore it to
2795 * @return This preferences
2797 public Preferences setPositiveTrust(Integer positiveTrust) {
2798 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2803 * Returns the negative trust.
2805 * @return The negative trust
2807 public int getNegativeTrust() {
2808 return options.getIntegerOption("NegativeTrust").get();
2812 * Validates the negative trust.
2814 * @param negativeTrust
2815 * The negative trust to validate
2816 * @return {@code true} if the negative trust was valid, {@code false}
2819 public boolean validateNegativeTrust(Integer negativeTrust) {
2820 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2824 * Sets the negative trust.
2826 * @param negativeTrust
2827 * The negative trust, or {@code null} to restore it to the
2829 * @return The preferences
2831 public Preferences setNegativeTrust(Integer negativeTrust) {
2832 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2837 * Returns the trust comment. This is the comment that is set in the web
2838 * of trust when a trust value is assigned to an identity.
2840 * @return The trust comment
2842 public String getTrustComment() {
2843 return options.getStringOption("TrustComment").get();
2847 * Sets the trust comment.
2849 * @param trustComment
2850 * The trust comment, or {@code null} to restore it to the
2852 * @return This preferences
2854 public Preferences setTrustComment(String trustComment) {
2855 options.getStringOption("TrustComment").set(trustComment);
2860 * Returns whether the {@link FcpInterface FCP interface} is currently
2863 * @see FcpInterface#setActive(boolean)
2864 * @return {@code true} if the FCP interface is currently active,
2865 * {@code false} otherwise
2867 public boolean isFcpInterfaceActive() {
2868 return options.getBooleanOption("ActivateFcpInterface").get();
2872 * Sets whether the {@link FcpInterface FCP interface} is currently
2875 * @see FcpInterface#setActive(boolean)
2876 * @param fcpInterfaceActive
2877 * {@code true} to activate the FCP interface, {@code false}
2878 * to deactivate the FCP interface
2879 * @return This preferences object
2881 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2882 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2887 * Returns the action level for which full access to the FCP interface
2890 * @return The action level for which full access to the FCP interface
2893 public FullAccessRequired getFcpFullAccessRequired() {
2894 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2898 * Sets the action level for which full access to the FCP interface is
2901 * @param fcpFullAccessRequired
2903 * @return This preferences
2905 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2906 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);