2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Profile.Field;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.data.TemporaryImage;
49 import net.pterodactylus.sone.data.impl.PostImpl;
50 import net.pterodactylus.sone.fcp.FcpInterface;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.sone.freenet.wot.IdentityListener;
54 import net.pterodactylus.sone.freenet.wot.IdentityManager;
55 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
56 import net.pterodactylus.sone.main.SonePlugin;
57 import net.pterodactylus.util.config.Configuration;
58 import net.pterodactylus.util.config.ConfigurationException;
59 import net.pterodactylus.util.logging.Logging;
60 import net.pterodactylus.util.number.Numbers;
61 import net.pterodactylus.util.service.AbstractService;
62 import net.pterodactylus.util.thread.NamedThreadFactory;
63 import net.pterodactylus.util.thread.Ticker;
64 import net.pterodactylus.util.validation.EqualityValidator;
65 import net.pterodactylus.util.validation.IntegerRangeValidator;
66 import net.pterodactylus.util.validation.OrValidator;
67 import net.pterodactylus.util.validation.Validation;
68 import net.pterodactylus.util.version.Version;
69 import freenet.keys.FreenetURI;
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener, PostReplyProvider {
79 private static final Logger logger = Logging.getLogger(Core.class);
81 /** The start time. */
82 private final long startupTime = System.currentTimeMillis();
85 private final Options options = new Options();
87 /** The preferences. */
88 private final Preferences preferences = new Preferences(options);
90 /** The core listener manager. */
91 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
93 /** The configuration. */
94 private Configuration configuration;
96 /** Whether we’re currently saving the configuration. */
97 private boolean storingConfiguration = false;
99 /** The identity manager. */
100 private final IdentityManager identityManager;
102 /** Interface to freenet. */
103 private final FreenetInterface freenetInterface;
105 /** The Sone downloader. */
106 private final SoneDownloader soneDownloader;
108 /** The image inserter. */
109 private final ImageInserter imageInserter;
111 /** Sone downloader thread-pool. */
112 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
114 /** The update checker. */
115 private final UpdateChecker updateChecker;
117 /** The trust updater. */
118 private final WebOfTrustUpdater webOfTrustUpdater;
120 /** The FCP interface. */
121 private volatile FcpInterface fcpInterface;
123 /** The times Sones were followed. */
124 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
126 /** Locked local Sones. */
127 /* synchronize on itself. */
128 private final Set<Sone> lockedSones = new HashSet<Sone>();
130 /** Sone inserters. */
131 /* synchronize access on this on localSones. */
132 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
134 /** Sone rescuers. */
135 /* synchronize access on this on localSones. */
136 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
138 /** All local Sones. */
139 /* synchronize access on this on itself. */
140 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
142 /** All remote Sones. */
143 /* synchronize access on this on itself. */
144 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
146 /** All known Sones. */
147 private final Set<String> knownSones = new HashSet<String>();
150 private final Map<String, Post> posts = new HashMap<String, Post>();
152 /** All known posts. */
153 private final Set<String> knownPosts = new HashSet<String>();
156 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
158 /** All known replies. */
159 private final Set<String> knownReplies = new HashSet<String>();
161 /** All bookmarked posts. */
162 /* synchronize access on itself. */
163 private final Set<String> bookmarkedPosts = new HashSet<String>();
165 /** Trusted identities, sorted by own identities. */
166 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
168 /** All known albums. */
169 private final Map<String, Album> albums = new HashMap<String, Album>();
171 /** All known images. */
172 private final Map<String, Image> images = new HashMap<String, Image>();
174 /** All temporary images. */
175 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
177 /** Ticker for threads that mark own elements as known. */
178 private final Ticker localElementTicker = new Ticker();
180 /** The time the configuration was last touched. */
181 private volatile long lastConfigurationUpdate;
184 * Creates a new core.
186 * @param configuration
187 * The configuration of the core
188 * @param freenetInterface
189 * The freenet interface
190 * @param identityManager
191 * The identity manager
192 * @param webOfTrustUpdater
193 * The WebOfTrust updater
195 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
197 this.configuration = configuration;
198 this.freenetInterface = freenetInterface;
199 this.identityManager = identityManager;
200 this.soneDownloader = new SoneDownloader(this, freenetInterface);
201 this.imageInserter = new ImageInserter(this, freenetInterface);
202 this.updateChecker = new UpdateChecker(freenetInterface);
203 this.webOfTrustUpdater = webOfTrustUpdater;
207 // LISTENER MANAGEMENT
211 * Adds a new core listener.
213 * @param coreListener
214 * The listener to add
216 public void addCoreListener(CoreListener coreListener) {
217 coreListenerManager.addListener(coreListener);
221 * Removes a core listener.
223 * @param coreListener
224 * The listener to remove
226 public void removeCoreListener(CoreListener coreListener) {
227 coreListenerManager.removeListener(coreListener);
235 * Returns the time Sone was started.
237 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
239 public long getStartupTime() {
244 * Sets the configuration to use. This will automatically save the current
245 * configuration to the given configuration.
247 * @param configuration
248 * The new configuration to use
250 public void setConfiguration(Configuration configuration) {
251 this.configuration = configuration;
252 touchConfiguration();
256 * Returns the options used by the core.
258 * @return The options of the core
260 public Preferences getPreferences() {
265 * Returns the identity manager used by the core.
267 * @return The identity manager
269 public IdentityManager getIdentityManager() {
270 return identityManager;
274 * Returns the update checker.
276 * @return The update checker
278 public UpdateChecker getUpdateChecker() {
279 return updateChecker;
283 * Sets the FCP interface to use.
285 * @param fcpInterface
286 * The FCP interface to use
288 public void setFcpInterface(FcpInterface fcpInterface) {
289 this.fcpInterface = fcpInterface;
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
301 synchronized (localSones) {
302 SoneRescuer soneRescuer = soneRescuers.get(sone);
303 if (soneRescuer == null) {
304 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
305 soneRescuers.put(sone, soneRescuer);
313 * Returns whether the given Sone is currently locked.
317 * @return {@code true} if the Sone is locked, {@code false} if it is not
319 public boolean isLocked(Sone sone) {
320 synchronized (lockedSones) {
321 return lockedSones.contains(sone);
326 * Returns all Sones, remote and local.
330 public Set<Sone> getSones() {
331 Set<Sone> allSones = new HashSet<Sone>();
332 allSones.addAll(getLocalSones());
333 allSones.addAll(getRemoteSones());
338 * Returns the Sone with the given ID, regardless whether it’s local or
342 * The ID of the Sone to get
343 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Sone getSone(String id) {
347 return getSone(id, true);
351 * Returns the Sone with the given ID, regardless whether it’s local or
355 * The ID of the Sone to get
357 * {@code true} to create a new Sone if none exists,
358 * {@code false} to return {@code null} if a Sone with the given
360 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Sone getSone(String id, boolean create) {
365 if (isLocalSone(id)) {
366 return getLocalSone(id);
368 return getRemoteSone(id, create);
372 * Checks whether the core knows a Sone with the given ID.
376 * @return {@code true} if there is a Sone with the given ID, {@code false}
379 public boolean hasSone(String id) {
380 return isLocalSone(id) || isRemoteSone(id);
384 * Returns whether the given Sone is a local Sone.
387 * The Sone to check for its locality
388 * @return {@code true} if the given Sone is local, {@code false} otherwise
390 public boolean isLocalSone(Sone sone) {
391 synchronized (localSones) {
392 return localSones.containsKey(sone.getId());
397 * Returns whether the given ID is the ID of a local Sone.
400 * The Sone ID to check for its locality
401 * @return {@code true} if the given ID is a local Sone, {@code false}
404 public boolean isLocalSone(String id) {
405 synchronized (localSones) {
406 return localSones.containsKey(id);
411 * Returns all local Sones.
413 * @return All local Sones
415 public Set<Sone> getLocalSones() {
416 synchronized (localSones) {
417 return new HashSet<Sone>(localSones.values());
422 * Returns the local Sone with the given ID.
425 * The ID of the Sone to get
426 * @return The Sone with the given ID
428 public Sone getLocalSone(String id) {
429 return getLocalSone(id, true);
433 * Returns the local Sone with the given ID, optionally creating a new Sone.
438 * {@code true} to create a new Sone if none exists,
439 * {@code false} to return null if none exists
440 * @return The Sone with the given ID, or {@code null}
442 public Sone getLocalSone(String id, boolean create) {
443 synchronized (localSones) {
444 Sone sone = localSones.get(id);
445 if ((sone == null) && create) {
447 localSones.put(id, sone);
454 * Returns all remote Sones.
456 * @return All remote Sones
458 public Set<Sone> getRemoteSones() {
459 synchronized (remoteSones) {
460 return new HashSet<Sone>(remoteSones.values());
465 * Returns the remote Sone with the given ID.
468 * The ID of the remote Sone to get
470 * {@code true} to always create a Sone, {@code false} to return
471 * {@code null} if no Sone with the given ID exists
472 * @return The Sone with the given ID
474 public Sone getRemoteSone(String id, boolean create) {
475 synchronized (remoteSones) {
476 Sone sone = remoteSones.get(id);
477 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
479 remoteSones.put(id, sone);
486 * Returns whether the given Sone is a remote Sone.
490 * @return {@code true} if the given Sone is a remote Sone, {@code false}
493 public boolean isRemoteSone(Sone sone) {
494 synchronized (remoteSones) {
495 return remoteSones.containsKey(sone.getId());
500 * Returns whether the Sone with the given ID is a remote Sone.
503 * The ID of the Sone to check
504 * @return {@code true} if the Sone with the given ID is a remote Sone,
505 * {@code false} otherwise
507 public boolean isRemoteSone(String id) {
508 synchronized (remoteSones) {
509 return remoteSones.containsKey(id);
514 * Returns whether the given Sone has been modified.
517 * The Sone to check for modifications
518 * @return {@code true} if a modification has been detected in the Sone,
519 * {@code false} otherwise
521 public boolean isModifiedSone(Sone sone) {
522 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
526 * Returns the time when the given was first followed by any local Sone.
529 * The Sone to get the time for
530 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
531 * been followed, or {@link Long#MAX_VALUE}
533 public long getSoneFollowingTime(Sone sone) {
534 synchronized (soneFollowingTimes) {
535 if (soneFollowingTimes.containsKey(sone)) {
536 return soneFollowingTimes.get(sone);
538 return Long.MAX_VALUE;
543 * Returns whether the target Sone is trusted by the origin Sone.
549 * @return {@code true} if the target Sone is trusted by the origin Sone
551 public boolean isSoneTrusted(Sone origin, Sone target) {
552 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
553 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
557 * Returns the post with the given ID.
560 * The ID of the post to get
561 * @return The post with the given ID, or a new post with the given ID
563 public Post getPost(String postId) {
564 return getPost(postId, true);
568 * Returns the post with the given ID, optionally creating a new post.
571 * The ID of the post to get
573 * {@code true} it create a new post if no post with the given ID
574 * exists, {@code false} to return {@code null}
575 * @return The post, or {@code null} if there is no such post
578 public Post getPost(String postId, boolean create) {
579 synchronized (posts) {
580 Post post = posts.get(postId);
581 if ((post == null) && create) {
582 post = new PostImpl(postId);
583 posts.put(postId, post);
590 * Returns all posts that have the given Sone as recipient.
592 * @see Post#getRecipient()
594 * The recipient of the posts
595 * @return All posts that have the given Sone as recipient
597 public Set<Post> getDirectedPosts(Sone recipient) {
598 Validation.begin().isNotNull("Recipient", recipient).check();
599 Set<Post> directedPosts = new HashSet<Post>();
600 synchronized (posts) {
601 for (Post post : posts.values()) {
602 if (recipient.equals(post.getRecipient())) {
603 directedPosts.add(post);
607 return directedPosts;
614 public PostReply getPostReply(String replyId, boolean create) {
615 synchronized (replies) {
616 PostReply reply = replies.get(replyId);
617 if (create && (reply == null)) {
618 reply = new PostReply(replyId);
619 replies.put(replyId, reply);
626 * Returns all replies for the given post, order ascending by time.
629 * The post to get all replies for
630 * @return All replies for the given post
632 public List<PostReply> getReplies(Post post) {
633 Set<Sone> sones = getSones();
634 List<PostReply> replies = new ArrayList<PostReply>();
635 for (Sone sone : sones) {
636 for (PostReply reply : sone.getReplies()) {
637 if (reply.getPost().equals(post)) {
642 Collections.sort(replies, Reply.TIME_COMPARATOR);
647 * Returns all Sones that have liked the given post.
650 * The post to get the liking Sones for
651 * @return The Sones that like the given post
653 public Set<Sone> getLikes(Post post) {
654 Set<Sone> sones = new HashSet<Sone>();
655 for (Sone sone : getSones()) {
656 if (sone.getLikedPostIds().contains(post.getId())) {
664 * Returns all Sones that have liked the given reply.
667 * The reply to get the liking Sones for
668 * @return The Sones that like the given reply
670 public Set<Sone> getLikes(PostReply reply) {
671 Set<Sone> sones = new HashSet<Sone>();
672 for (Sone sone : getSones()) {
673 if (sone.getLikedReplyIds().contains(reply.getId())) {
681 * Returns whether the given post is bookmarked.
685 * @return {@code true} if the given post is bookmarked, {@code false}
688 public boolean isBookmarked(Post post) {
689 return isPostBookmarked(post.getId());
693 * Returns whether the post with the given ID is bookmarked.
696 * The ID of the post to check
697 * @return {@code true} if the post with the given ID is bookmarked,
698 * {@code false} otherwise
700 public boolean isPostBookmarked(String id) {
701 synchronized (bookmarkedPosts) {
702 return bookmarkedPosts.contains(id);
707 * Returns all currently known bookmarked posts.
709 * @return All bookmarked posts
711 public Set<Post> getBookmarkedPosts() {
712 Set<Post> posts = new HashSet<Post>();
713 synchronized (bookmarkedPosts) {
714 for (String bookmarkedPostId : bookmarkedPosts) {
715 Post post = getPost(bookmarkedPostId, false);
725 * Returns the album with the given ID, creating a new album if no album
726 * with the given ID can be found.
729 * The ID of the album
730 * @return The album with the given ID
732 public Album getAlbum(String albumId) {
733 return getAlbum(albumId, true);
737 * Returns the album with the given ID, optionally creating a new album if
738 * an album with the given ID can not be found.
741 * The ID of the album
743 * {@code true} to create a new album if none exists for the
745 * @return The album with the given ID, or {@code null} if no album with the
746 * given ID exists and {@code create} is {@code false}
748 public Album getAlbum(String albumId, boolean create) {
749 synchronized (albums) {
750 Album album = albums.get(albumId);
751 if (create && (album == null)) {
752 album = new Album(albumId);
753 albums.put(albumId, album);
760 * Returns the image with the given ID, creating it if necessary.
763 * The ID of the image
764 * @return The image with the given ID
766 public Image getImage(String imageId) {
767 return getImage(imageId, true);
771 * Returns the image with the given ID, optionally creating it if it does
775 * The ID of the image
777 * {@code true} to create an image if none exists with the given
779 * @return The image with the given ID, or {@code null} if none exists and
782 public Image getImage(String imageId, boolean create) {
783 synchronized (images) {
784 Image image = images.get(imageId);
785 if (create && (image == null)) {
786 image = new Image(imageId);
787 images.put(imageId, image);
794 * Returns the temporary image with the given ID.
797 * The ID of the temporary image
798 * @return The temporary image, or {@code null} if there is no temporary
799 * image with the given ID
801 public TemporaryImage getTemporaryImage(String imageId) {
802 synchronized (temporaryImages) {
803 return temporaryImages.get(imageId);
812 * Locks the given Sone. A locked Sone will not be inserted by
813 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
819 public void lockSone(Sone sone) {
820 synchronized (lockedSones) {
821 if (lockedSones.add(sone)) {
822 coreListenerManager.fireSoneLocked(sone);
828 * Unlocks the given Sone.
830 * @see #lockSone(Sone)
834 public void unlockSone(Sone sone) {
835 synchronized (lockedSones) {
836 if (lockedSones.remove(sone)) {
837 coreListenerManager.fireSoneUnlocked(sone);
843 * Adds a local Sone from the given own identity.
846 * The own identity to create a Sone from
847 * @return The added (or already existing) Sone
849 public Sone addLocalSone(OwnIdentity ownIdentity) {
850 if (ownIdentity == null) {
851 logger.log(Level.WARNING, "Given OwnIdentity is null!");
854 synchronized (localSones) {
857 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
858 } catch (MalformedURLException mue1) {
859 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
862 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
863 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
865 /* TODO - load posts ’n stuff */
866 localSones.put(ownIdentity.getId(), sone);
867 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
868 soneInserter.addSoneInsertListener(this);
869 soneInserters.put(sone, soneInserter);
870 sone.setStatus(SoneStatus.idle);
872 soneInserter.start();
878 * Creates a new Sone for the given own identity.
881 * The own identity to create a Sone for
882 * @return The created Sone
884 public Sone createSone(OwnIdentity ownIdentity) {
885 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
886 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
889 Sone sone = addLocalSone(ownIdentity);
890 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
891 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
892 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
893 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
894 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
895 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
897 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
898 touchConfiguration();
903 * Adds the Sone of the given identity.
906 * The identity whose Sone to add
907 * @return The added or already existing Sone
909 public Sone addRemoteSone(Identity identity) {
910 if (identity == null) {
911 logger.log(Level.WARNING, "Given Identity is null!");
914 synchronized (remoteSones) {
915 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
916 boolean newSone = sone.getRequestUri() == null;
917 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
918 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
920 synchronized (knownSones) {
921 newSone = !knownSones.contains(sone.getId());
923 sone.setKnown(!newSone);
925 coreListenerManager.fireNewSoneFound(sone);
926 for (Sone localSone : getLocalSones()) {
927 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
928 followSone(localSone, sone);
933 soneDownloader.addSone(sone);
934 soneDownloaders.execute(new Runnable() {
937 @SuppressWarnings("synthetic-access")
939 soneDownloader.fetchSone(sone, sone.getRequestUri());
948 * Lets the given local Sone follow the Sone with the given ID.
951 * The local Sone that should follow another Sone
953 * The ID of the Sone to follow
955 public void followSone(Sone sone, String soneId) {
956 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
957 Sone followedSone = getSone(soneId, true);
958 if (followedSone == null) {
959 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
962 followSone(sone, getSone(soneId));
966 * Lets the given local Sone follow the other given Sone. If the given Sone
967 * was not followed by any local Sone before, this will mark all elements of
968 * the followed Sone as read that have been created before the current
972 * The local Sone that should follow the other Sone
973 * @param followedSone
974 * The Sone that should be followed
976 public void followSone(Sone sone, Sone followedSone) {
977 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
978 sone.addFriend(followedSone.getId());
979 synchronized (soneFollowingTimes) {
980 if (!soneFollowingTimes.containsKey(followedSone)) {
981 long now = System.currentTimeMillis();
982 soneFollowingTimes.put(followedSone, now);
983 for (Post post : followedSone.getPosts()) {
984 if (post.getTime() < now) {
988 for (PostReply reply : followedSone.getReplies()) {
989 if (reply.getTime() < now) {
990 markReplyKnown(reply);
995 touchConfiguration();
999 * Lets the given local Sone unfollow the Sone with the given ID.
1002 * The local Sone that should unfollow another Sone
1004 * The ID of the Sone being unfollowed
1006 public void unfollowSone(Sone sone, String soneId) {
1007 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1008 unfollowSone(sone, getSone(soneId, false));
1012 * Lets the given local Sone unfollow the other given Sone. If the given
1013 * local Sone is the last local Sone that followed the given Sone, its
1014 * following time will be removed.
1017 * The local Sone that should unfollow another Sone
1018 * @param unfollowedSone
1019 * The Sone being unfollowed
1021 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1022 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1023 sone.removeFriend(unfollowedSone.getId());
1024 boolean unfollowedSoneStillFollowed = false;
1025 for (Sone localSone : getLocalSones()) {
1026 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1028 if (!unfollowedSoneStillFollowed) {
1029 synchronized (soneFollowingTimes) {
1030 soneFollowingTimes.remove(unfollowedSone);
1033 touchConfiguration();
1037 * Sets the trust value of the given origin Sone for the target Sone.
1044 * The trust value (from {@code -100} to {@code 100})
1046 public void setTrust(Sone origin, Sone target, int trustValue) {
1047 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();
1048 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1052 * Removes any trust assignment for the given target Sone.
1059 public void removeTrust(Sone origin, Sone target) {
1060 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1061 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1065 * Assigns the configured positive trust value for the given target.
1072 public void trustSone(Sone origin, Sone target) {
1073 setTrust(origin, target, preferences.getPositiveTrust());
1077 * Assigns the configured negative trust value for the given target.
1084 public void distrustSone(Sone origin, Sone target) {
1085 setTrust(origin, target, preferences.getNegativeTrust());
1089 * Removes the trust assignment for the given target.
1096 public void untrustSone(Sone origin, Sone target) {
1097 removeTrust(origin, target);
1101 * Updates the stored Sone with the given Sone.
1106 public void updateSone(Sone sone) {
1107 updateSone(sone, false);
1111 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1112 * {@code true}, an older Sone than the current Sone can be given to restore
1116 * The Sone to update
1117 * @param soneRescueMode
1118 * {@code true} if the stored Sone should be updated regardless
1119 * of the age of the given Sone
1121 public void updateSone(Sone sone, boolean soneRescueMode) {
1122 if (hasSone(sone.getId())) {
1123 Sone storedSone = getSone(sone.getId());
1124 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1125 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1128 synchronized (posts) {
1129 if (!soneRescueMode) {
1130 for (Post post : storedSone.getPosts()) {
1131 posts.remove(post.getId());
1132 if (!sone.getPosts().contains(post)) {
1133 coreListenerManager.firePostRemoved(post);
1137 List<Post> storedPosts = storedSone.getPosts();
1138 synchronized (knownPosts) {
1139 for (Post post : sone.getPosts()) {
1140 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1141 if (!storedPosts.contains(post)) {
1142 if (post.getTime() < getSoneFollowingTime(sone)) {
1143 knownPosts.add(post.getId());
1144 post.setKnown(true);
1145 } else if (!knownPosts.contains(post.getId())) {
1146 coreListenerManager.fireNewPostFound(post);
1149 posts.put(post.getId(), post);
1153 synchronized (replies) {
1154 if (!soneRescueMode) {
1155 for (PostReply reply : storedSone.getReplies()) {
1156 replies.remove(reply.getId());
1157 if (!sone.getReplies().contains(reply)) {
1158 coreListenerManager.fireReplyRemoved(reply);
1162 Set<PostReply> storedReplies = storedSone.getReplies();
1163 synchronized (knownReplies) {
1164 for (PostReply reply : sone.getReplies()) {
1165 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1166 if (!storedReplies.contains(reply)) {
1167 if (reply.getTime() < getSoneFollowingTime(sone)) {
1168 knownReplies.add(reply.getId());
1169 reply.setKnown(true);
1170 } else if (!knownReplies.contains(reply.getId())) {
1171 coreListenerManager.fireNewReplyFound(reply);
1174 replies.put(reply.getId(), reply);
1178 synchronized (albums) {
1179 synchronized (images) {
1180 for (Album album : storedSone.getAlbums()) {
1181 albums.remove(album.getId());
1182 for (Image image : album.getImages()) {
1183 images.remove(image.getId());
1186 for (Album album : sone.getAlbums()) {
1187 albums.put(album.getId(), album);
1188 for (Image image : album.getImages()) {
1189 images.put(image.getId(), image);
1194 synchronized (storedSone) {
1195 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1196 storedSone.setTime(sone.getTime());
1198 storedSone.setClient(sone.getClient());
1199 storedSone.setProfile(sone.getProfile());
1200 if (soneRescueMode) {
1201 for (Post post : sone.getPosts()) {
1202 storedSone.addPost(post);
1204 for (PostReply reply : sone.getReplies()) {
1205 storedSone.addReply(reply);
1207 for (String likedPostId : sone.getLikedPostIds()) {
1208 storedSone.addLikedPostId(likedPostId);
1210 for (String likedReplyId : sone.getLikedReplyIds()) {
1211 storedSone.addLikedReplyId(likedReplyId);
1213 for (Album album : sone.getAlbums()) {
1214 storedSone.addAlbum(album);
1217 storedSone.setPosts(sone.getPosts());
1218 storedSone.setReplies(sone.getReplies());
1219 storedSone.setLikePostIds(sone.getLikedPostIds());
1220 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1221 storedSone.setAlbums(sone.getAlbums());
1223 storedSone.setLatestEdition(sone.getLatestEdition());
1229 * Deletes the given Sone. This will remove the Sone from the
1230 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1231 * and remove the context from its identity.
1234 * The Sone to delete
1236 public void deleteSone(Sone sone) {
1237 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1238 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1241 synchronized (localSones) {
1242 if (!localSones.containsKey(sone.getId())) {
1243 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1246 localSones.remove(sone.getId());
1247 SoneInserter soneInserter = soneInserters.remove(sone);
1248 soneInserter.removeSoneInsertListener(this);
1249 soneInserter.stop();
1251 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1252 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1254 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1255 } catch (ConfigurationException ce1) {
1256 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1261 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1262 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1265 * The Sone to mark as known
1267 public void markSoneKnown(Sone sone) {
1268 if (!sone.isKnown()) {
1269 sone.setKnown(true);
1270 synchronized (knownSones) {
1271 knownSones.add(sone.getId());
1273 coreListenerManager.fireMarkSoneKnown(sone);
1274 touchConfiguration();
1279 * Loads and updates the given Sone from the configuration. If any error is
1280 * encountered, loading is aborted and the given Sone is not changed.
1283 * The Sone to load and update
1285 public void loadSone(Sone sone) {
1286 if (!isLocalSone(sone)) {
1287 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1291 /* initialize options. */
1292 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1293 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1294 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1295 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1296 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1297 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1300 String sonePrefix = "Sone/" + sone.getId();
1301 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1302 if (soneTime == null) {
1303 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1306 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1309 Profile profile = new Profile(sone);
1310 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1311 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1312 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1313 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1314 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1315 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1317 /* load profile fields. */
1319 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1320 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1321 if (fieldName == null) {
1324 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1325 profile.addField(fieldName).setValue(fieldValue);
1329 Set<Post> posts = new HashSet<Post>();
1331 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1332 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1333 if (postId == null) {
1336 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1337 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1338 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1339 if ((postTime == 0) || (postText == null)) {
1340 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1343 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1344 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1345 post.setRecipient(getSone(postRecipientId));
1351 Set<PostReply> replies = new HashSet<PostReply>();
1353 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1354 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1355 if (replyId == null) {
1358 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1359 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1360 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1361 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1362 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1365 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1368 /* load post likes. */
1369 Set<String> likedPostIds = new HashSet<String>();
1371 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1372 if (likedPostId == null) {
1375 likedPostIds.add(likedPostId);
1378 /* load reply likes. */
1379 Set<String> likedReplyIds = new HashSet<String>();
1381 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1382 if (likedReplyId == null) {
1385 likedReplyIds.add(likedReplyId);
1389 Set<String> friends = new HashSet<String>();
1391 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1392 if (friendId == null) {
1395 friends.add(friendId);
1399 List<Album> topLevelAlbums = new ArrayList<Album>();
1400 int albumCounter = 0;
1402 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1403 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1404 if (albumId == null) {
1407 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1408 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1409 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1410 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1411 if ((albumTitle == null) || (albumDescription == null)) {
1412 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1415 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1416 if (albumParentId != null) {
1417 Album parentAlbum = getAlbum(albumParentId, false);
1418 if (parentAlbum == null) {
1419 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1422 parentAlbum.addAlbum(album);
1424 if (!topLevelAlbums.contains(album)) {
1425 topLevelAlbums.add(album);
1431 int imageCounter = 0;
1433 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1434 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1435 if (imageId == null) {
1438 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1439 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1440 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1441 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1442 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1443 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1444 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1445 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1446 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1449 Album album = getAlbum(albumId, false);
1450 if (album == null) {
1451 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1454 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1455 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1456 album.addImage(image);
1460 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1461 if (avatarId != null) {
1462 profile.setAvatar(getImage(avatarId, false));
1466 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1467 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1468 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1469 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1470 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1471 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1473 /* if we’re still here, Sone was loaded successfully. */
1474 synchronized (sone) {
1475 sone.setTime(soneTime);
1476 sone.setProfile(profile);
1477 sone.setPosts(posts);
1478 sone.setReplies(replies);
1479 sone.setLikePostIds(likedPostIds);
1480 sone.setLikeReplyIds(likedReplyIds);
1481 for (String friendId : friends) {
1482 followSone(sone, friendId);
1484 sone.setAlbums(topLevelAlbums);
1485 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1487 synchronized (knownSones) {
1488 for (String friend : friends) {
1489 knownSones.add(friend);
1492 synchronized (knownPosts) {
1493 for (Post post : posts) {
1494 knownPosts.add(post.getId());
1497 synchronized (knownReplies) {
1498 for (PostReply reply : replies) {
1499 knownReplies.add(reply.getId());
1505 * Creates a new post.
1508 * The Sone that creates the post
1510 * The text of the post
1511 * @return The created post
1513 public Post createPost(Sone sone, String text) {
1514 return createPost(sone, System.currentTimeMillis(), text);
1518 * Creates a new post.
1521 * The Sone that creates the post
1523 * The time of the post
1525 * The text of the post
1526 * @return The created post
1528 public Post createPost(Sone sone, long time, String text) {
1529 return createPost(sone, null, time, text);
1533 * Creates a new post.
1536 * The Sone that creates the post
1538 * The recipient Sone, or {@code null} if this post does not have
1541 * The text of the post
1542 * @return The created post
1544 public Post createPost(Sone sone, Sone recipient, String text) {
1545 return createPost(sone, recipient, System.currentTimeMillis(), text);
1549 * Creates a new post.
1552 * The Sone that creates the post
1554 * The recipient Sone, or {@code null} if this post does not have
1557 * The time of the post
1559 * The text of the post
1560 * @return The created post
1562 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1563 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1564 if (!isLocalSone(sone)) {
1565 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1568 final Post post = new PostImpl(sone, time, text);
1569 if (recipient != null) {
1570 post.setRecipient(recipient);
1572 synchronized (posts) {
1573 posts.put(post.getId(), post);
1575 coreListenerManager.fireNewPostFound(post);
1577 touchConfiguration();
1578 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1585 markPostKnown(post);
1587 }, "Mark " + post + " read.");
1592 * Deletes the given post.
1595 * The post to delete
1597 public void deletePost(Post post) {
1598 if (!isLocalSone(post.getSone())) {
1599 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1602 post.getSone().removePost(post);
1603 synchronized (posts) {
1604 posts.remove(post.getId());
1606 coreListenerManager.firePostRemoved(post);
1607 markPostKnown(post);
1608 touchConfiguration();
1612 * Marks the given post as known, if it is currently not a known post
1613 * (according to {@link Post#isKnown()}).
1616 * The post to mark as known
1618 public void markPostKnown(Post post) {
1619 post.setKnown(true);
1620 synchronized (knownPosts) {
1621 coreListenerManager.fireMarkPostKnown(post);
1622 if (knownPosts.add(post.getId())) {
1623 touchConfiguration();
1626 for (PostReply reply : getReplies(post)) {
1627 markReplyKnown(reply);
1632 * Bookmarks the given post.
1635 * The post to bookmark
1637 public void bookmark(Post post) {
1638 bookmarkPost(post.getId());
1642 * Bookmarks the post with the given ID.
1645 * The ID of the post to bookmark
1647 public void bookmarkPost(String id) {
1648 synchronized (bookmarkedPosts) {
1649 bookmarkedPosts.add(id);
1654 * Removes the given post from the bookmarks.
1657 * The post to unbookmark
1659 public void unbookmark(Post post) {
1660 unbookmarkPost(post.getId());
1664 * Removes the post with the given ID from the bookmarks.
1667 * The ID of the post to unbookmark
1669 public void unbookmarkPost(String id) {
1670 synchronized (bookmarkedPosts) {
1671 bookmarkedPosts.remove(id);
1676 * Creates a new reply.
1679 * The Sone that creates the reply
1681 * The post that this reply refers to
1683 * The text of the reply
1684 * @return The created reply
1686 public PostReply createReply(Sone sone, Post post, String text) {
1687 return createReply(sone, post, System.currentTimeMillis(), text);
1691 * Creates a new reply.
1694 * The Sone that creates the reply
1696 * The post that this reply refers to
1698 * The time of the reply
1700 * The text of the reply
1701 * @return The created reply
1703 public PostReply createReply(Sone sone, Post post, long time, String text) {
1704 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1705 if (!isLocalSone(sone)) {
1706 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1709 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1710 synchronized (replies) {
1711 replies.put(reply.getId(), reply);
1713 synchronized (knownReplies) {
1714 coreListenerManager.fireNewReplyFound(reply);
1716 sone.addReply(reply);
1717 touchConfiguration();
1718 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1725 markReplyKnown(reply);
1727 }, "Mark " + reply + " read.");
1732 * Deletes the given reply.
1735 * The reply to delete
1737 public void deleteReply(PostReply reply) {
1738 Sone sone = reply.getSone();
1739 if (!isLocalSone(sone)) {
1740 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1743 synchronized (replies) {
1744 replies.remove(reply.getId());
1746 synchronized (knownReplies) {
1747 markReplyKnown(reply);
1748 knownReplies.remove(reply.getId());
1750 sone.removeReply(reply);
1751 touchConfiguration();
1755 * Marks the given reply as known, if it is currently not a known reply
1756 * (according to {@link Reply#isKnown()}).
1759 * The reply to mark as known
1761 public void markReplyKnown(PostReply reply) {
1762 reply.setKnown(true);
1763 synchronized (knownReplies) {
1764 coreListenerManager.fireMarkReplyKnown(reply);
1765 if (knownReplies.add(reply.getId())) {
1766 touchConfiguration();
1772 * Creates a new top-level album for the given Sone.
1775 * The Sone to create the album for
1776 * @return The new album
1778 public Album createAlbum(Sone sone) {
1779 return createAlbum(sone, null);
1783 * Creates a new album for the given Sone.
1786 * The Sone to create the album for
1788 * The parent of the album (may be {@code null} to create a
1790 * @return The new album
1792 public Album createAlbum(Sone sone, Album parent) {
1793 Album album = new Album();
1794 synchronized (albums) {
1795 albums.put(album.getId(), album);
1797 album.setSone(sone);
1798 if (parent != null) {
1799 parent.addAlbum(album);
1801 sone.addAlbum(album);
1807 * Deletes the given album. The owner of the album has to be a local Sone,
1808 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1811 * The album to remove
1813 public void deleteAlbum(Album album) {
1814 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1815 if (!album.isEmpty()) {
1818 if (album.getParent() == null) {
1819 album.getSone().removeAlbum(album);
1821 album.getParent().removeAlbum(album);
1823 synchronized (albums) {
1824 albums.remove(album.getId());
1826 touchConfiguration();
1830 * Creates a new image.
1833 * The Sone creating the image
1835 * The album the image will be inserted into
1836 * @param temporaryImage
1837 * The temporary image to create the image from
1838 * @return The newly created image
1840 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1841 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();
1842 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1843 album.addImage(image);
1844 synchronized (images) {
1845 images.put(image.getId(), image);
1847 imageInserter.insertImage(temporaryImage, image);
1852 * Deletes the given image. This method will also delete a matching
1855 * @see #deleteTemporaryImage(TemporaryImage)
1857 * The image to delete
1859 public void deleteImage(Image image) {
1860 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1861 deleteTemporaryImage(image.getId());
1862 image.getAlbum().removeImage(image);
1863 synchronized (images) {
1864 images.remove(image.getId());
1866 touchConfiguration();
1870 * Creates a new temporary image.
1873 * The MIME type of the temporary image
1875 * The encoded data of the image
1876 * @return The temporary image
1878 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1879 TemporaryImage temporaryImage = new TemporaryImage();
1880 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1881 synchronized (temporaryImages) {
1882 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1884 return temporaryImage;
1888 * Deletes the given temporary image.
1890 * @param temporaryImage
1891 * The temporary image to delete
1893 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1894 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1895 deleteTemporaryImage(temporaryImage.getId());
1899 * Deletes the temporary image with the given ID.
1902 * The ID of the temporary image to delete
1904 public void deleteTemporaryImage(String imageId) {
1905 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1906 synchronized (temporaryImages) {
1907 temporaryImages.remove(imageId);
1909 Image image = getImage(imageId, false);
1910 if (image != null) {
1911 imageInserter.cancelImageInsert(image);
1916 * Notifies the core that the configuration, either of the core or of a
1917 * single local Sone, has changed, and that the configuration should be
1920 public void touchConfiguration() {
1921 lastConfigurationUpdate = System.currentTimeMillis();
1932 public void serviceStart() {
1933 loadConfiguration();
1934 updateChecker.addUpdateListener(this);
1935 updateChecker.start();
1936 webOfTrustUpdater.start();
1943 public void serviceRun() {
1944 long lastSaved = System.currentTimeMillis();
1945 while (!shouldStop()) {
1947 long now = System.currentTimeMillis();
1948 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1949 for (Sone localSone : getLocalSones()) {
1950 saveSone(localSone);
1952 saveConfiguration();
1962 public void serviceStop() {
1963 synchronized (localSones) {
1964 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1965 soneInserter.getValue().removeSoneInsertListener(this);
1966 soneInserter.getValue().stop();
1967 saveSone(soneInserter.getKey());
1970 saveConfiguration();
1971 webOfTrustUpdater.stop();
1972 updateChecker.stop();
1973 updateChecker.removeUpdateListener(this);
1974 soneDownloader.stop();
1982 * Saves the given Sone. This will persist all local settings for the given
1983 * Sone, such as the friends list and similar, private options.
1988 private synchronized void saveSone(Sone sone) {
1989 if (!isLocalSone(sone)) {
1990 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1993 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1994 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1998 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2000 /* save Sone into configuration. */
2001 String sonePrefix = "Sone/" + sone.getId();
2002 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2003 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2006 Profile profile = sone.getProfile();
2007 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2008 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2009 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2010 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2011 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2012 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2013 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2015 /* save profile fields. */
2016 int fieldCounter = 0;
2017 for (Field profileField : profile.getFields()) {
2018 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2019 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2020 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2022 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2025 int postCounter = 0;
2026 for (Post post : sone.getPosts()) {
2027 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2028 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2029 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2030 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2031 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2033 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2036 int replyCounter = 0;
2037 for (PostReply reply : sone.getReplies()) {
2038 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2039 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2040 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2041 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2042 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2044 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2046 /* save post likes. */
2047 int postLikeCounter = 0;
2048 for (String postId : sone.getLikedPostIds()) {
2049 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2051 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2053 /* save reply likes. */
2054 int replyLikeCounter = 0;
2055 for (String replyId : sone.getLikedReplyIds()) {
2056 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2058 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2061 int friendCounter = 0;
2062 for (String friendId : sone.getFriends()) {
2063 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2065 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2067 /* save albums. first, collect in a flat structure, top-level first. */
2068 List<Album> albums = sone.getAllAlbums();
2070 int albumCounter = 0;
2071 for (Album album : albums) {
2072 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2073 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2074 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2075 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2076 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2077 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2079 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2082 int imageCounter = 0;
2083 for (Album album : albums) {
2084 for (Image image : album.getImages()) {
2085 if (!image.isInserted()) {
2088 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2089 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2090 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2091 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2092 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2093 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2094 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2095 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2096 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2099 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2102 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2103 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2104 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2105 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2106 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2107 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2109 configuration.save();
2111 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2113 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2114 } catch (ConfigurationException ce1) {
2115 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2120 * Saves the current options.
2122 private void saveConfiguration() {
2123 synchronized (configuration) {
2124 if (storingConfiguration) {
2125 logger.log(Level.FINE, "Already storing configuration…");
2128 storingConfiguration = true;
2131 /* store the options first. */
2133 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2134 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2135 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2136 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2137 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2138 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2139 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2140 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2141 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2142 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2143 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2144 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2146 /* save known Sones. */
2147 int soneCounter = 0;
2148 synchronized (knownSones) {
2149 for (String knownSoneId : knownSones) {
2150 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2152 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2155 /* save Sone following times. */
2157 synchronized (soneFollowingTimes) {
2158 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2159 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2160 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2163 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2166 /* save known posts. */
2167 int postCounter = 0;
2168 synchronized (knownPosts) {
2169 for (String knownPostId : knownPosts) {
2170 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2172 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2175 /* save known replies. */
2176 int replyCounter = 0;
2177 synchronized (knownReplies) {
2178 for (String knownReplyId : knownReplies) {
2179 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2181 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2184 /* save bookmarked posts. */
2185 int bookmarkedPostCounter = 0;
2186 synchronized (bookmarkedPosts) {
2187 for (String bookmarkedPostId : bookmarkedPosts) {
2188 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2191 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2194 configuration.save();
2196 } catch (ConfigurationException ce1) {
2197 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2199 synchronized (configuration) {
2200 storingConfiguration = false;
2206 * Loads the configuration.
2208 @SuppressWarnings("unchecked")
2209 private void loadConfiguration() {
2210 /* create options. */
2211 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2214 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2215 SoneInserter.setInsertionDelay(newValue);
2219 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2220 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2221 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2222 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2223 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2224 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2225 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2226 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2227 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2230 @SuppressWarnings("synthetic-access")
2231 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2232 fcpInterface.setActive(newValue);
2235 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2238 @SuppressWarnings("synthetic-access")
2239 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2240 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2245 loadConfigurationValue("InsertionDelay");
2246 loadConfigurationValue("PostsPerPage");
2247 loadConfigurationValue("ImagesPerPage");
2248 loadConfigurationValue("CharactersPerPost");
2249 loadConfigurationValue("PostCutOffLength");
2250 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2251 loadConfigurationValue("PositiveTrust");
2252 loadConfigurationValue("NegativeTrust");
2253 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2254 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2255 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2257 /* load known Sones. */
2258 int soneCounter = 0;
2260 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2261 if (knownSoneId == null) {
2264 synchronized (knownSones) {
2265 knownSones.add(knownSoneId);
2269 /* load Sone following times. */
2272 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2273 if (soneId == null) {
2276 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2277 Sone followedSone = getSone(soneId);
2278 if (followedSone == null) {
2279 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2281 synchronized (soneFollowingTimes) {
2282 soneFollowingTimes.put(getSone(soneId), time);
2288 /* load known posts. */
2289 int postCounter = 0;
2291 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2292 if (knownPostId == null) {
2295 synchronized (knownPosts) {
2296 knownPosts.add(knownPostId);
2300 /* load known replies. */
2301 int replyCounter = 0;
2303 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2304 if (knownReplyId == null) {
2307 synchronized (knownReplies) {
2308 knownReplies.add(knownReplyId);
2312 /* load bookmarked posts. */
2313 int bookmarkedPostCounter = 0;
2315 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2316 if (bookmarkedPostId == null) {
2319 synchronized (bookmarkedPosts) {
2320 bookmarkedPosts.add(bookmarkedPostId);
2327 * Loads an {@link Integer} configuration value for the option with the
2328 * given name, logging validation failures.
2331 * The name of the option to load
2333 private void loadConfigurationValue(String optionName) {
2335 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2336 } catch (IllegalArgumentException iae1) {
2337 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2342 * Generate a Sone URI from the given URI and latest edition.
2345 * The URI to derive the Sone URI from
2346 * @return The derived URI
2348 private static FreenetURI getSoneUri(String uriString) {
2350 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2352 } catch (MalformedURLException mue1) {
2353 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2359 // INTERFACE IdentityListener
2366 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2367 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2368 if (ownIdentity.hasContext("Sone")) {
2369 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2370 addLocalSone(ownIdentity);
2378 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2379 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2380 trustedIdentities.remove(ownIdentity);
2387 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2388 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2389 trustedIdentities.get(ownIdentity).add(identity);
2390 addRemoteSone(identity);
2397 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2398 soneDownloaders.execute(new Runnable() {
2401 @SuppressWarnings("synthetic-access")
2403 Sone sone = getRemoteSone(identity.getId(), false);
2404 sone.setIdentity(identity);
2405 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2406 soneDownloader.addSone(sone);
2407 soneDownloader.fetchSone(sone);
2416 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2417 trustedIdentities.get(ownIdentity).remove(identity);
2418 boolean foundIdentity = false;
2419 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2420 if (trustedIdentity.getKey().equals(ownIdentity)) {
2423 if (trustedIdentity.getValue().contains(identity)) {
2424 foundIdentity = true;
2427 if (foundIdentity) {
2428 /* some local identity still trusts this identity, don’t remove. */
2431 Sone sone = getSone(identity.getId(), false);
2433 /* TODO - we don’t have the Sone anymore. should this happen? */
2436 synchronized (posts) {
2437 synchronized (knownPosts) {
2438 for (Post post : sone.getPosts()) {
2439 posts.remove(post.getId());
2440 coreListenerManager.firePostRemoved(post);
2444 synchronized (replies) {
2445 synchronized (knownReplies) {
2446 for (PostReply reply : sone.getReplies()) {
2447 replies.remove(reply.getId());
2448 coreListenerManager.fireReplyRemoved(reply);
2452 synchronized (remoteSones) {
2453 remoteSones.remove(identity.getId());
2455 coreListenerManager.fireSoneRemoved(sone);
2459 // INTERFACE UpdateListener
2466 public void updateFound(Version version, long releaseTime, long latestEdition) {
2467 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2471 // INTERFACE ImageInsertListener
2478 public void insertStarted(Sone sone) {
2479 coreListenerManager.fireSoneInserting(sone);
2486 public void insertFinished(Sone sone, long insertDuration) {
2487 coreListenerManager.fireSoneInserted(sone, insertDuration);
2494 public void insertAborted(Sone sone, Throwable cause) {
2495 coreListenerManager.fireSoneInsertAborted(sone, cause);
2499 // SONEINSERTLISTENER METHODS
2506 public void imageInsertStarted(Image image) {
2507 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2508 coreListenerManager.fireImageInsertStarted(image);
2515 public void imageInsertAborted(Image image) {
2516 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2517 coreListenerManager.fireImageInsertAborted(image);
2524 public void imageInsertFinished(Image image, FreenetURI key) {
2525 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2526 image.setKey(key.toString());
2527 deleteTemporaryImage(image.getId());
2528 touchConfiguration();
2529 coreListenerManager.fireImageInsertFinished(image);
2536 public void imageInsertFailed(Image image, Throwable cause) {
2537 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2538 coreListenerManager.fireImageInsertFailed(image, cause);
2542 * Convenience interface for external classes that want to access the core’s
2545 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2547 public static class Preferences {
2549 /** The wrapped options. */
2550 private final Options options;
2553 * Creates a new preferences object wrapped around the given options.
2556 * The options to wrap
2558 public Preferences(Options options) {
2559 this.options = options;
2563 * Returns the insertion delay.
2565 * @return The insertion delay
2567 public int getInsertionDelay() {
2568 return options.getIntegerOption("InsertionDelay").get();
2572 * Validates the given insertion delay.
2574 * @param insertionDelay
2575 * The insertion delay to validate
2576 * @return {@code true} if the given insertion delay was valid,
2577 * {@code false} otherwise
2579 public boolean validateInsertionDelay(Integer insertionDelay) {
2580 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2584 * Sets the insertion delay
2586 * @param insertionDelay
2587 * The new insertion delay, or {@code null} to restore it to
2589 * @return This preferences
2591 public Preferences setInsertionDelay(Integer insertionDelay) {
2592 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2597 * Returns the number of posts to show per page.
2599 * @return The number of posts to show per page
2601 public int getPostsPerPage() {
2602 return options.getIntegerOption("PostsPerPage").get();
2606 * Validates the number of posts per page.
2608 * @param postsPerPage
2609 * The number of posts per page
2610 * @return {@code true} if the number of posts per page was valid,
2611 * {@code false} otherwise
2613 public boolean validatePostsPerPage(Integer postsPerPage) {
2614 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2618 * Sets the number of posts to show per page.
2620 * @param postsPerPage
2621 * The number of posts to show per page
2622 * @return This preferences object
2624 public Preferences setPostsPerPage(Integer postsPerPage) {
2625 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2630 * Returns the number of images to show per page.
2632 * @return The number of images to show per page
2634 public int getImagesPerPage() {
2635 return options.getIntegerOption("ImagesPerPage").get();
2639 * Validates the number of images per page.
2641 * @param imagesPerPage
2642 * The number of images per page
2643 * @return {@code true} if the number of images per page was valid,
2644 * {@code false} otherwise
2646 public boolean validateImagesPerPage(Integer imagesPerPage) {
2647 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2651 * Sets the number of images per page.
2653 * @param imagesPerPage
2654 * The number of images per page
2655 * @return This preferences object
2657 public Preferences setImagesPerPage(Integer imagesPerPage) {
2658 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2663 * Returns the number of characters per post, or <code>-1</code> if the
2664 * posts should not be cut off.
2666 * @return The numbers of characters per post
2668 public int getCharactersPerPost() {
2669 return options.getIntegerOption("CharactersPerPost").get();
2673 * Validates the number of characters per post.
2675 * @param charactersPerPost
2676 * The number of characters per post
2677 * @return {@code true} if the number of characters per post was valid,
2678 * {@code false} otherwise
2680 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2681 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2685 * Sets the number of characters per post.
2687 * @param charactersPerPost
2688 * The number of characters per post, or <code>-1</code> to
2689 * not cut off the posts
2690 * @return This preferences objects
2692 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2693 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2698 * Returns the number of characters the shortened post should have.
2700 * @return The number of characters of the snippet
2702 public int getPostCutOffLength() {
2703 return options.getIntegerOption("PostCutOffLength").get();
2707 * Validates the number of characters after which to cut off the post.
2709 * @param postCutOffLength
2710 * The number of characters of the snippet
2711 * @return {@code true} if the number of characters of the snippet is
2712 * valid, {@code false} otherwise
2714 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2715 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2719 * Sets the number of characters the shortened post should have.
2721 * @param postCutOffLength
2722 * The number of characters of the snippet
2723 * @return This preferences
2725 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2726 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2731 * Returns whether Sone requires full access to be even visible.
2733 * @return {@code true} if Sone requires full access, {@code false}
2736 public boolean isRequireFullAccess() {
2737 return options.getBooleanOption("RequireFullAccess").get();
2741 * Sets whether Sone requires full access to be even visible.
2743 * @param requireFullAccess
2744 * {@code true} if Sone requires full access, {@code false}
2747 public void setRequireFullAccess(Boolean requireFullAccess) {
2748 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2752 * Returns the positive trust.
2754 * @return The positive trust
2756 public int getPositiveTrust() {
2757 return options.getIntegerOption("PositiveTrust").get();
2761 * Validates the positive trust.
2763 * @param positiveTrust
2764 * The positive trust to validate
2765 * @return {@code true} if the positive trust was valid, {@code false}
2768 public boolean validatePositiveTrust(Integer positiveTrust) {
2769 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2773 * Sets the positive trust.
2775 * @param positiveTrust
2776 * The new positive trust, or {@code null} to restore it to
2778 * @return This preferences
2780 public Preferences setPositiveTrust(Integer positiveTrust) {
2781 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2786 * Returns the negative trust.
2788 * @return The negative trust
2790 public int getNegativeTrust() {
2791 return options.getIntegerOption("NegativeTrust").get();
2795 * Validates the negative trust.
2797 * @param negativeTrust
2798 * The negative trust to validate
2799 * @return {@code true} if the negative trust was valid, {@code false}
2802 public boolean validateNegativeTrust(Integer negativeTrust) {
2803 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2807 * Sets the negative trust.
2809 * @param negativeTrust
2810 * The negative trust, or {@code null} to restore it to the
2812 * @return The preferences
2814 public Preferences setNegativeTrust(Integer negativeTrust) {
2815 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2820 * Returns the trust comment. This is the comment that is set in the web
2821 * of trust when a trust value is assigned to an identity.
2823 * @return The trust comment
2825 public String getTrustComment() {
2826 return options.getStringOption("TrustComment").get();
2830 * Sets the trust comment.
2832 * @param trustComment
2833 * The trust comment, or {@code null} to restore it to the
2835 * @return This preferences
2837 public Preferences setTrustComment(String trustComment) {
2838 options.getStringOption("TrustComment").set(trustComment);
2843 * Returns whether the {@link FcpInterface FCP interface} is currently
2846 * @see FcpInterface#setActive(boolean)
2847 * @return {@code true} if the FCP interface is currently active,
2848 * {@code false} otherwise
2850 public boolean isFcpInterfaceActive() {
2851 return options.getBooleanOption("ActivateFcpInterface").get();
2855 * Sets whether the {@link FcpInterface FCP interface} is currently
2858 * @see FcpInterface#setActive(boolean)
2859 * @param fcpInterfaceActive
2860 * {@code true} to activate the FCP interface, {@code false}
2861 * to deactivate the FCP interface
2862 * @return This preferences object
2864 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2865 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2870 * Returns the action level for which full access to the FCP interface
2873 * @return The action level for which full access to the FCP interface
2876 public FullAccessRequired getFcpFullAccessRequired() {
2877 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2881 * Sets the action level for which full access to the FCP interface is
2884 * @param fcpFullAccessRequired
2886 * @return This preferences
2888 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2889 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);