2 * Sone - Core.java - Copyright © 2010 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;
28 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.Reply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.TemporaryImage;
46 import net.pterodactylus.sone.data.Profile.Field;
47 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.fcp.FcpInterface;
50 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
51 import net.pterodactylus.sone.freenet.wot.Identity;
52 import net.pterodactylus.sone.freenet.wot.IdentityListener;
53 import net.pterodactylus.sone.freenet.wot.IdentityManager;
54 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
55 import net.pterodactylus.sone.freenet.wot.Trust;
56 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
57 import net.pterodactylus.sone.main.SonePlugin;
58 import net.pterodactylus.util.config.Configuration;
59 import net.pterodactylus.util.config.ConfigurationException;
60 import net.pterodactylus.util.logging.Logging;
61 import net.pterodactylus.util.number.Numbers;
62 import net.pterodactylus.util.service.AbstractService;
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);
82 private final Options options = new Options();
84 /** The preferences. */
85 private final Preferences preferences = new Preferences(options);
87 /** The core listener manager. */
88 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
90 /** The configuration. */
91 private Configuration configuration;
93 /** Whether we’re currently saving the configuration. */
94 private boolean storingConfiguration = false;
96 /** The identity manager. */
97 private final IdentityManager identityManager;
99 /** Interface to freenet. */
100 private final FreenetInterface freenetInterface;
102 /** The Sone downloader. */
103 private final SoneDownloader soneDownloader;
105 /** The image inserter. */
106 private final ImageInserter imageInserter;
108 /** Sone downloader thread-pool. */
109 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
111 /** The update checker. */
112 private final UpdateChecker updateChecker;
114 /** The FCP interface. */
115 private volatile FcpInterface fcpInterface;
117 /** The times Sones were followed. */
118 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
120 /** Locked local Sones. */
121 /* synchronize on itself. */
122 private final Set<Sone> lockedSones = new HashSet<Sone>();
124 /** Sone inserters. */
125 /* synchronize access on this on localSones. */
126 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
128 /** Sone rescuers. */
129 /* synchronize access on this on localSones. */
130 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
132 /** All local Sones. */
133 /* synchronize access on this on itself. */
134 private Map<String, Sone> localSones = new HashMap<String, Sone>();
136 /** All remote Sones. */
137 /* synchronize access on this on itself. */
138 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
140 /** All known Sones. */
141 private Set<String> knownSones = new HashSet<String>();
144 private Map<String, Post> posts = new HashMap<String, Post>();
146 /** All known posts. */
147 private Set<String> knownPosts = new HashSet<String>();
150 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
152 /** All known replies. */
153 private Set<String> knownReplies = new HashSet<String>();
155 /** All bookmarked posts. */
156 /* synchronize access on itself. */
157 private Set<String> bookmarkedPosts = new HashSet<String>();
159 /** Trusted identities, sorted by own identities. */
160 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
162 /** All known albums. */
163 private Map<String, Album> albums = new HashMap<String, Album>();
165 /** All known images. */
166 private Map<String, Image> images = new HashMap<String, Image>();
168 /** All temporary images. */
169 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
171 /** Ticker for threads that mark own elements as known. */
172 private Ticker localElementTicker = new Ticker();
174 /** The time the configuration was last touched. */
175 private volatile long lastConfigurationUpdate;
178 * Creates a new core.
180 * @param configuration
181 * The configuration of the core
182 * @param freenetInterface
183 * The freenet interface
184 * @param identityManager
185 * The identity manager
187 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
189 this.configuration = configuration;
190 this.freenetInterface = freenetInterface;
191 this.identityManager = identityManager;
192 this.soneDownloader = new SoneDownloader(this, freenetInterface);
193 this.imageInserter = new ImageInserter(this, freenetInterface);
194 this.updateChecker = new UpdateChecker(freenetInterface);
198 // LISTENER MANAGEMENT
202 * Adds a new core listener.
204 * @param coreListener
205 * The listener to add
207 public void addCoreListener(CoreListener coreListener) {
208 coreListenerManager.addListener(coreListener);
212 * Removes a core listener.
214 * @param coreListener
215 * The listener to remove
217 public void removeCoreListener(CoreListener coreListener) {
218 coreListenerManager.removeListener(coreListener);
226 * Sets the configuration to use. This will automatically save the current
227 * configuration to the given configuration.
229 * @param configuration
230 * The new configuration to use
232 public void setConfiguration(Configuration configuration) {
233 this.configuration = configuration;
234 touchConfiguration();
238 * Returns the options used by the core.
240 * @return The options of the core
242 public Preferences getPreferences() {
247 * Returns the identity manager used by the core.
249 * @return The identity manager
251 public IdentityManager getIdentityManager() {
252 return identityManager;
256 * Returns the update checker.
258 * @return The update checker
260 public UpdateChecker getUpdateChecker() {
261 return updateChecker;
265 * Sets the FCP interface to use.
267 * @param fcpInterface
268 * The FCP interface to use
270 public void setFcpInterface(FcpInterface fcpInterface) {
271 this.fcpInterface = fcpInterface;
275 * Returns the Sone rescuer for the given local Sone.
278 * The local Sone to get the rescuer for
279 * @return The Sone rescuer for the given Sone
281 public SoneRescuer getSoneRescuer(Sone sone) {
282 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
283 synchronized (localSones) {
284 SoneRescuer soneRescuer = soneRescuers.get(sone);
285 if (soneRescuer == null) {
286 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
287 soneRescuers.put(sone, soneRescuer);
295 * Returns whether the given Sone is currently locked.
299 * @return {@code true} if the Sone is locked, {@code false} if it is not
301 public boolean isLocked(Sone sone) {
302 synchronized (lockedSones) {
303 return lockedSones.contains(sone);
308 * Returns all Sones, remote and local.
312 public Set<Sone> getSones() {
313 Set<Sone> allSones = new HashSet<Sone>();
314 allSones.addAll(getLocalSones());
315 allSones.addAll(getRemoteSones());
320 * Returns the Sone with the given ID, regardless whether it’s local or
324 * The ID of the Sone to get
325 * @return The Sone with the given ID, or {@code null} if there is no such
328 public Sone getSone(String id) {
329 return getSone(id, true);
333 * Returns the Sone with the given ID, regardless whether it’s local or
337 * The ID of the Sone to get
339 * {@code true} to create a new Sone if none exists,
340 * {@code false} to return {@code null} if a Sone with the given
342 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Sone getSone(String id, boolean create) {
347 if (isLocalSone(id)) {
348 return getLocalSone(id);
350 return getRemoteSone(id, create);
354 * Checks whether the core knows a Sone with the given ID.
358 * @return {@code true} if there is a Sone with the given ID, {@code false}
361 public boolean hasSone(String id) {
362 return isLocalSone(id) || isRemoteSone(id);
366 * Returns whether the given Sone is a local Sone.
369 * The Sone to check for its locality
370 * @return {@code true} if the given Sone is local, {@code false} otherwise
372 public boolean isLocalSone(Sone sone) {
373 synchronized (localSones) {
374 return localSones.containsKey(sone.getId());
379 * Returns whether the given ID is the ID of a local Sone.
382 * The Sone ID to check for its locality
383 * @return {@code true} if the given ID is a local Sone, {@code false}
386 public boolean isLocalSone(String id) {
387 synchronized (localSones) {
388 return localSones.containsKey(id);
393 * Returns all local Sones.
395 * @return All local Sones
397 public Set<Sone> getLocalSones() {
398 synchronized (localSones) {
399 return new HashSet<Sone>(localSones.values());
404 * Returns the local Sone with the given ID.
407 * The ID of the Sone to get
408 * @return The Sone with the given ID
410 public Sone getLocalSone(String id) {
411 return getLocalSone(id, true);
415 * Returns the local Sone with the given ID, optionally creating a new Sone.
420 * {@code true} to create a new Sone if none exists,
421 * {@code false} to return null if none exists
422 * @return The Sone with the given ID, or {@code null}
424 public Sone getLocalSone(String id, boolean create) {
425 synchronized (localSones) {
426 Sone sone = localSones.get(id);
427 if ((sone == null) && create) {
429 localSones.put(id, sone);
436 * Returns all remote Sones.
438 * @return All remote Sones
440 public Set<Sone> getRemoteSones() {
441 synchronized (remoteSones) {
442 return new HashSet<Sone>(remoteSones.values());
447 * Returns the remote Sone with the given ID.
450 * The ID of the remote Sone to get
452 * {@code true} to always create a Sone, {@code false} to return
453 * {@code null} if no Sone with the given ID exists
454 * @return The Sone with the given ID
456 public Sone getRemoteSone(String id, boolean create) {
457 synchronized (remoteSones) {
458 Sone sone = remoteSones.get(id);
459 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
461 remoteSones.put(id, sone);
468 * Returns whether the given Sone is a remote Sone.
472 * @return {@code true} if the given Sone is a remote Sone, {@code false}
475 public boolean isRemoteSone(Sone sone) {
476 synchronized (remoteSones) {
477 return remoteSones.containsKey(sone.getId());
482 * Returns whether the Sone with the given ID is a remote Sone.
485 * The ID of the Sone to check
486 * @return {@code true} if the Sone with the given ID is a remote Sone,
487 * {@code false} otherwise
489 public boolean isRemoteSone(String id) {
490 synchronized (remoteSones) {
491 return remoteSones.containsKey(id);
496 * Returns whether the given Sone has been modified.
499 * The Sone to check for modifications
500 * @return {@code true} if a modification has been detected in the Sone,
501 * {@code false} otherwise
503 public boolean isModifiedSone(Sone sone) {
504 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
508 * Returns the time when the given was first followed by any local Sone.
511 * The Sone to get the time for
512 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
513 * been followed, or {@link Long#MAX_VALUE}
515 public long getSoneFollowingTime(Sone sone) {
516 synchronized (soneFollowingTimes) {
517 if (soneFollowingTimes.containsKey(sone)) {
518 return soneFollowingTimes.get(sone);
520 return Long.MAX_VALUE;
525 * Returns whether the target Sone is trusted by the origin Sone.
531 * @return {@code true} if the target Sone is trusted by the origin Sone
533 public boolean isSoneTrusted(Sone origin, Sone target) {
534 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
535 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
539 * Returns the post with the given ID.
542 * The ID of the post to get
543 * @return The post with the given ID, or a new post with the given ID
545 public Post getPost(String postId) {
546 return getPost(postId, true);
550 * Returns the post with the given ID, optionally creating a new post.
553 * The ID of the post to get
555 * {@code true} it create a new post if no post with the given ID
556 * exists, {@code false} to return {@code null}
557 * @return The post, or {@code null} if there is no such post
560 public Post getPost(String postId, boolean create) {
561 synchronized (posts) {
562 Post post = posts.get(postId);
563 if ((post == null) && create) {
564 post = new Post(postId);
565 posts.put(postId, post);
572 * Returns all posts that have the given Sone as recipient.
574 * @see Post#getRecipient()
576 * The recipient of the posts
577 * @return All posts that have the given Sone as recipient
579 public Set<Post> getDirectedPosts(Sone recipient) {
580 Validation.begin().isNotNull("Recipient", recipient).check();
581 Set<Post> directedPosts = new HashSet<Post>();
582 synchronized (posts) {
583 for (Post post : posts.values()) {
584 if (recipient.equals(post.getRecipient())) {
585 directedPosts.add(post);
589 return directedPosts;
593 * Returns the reply with the given ID. If there is no reply with the given
594 * ID yet, a new one is created.
597 * The ID of the reply to get
600 public PostReply getReply(String replyId) {
601 return getReply(replyId, true);
605 * Returns the reply with the given ID. If there is no reply with the given
606 * ID yet, a new one is created, unless {@code create} is false in which
607 * case {@code null} is returned.
610 * The ID of the reply to get
612 * {@code true} to always return a {@link Reply}, {@code false}
613 * to return {@code null} if no reply can be found
614 * @return The reply, or {@code null} if there is no such reply
616 public PostReply getReply(String replyId, boolean create) {
617 synchronized (replies) {
618 PostReply reply = replies.get(replyId);
619 if (create && (reply == null)) {
620 reply = new PostReply(replyId);
621 replies.put(replyId, reply);
628 * Returns all replies for the given post, order ascending by time.
631 * The post to get all replies for
632 * @return All replies for the given post
634 public List<PostReply> getReplies(Post post) {
635 Set<Sone> sones = getSones();
636 List<PostReply> replies = new ArrayList<PostReply>();
637 for (Sone sone : sones) {
638 for (PostReply reply : sone.getReplies()) {
639 if (reply.getPost().equals(post)) {
644 Collections.sort(replies, Reply.TIME_COMPARATOR);
649 * Returns all Sones that have liked the given post.
652 * The post to get the liking Sones for
653 * @return The Sones that like the given post
655 public Set<Sone> getLikes(Post post) {
656 Set<Sone> sones = new HashSet<Sone>();
657 for (Sone sone : getSones()) {
658 if (sone.getLikedPostIds().contains(post.getId())) {
666 * Returns all Sones that have liked the given reply.
669 * The reply to get the liking Sones for
670 * @return The Sones that like the given reply
672 public Set<Sone> getLikes(PostReply reply) {
673 Set<Sone> sones = new HashSet<Sone>();
674 for (Sone sone : getSones()) {
675 if (sone.getLikedReplyIds().contains(reply.getId())) {
683 * Returns whether the given post is bookmarked.
687 * @return {@code true} if the given post is bookmarked, {@code false}
690 public boolean isBookmarked(Post post) {
691 return isPostBookmarked(post.getId());
695 * Returns whether the post with the given ID is bookmarked.
698 * The ID of the post to check
699 * @return {@code true} if the post with the given ID is bookmarked,
700 * {@code false} otherwise
702 public boolean isPostBookmarked(String id) {
703 synchronized (bookmarkedPosts) {
704 return bookmarkedPosts.contains(id);
709 * Returns all currently known bookmarked posts.
711 * @return All bookmarked posts
713 public Set<Post> getBookmarkedPosts() {
714 Set<Post> posts = new HashSet<Post>();
715 synchronized (bookmarkedPosts) {
716 for (String bookmarkedPostId : bookmarkedPosts) {
717 Post post = getPost(bookmarkedPostId, false);
727 * Returns the album with the given ID, creating a new album if no album
728 * with the given ID can be found.
731 * The ID of the album
732 * @return The album with the given ID
734 public Album getAlbum(String albumId) {
735 return getAlbum(albumId, true);
739 * Returns the album with the given ID, optionally creating a new album if
740 * an album with the given ID can not be found.
743 * The ID of the album
745 * {@code true} to create a new album if none exists for the
747 * @return The album with the given ID, or {@code null} if no album with the
748 * given ID exists and {@code create} is {@code false}
750 public Album getAlbum(String albumId, boolean create) {
751 synchronized (albums) {
752 Album album = albums.get(albumId);
753 if (create && (album == null)) {
754 album = new Album(albumId);
755 albums.put(albumId, album);
762 * Returns the image with the given ID, creating it if necessary.
765 * The ID of the image
766 * @return The image with the given ID
768 public Image getImage(String imageId) {
769 return getImage(imageId, true);
773 * Returns the image with the given ID, optionally creating it if it does
777 * The ID of the image
779 * {@code true} to create an image if none exists with the given
781 * @return The image with the given ID, or {@code null} if none exists and
784 public Image getImage(String imageId, boolean create) {
785 synchronized (images) {
786 Image image = images.get(imageId);
787 if (create && (image == null)) {
788 image = new Image(imageId);
789 images.put(imageId, image);
796 * Returns the temporary image with the given ID.
799 * The ID of the temporary image
800 * @return The temporary image, or {@code null} if there is no temporary
801 * image with the given ID
803 public TemporaryImage getTemporaryImage(String imageId) {
804 synchronized (temporaryImages) {
805 return temporaryImages.get(imageId);
814 * Locks the given Sone. A locked Sone will not be inserted by
815 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
821 public void lockSone(Sone sone) {
822 synchronized (lockedSones) {
823 if (lockedSones.add(sone)) {
824 coreListenerManager.fireSoneLocked(sone);
830 * Unlocks the given Sone.
832 * @see #lockSone(Sone)
836 public void unlockSone(Sone sone) {
837 synchronized (lockedSones) {
838 if (lockedSones.remove(sone)) {
839 coreListenerManager.fireSoneUnlocked(sone);
845 * Adds a local Sone from the given own identity.
848 * The own identity to create a Sone from
849 * @return The added (or already existing) Sone
851 public Sone addLocalSone(OwnIdentity ownIdentity) {
852 if (ownIdentity == null) {
853 logger.log(Level.WARNING, "Given OwnIdentity is null!");
856 synchronized (localSones) {
859 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
860 } catch (MalformedURLException mue1) {
861 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
864 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
865 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
867 /* TODO - load posts ’n stuff */
868 localSones.put(ownIdentity.getId(), sone);
869 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
870 soneInserter.addSoneInsertListener(this);
871 soneInserters.put(sone, soneInserter);
872 sone.setStatus(SoneStatus.idle);
874 soneInserter.start();
880 * Creates a new Sone for the given own identity.
883 * The own identity to create a Sone for
884 * @return The created Sone
886 public Sone createSone(OwnIdentity ownIdentity) {
888 ownIdentity.addContext("Sone");
889 } catch (WebOfTrustException wote1) {
890 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
893 Sone sone = addLocalSone(ownIdentity);
894 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
895 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
896 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
897 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
898 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
899 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
901 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
902 touchConfiguration();
907 * Adds the Sone of the given identity.
910 * The identity whose Sone to add
911 * @return The added or already existing Sone
913 public Sone addRemoteSone(Identity identity) {
914 if (identity == null) {
915 logger.log(Level.WARNING, "Given Identity is null!");
918 synchronized (remoteSones) {
919 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
920 boolean newSone = sone.getRequestUri() == null;
921 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
922 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
924 synchronized (knownSones) {
925 newSone = !knownSones.contains(sone.getId());
927 sone.setKnown(!newSone);
929 coreListenerManager.fireNewSoneFound(sone);
930 for (Sone localSone : getLocalSones()) {
931 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
932 followSone(localSone, sone);
937 soneDownloader.addSone(sone);
938 soneDownloaders.execute(new Runnable() {
941 @SuppressWarnings("synthetic-access")
943 soneDownloader.fetchSone(sone, sone.getRequestUri());
952 * Lets the given local Sone follow the Sone with the given ID.
955 * The local Sone that should follow another Sone
957 * The ID of the Sone to follow
959 public void followSone(Sone sone, String soneId) {
960 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
961 Sone followedSone = getSone(soneId, true);
962 if (followedSone == null) {
963 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
966 followSone(sone, getSone(soneId));
970 * Lets the given local Sone follow the other given Sone. If the given Sone
971 * was not followed by any local Sone before, this will mark all elements of
972 * the followed Sone as read that have been created before the current
976 * The local Sone that should follow the other Sone
977 * @param followedSone
978 * The Sone that should be followed
980 public void followSone(Sone sone, Sone followedSone) {
981 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
982 sone.addFriend(followedSone.getId());
983 synchronized (soneFollowingTimes) {
984 if (!soneFollowingTimes.containsKey(followedSone)) {
985 long now = System.currentTimeMillis();
986 soneFollowingTimes.put(followedSone, now);
987 for (Post post : followedSone.getPosts()) {
988 if (post.getTime() < now) {
992 for (PostReply reply : followedSone.getReplies()) {
993 if (reply.getTime() < now) {
994 markReplyKnown(reply);
999 touchConfiguration();
1003 * Lets the given local Sone unfollow the Sone with the given ID.
1006 * The local Sone that should unfollow another Sone
1008 * The ID of the Sone being unfollowed
1010 public void unfollowSone(Sone sone, String soneId) {
1011 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1012 unfollowSone(sone, getSone(soneId, false));
1016 * Lets the given local Sone unfollow the other given Sone. If the given
1017 * local Sone is the last local Sone that followed the given Sone, its
1018 * following time will be removed.
1021 * The local Sone that should unfollow another Sone
1022 * @param unfollowedSone
1023 * The Sone being unfollowed
1025 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1026 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1027 sone.removeFriend(unfollowedSone.getId());
1028 boolean unfollowedSoneStillFollowed = false;
1029 for (Sone localSone : getLocalSones()) {
1030 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1032 if (!unfollowedSoneStillFollowed) {
1033 synchronized (soneFollowingTimes) {
1034 soneFollowingTimes.remove(unfollowedSone);
1037 touchConfiguration();
1041 * Retrieves the trust relationship from the origin to the target. If the
1042 * trust relationship can not be retrieved, {@code null} is returned.
1044 * @see Identity#getTrust(OwnIdentity)
1046 * The origin of the trust tree
1048 * The target of the trust
1049 * @return The trust relationship
1051 public Trust getTrust(Sone origin, Sone target) {
1052 if (!isLocalSone(origin)) {
1053 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1056 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1060 * Sets the trust value of the given origin Sone for the target Sone.
1067 * The trust value (from {@code -100} to {@code 100})
1069 public void setTrust(Sone origin, Sone target, int trustValue) {
1070 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();
1072 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1073 } catch (WebOfTrustException wote1) {
1074 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1079 * Removes any trust assignment for the given target Sone.
1086 public void removeTrust(Sone origin, Sone target) {
1087 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1089 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1090 } catch (WebOfTrustException wote1) {
1091 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1096 * Assigns the configured positive trust value for the given target.
1103 public void trustSone(Sone origin, Sone target) {
1104 setTrust(origin, target, preferences.getPositiveTrust());
1108 * Assigns the configured negative trust value for the given target.
1115 public void distrustSone(Sone origin, Sone target) {
1116 setTrust(origin, target, preferences.getNegativeTrust());
1120 * Removes the trust assignment for the given target.
1127 public void untrustSone(Sone origin, Sone target) {
1128 removeTrust(origin, target);
1132 * Updates the stored Sone with the given Sone.
1137 public void updateSone(Sone sone) {
1138 updateSone(sone, false);
1142 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1143 * {@code true}, an older Sone than the current Sone can be given to restore
1147 * The Sone to update
1148 * @param soneRescueMode
1149 * {@code true} if the stored Sone should be updated regardless
1150 * of the age of the given Sone
1152 public void updateSone(Sone sone, boolean soneRescueMode) {
1153 if (hasSone(sone.getId())) {
1154 Sone storedSone = getSone(sone.getId());
1155 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1156 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1159 synchronized (posts) {
1160 if (!soneRescueMode) {
1161 for (Post post : storedSone.getPosts()) {
1162 posts.remove(post.getId());
1163 if (!sone.getPosts().contains(post)) {
1164 coreListenerManager.firePostRemoved(post);
1168 List<Post> storedPosts = storedSone.getPosts();
1169 synchronized (knownPosts) {
1170 for (Post post : sone.getPosts()) {
1171 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1172 if (!storedPosts.contains(post)) {
1173 if (post.getTime() < getSoneFollowingTime(sone)) {
1174 knownPosts.add(post.getId());
1175 } else if (!knownPosts.contains(post.getId())) {
1176 sone.setKnown(false);
1177 coreListenerManager.fireNewPostFound(post);
1180 posts.put(post.getId(), post);
1184 synchronized (replies) {
1185 if (!soneRescueMode) {
1186 for (PostReply reply : storedSone.getReplies()) {
1187 replies.remove(reply.getId());
1188 if (!sone.getReplies().contains(reply)) {
1189 coreListenerManager.fireReplyRemoved(reply);
1193 Set<PostReply> storedReplies = storedSone.getReplies();
1194 synchronized (knownReplies) {
1195 for (PostReply reply : sone.getReplies()) {
1196 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1197 if (!storedReplies.contains(reply)) {
1198 if (reply.getTime() < getSoneFollowingTime(sone)) {
1199 knownReplies.add(reply.getId());
1200 } else if (!knownReplies.contains(reply.getId())) {
1201 reply.setKnown(false);
1202 coreListenerManager.fireNewReplyFound(reply);
1205 replies.put(reply.getId(), reply);
1209 synchronized (albums) {
1210 synchronized (images) {
1211 for (Album album : storedSone.getAlbums()) {
1212 albums.remove(album.getId());
1213 for (Image image : album.getImages()) {
1214 images.remove(image.getId());
1217 for (Album album : sone.getAlbums()) {
1218 albums.put(album.getId(), album);
1219 for (Image image : album.getImages()) {
1220 images.put(image.getId(), image);
1225 synchronized (storedSone) {
1226 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1227 storedSone.setTime(sone.getTime());
1229 storedSone.setClient(sone.getClient());
1230 storedSone.setProfile(sone.getProfile());
1231 if (soneRescueMode) {
1232 for (Post post : sone.getPosts()) {
1233 storedSone.addPost(post);
1235 for (PostReply reply : sone.getReplies()) {
1236 storedSone.addReply(reply);
1238 for (String likedPostId : sone.getLikedPostIds()) {
1239 storedSone.addLikedPostId(likedPostId);
1241 for (String likedReplyId : sone.getLikedReplyIds()) {
1242 storedSone.addLikedReplyId(likedReplyId);
1244 for (Album album : sone.getAlbums()) {
1245 storedSone.addAlbum(album);
1248 storedSone.setPosts(sone.getPosts());
1249 storedSone.setReplies(sone.getReplies());
1250 storedSone.setLikePostIds(sone.getLikedPostIds());
1251 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1252 storedSone.setAlbums(sone.getAlbums());
1254 storedSone.setLatestEdition(sone.getLatestEdition());
1260 * Deletes the given Sone. This will remove the Sone from the
1261 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1262 * and remove the context from its identity.
1265 * The Sone to delete
1267 public void deleteSone(Sone sone) {
1268 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1269 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1272 synchronized (localSones) {
1273 if (!localSones.containsKey(sone.getId())) {
1274 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1277 localSones.remove(sone.getId());
1278 SoneInserter soneInserter = soneInserters.remove(sone);
1279 soneInserter.removeSoneInsertListener(this);
1280 soneInserter.stop();
1283 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1284 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1285 } catch (WebOfTrustException wote1) {
1286 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1289 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1290 } catch (ConfigurationException ce1) {
1291 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1296 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1297 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1300 * The Sone to mark as known
1302 public void markSoneKnown(Sone sone) {
1303 if (!sone.isKnown()) {
1304 sone.setKnown(true);
1305 synchronized (knownSones) {
1306 knownSones.add(sone.getId());
1308 coreListenerManager.fireMarkSoneKnown(sone);
1309 touchConfiguration();
1314 * Loads and updates the given Sone from the configuration. If any error is
1315 * encountered, loading is aborted and the given Sone is not changed.
1318 * The Sone to load and update
1320 public void loadSone(Sone sone) {
1321 if (!isLocalSone(sone)) {
1322 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1326 /* initialize options. */
1327 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1328 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1329 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1330 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1331 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1332 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1335 String sonePrefix = "Sone/" + sone.getId();
1336 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1337 if (soneTime == null) {
1338 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1341 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1344 Profile profile = new Profile(sone);
1345 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1346 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1347 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1348 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1349 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1350 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1352 /* load profile fields. */
1354 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1355 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1356 if (fieldName == null) {
1359 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1360 profile.addField(fieldName).setValue(fieldValue);
1364 Set<Post> posts = new HashSet<Post>();
1366 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1367 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1368 if (postId == null) {
1371 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1372 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1373 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1374 if ((postTime == 0) || (postText == null)) {
1375 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1378 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1379 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1380 post.setRecipient(getSone(postRecipientId));
1386 Set<PostReply> replies = new HashSet<PostReply>();
1388 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1389 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1390 if (replyId == null) {
1393 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1394 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1395 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1396 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1397 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1400 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1403 /* load post likes. */
1404 Set<String> likedPostIds = new HashSet<String>();
1406 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1407 if (likedPostId == null) {
1410 likedPostIds.add(likedPostId);
1413 /* load reply likes. */
1414 Set<String> likedReplyIds = new HashSet<String>();
1416 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1417 if (likedReplyId == null) {
1420 likedReplyIds.add(likedReplyId);
1424 Set<String> friends = new HashSet<String>();
1426 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1427 if (friendId == null) {
1430 friends.add(friendId);
1434 List<Album> topLevelAlbums = new ArrayList<Album>();
1435 int albumCounter = 0;
1437 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1438 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1439 if (albumId == null) {
1442 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1443 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1444 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1445 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1446 if ((albumTitle == null) || (albumDescription == null)) {
1447 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1450 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1451 if (albumParentId != null) {
1452 Album parentAlbum = getAlbum(albumParentId, false);
1453 if (parentAlbum == null) {
1454 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1457 parentAlbum.addAlbum(album);
1459 topLevelAlbums.add(album);
1464 int imageCounter = 0;
1466 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1467 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1468 if (imageId == null) {
1471 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1472 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1473 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1474 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1475 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1476 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1477 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1478 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1479 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1482 Album album = getAlbum(albumId, false);
1483 if (album == null) {
1484 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1487 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1488 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1489 album.addImage(image);
1493 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1494 if (avatarId != null) {
1495 profile.setAvatar(getImage(avatarId, false));
1499 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1500 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1501 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1502 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1503 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1504 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1506 /* if we’re still here, Sone was loaded successfully. */
1507 synchronized (sone) {
1508 sone.setTime(soneTime);
1509 sone.setProfile(profile);
1510 sone.setPosts(posts);
1511 sone.setReplies(replies);
1512 sone.setLikePostIds(likedPostIds);
1513 sone.setLikeReplyIds(likedReplyIds);
1514 for (String friendId : friends) {
1515 followSone(sone, friendId);
1517 sone.setAlbums(topLevelAlbums);
1518 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1520 synchronized (knownSones) {
1521 for (String friend : friends) {
1522 knownSones.add(friend);
1525 synchronized (knownPosts) {
1526 for (Post post : posts) {
1527 knownPosts.add(post.getId());
1530 synchronized (knownReplies) {
1531 for (PostReply reply : replies) {
1532 knownReplies.add(reply.getId());
1538 * Creates a new post.
1541 * The Sone that creates the post
1543 * The text of the post
1544 * @return The created post
1546 public Post createPost(Sone sone, String text) {
1547 return createPost(sone, System.currentTimeMillis(), text);
1551 * Creates a new post.
1554 * The Sone that creates the post
1556 * The time of the post
1558 * The text of the post
1559 * @return The created post
1561 public Post createPost(Sone sone, long time, String text) {
1562 return createPost(sone, null, time, text);
1566 * Creates a new post.
1569 * The Sone that creates the post
1571 * The recipient Sone, or {@code null} if this post does not have
1574 * The text of the post
1575 * @return The created post
1577 public Post createPost(Sone sone, Sone recipient, String text) {
1578 return createPost(sone, recipient, System.currentTimeMillis(), text);
1582 * Creates a new post.
1585 * The Sone that creates the post
1587 * The recipient Sone, or {@code null} if this post does not have
1590 * The time of the post
1592 * The text of the post
1593 * @return The created post
1595 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1596 if (!isLocalSone(sone)) {
1597 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1600 final Post post = new Post(sone, time, text);
1601 if (recipient != null) {
1602 post.setRecipient(recipient);
1604 synchronized (posts) {
1605 posts.put(post.getId(), post);
1607 coreListenerManager.fireNewPostFound(post);
1609 touchConfiguration();
1610 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1617 markPostKnown(post);
1619 }, "Mark " + post + " read.");
1624 * Deletes the given post.
1627 * The post to delete
1629 public void deletePost(Post post) {
1630 if (!isLocalSone(post.getSone())) {
1631 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1634 post.getSone().removePost(post);
1635 synchronized (posts) {
1636 posts.remove(post.getId());
1638 coreListenerManager.firePostRemoved(post);
1639 markPostKnown(post);
1640 touchConfiguration();
1644 * Marks the given post as known, if it is currently a new post (according
1645 * to {@link #isNewPost(String)}).
1648 * The post to mark as known
1650 public void markPostKnown(Post post) {
1651 post.setKnown(true);
1652 synchronized (knownPosts) {
1653 if (knownPosts.add(post.getId())) {
1654 coreListenerManager.fireMarkPostKnown(post);
1655 touchConfiguration();
1661 * Bookmarks the given post.
1664 * The post to bookmark
1666 public void bookmark(Post post) {
1667 bookmarkPost(post.getId());
1671 * Bookmarks the post with the given ID.
1674 * The ID of the post to bookmark
1676 public void bookmarkPost(String id) {
1677 synchronized (bookmarkedPosts) {
1678 bookmarkedPosts.add(id);
1683 * Removes the given post from the bookmarks.
1686 * The post to unbookmark
1688 public void unbookmark(Post post) {
1689 unbookmarkPost(post.getId());
1693 * Removes the post with the given ID from the bookmarks.
1696 * The ID of the post to unbookmark
1698 public void unbookmarkPost(String id) {
1699 synchronized (bookmarkedPosts) {
1700 bookmarkedPosts.remove(id);
1705 * Creates a new reply.
1708 * The Sone that creates the reply
1710 * The post that this reply refers to
1712 * The text of the reply
1713 * @return The created reply
1715 public PostReply createReply(Sone sone, Post post, String text) {
1716 return createReply(sone, post, System.currentTimeMillis(), text);
1720 * Creates a new reply.
1723 * The Sone that creates the reply
1725 * The post that this reply refers to
1727 * The time of the reply
1729 * The text of the reply
1730 * @return The created reply
1732 public PostReply createReply(Sone sone, Post post, long time, String text) {
1733 if (!isLocalSone(sone)) {
1734 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1737 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1738 synchronized (replies) {
1739 replies.put(reply.getId(), reply);
1741 synchronized (knownReplies) {
1742 coreListenerManager.fireNewReplyFound(reply);
1744 sone.addReply(reply);
1745 touchConfiguration();
1746 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1753 markReplyKnown(reply);
1755 }, "Mark " + reply + " read.");
1760 * Deletes the given reply.
1763 * The reply to delete
1765 public void deleteReply(PostReply reply) {
1766 Sone sone = reply.getSone();
1767 if (!isLocalSone(sone)) {
1768 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1771 synchronized (replies) {
1772 replies.remove(reply.getId());
1774 synchronized (knownReplies) {
1775 markReplyKnown(reply);
1776 knownReplies.remove(reply.getId());
1778 sone.removeReply(reply);
1779 touchConfiguration();
1783 * Marks the given reply as known, if it is currently a new reply (according
1784 * to {@link #isNewReply(String)}).
1787 * The reply to mark as known
1789 public void markReplyKnown(PostReply reply) {
1790 reply.setKnown(true);
1791 synchronized (knownReplies) {
1792 if (knownReplies.add(reply.getId())) {
1793 coreListenerManager.fireMarkReplyKnown(reply);
1794 touchConfiguration();
1800 * Creates a new top-level album for the given Sone.
1803 * The Sone to create the album for
1804 * @return The new album
1806 public Album createAlbum(Sone sone) {
1807 return createAlbum(sone, null);
1811 * Creates a new album for the given Sone.
1814 * The Sone to create the album for
1816 * The parent of the album (may be {@code null} to create a
1818 * @return The new album
1820 public Album createAlbum(Sone sone, Album parent) {
1821 Album album = new Album();
1822 synchronized (albums) {
1823 albums.put(album.getId(), album);
1825 album.setSone(sone);
1826 if (parent != null) {
1827 parent.addAlbum(album);
1829 sone.addAlbum(album);
1835 * Deletes the given album. The owner of the album has to be a local Sone,
1836 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1839 * The album to remove
1841 public void deleteAlbum(Album album) {
1842 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1843 if (!album.isEmpty()) {
1846 if (album.getParent() == null) {
1847 album.getSone().removeAlbum(album);
1849 album.getParent().removeAlbum(album);
1851 synchronized (albums) {
1852 albums.remove(album.getId());
1854 saveSone(album.getSone());
1858 * Creates a new image.
1861 * The Sone creating the image
1863 * The album the image will be inserted into
1864 * @param temporaryImage
1865 * The temporary image to create the image from
1866 * @return The newly created image
1868 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1869 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();
1870 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1871 album.addImage(image);
1872 synchronized (images) {
1873 images.put(image.getId(), image);
1875 imageInserter.insertImage(temporaryImage, image);
1880 * Deletes the given image. This method will also delete a matching
1883 * @see #deleteTemporaryImage(TemporaryImage)
1885 * The image to delete
1887 public void deleteImage(Image image) {
1888 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1889 deleteTemporaryImage(image.getId());
1890 image.getAlbum().removeImage(image);
1891 synchronized (images) {
1892 images.remove(image.getId());
1894 saveSone(image.getSone());
1898 * Creates a new temporary image.
1901 * The MIME type of the temporary image
1903 * The encoded data of the image
1904 * @return The temporary image
1906 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1907 TemporaryImage temporaryImage = new TemporaryImage();
1908 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1909 synchronized (temporaryImages) {
1910 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1912 return temporaryImage;
1916 * Deletes the given temporary image.
1918 * @param temporaryImage
1919 * The temporary image to delete
1921 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1922 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1923 deleteTemporaryImage(temporaryImage.getId());
1927 * Deletes the temporary image with the given ID.
1930 * The ID of the temporary image to delete
1932 public void deleteTemporaryImage(String imageId) {
1933 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1934 synchronized (temporaryImages) {
1935 temporaryImages.remove(imageId);
1937 Image image = getImage(imageId, false);
1938 if (image != null) {
1939 imageInserter.cancelImageInsert(image);
1944 * Notifies the core that the configuration, either of the core or of a
1945 * single local Sone, has changed, and that the configuration should be
1948 public void touchConfiguration() {
1949 lastConfigurationUpdate = System.currentTimeMillis();
1960 public void serviceStart() {
1961 loadConfiguration();
1962 updateChecker.addUpdateListener(this);
1963 updateChecker.start();
1970 public void serviceRun() {
1971 long lastSaved = System.currentTimeMillis();
1972 while (!shouldStop()) {
1974 long now = System.currentTimeMillis();
1975 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1976 for (Sone localSone : getLocalSones()) {
1977 saveSone(localSone);
1979 saveConfiguration();
1989 public void serviceStop() {
1990 synchronized (localSones) {
1991 for (SoneInserter soneInserter : soneInserters.values()) {
1992 soneInserter.removeSoneInsertListener(this);
1993 soneInserter.stop();
1996 updateChecker.stop();
1997 updateChecker.removeUpdateListener(this);
1998 soneDownloader.stop();
2006 * Saves the given Sone. This will persist all local settings for the given
2007 * Sone, such as the friends list and similar, private options.
2012 private synchronized void saveSone(Sone sone) {
2013 if (!isLocalSone(sone)) {
2014 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2017 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2018 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2022 logger.log(Level.INFO, "Saving Sone: %s", sone);
2024 /* save Sone into configuration. */
2025 String sonePrefix = "Sone/" + sone.getId();
2026 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2027 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2030 Profile profile = sone.getProfile();
2031 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2032 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2033 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2034 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2035 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2036 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2037 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2039 /* save profile fields. */
2040 int fieldCounter = 0;
2041 for (Field profileField : profile.getFields()) {
2042 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2043 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2044 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2046 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2049 int postCounter = 0;
2050 for (Post post : sone.getPosts()) {
2051 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2052 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2053 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2054 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2055 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2057 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2060 int replyCounter = 0;
2061 for (PostReply reply : sone.getReplies()) {
2062 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2063 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2064 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2065 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2066 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2068 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2070 /* save post likes. */
2071 int postLikeCounter = 0;
2072 for (String postId : sone.getLikedPostIds()) {
2073 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2075 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2077 /* save reply likes. */
2078 int replyLikeCounter = 0;
2079 for (String replyId : sone.getLikedReplyIds()) {
2080 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2082 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2085 int friendCounter = 0;
2086 for (String friendId : sone.getFriends()) {
2087 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2089 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2091 /* save albums. first, collect in a flat structure, top-level first. */
2092 List<Album> albums = sone.getAllAlbums();
2094 int albumCounter = 0;
2095 for (Album album : albums) {
2096 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2097 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2098 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2099 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2100 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2101 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2103 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2106 int imageCounter = 0;
2107 for (Album album : albums) {
2108 for (Image image : album.getImages()) {
2109 if (!image.isInserted()) {
2112 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2113 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2114 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2115 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2116 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2117 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2118 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2119 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2120 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2123 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2126 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2127 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2128 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2129 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2130 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2131 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2133 configuration.save();
2135 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2137 logger.log(Level.INFO, "Sone %s saved.", sone);
2138 } catch (ConfigurationException ce1) {
2139 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2140 } catch (WebOfTrustException wote1) {
2141 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2146 * Saves the current options.
2148 private void saveConfiguration() {
2149 synchronized (configuration) {
2150 if (storingConfiguration) {
2151 logger.log(Level.FINE, "Already storing configuration…");
2154 storingConfiguration = true;
2157 /* store the options first. */
2159 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2160 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2161 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2162 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2163 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2164 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2165 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2166 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2167 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2168 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2169 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2170 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2171 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2172 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2174 /* save known Sones. */
2175 int soneCounter = 0;
2176 synchronized (knownSones) {
2177 for (String knownSoneId : knownSones) {
2178 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2180 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2183 /* save Sone following times. */
2185 synchronized (soneFollowingTimes) {
2186 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2187 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2188 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2191 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2194 /* save known posts. */
2195 int postCounter = 0;
2196 synchronized (knownPosts) {
2197 for (String knownPostId : knownPosts) {
2198 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2200 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2203 /* save known replies. */
2204 int replyCounter = 0;
2205 synchronized (knownReplies) {
2206 for (String knownReplyId : knownReplies) {
2207 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2209 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2212 /* save bookmarked posts. */
2213 int bookmarkedPostCounter = 0;
2214 synchronized (bookmarkedPosts) {
2215 for (String bookmarkedPostId : bookmarkedPosts) {
2216 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2219 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2222 configuration.save();
2224 } catch (ConfigurationException ce1) {
2225 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2227 synchronized (configuration) {
2228 storingConfiguration = false;
2234 * Loads the configuration.
2236 @SuppressWarnings("unchecked")
2237 private void loadConfiguration() {
2238 /* create options. */
2239 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2242 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2243 SoneInserter.setInsertionDelay(newValue);
2247 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2248 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2249 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2250 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2251 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2252 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2253 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2254 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2257 @SuppressWarnings("synthetic-access")
2258 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2259 fcpInterface.setActive(newValue);
2262 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2265 @SuppressWarnings("synthetic-access")
2266 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2267 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2271 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2272 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2273 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2275 /* read options from configuration. */
2276 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2277 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2278 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2279 options.getBooleanOption("ClearOnNextRestart").set(null);
2280 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2281 if (clearConfiguration) {
2282 /* stop loading the configuration. */
2286 loadConfigurationValue("InsertionDelay");
2287 loadConfigurationValue("PostsPerPage");
2288 loadConfigurationValue("CharactersPerPost");
2289 loadConfigurationValue("PostCutOffLength");
2290 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2291 loadConfigurationValue("PositiveTrust");
2292 loadConfigurationValue("NegativeTrust");
2293 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2294 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2295 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2296 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2298 /* load known Sones. */
2299 int soneCounter = 0;
2301 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2302 if (knownSoneId == null) {
2305 synchronized (knownSones) {
2306 knownSones.add(knownSoneId);
2310 /* load Sone following times. */
2313 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2314 if (soneId == null) {
2317 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2318 Sone followedSone = getSone(soneId);
2319 if (followedSone == null) {
2320 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2322 synchronized (soneFollowingTimes) {
2323 soneFollowingTimes.put(getSone(soneId), time);
2329 /* load known posts. */
2330 int postCounter = 0;
2332 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2333 if (knownPostId == null) {
2336 synchronized (knownPosts) {
2337 knownPosts.add(knownPostId);
2341 /* load known replies. */
2342 int replyCounter = 0;
2344 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2345 if (knownReplyId == null) {
2348 synchronized (knownReplies) {
2349 knownReplies.add(knownReplyId);
2353 /* load bookmarked posts. */
2354 int bookmarkedPostCounter = 0;
2356 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2357 if (bookmarkedPostId == null) {
2360 synchronized (bookmarkedPosts) {
2361 bookmarkedPosts.add(bookmarkedPostId);
2368 * Loads an {@link Integer} configuration value for the option with the
2369 * given name, logging validation failures.
2372 * The name of the option to load
2374 private void loadConfigurationValue(String optionName) {
2376 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2377 } catch (IllegalArgumentException iae1) {
2378 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2383 * Generate a Sone URI from the given URI and latest edition.
2386 * The URI to derive the Sone URI from
2387 * @return The derived URI
2389 private FreenetURI getSoneUri(String uriString) {
2391 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2393 } catch (MalformedURLException mue1) {
2394 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2400 // INTERFACE IdentityListener
2407 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2408 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2409 if (ownIdentity.hasContext("Sone")) {
2410 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2411 addLocalSone(ownIdentity);
2419 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2420 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2421 trustedIdentities.remove(ownIdentity);
2428 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2429 logger.log(Level.FINEST, "Adding Identity: " + identity);
2430 trustedIdentities.get(ownIdentity).add(identity);
2431 addRemoteSone(identity);
2438 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2439 new Thread(new Runnable() {
2442 @SuppressWarnings("synthetic-access")
2444 Sone sone = getRemoteSone(identity.getId(), false);
2445 sone.setIdentity(identity);
2446 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2447 soneDownloader.addSone(sone);
2448 soneDownloader.fetchSone(sone);
2457 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2458 trustedIdentities.get(ownIdentity).remove(identity);
2459 boolean foundIdentity = false;
2460 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2461 if (trustedIdentity.getKey().equals(ownIdentity)) {
2464 if (trustedIdentity.getValue().contains(identity)) {
2465 foundIdentity = true;
2468 if (foundIdentity) {
2469 /* some local identity still trusts this identity, don’t remove. */
2472 Sone sone = getSone(identity.getId(), false);
2474 /* TODO - we don’t have the Sone anymore. should this happen? */
2477 synchronized (posts) {
2478 synchronized (knownPosts) {
2479 for (Post post : sone.getPosts()) {
2480 posts.remove(post.getId());
2481 coreListenerManager.firePostRemoved(post);
2485 synchronized (replies) {
2486 synchronized (knownReplies) {
2487 for (PostReply reply : sone.getReplies()) {
2488 replies.remove(reply.getId());
2489 coreListenerManager.fireReplyRemoved(reply);
2493 synchronized (remoteSones) {
2494 remoteSones.remove(identity.getId());
2496 coreListenerManager.fireSoneRemoved(sone);
2500 // INTERFACE UpdateListener
2507 public void updateFound(Version version, long releaseTime, long latestEdition) {
2508 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2512 // INTERFACE ImageInsertListener
2519 public void insertStarted(Sone sone) {
2520 coreListenerManager.fireSoneInserting(sone);
2527 public void insertFinished(Sone sone, long insertDuration) {
2528 coreListenerManager.fireSoneInserted(sone, insertDuration);
2535 public void insertAborted(Sone sone, Throwable cause) {
2536 coreListenerManager.fireSoneInsertAborted(sone, cause);
2540 // SONEINSERTLISTENER METHODS
2547 public void imageInsertStarted(Image image) {
2548 logger.log(Level.WARNING, "Image insert started for " + image);
2549 coreListenerManager.fireImageInsertStarted(image);
2556 public void imageInsertAborted(Image image) {
2557 logger.log(Level.WARNING, "Image insert aborted for " + image);
2558 coreListenerManager.fireImageInsertAborted(image);
2565 public void imageInsertFinished(Image image, FreenetURI key) {
2566 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2567 image.setKey(key.toString());
2568 deleteTemporaryImage(image.getId());
2569 saveSone(image.getSone());
2570 coreListenerManager.fireImageInsertFinished(image);
2577 public void imageInsertFailed(Image image, Throwable cause) {
2578 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2579 coreListenerManager.fireImageInsertFailed(image, cause);
2583 * Convenience interface for external classes that want to access the core’s
2586 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2588 public static class Preferences {
2590 /** The wrapped options. */
2591 private final Options options;
2594 * Creates a new preferences object wrapped around the given options.
2597 * The options to wrap
2599 public Preferences(Options options) {
2600 this.options = options;
2604 * Returns the insertion delay.
2606 * @return The insertion delay
2608 public int getInsertionDelay() {
2609 return options.getIntegerOption("InsertionDelay").get();
2613 * Validates the given insertion delay.
2615 * @param insertionDelay
2616 * The insertion delay to validate
2617 * @return {@code true} if the given insertion delay was valid,
2618 * {@code false} otherwise
2620 public boolean validateInsertionDelay(Integer insertionDelay) {
2621 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2625 * Sets the insertion delay
2627 * @param insertionDelay
2628 * The new insertion delay, or {@code null} to restore it to
2630 * @return This preferences
2632 public Preferences setInsertionDelay(Integer insertionDelay) {
2633 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2638 * Returns the number of posts to show per page.
2640 * @return The number of posts to show per page
2642 public int getPostsPerPage() {
2643 return options.getIntegerOption("PostsPerPage").get();
2647 * Validates the number of posts per page.
2649 * @param postsPerPage
2650 * The number of posts per page
2651 * @return {@code true} if the number of posts per page was valid,
2652 * {@code false} otherwise
2654 public boolean validatePostsPerPage(Integer postsPerPage) {
2655 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2659 * Sets the number of posts to show per page.
2661 * @param postsPerPage
2662 * The number of posts to show per page
2663 * @return This preferences object
2665 public Preferences setPostsPerPage(Integer postsPerPage) {
2666 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2671 * Returns the number of characters per post, or <code>-1</code> if the
2672 * posts should not be cut off.
2674 * @return The numbers of characters per post
2676 public int getCharactersPerPost() {
2677 return options.getIntegerOption("CharactersPerPost").get();
2681 * Validates the number of characters per post.
2683 * @param charactersPerPost
2684 * The number of characters per post
2685 * @return {@code true} if the number of characters per post was valid,
2686 * {@code false} otherwise
2688 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2689 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2693 * Sets the number of characters per post.
2695 * @param charactersPerPost
2696 * The number of characters per post, or <code>-1</code> to
2697 * not cut off the posts
2698 * @return This preferences objects
2700 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2701 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2706 * Returns the number of characters the shortened post should have.
2708 * @return The number of characters of the snippet
2710 public int getPostCutOffLength() {
2711 return options.getIntegerOption("PostCutOffLength").get();
2715 * Validates the number of characters after which to cut off the post.
2717 * @param postCutOffLength
2718 * The number of characters of the snippet
2719 * @return {@code true} if the number of characters of the snippet is
2720 * valid, {@code false} otherwise
2722 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2723 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2727 * Sets the number of characters the shortened post should have.
2729 * @param postCutOffLength
2730 * The number of characters of the snippet
2731 * @return This preferences
2733 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2734 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2739 * Returns whether Sone requires full access to be even visible.
2741 * @return {@code true} if Sone requires full access, {@code false}
2744 public boolean isRequireFullAccess() {
2745 return options.getBooleanOption("RequireFullAccess").get();
2749 * Sets whether Sone requires full access to be even visible.
2751 * @param requireFullAccess
2752 * {@code true} if Sone requires full access, {@code false}
2755 public void setRequireFullAccess(Boolean requireFullAccess) {
2756 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2760 * Returns the positive trust.
2762 * @return The positive trust
2764 public int getPositiveTrust() {
2765 return options.getIntegerOption("PositiveTrust").get();
2769 * Validates the positive trust.
2771 * @param positiveTrust
2772 * The positive trust to validate
2773 * @return {@code true} if the positive trust was valid, {@code false}
2776 public boolean validatePositiveTrust(Integer positiveTrust) {
2777 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2781 * Sets the positive trust.
2783 * @param positiveTrust
2784 * The new positive trust, or {@code null} to restore it to
2786 * @return This preferences
2788 public Preferences setPositiveTrust(Integer positiveTrust) {
2789 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2794 * Returns the negative trust.
2796 * @return The negative trust
2798 public int getNegativeTrust() {
2799 return options.getIntegerOption("NegativeTrust").get();
2803 * Validates the negative trust.
2805 * @param negativeTrust
2806 * The negative trust to validate
2807 * @return {@code true} if the negative trust was valid, {@code false}
2810 public boolean validateNegativeTrust(Integer negativeTrust) {