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.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.data.Album;
39 import net.pterodactylus.sone.data.Client;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Profile;
44 import net.pterodactylus.sone.data.Profile.Field;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.data.TemporaryImage;
50 import net.pterodactylus.sone.data.impl.PostImpl;
51 import net.pterodactylus.sone.database.Database;
52 import net.pterodactylus.sone.fcp.FcpInterface;
53 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
54 import net.pterodactylus.sone.freenet.wot.Identity;
55 import net.pterodactylus.sone.freenet.wot.IdentityListener;
56 import net.pterodactylus.sone.freenet.wot.IdentityManager;
57 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
58 import net.pterodactylus.sone.main.SonePlugin;
59 import net.pterodactylus.util.config.Configuration;
60 import net.pterodactylus.util.config.ConfigurationException;
61 import net.pterodactylus.util.logging.Logging;
62 import net.pterodactylus.util.number.Numbers;
63 import net.pterodactylus.util.service.AbstractService;
64 import net.pterodactylus.util.thread.Ticker;
65 import net.pterodactylus.util.validation.EqualityValidator;
66 import net.pterodactylus.util.validation.IntegerRangeValidator;
67 import net.pterodactylus.util.validation.OrValidator;
68 import net.pterodactylus.util.validation.Validation;
69 import net.pterodactylus.util.version.Version;
70 import freenet.keys.FreenetURI;
75 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
80 private static final Logger logger = Logging.getLogger(Core.class);
83 private final Options options = new Options();
85 /** The preferences. */
86 private final Preferences preferences = new Preferences(options);
88 /** The core listener manager. */
89 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
91 /** The configuration. */
92 private Configuration configuration;
94 /** Whether we’re currently saving the configuration. */
95 private boolean storingConfiguration = false;
98 private Database database;
100 /** The identity manager. */
101 private final IdentityManager identityManager;
103 /** Interface to freenet. */
104 private final FreenetInterface freenetInterface;
106 /** The Sone downloader. */
107 private final SoneDownloader soneDownloader;
109 /** The image inserter. */
110 private final ImageInserter imageInserter;
112 /** Sone downloader thread-pool. */
113 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
115 /** The update checker. */
116 private final UpdateChecker updateChecker;
118 /** The trust updater. */
119 private final WebOfTrustUpdater webOfTrustUpdater;
121 /** The FCP interface. */
122 private volatile FcpInterface fcpInterface;
124 /** The times Sones were followed. */
125 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
127 /** Locked local Sones. */
128 /* synchronize on itself. */
129 private final Set<Sone> lockedSones = new HashSet<Sone>();
131 /** Sone inserters. */
132 /* synchronize access on this on localSones. */
133 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
135 /** Sone rescuers. */
136 /* synchronize access on this on localSones. */
137 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
139 /** All known Sones. */
140 private final Set<String> knownSones = new HashSet<String>();
143 private final Map<String, Post> posts = new HashMap<String, Post>();
145 /** All known posts. */
146 private final Set<String> knownPosts = new HashSet<String>();
149 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
151 /** All known replies. */
152 private final Set<String> knownReplies = new HashSet<String>();
154 /** All bookmarked posts. */
155 /* synchronize access on itself. */
156 private final Set<String> bookmarkedPosts = new HashSet<String>();
158 /** Trusted identities, sorted by own identities. */
159 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
161 /** All known albums. */
162 private final Map<String, Album> albums = new HashMap<String, Album>();
164 /** All known images. */
165 private final Map<String, Image> images = new HashMap<String, Image>();
167 /** All temporary images. */
168 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
170 /** Ticker for threads that mark own elements as known. */
171 private final Ticker localElementTicker = new Ticker();
173 /** The time the configuration was last touched. */
174 private volatile long lastConfigurationUpdate;
177 * Creates a new core.
179 * @param configuration
180 * The configuration of the core
182 * The database to use
183 * @param freenetInterface
184 * The freenet interface
185 * @param identityManager
186 * The identity manager
187 * @param webOfTrustUpdater
188 * The WebOfTrust updater
190 public Core(Configuration configuration, Database database, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
192 this.configuration = configuration;
193 this.database = database;
194 this.freenetInterface = freenetInterface;
195 this.identityManager = identityManager;
196 this.soneDownloader = new SoneDownloader(this, freenetInterface);
197 this.imageInserter = new ImageInserter(this, freenetInterface);
198 this.updateChecker = new UpdateChecker(freenetInterface);
199 this.webOfTrustUpdater = webOfTrustUpdater;
203 // LISTENER MANAGEMENT
207 * Adds a new core listener.
209 * @param coreListener
210 * The listener to add
212 public void addCoreListener(CoreListener coreListener) {
213 coreListenerManager.addListener(coreListener);
217 * Removes a core listener.
219 * @param coreListener
220 * The listener to remove
222 public void removeCoreListener(CoreListener coreListener) {
223 coreListenerManager.removeListener(coreListener);
231 * Sets the configuration to use. This will automatically save the current
232 * configuration to the given configuration.
234 * @param configuration
235 * The new configuration to use
237 public void setConfiguration(Configuration configuration) {
238 this.configuration = configuration;
239 touchConfiguration();
243 * Returns the options used by the core.
245 * @return The options of the core
247 public Preferences getPreferences() {
252 * Returns the identity manager used by the core.
254 * @return The identity manager
256 public IdentityManager getIdentityManager() {
257 return identityManager;
261 * Returns the update checker.
263 * @return The update checker
265 public UpdateChecker getUpdateChecker() {
266 return updateChecker;
270 * Sets the FCP interface to use.
272 * @param fcpInterface
273 * The FCP interface to use
275 public void setFcpInterface(FcpInterface fcpInterface) {
276 this.fcpInterface = fcpInterface;
280 * Returns the Sone rescuer for the given local Sone.
283 * The local Sone to get the rescuer for
284 * @return The Sone rescuer for the given Sone
286 public SoneRescuer getSoneRescuer(Sone sone) {
287 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
288 synchronized (soneRescuers) {
289 SoneRescuer soneRescuer = soneRescuers.get(sone);
290 if (soneRescuer == null) {
291 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
292 soneRescuers.put(sone, soneRescuer);
300 * Returns whether the given Sone is currently locked.
304 * @return {@code true} if the Sone is locked, {@code false} if it is not
306 public boolean isLocked(Sone sone) {
307 synchronized (lockedSones) {
308 return lockedSones.contains(sone);
313 * Returns all Sones, remote and local.
317 public Collection<Sone> getSones() {
318 return database.getSones();
322 * Returns the Sone with the given ID, regardless whether it’s local or
326 * The ID of the Sone to get
327 * @return The Sone with the given ID, or {@code null} if there is no such
330 public Sone getSone(String id) {
331 return getSone(id, true);
335 * Returns the Sone with the given ID, regardless whether it’s local or
339 * The ID of the Sone to get
341 * {@code true} to create a new Sone if none exists,
342 * {@code false} to return {@code null} if a Sone with the given
344 * @return The Sone with the given ID, or {@code null} if there is no such
348 public Sone getSone(String id, boolean create) {
349 return database.getSone(id, create);
353 * Checks whether the core knows a Sone with the given ID.
357 * @return {@code true} if there is a Sone with the given ID, {@code false}
360 public boolean hasSone(String id) {
361 return database.getSone(id, false) != null;
365 * Returns all local Sones.
367 * @return All local Sones
369 public Collection<Sone> getLocalSones() {
370 return database.getLocalSones();
374 * Returns the local Sone with the given ID.
377 * The ID of the Sone to get
378 * @return The Sone with the given ID
380 public Sone getLocalSone(String id) {
381 return getLocalSone(id, true);
385 * Returns the local Sone with the given ID, optionally creating a new Sone.
390 * {@code true} to create a new Sone if none exists,
391 * {@code false} to return null if none exists
392 * @return The Sone with the given ID, or {@code null}
394 public Sone getLocalSone(String id, boolean create) {
395 return database.getLocalSone(id, create);
399 * Returns all remote Sones.
401 * @return All remote Sones
403 public Collection<Sone> getRemoteSones() {
404 return database.getRemoteSones();
408 * Returns the remote Sone with the given ID.
411 * The ID of the remote Sone to get
413 * {@code true} to always create a Sone, {@code false} to return
414 * {@code null} if no Sone with the given ID exists
415 * @return The Sone with the given ID
417 public Sone getRemoteSone(String id, boolean create) {
418 return database.getRemoteSone(id, create);
422 * Returns whether the given Sone has been modified.
425 * The Sone to check for modifications
426 * @return {@code true} if a modification has been detected in the Sone,
427 * {@code false} otherwise
429 public boolean isModifiedSone(Sone sone) {
430 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
434 * Returns the time when the given was first followed by any local Sone.
437 * The Sone to get the time for
438 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
439 * been followed, or {@link Long#MAX_VALUE}
441 public long getSoneFollowingTime(Sone sone) {
442 synchronized (soneFollowingTimes) {
443 if (soneFollowingTimes.containsKey(sone)) {
444 return soneFollowingTimes.get(sone);
446 return Long.MAX_VALUE;
451 * Returns whether the target Sone is trusted by the origin Sone.
457 * @return {@code true} if the target Sone is trusted by the origin Sone
459 public boolean isSoneTrusted(Sone origin, Sone target) {
460 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
461 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
465 * Returns the post with the given ID, optionally creating a new post.
468 * The ID of the post to get
470 * {@code true} it create a new post if no post with the given ID
471 * exists, {@code false} to return {@code null}
472 * @return The post, or {@code null} if there is no such post
475 public Post getPost(String postId, boolean create) {
476 synchronized (posts) {
477 Post post = posts.get(postId);
478 if ((post == null) && create) {
479 post = new PostImpl(postId);
480 posts.put(postId, post);
487 * Returns all posts that have the given Sone as recipient.
489 * @see Post#getRecipient()
491 * The recipient of the posts
492 * @return All posts that have the given Sone as recipient
494 public Set<Post> getDirectedPosts(Sone recipient) {
495 Validation.begin().isNotNull("Recipient", recipient).check();
496 Set<Post> directedPosts = new HashSet<Post>();
497 synchronized (posts) {
498 for (Post post : posts.values()) {
499 if (recipient.equals(post.getRecipient())) {
500 directedPosts.add(post);
504 return directedPosts;
508 * Returns the reply with the given ID. If there is no reply with the given
509 * ID yet, a new one is created.
512 * The ID of the reply to get
515 public PostReply getReply(String replyId) {
516 return getReply(replyId, true);
520 * Returns the reply with the given ID. If there is no reply with the given
521 * ID yet, a new one is created, unless {@code create} is false in which
522 * case {@code null} is returned.
525 * The ID of the reply to get
527 * {@code true} to always return a {@link Reply}, {@code false}
528 * to return {@code null} if no reply can be found
529 * @return The reply, or {@code null} if there is no such reply
531 public PostReply getReply(String replyId, boolean create) {
532 synchronized (replies) {
533 PostReply reply = replies.get(replyId);
534 if (create && (reply == null)) {
535 reply = new PostReply(replyId);
536 replies.put(replyId, reply);
543 * Returns all replies for the given post, order ascending by time.
546 * The post to get all replies for
547 * @return All replies for the given post
549 public List<PostReply> getReplies(Post post) {
550 Collection<Sone> sones = getSones();
551 List<PostReply> replies = new ArrayList<PostReply>();
552 for (Sone sone : sones) {
553 for (PostReply reply : sone.getReplies()) {
554 if (reply.getPost().equals(post)) {
559 Collections.sort(replies, Reply.TIME_COMPARATOR);
564 * Returns all Sones that have liked the given post.
567 * The post to get the liking Sones for
568 * @return The Sones that like the given post
570 public Set<Sone> getLikes(Post post) {
571 Set<Sone> sones = new HashSet<Sone>();
572 for (Sone sone : getSones()) {
573 if (sone.getLikedPostIds().contains(post.getId())) {
581 * Returns all Sones that have liked the given reply.
584 * The reply to get the liking Sones for
585 * @return The Sones that like the given reply
587 public Set<Sone> getLikes(PostReply reply) {
588 Set<Sone> sones = new HashSet<Sone>();
589 for (Sone sone : getSones()) {
590 if (sone.getLikedReplyIds().contains(reply.getId())) {
598 * Returns whether the given post is bookmarked.
602 * @return {@code true} if the given post is bookmarked, {@code false}
605 public boolean isBookmarked(Post post) {
606 return isPostBookmarked(post.getId());
610 * Returns whether the post with the given ID is bookmarked.
613 * The ID of the post to check
614 * @return {@code true} if the post with the given ID is bookmarked,
615 * {@code false} otherwise
617 public boolean isPostBookmarked(String id) {
618 synchronized (bookmarkedPosts) {
619 return bookmarkedPosts.contains(id);
624 * Returns all currently known bookmarked posts.
626 * @return All bookmarked posts
628 public Set<Post> getBookmarkedPosts() {
629 Set<Post> posts = new HashSet<Post>();
630 synchronized (bookmarkedPosts) {
631 for (String bookmarkedPostId : bookmarkedPosts) {
632 Post post = getPost(bookmarkedPostId, false);
642 * Returns the album with the given ID, creating a new album if no album
643 * with the given ID can be found.
646 * The ID of the album
647 * @return The album with the given ID
649 public Album getAlbum(String albumId) {
650 return getAlbum(albumId, true);
654 * Returns the album with the given ID, optionally creating a new album if
655 * an album with the given ID can not be found.
658 * The ID of the album
660 * {@code true} to create a new album if none exists for the
662 * @return The album with the given ID, or {@code null} if no album with the
663 * given ID exists and {@code create} is {@code false}
665 public Album getAlbum(String albumId, boolean create) {
666 synchronized (albums) {
667 Album album = albums.get(albumId);
668 if (create && (album == null)) {
669 album = new Album(albumId);
670 albums.put(albumId, album);
677 * Returns the image with the given ID, creating it if necessary.
680 * The ID of the image
681 * @return The image with the given ID
683 public Image getImage(String imageId) {
684 return getImage(imageId, true);
688 * Returns the image with the given ID, optionally creating it if it does
692 * The ID of the image
694 * {@code true} to create an image if none exists with the given
696 * @return The image with the given ID, or {@code null} if none exists and
699 public Image getImage(String imageId, boolean create) {
700 synchronized (images) {
701 Image image = images.get(imageId);
702 if (create && (image == null)) {
703 image = new Image(imageId);
704 images.put(imageId, image);
711 * Returns the temporary image with the given ID.
714 * The ID of the temporary image
715 * @return The temporary image, or {@code null} if there is no temporary
716 * image with the given ID
718 public TemporaryImage getTemporaryImage(String imageId) {
719 synchronized (temporaryImages) {
720 return temporaryImages.get(imageId);
729 * Locks the given Sone. A locked Sone will not be inserted by
730 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
736 public void lockSone(Sone sone) {
737 synchronized (lockedSones) {
738 if (lockedSones.add(sone)) {
739 coreListenerManager.fireSoneLocked(sone);
745 * Unlocks the given Sone.
747 * @see #lockSone(Sone)
751 public void unlockSone(Sone sone) {
752 synchronized (lockedSones) {
753 if (lockedSones.remove(sone)) {
754 coreListenerManager.fireSoneUnlocked(sone);
760 * Adds a local Sone from the given own identity.
763 * The own identity to create a Sone from
764 * @return The added (or already existing) Sone
766 public Sone addLocalSone(OwnIdentity ownIdentity) {
767 if (ownIdentity == null) {
768 logger.log(Level.WARNING, "Given OwnIdentity is null!");
773 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
774 } catch (MalformedURLException mue1) {
775 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
778 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
779 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
781 /* TODO - load posts ’n stuff */
782 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
783 soneInserter.addSoneInsertListener(this);
784 soneInserters.put(sone, soneInserter);
785 sone.setStatus(SoneStatus.idle);
787 soneInserter.start();
788 database.saveSone(sone);
793 * Creates a new Sone for the given own identity.
796 * The own identity to create a Sone for
797 * @return The created Sone
799 public Sone createSone(OwnIdentity ownIdentity) {
800 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
801 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
804 Sone sone = addLocalSone(ownIdentity);
805 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
806 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
807 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
808 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
809 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
810 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
812 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
813 touchConfiguration();
818 * Adds the Sone of the given identity.
821 * The identity whose Sone to add
822 * @return The added or already existing Sone
824 public Sone addRemoteSone(Identity identity) {
825 if (identity == null) {
826 logger.log(Level.WARNING, "Given Identity is null!");
829 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
830 boolean newSone = sone.getRequestUri() == null;
831 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
832 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
834 synchronized (knownSones) {
835 newSone = !knownSones.contains(sone.getId());
837 sone.setKnown(!newSone);
839 coreListenerManager.fireNewSoneFound(sone);
840 for (Sone localSone : getLocalSones()) {
841 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
842 followSone(localSone, sone);
847 soneDownloader.addSone(sone);
848 soneDownloaders.execute(new Runnable() {
851 @SuppressWarnings("synthetic-access")
853 soneDownloader.fetchSone(sone, sone.getRequestUri());
857 database.saveSone(sone);
862 * Lets the given local Sone follow the Sone with the given ID.
865 * The local Sone that should follow another Sone
867 * The ID of the Sone to follow
869 public void followSone(Sone sone, String soneId) {
870 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
871 Sone followedSone = getSone(soneId, true);
872 if (followedSone == null) {
873 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
876 followSone(sone, getSone(soneId));
880 * Lets the given local Sone follow the other given Sone. If the given Sone
881 * was not followed by any local Sone before, this will mark all elements of
882 * the followed Sone as read that have been created before the current
886 * The local Sone that should follow the other Sone
887 * @param followedSone
888 * The Sone that should be followed
890 public void followSone(Sone sone, Sone followedSone) {
891 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
892 sone.addFriend(followedSone.getId());
893 synchronized (soneFollowingTimes) {
894 if (!soneFollowingTimes.containsKey(followedSone)) {
895 long now = System.currentTimeMillis();
896 soneFollowingTimes.put(followedSone, now);
897 for (Post post : followedSone.getPosts()) {
898 if (post.getTime() < now) {
902 for (PostReply reply : followedSone.getReplies()) {
903 if (reply.getTime() < now) {
904 markReplyKnown(reply);
909 touchConfiguration();
913 * Lets the given local Sone unfollow the Sone with the given ID.
916 * The local Sone that should unfollow another Sone
918 * The ID of the Sone being unfollowed
920 public void unfollowSone(Sone sone, String soneId) {
921 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
922 unfollowSone(sone, getSone(soneId, false));
926 * Lets the given local Sone unfollow the other given Sone. If the given
927 * local Sone is the last local Sone that followed the given Sone, its
928 * following time will be removed.
931 * The local Sone that should unfollow another Sone
932 * @param unfollowedSone
933 * The Sone being unfollowed
935 public void unfollowSone(Sone sone, Sone unfollowedSone) {
936 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
937 sone.removeFriend(unfollowedSone.getId());
938 boolean unfollowedSoneStillFollowed = false;
939 for (Sone localSone : getLocalSones()) {
940 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
942 if (!unfollowedSoneStillFollowed) {
943 synchronized (soneFollowingTimes) {
944 soneFollowingTimes.remove(unfollowedSone);
947 touchConfiguration();
951 * Sets the trust value of the given origin Sone for
959 * The trust value (from {@code -100} to {@code 100})
961 public void setTrust(Sone origin, Sone target, int trustValue) {
962 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();
963 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
967 * Removes any trust assignment for the given target Sone.
974 public void removeTrust(Sone origin, Sone target) {
975 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
976 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
980 * Assigns the configured positive trust value for the given target.
987 public void trustSone(Sone origin, Sone target) {
988 setTrust(origin, target, preferences.getPositiveTrust());
992 * Assigns the configured negative trust value for the given target.
999 public void distrustSone(Sone origin, Sone target) {
1000 setTrust(origin, target, preferences.getNegativeTrust());
1004 * Removes the trust assignment for the given target.
1011 public void untrustSone(Sone origin, Sone target) {
1012 removeTrust(origin, target);
1016 * Updates the stored Sone with the given Sone.
1021 public void updateSone(Sone sone) {
1022 updateSone(sone, false);
1026 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1027 * {@code true}, an older Sone than the current Sone can be given to restore
1031 * The Sone to update
1032 * @param soneRescueMode
1033 * {@code true} if the stored Sone should be updated regardless
1034 * of the age of the given Sone
1036 public void updateSone(Sone sone, boolean soneRescueMode) {
1037 if (hasSone(sone.getId())) {
1038 Sone storedSone = getSone(sone.getId());
1039 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1040 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1043 synchronized (posts) {
1044 if (!soneRescueMode) {
1045 for (Post post : storedSone.getPosts()) {
1046 posts.remove(post.getId());
1047 if (!sone.getPosts().contains(post)) {
1048 coreListenerManager.firePostRemoved(post);
1052 List<Post> storedPosts = storedSone.getPosts();
1053 synchronized (knownPosts) {
1054 for (Post post : sone.getPosts()) {
1055 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1056 if (!storedPosts.contains(post)) {
1057 if (post.getTime() < getSoneFollowingTime(sone)) {
1058 knownPosts.add(post.getId());
1059 } else if (!knownPosts.contains(post.getId())) {
1060 sone.setKnown(false);
1061 coreListenerManager.fireNewPostFound(post);
1064 posts.put(post.getId(), post);
1068 synchronized (replies) {
1069 if (!soneRescueMode) {
1070 for (PostReply reply : storedSone.getReplies()) {
1071 replies.remove(reply.getId());
1072 if (!sone.getReplies().contains(reply)) {
1073 coreListenerManager.fireReplyRemoved(reply);
1077 Set<PostReply> storedReplies = storedSone.getReplies();
1078 synchronized (knownReplies) {
1079 for (PostReply reply : sone.getReplies()) {
1080 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1081 if (!storedReplies.contains(reply)) {
1082 if (reply.getTime() < getSoneFollowingTime(sone)) {
1083 knownReplies.add(reply.getId());
1084 } else if (!knownReplies.contains(reply.getId())) {
1085 reply.setKnown(false);
1086 coreListenerManager.fireNewReplyFound(reply);
1089 replies.put(reply.getId(), reply);
1093 synchronized (albums) {
1094 synchronized (images) {
1095 for (Album album : storedSone.getAlbums()) {
1096 albums.remove(album.getId());
1097 for (Image image : album.getImages()) {
1098 images.remove(image.getId());
1101 for (Album album : sone.getAlbums()) {
1102 albums.put(album.getId(), album);
1103 for (Image image : album.getImages()) {
1104 images.put(image.getId(), image);
1109 synchronized (storedSone) {
1110 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1111 storedSone.setTime(sone.getTime());
1113 storedSone.setClient(sone.getClient());
1114 storedSone.setProfile(sone.getProfile());
1115 if (soneRescueMode) {
1116 for (Post post : sone.getPosts()) {
1117 storedSone.addPost(post);
1119 for (PostReply reply : sone.getReplies()) {
1120 storedSone.addReply(reply);
1122 for (String likedPostId : sone.getLikedPostIds()) {
1123 storedSone.addLikedPostId(likedPostId);
1125 for (String likedReplyId : sone.getLikedReplyIds()) {
1126 storedSone.addLikedReplyId(likedReplyId);
1128 for (Album album : sone.getAlbums()) {
1129 storedSone.addAlbum(album);
1132 storedSone.setPosts(sone.getPosts());
1133 storedSone.setReplies(sone.getReplies());
1134 storedSone.setLikePostIds(sone.getLikedPostIds());
1135 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1136 storedSone.setAlbums(sone.getAlbums());
1138 storedSone.setLatestEdition(sone.getLatestEdition());
1144 * Deletes the given Sone. This will remove the Sone from the
1145 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1146 * and remove the context from its identity.
1149 * The Sone to delete
1151 public void deleteSone(Sone sone) {
1152 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1153 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1156 if (!sone.isLocal()) {
1157 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1160 database.removeSone(sone.getId());
1161 SoneInserter soneInserter = soneInserters.remove(sone);
1162 soneInserter.removeSoneInsertListener(this);
1163 soneInserter.stop();
1164 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1165 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1167 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1168 } catch (ConfigurationException ce1) {
1169 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1174 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1175 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1178 * The Sone to mark as known
1180 public void markSoneKnown(Sone sone) {
1181 if (!sone.isKnown()) {
1182 sone.setKnown(true);
1183 synchronized (knownSones) {
1184 knownSones.add(sone.getId());
1186 coreListenerManager.fireMarkSoneKnown(sone);
1187 touchConfiguration();
1192 * Loads and updates the given Sone from the configuration. If any error is
1193 * encountered, loading is aborted and the given Sone is not changed.
1196 * The Sone to load and update
1198 public void loadSone(Sone sone) {
1199 if (!sone.isLocal()) {
1200 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1204 /* initialize options. */
1205 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1206 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1207 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1208 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1209 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1210 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1213 String sonePrefix = "Sone/" + sone.getId();
1214 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1215 if (soneTime == null) {
1216 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1219 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1222 Profile profile = new Profile(sone);
1223 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1224 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1225 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1226 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1227 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1228 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1230 /* load profile fields. */
1232 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1233 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1234 if (fieldName == null) {
1237 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1238 profile.addField(fieldName).setValue(fieldValue);
1242 Set<Post> posts = new HashSet<Post>();
1244 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1245 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1246 if (postId == null) {
1249 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1250 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1251 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1252 if ((postTime == 0) || (postText == null)) {
1253 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1256 Post post = getPost(postId, true).setSone(sone).setTime(postTime).setText(postText);
1257 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1258 post.setRecipient(getSone(postRecipientId));
1264 Set<PostReply> replies = new HashSet<PostReply>();
1266 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1267 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1268 if (replyId == null) {
1271 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1272 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1273 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1274 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1275 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1278 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId, true)).setTime(replyTime).setText(replyText));
1281 /* load post likes. */
1282 Set<String> likedPostIds = new HashSet<String>();
1284 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1285 if (likedPostId == null) {
1288 likedPostIds.add(likedPostId);
1291 /* load reply likes. */
1292 Set<String> likedReplyIds = new HashSet<String>();
1294 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1295 if (likedReplyId == null) {
1298 likedReplyIds.add(likedReplyId);
1302 Set<String> friends = new HashSet<String>();
1304 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1305 if (friendId == null) {
1308 friends.add(friendId);
1312 List<Album> topLevelAlbums = new ArrayList<Album>();
1313 int albumCounter = 0;
1315 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1316 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1317 if (albumId == null) {
1320 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1321 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1322 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1323 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1324 if ((albumTitle == null) || (albumDescription == null)) {
1325 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1328 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1329 if (albumParentId != null) {
1330 Album parentAlbum = getAlbum(albumParentId, false);
1331 if (parentAlbum == null) {
1332 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1335 parentAlbum.addAlbum(album);
1337 if (!topLevelAlbums.contains(album)) {
1338 topLevelAlbums.add(album);
1344 int imageCounter = 0;
1346 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1347 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1348 if (imageId == null) {
1351 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1352 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1353 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1354 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1355 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1356 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1357 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1358 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1359 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1362 Album album = getAlbum(albumId, false);
1363 if (album == null) {
1364 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1367 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1368 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1369 album.addImage(image);
1373 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1374 if (avatarId != null) {
1375 profile.setAvatar(getImage(avatarId, false));
1379 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1380 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1381 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1382 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1383 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1384 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1386 /* if we’re still here, Sone was loaded successfully. */
1387 synchronized (sone) {
1388 sone.setTime(soneTime);
1389 sone.setProfile(profile);
1390 sone.setPosts(posts);
1391 sone.setReplies(replies);
1392 sone.setLikePostIds(likedPostIds);
1393 sone.setLikeReplyIds(likedReplyIds);
1394 for (String friendId : friends) {
1395 followSone(sone, friendId);
1397 sone.setAlbums(topLevelAlbums);
1398 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1400 synchronized (knownSones) {
1401 for (String friend : friends) {
1402 knownSones.add(friend);
1405 synchronized (knownPosts) {
1406 for (Post post : posts) {
1407 knownPosts.add(post.getId());
1410 synchronized (knownReplies) {
1411 for (PostReply reply : replies) {
1412 knownReplies.add(reply.getId());
1418 * Creates a new post.
1421 * The Sone that creates the post
1423 * The recipient Sone, or {@code null} if this post does not have
1426 * The time of the post
1428 * The text of the post
1429 * @return The created post
1431 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1432 if (!sone.isLocal()) {
1433 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1436 final Post post = new PostImpl(sone, time, text);
1437 if (recipient != null) {
1438 post.setRecipient(recipient);
1440 synchronized (posts) {
1441 posts.put(post.getId(), post);
1443 coreListenerManager.fireNewPostFound(post);
1445 touchConfiguration();
1446 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1453 markPostKnown(post);
1455 }, "Mark " + post + " read.");
1460 * Deletes the given post.
1463 * The post to delete
1465 public void deletePost(Post post) {
1466 if (!post.getSone().isLocal()) {
1467 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1470 post.getSone().removePost(post);
1471 synchronized (posts) {
1472 posts.remove(post.getId());
1474 coreListenerManager.firePostRemoved(post);
1475 markPostKnown(post);
1476 touchConfiguration();
1480 * Marks the given post as known, if it is currently not a known post
1481 * (according to {@link Post#isKnown()}).
1484 * The post to mark as known
1486 public void markPostKnown(Post post) {
1487 post.setKnown(true);
1488 synchronized (knownPosts) {
1489 coreListenerManager.fireMarkPostKnown(post);
1490 if (knownPosts.add(post.getId())) {
1491 touchConfiguration();
1494 for (PostReply reply : getReplies(post)) {
1495 markReplyKnown(reply);
1500 * Bookmarks the given post.
1503 * The post to bookmark
1505 public void bookmark(Post post) {
1506 bookmarkPost(post.getId());
1510 * Bookmarks the post with the given ID.
1513 * The ID of the post to bookmark
1515 public void bookmarkPost(String id) {
1516 synchronized (bookmarkedPosts) {
1517 bookmarkedPosts.add(id);
1522 * Removes the given post from the bookmarks.
1525 * The post to unbookmark
1527 public void unbookmark(Post post) {
1528 unbookmarkPost(post.getId());
1532 * Removes the post with the given ID from the bookmarks.
1535 * The ID of the post to unbookmark
1537 public void unbookmarkPost(String id) {
1538 synchronized (bookmarkedPosts) {
1539 bookmarkedPosts.remove(id);
1544 * Creates a new reply.
1547 * The Sone that creates the reply
1549 * The post that this reply refers to
1551 * The text of the reply
1552 * @return The created reply
1554 public PostReply createReply(Sone sone, Post post, String text) {
1555 return createReply(sone, post, System.currentTimeMillis(), text);
1559 * Creates a new reply.
1562 * The Sone that creates the reply
1564 * The post that this reply refers to
1566 * The time of the reply
1568 * The text of the reply
1569 * @return The created reply
1571 public PostReply createReply(Sone sone, Post post, long time, String text) {
1572 if (!sone.isLocal()) {
1573 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1576 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1577 synchronized (replies) {
1578 replies.put(reply.getId(), reply);
1580 synchronized (knownReplies) {
1581 coreListenerManager.fireNewReplyFound(reply);
1583 sone.addReply(reply);
1584 touchConfiguration();
1585 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1592 markReplyKnown(reply);
1594 }, "Mark " + reply + " read.");
1599 * Deletes the given reply.
1602 * The reply to delete
1604 public void deleteReply(PostReply reply) {
1605 Sone sone = reply.getSone();
1606 if (!sone.isLocal()) {
1607 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1610 synchronized (replies) {
1611 replies.remove(reply.getId());
1613 synchronized (knownReplies) {
1614 markReplyKnown(reply);
1615 knownReplies.remove(reply.getId());
1617 sone.removeReply(reply);
1618 touchConfiguration();
1622 * Marks the given reply as known, if it is currently not a known reply
1623 * (according to {@link Reply#isKnown()}).
1626 * The reply to mark as known
1628 public void markReplyKnown(PostReply reply) {
1629 reply.setKnown(true);
1630 synchronized (knownReplies) {
1631 coreListenerManager.fireMarkReplyKnown(reply);
1632 if (knownReplies.add(reply.getId())) {
1633 touchConfiguration();
1639 * Creates a new top-level album for the given Sone.
1642 * The Sone to create the album for
1643 * @return The new album
1645 public Album createAlbum(Sone sone) {
1646 return createAlbum(sone, null);
1650 * Creates a new album for the given Sone.
1653 * The Sone to create the album for
1655 * The parent of the album (may be {@code null} to create a
1657 * @return The new album
1659 public Album createAlbum(Sone sone, Album parent) {
1660 Album album = new Album();
1661 synchronized (albums) {
1662 albums.put(album.getId(), album);
1664 album.setSone(sone);
1665 if (parent != null) {
1666 parent.addAlbum(album);
1668 sone.addAlbum(album);
1674 * Deletes the given album. The owner of the album has to be a local Sone,
1675 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1678 * The album to remove
1680 public void deleteAlbum(Album album) {
1681 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1682 if (!album.isEmpty()) {
1685 if (album.getParent() == null) {
1686 album.getSone().removeAlbum(album);
1688 album.getParent().removeAlbum(album);
1690 synchronized (albums) {
1691 albums.remove(album.getId());
1693 touchConfiguration();
1697 * Creates a new image.
1700 * The Sone creating the image
1702 * The album the image will be inserted into
1703 * @param temporaryImage
1704 * The temporary image to create the image from
1705 * @return The newly created image
1707 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1708 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1709 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1710 album.addImage(image);
1711 synchronized (images) {
1712 images.put(image.getId(), image);
1714 imageInserter.insertImage(temporaryImage, image);
1719 * Deletes the given image. This method will also delete a matching
1722 * @see #deleteTemporaryImage(TemporaryImage)
1724 * The image to delete
1726 public void deleteImage(Image image) {
1727 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1728 deleteTemporaryImage(image.getId());
1729 image.getAlbum().removeImage(image);
1730 synchronized (images) {
1731 images.remove(image.getId());
1733 touchConfiguration();
1737 * Creates a new temporary image.
1740 * The MIME type of the temporary image
1742 * The encoded data of the image
1743 * @return The temporary image
1745 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1746 TemporaryImage temporaryImage = new TemporaryImage();
1747 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1748 synchronized (temporaryImages) {
1749 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1751 return temporaryImage;
1755 * Deletes the given temporary image.
1757 * @param temporaryImage
1758 * The temporary image to delete
1760 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1761 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1762 deleteTemporaryImage(temporaryImage.getId());
1766 * Deletes the temporary image with the given ID.
1769 * The ID of the temporary image to delete
1771 public void deleteTemporaryImage(String imageId) {
1772 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1773 synchronized (temporaryImages) {
1774 temporaryImages.remove(imageId);
1776 Image image = getImage(imageId, false);
1777 if (image != null) {
1778 imageInserter.cancelImageInsert(image);
1783 * Notifies the core that the configuration, either of the core or of a
1784 * single local Sone, has changed, and that the configuration should be
1787 public void touchConfiguration() {
1788 lastConfigurationUpdate = System.currentTimeMillis();
1799 public void serviceStart() {
1800 loadConfiguration();
1801 updateChecker.addUpdateListener(this);
1802 updateChecker.start();
1803 webOfTrustUpdater.start();
1810 public void serviceRun() {
1811 long lastSaved = System.currentTimeMillis();
1812 while (!shouldStop()) {
1814 long now = System.currentTimeMillis();
1815 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1816 for (Sone localSone : getLocalSones()) {
1817 saveSone(localSone);
1819 saveConfiguration();
1829 public void serviceStop() {
1830 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1831 soneInserter.getValue().removeSoneInsertListener(this);
1832 soneInserter.getValue().stop();
1833 saveSone(soneInserter.getKey());
1835 saveConfiguration();
1836 webOfTrustUpdater.stop();
1837 updateChecker.stop();
1838 updateChecker.removeUpdateListener(this);
1839 soneDownloader.stop();
1847 * Saves the given Sone. This will persist all local settings for the given
1848 * Sone, such as the friends list and similar, private options.
1853 private synchronized void saveSone(Sone sone) {
1854 if (!sone.isLocal()) {
1855 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1858 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1859 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1863 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1865 /* save Sone into configuration. */
1866 String sonePrefix = "Sone/" + sone.getId();
1867 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1868 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1871 Profile profile = sone.getProfile();
1872 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1873 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1874 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1875 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1876 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1877 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1878 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1880 /* save profile fields. */
1881 int fieldCounter = 0;
1882 for (Field profileField : profile.getFields()) {
1883 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1884 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1885 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1887 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1890 int postCounter = 0;
1891 for (Post post : sone.getPosts()) {
1892 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1893 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1894 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1895 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1896 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1898 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1901 int replyCounter = 0;
1902 for (PostReply reply : sone.getReplies()) {
1903 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1904 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1905 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1906 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1907 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1909 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1911 /* save post likes. */
1912 int postLikeCounter = 0;
1913 for (String postId : sone.getLikedPostIds()) {
1914 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1916 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1918 /* save reply likes. */
1919 int replyLikeCounter = 0;
1920 for (String replyId : sone.getLikedReplyIds()) {
1921 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1923 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1926 int friendCounter = 0;
1927 for (String friendId : sone.getFriends()) {
1928 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1930 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1932 /* save albums. first, collect in a flat structure, top-level first. */
1933 List<Album> albums = sone.getAllAlbums();
1935 int albumCounter = 0;
1936 for (Album album : albums) {
1937 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1938 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1939 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1940 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1941 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1942 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1944 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1947 int imageCounter = 0;
1948 for (Album album : albums) {
1949 for (Image image : album.getImages()) {
1950 if (!image.isInserted()) {
1953 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1954 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1955 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1956 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1957 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1958 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1959 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1960 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1961 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1964 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1967 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1968 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1969 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1970 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1971 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1972 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1974 configuration.save();
1976 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1978 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1979 } catch (ConfigurationException ce1) {
1980 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1985 * Saves the current options.
1987 private void saveConfiguration() {
1988 synchronized (configuration) {
1989 if (storingConfiguration) {
1990 logger.log(Level.FINE, "Already storing configuration…");
1993 storingConfiguration = true;
1996 /* store the options first. */
1998 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1999 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2000 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2001 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2002 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2003 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2004 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2005 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2006 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2007 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2008 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2009 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2011 /* save known Sones. */
2012 int soneCounter = 0;
2013 synchronized (knownSones) {
2014 for (String knownSoneId : knownSones) {
2015 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2017 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2020 /* save Sone following times. */
2022 synchronized (soneFollowingTimes) {
2023 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2024 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2025 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2028 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2031 /* save known posts. */
2032 int postCounter = 0;
2033 synchronized (knownPosts) {
2034 for (String knownPostId : knownPosts) {
2035 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2037 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2040 /* save known replies. */
2041 int replyCounter = 0;
2042 synchronized (knownReplies) {
2043 for (String knownReplyId : knownReplies) {
2044 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2046 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2049 /* save bookmarked posts. */
2050 int bookmarkedPostCounter = 0;
2051 synchronized (bookmarkedPosts) {
2052 for (String bookmarkedPostId : bookmarkedPosts) {
2053 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2056 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2059 configuration.save();
2061 } catch (ConfigurationException ce1) {
2062 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2064 synchronized (configuration) {
2065 storingConfiguration = false;
2071 * Loads the configuration.
2073 @SuppressWarnings("unchecked")
2074 private void loadConfiguration() {
2075 /* create options. */
2076 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2079 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2080 SoneInserter.setInsertionDelay(newValue);
2084 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2085 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2086 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2087 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2088 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2089 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2090 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2091 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2092 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2095 @SuppressWarnings("synthetic-access")
2096 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2097 fcpInterface.setActive(newValue);
2100 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2103 @SuppressWarnings("synthetic-access")
2104 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2105 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2110 loadConfigurationValue("InsertionDelay");
2111 loadConfigurationValue("PostsPerPage");
2112 loadConfigurationValue("ImagesPerPage");
2113 loadConfigurationValue("CharactersPerPost");
2114 loadConfigurationValue("PostCutOffLength");
2115 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2116 loadConfigurationValue("PositiveTrust");
2117 loadConfigurationValue("NegativeTrust");
2118 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2119 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2120 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2122 /* load known Sones. */
2123 int soneCounter = 0;
2125 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2126 if (knownSoneId == null) {
2129 synchronized (knownSones) {
2130 knownSones.add(knownSoneId);
2134 /* load Sone following times. */
2137 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2138 if (soneId == null) {
2141 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2142 Sone followedSone = getSone(soneId);
2143 if (followedSone == null) {
2144 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2146 synchronized (soneFollowingTimes) {
2147 soneFollowingTimes.put(getSone(soneId), time);
2153 /* load known posts. */
2154 int postCounter = 0;
2156 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2157 if (knownPostId == null) {
2160 synchronized (knownPosts) {
2161 knownPosts.add(knownPostId);
2165 /* load known replies. */
2166 int replyCounter = 0;
2168 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2169 if (knownReplyId == null) {
2172 synchronized (knownReplies) {
2173 knownReplies.add(knownReplyId);
2177 /* load bookmarked posts. */
2178 int bookmarkedPostCounter = 0;
2180 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2181 if (bookmarkedPostId == null) {
2184 synchronized (bookmarkedPosts) {
2185 bookmarkedPosts.add(bookmarkedPostId);
2192 * Loads an {@link Integer} configuration value for the option with the
2193 * given name, logging validation failures.
2196 * The name of the option to load
2198 private void loadConfigurationValue(String optionName) {
2200 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2201 } catch (IllegalArgumentException iae1) {
2202 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2207 * Generate a Sone URI from the given URI and latest edition.
2210 * The URI to derive the Sone URI from
2211 * @return The derived URI
2213 private static FreenetURI getSoneUri(String uriString) {
2215 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2217 } catch (MalformedURLException mue1) {
2218 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2224 // INTERFACE IdentityListener
2231 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2232 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2233 if (ownIdentity.hasContext("Sone")) {
2234 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2235 addLocalSone(ownIdentity);
2243 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2244 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2245 trustedIdentities.remove(ownIdentity);
2252 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2253 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2254 trustedIdentities.get(ownIdentity).add(identity);
2255 addRemoteSone(identity);
2262 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2263 new Thread(new Runnable() {
2266 @SuppressWarnings("synthetic-access")
2268 Sone sone = getRemoteSone(identity.getId(), false);
2269 sone.setIdentity(identity);
2270 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2271 soneDownloader.addSone(sone);
2272 soneDownloader.fetchSone(sone);
2281 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2282 trustedIdentities.get(ownIdentity).remove(identity);
2283 boolean foundIdentity = false;
2284 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2285 if (trustedIdentity.getKey().equals(ownIdentity)) {
2288 if (trustedIdentity.getValue().contains(identity)) {
2289 foundIdentity = true;
2292 if (foundIdentity) {
2293 /* some local identity still trusts this identity, don’t remove. */
2296 Sone sone = getSone(identity.getId(), false);
2298 /* TODO - we don’t have the Sone anymore. should this happen? */
2301 synchronized (posts) {
2302 synchronized (knownPosts) {
2303 for (Post post : sone.getPosts()) {
2304 posts.remove(post.getId());
2305 coreListenerManager.firePostRemoved(post);
2309 synchronized (replies) {
2310 synchronized (knownReplies) {
2311 for (PostReply reply : sone.getReplies()) {
2312 replies.remove(reply.getId());
2313 coreListenerManager.fireReplyRemoved(reply);
2317 database.removeSone(identity.getId());
2318 coreListenerManager.fireSoneRemoved(sone);
2322 // INTERFACE UpdateListener
2329 public void updateFound(Version version, long releaseTime, long latestEdition) {
2330 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2334 // INTERFACE ImageInsertListener
2341 public void insertStarted(Sone sone) {
2342 coreListenerManager.fireSoneInserting(sone);
2349 public void insertFinished(Sone sone, long insertDuration) {
2350 coreListenerManager.fireSoneInserted(sone, insertDuration);
2357 public void insertAborted(Sone sone, Throwable cause) {
2358 coreListenerManager.fireSoneInsertAborted(sone, cause);
2362 // SONEINSERTLISTENER METHODS
2369 public void imageInsertStarted(Image image) {
2370 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2371 coreListenerManager.fireImageInsertStarted(image);
2378 public void imageInsertAborted(Image image) {
2379 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2380 coreListenerManager.fireImageInsertAborted(image);
2387 public void imageInsertFinished(Image image, FreenetURI key) {
2388 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2389 image.setKey(key.toString());
2390 deleteTemporaryImage(image.getId());
2391 touchConfiguration();
2392 coreListenerManager.fireImageInsertFinished(image);
2399 public void imageInsertFailed(Image image, Throwable cause) {
2400 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2401 coreListenerManager.fireImageInsertFailed(image, cause);
2405 * Convenience interface for external classes that want to access the core’s
2408 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2410 public static class Preferences {
2412 /** The wrapped options. */
2413 private final Options options;
2416 * Creates a new preferences object wrapped around the given options.
2419 * The options to wrap
2421 public Preferences(Options options) {
2422 this.options = options;
2426 * Returns the insertion delay.
2428 * @return The insertion delay
2430 public int getInsertionDelay() {
2431 return options.getIntegerOption("InsertionDelay").get();
2435 * Validates the given insertion delay.
2437 * @param insertionDelay
2438 * The insertion delay to validate
2439 * @return {@code true} if the given insertion delay was valid,
2440 * {@code false} otherwise
2442 public boolean validateInsertionDelay(Integer insertionDelay) {
2443 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2447 * Sets the insertion delay
2449 * @param insertionDelay
2450 * The new insertion delay, or {@code null} to restore it to
2452 * @return This preferences
2454 public Preferences setInsertionDelay(Integer insertionDelay) {
2455 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2460 * Returns the number of posts to show per page.
2462 * @return The number of posts to show per page
2464 public int getPostsPerPage() {
2465 return options.getIntegerOption("PostsPerPage").get();
2469 * Validates the number of posts per page.
2471 * @param postsPerPage
2472 * The number of posts per page
2473 * @return {@code true} if the number of posts per page was valid,
2474 * {@code false} otherwise
2476 public boolean validatePostsPerPage(Integer postsPerPage) {
2477 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2481 * Sets the number of posts to show per page.
2483 * @param postsPerPage
2484 * The number of posts to show per page
2485 * @return This preferences object
2487 public Preferences setPostsPerPage(Integer postsPerPage) {
2488 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2493 * Returns the number of images to show per page.
2495 * @return The number of images to show per page
2497 public int getImagesPerPage() {
2498 return options.getIntegerOption("ImagesPerPage").get();
2502 * Validates the number of images per page.
2504 * @param imagesPerPage
2505 * The number of images per page
2506 * @return {@code true} if the number of images per page was valid,
2507 * {@code false} otherwise
2509 public boolean validateImagesPerPage(Integer imagesPerPage) {
2510 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2514 * Sets the number of images per page.
2516 * @param imagesPerPage
2517 * The number of images per page
2518 * @return This preferences object
2520 public Preferences setImagesPerPage(Integer imagesPerPage) {
2521 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2526 * Returns the number of characters per post, or <code>-1</code> if the
2527 * posts should not be cut off.
2529 * @return The numbers of characters per post
2531 public int getCharactersPerPost() {
2532 return options.getIntegerOption("CharactersPerPost").get();
2536 * Validates the number of characters per post.
2538 * @param charactersPerPost
2539 * The number of characters per post
2540 * @return {@code true} if the number of characters per post was valid,
2541 * {@code false} otherwise
2543 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2544 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2548 * Sets the number of characters per post.
2550 * @param charactersPerPost
2551 * The number of characters per post, or <code>-1</code> to
2552 * not cut off the posts
2553 * @return This preferences objects
2555 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2556 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2561 * Returns the number of characters the shortened post should have.
2563 * @return The number of characters of the snippet
2565 public int getPostCutOffLength() {
2566 return options.getIntegerOption("PostCutOffLength").get();
2570 * Validates the number of characters after which to cut off the post.
2572 * @param postCutOffLength
2573 * The number of characters of the snippet
2574 * @return {@code true} if the number of characters of the snippet is
2575 * valid, {@code false} otherwise
2577 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2578 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2582 * Sets the number of characters the shortened post should have.
2584 * @param postCutOffLength
2585 * The number of characters of the snippet
2586 * @return This preferences
2588 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2589 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2594 * Returns whether Sone requires full access to be even visible.
2596 * @return {@code true} if Sone requires full access, {@code false}
2599 public boolean isRequireFullAccess() {
2600 return options.getBooleanOption("RequireFullAccess").get();
2604 * Sets whether Sone requires full access to be even visible.
2606 * @param requireFullAccess
2607 * {@code true} if Sone requires full access, {@code false}
2610 public void setRequireFullAccess(Boolean requireFullAccess) {
2611 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2615 * Returns the positive trust.
2617 * @return The positive trust
2619 public int getPositiveTrust() {
2620 return options.getIntegerOption("PositiveTrust").get();
2624 * Validates the positive trust.
2626 * @param positiveTrust
2627 * The positive trust to validate
2628 * @return {@code true} if the positive trust was valid, {@code false}
2631 public boolean validatePositiveTrust(Integer positiveTrust) {
2632 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2636 * Sets the positive trust.
2638 * @param positiveTrust
2639 * The new positive trust, or {@code null} to restore it to
2641 * @return This preferences
2643 public Preferences setPositiveTrust(Integer positiveTrust) {
2644 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2649 * Returns the negative trust.
2651 * @return The negative trust
2653 public int getNegativeTrust() {
2654 return options.getIntegerOption("NegativeTrust").get();
2658 * Validates the negative trust.
2660 * @param negativeTrust
2661 * The negative trust to validate
2662 * @return {@code true} if the negative trust was valid, {@code false}
2665 public boolean validateNegativeTrust(Integer negativeTrust) {
2666 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2670 * Sets the negative trust.
2672 * @param negativeTrust
2673 * The negative trust, or {@code null} to restore it to the
2675 * @return The preferences
2677 public Preferences setNegativeTrust(Integer negativeTrust) {
2678 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2683 * Returns the trust comment. This is the comment that is set in the web
2684 * of trust when a trust value is assigned to an identity.
2686 * @return The trust comment
2688 public String getTrustComment() {
2689 return options.getStringOption("TrustComment").get();
2693 * Sets the trust comment.
2695 * @param trustComment
2696 * The trust comment, or {@code null} to restore it to the
2698 * @return This preferences
2700 public Preferences setTrustComment(String trustComment) {
2701 options.getStringOption("TrustComment").set(trustComment);
2706 * Returns whether the {@link FcpInterface FCP interface} is currently
2709 * @see FcpInterface#setActive(boolean)
2710 * @return {@code true} if the FCP interface is currently active,
2711 * {@code false} otherwise
2713 public boolean isFcpInterfaceActive() {
2714 return options.getBooleanOption("ActivateFcpInterface").get();
2718 * Sets whether the {@link FcpInterface FCP interface} is currently
2721 * @see FcpInterface#setActive(boolean)
2722 * @param fcpInterfaceActive
2723 * {@code true} to activate the FCP interface, {@code false}
2724 * to deactivate the FCP interface
2725 * @return This preferences object
2727 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2728 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2733 * Returns the action level for which full access to the FCP interface
2736 * @return The action level for which full access to the FCP interface
2739 public FullAccessRequired getFcpFullAccessRequired() {
2740 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2744 * Sets the action level for which full access to the FCP interface is
2747 * @param fcpFullAccessRequired
2749 * @return This preferences
2751 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2752 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);