2 * Sone - Core.java - Copyright © 2010 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.Profile;
42 import net.pterodactylus.sone.data.Reply;
43 import net.pterodactylus.sone.data.Sone;
44 import net.pterodactylus.sone.data.TemporaryImage;
45 import net.pterodactylus.sone.data.Profile.Field;
46 import net.pterodactylus.sone.fcp.FcpInterface;
47 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
48 import net.pterodactylus.sone.freenet.wot.Identity;
49 import net.pterodactylus.sone.freenet.wot.IdentityListener;
50 import net.pterodactylus.sone.freenet.wot.IdentityManager;
51 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
52 import net.pterodactylus.sone.freenet.wot.Trust;
53 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
54 import net.pterodactylus.sone.main.SonePlugin;
55 import net.pterodactylus.util.config.Configuration;
56 import net.pterodactylus.util.config.ConfigurationException;
57 import net.pterodactylus.util.logging.Logging;
58 import net.pterodactylus.util.number.Numbers;
59 import net.pterodactylus.util.service.AbstractService;
60 import net.pterodactylus.util.thread.Ticker;
61 import net.pterodactylus.util.validation.EqualityValidator;
62 import net.pterodactylus.util.validation.IntegerRangeValidator;
63 import net.pterodactylus.util.validation.OrValidator;
64 import net.pterodactylus.util.validation.Validation;
65 import net.pterodactylus.util.version.Version;
66 import freenet.keys.FreenetURI;
71 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
73 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
76 * Enumeration for the possible states of a {@link Sone}.
78 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
80 public enum SoneStatus {
82 /** The Sone is unknown, i.e. not yet downloaded. */
85 /** The Sone is idle, i.e. not being downloaded or inserted. */
88 /** The Sone is currently being inserted. */
91 /** The Sone is currently being downloaded. */
96 private static final Logger logger = Logging.getLogger(Core.class);
99 private final Options options = new Options();
101 /** The preferences. */
102 private final Preferences preferences = new Preferences(options);
104 /** The core listener manager. */
105 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
107 /** The configuration. */
108 private Configuration configuration;
110 /** Whether we’re currently saving the configuration. */
111 private boolean storingConfiguration = false;
113 /** The identity manager. */
114 private final IdentityManager identityManager;
116 /** Interface to freenet. */
117 private final FreenetInterface freenetInterface;
119 /** The Sone downloader. */
120 private final SoneDownloader soneDownloader;
122 /** The image inserter. */
123 private final ImageInserter imageInserter;
125 /** Sone downloader thread-pool. */
126 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
128 /** The update checker. */
129 private final UpdateChecker updateChecker;
131 /** The FCP interface. */
132 private volatile FcpInterface fcpInterface;
134 /** The Sones’ statuses. */
135 /* synchronize access on itself. */
136 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
138 /** Locked local Sones. */
139 /* synchronize on itself. */
140 private final Set<Sone> lockedSones = new HashSet<Sone>();
142 /** Sone inserters. */
143 /* synchronize access on this on localSones. */
144 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
146 /** Sone rescuers. */
147 /* synchronize access on this on localSones. */
148 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
150 /** All local Sones. */
151 /* synchronize access on this on itself. */
152 private Map<String, Sone> localSones = new HashMap<String, Sone>();
154 /** All remote Sones. */
155 /* synchronize access on this on itself. */
156 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
158 /** All new Sones. */
159 private Set<String> newSones = new HashSet<String>();
161 /** All known Sones. */
162 /* synchronize access on {@link #newSones}. */
163 private Set<String> knownSones = new HashSet<String>();
166 private Map<String, Post> posts = new HashMap<String, Post>();
168 /** All new posts. */
169 private Set<String> newPosts = new HashSet<String>();
171 /** All known posts. */
172 /* synchronize access on {@link #newPosts}. */
173 private Set<String> knownPosts = new HashSet<String>();
176 private Map<String, Reply> replies = new HashMap<String, Reply>();
178 /** All new replies. */
179 private Set<String> newReplies = new HashSet<String>();
181 /** All known replies. */
182 private Set<String> knownReplies = new HashSet<String>();
184 /** All bookmarked posts. */
185 /* synchronize access on itself. */
186 private Set<String> bookmarkedPosts = new HashSet<String>();
188 /** Trusted identities, sorted by own identities. */
189 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
191 /** All known albums. */
192 private Map<String, Album> albums = new HashMap<String, Album>();
194 /** All known images. */
195 private Map<String, Image> images = new HashMap<String, Image>();
197 /** All temporary images. */
198 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
200 /** Ticker for threads that mark own elements as known. */
201 private Ticker localElementTicker = new Ticker();
203 /** The time the configuration was last touched. */
204 private volatile long lastConfigurationUpdate;
207 * Creates a new core.
209 * @param configuration
210 * The configuration of the core
211 * @param freenetInterface
212 * The freenet interface
213 * @param identityManager
214 * The identity manager
216 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
218 this.configuration = configuration;
219 this.freenetInterface = freenetInterface;
220 this.identityManager = identityManager;
221 this.soneDownloader = new SoneDownloader(this, freenetInterface);
222 this.imageInserter = new ImageInserter(this, freenetInterface);
223 this.updateChecker = new UpdateChecker(freenetInterface);
227 // LISTENER MANAGEMENT
231 * Adds a new core listener.
233 * @param coreListener
234 * The listener to add
236 public void addCoreListener(CoreListener coreListener) {
237 coreListenerManager.addListener(coreListener);
241 * Removes a core listener.
243 * @param coreListener
244 * The listener to remove
246 public void removeCoreListener(CoreListener coreListener) {
247 coreListenerManager.removeListener(coreListener);
255 * Sets the configuration to use. This will automatically save the current
256 * configuration to the given configuration.
258 * @param configuration
259 * The new configuration to use
261 public void setConfiguration(Configuration configuration) {
262 this.configuration = configuration;
263 touchConfiguration();
267 * Returns the options used by the core.
269 * @return The options of the core
271 public Preferences getPreferences() {
276 * Returns the identity manager used by the core.
278 * @return The identity manager
280 public IdentityManager getIdentityManager() {
281 return identityManager;
285 * Returns the update checker.
287 * @return The update checker
289 public UpdateChecker getUpdateChecker() {
290 return updateChecker;
294 * Sets the FCP interface to use.
296 * @param fcpInterface
297 * The FCP interface to use
299 public void setFcpInterface(FcpInterface fcpInterface) {
300 this.fcpInterface = fcpInterface;
304 * Returns the status of the given Sone.
307 * The Sone to get the status for
308 * @return The status of the Sone
310 public SoneStatus getSoneStatus(Sone sone) {
311 synchronized (soneStatuses) {
312 return soneStatuses.get(sone);
317 * Sets the status of the given Sone.
320 * The Sone to set the status of
324 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
325 synchronized (soneStatuses) {
326 soneStatuses.put(sone, soneStatus);
331 * Returns the Sone rescuer for the given local Sone.
334 * The local Sone to get the rescuer for
335 * @return The Sone rescuer for the given Sone
337 public SoneRescuer getSoneRescuer(Sone sone) {
338 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
339 synchronized (localSones) {
340 SoneRescuer soneRescuer = soneRescuers.get(sone);
341 if (soneRescuer == null) {
342 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
343 soneRescuers.put(sone, soneRescuer);
351 * Returns whether the given Sone is currently locked.
355 * @return {@code true} if the Sone is locked, {@code false} if it is not
357 public boolean isLocked(Sone sone) {
358 synchronized (lockedSones) {
359 return lockedSones.contains(sone);
364 * Returns all Sones, remote and local.
368 public Set<Sone> getSones() {
369 Set<Sone> allSones = new HashSet<Sone>();
370 allSones.addAll(getLocalSones());
371 allSones.addAll(getRemoteSones());
376 * Returns the Sone with the given ID, regardless whether it’s local or
380 * The ID of the Sone to get
381 * @return The Sone with the given ID, or {@code null} if there is no such
384 public Sone getSone(String id) {
385 return getSone(id, true);
389 * Returns the Sone with the given ID, regardless whether it’s local or
393 * The ID of the Sone to get
395 * {@code true} to create a new Sone if none exists,
396 * {@code false} to return {@code null} if a Sone with the given
398 * @return The Sone with the given ID, or {@code null} if there is no such
402 public Sone getSone(String id, boolean create) {
403 if (isLocalSone(id)) {
404 return getLocalSone(id);
406 return getRemoteSone(id, create);
410 * Checks whether the core knows a Sone with the given ID.
414 * @return {@code true} if there is a Sone with the given ID, {@code false}
417 public boolean hasSone(String id) {
418 return isLocalSone(id) || isRemoteSone(id);
422 * Returns whether the given Sone is a local Sone.
425 * The Sone to check for its locality
426 * @return {@code true} if the given Sone is local, {@code false} otherwise
428 public boolean isLocalSone(Sone sone) {
429 synchronized (localSones) {
430 return localSones.containsKey(sone.getId());
435 * Returns whether the given ID is the ID of a local Sone.
438 * The Sone ID to check for its locality
439 * @return {@code true} if the given ID is a local Sone, {@code false}
442 public boolean isLocalSone(String id) {
443 synchronized (localSones) {
444 return localSones.containsKey(id);
449 * Returns all local Sones.
451 * @return All local Sones
453 public Set<Sone> getLocalSones() {
454 synchronized (localSones) {
455 return new HashSet<Sone>(localSones.values());
460 * Returns the local Sone with the given ID.
463 * The ID of the Sone to get
464 * @return The Sone with the given ID
466 public Sone getLocalSone(String id) {
467 return getLocalSone(id, true);
471 * Returns the local Sone with the given ID, optionally creating a new Sone.
476 * {@code true} to create a new Sone if none exists,
477 * {@code false} to return null if none exists
478 * @return The Sone with the given ID, or {@code null}
480 public Sone getLocalSone(String id, boolean create) {
481 synchronized (localSones) {
482 Sone sone = localSones.get(id);
483 if ((sone == null) && create) {
485 localSones.put(id, sone);
486 setSoneStatus(sone, SoneStatus.unknown);
493 * Returns all remote Sones.
495 * @return All remote Sones
497 public Set<Sone> getRemoteSones() {
498 synchronized (remoteSones) {
499 return new HashSet<Sone>(remoteSones.values());
504 * Returns the remote Sone with the given ID.
507 * The ID of the remote Sone to get
508 * @return The Sone with the given ID
510 public Sone getRemoteSone(String id) {
511 return getRemoteSone(id, true);
515 * Returns the remote Sone with the given ID.
518 * The ID of the remote Sone to get
520 * {@code true} to always create a Sone, {@code false} to return
521 * {@code null} if no Sone with the given ID exists
522 * @return The Sone with the given ID
524 public Sone getRemoteSone(String id, boolean create) {
525 synchronized (remoteSones) {
526 Sone sone = remoteSones.get(id);
527 if ((sone == null) && create) {
529 remoteSones.put(id, sone);
530 setSoneStatus(sone, SoneStatus.unknown);
537 * Returns whether the given Sone is a remote Sone.
541 * @return {@code true} if the given Sone is a remote Sone, {@code false}
544 public boolean isRemoteSone(Sone sone) {
545 synchronized (remoteSones) {
546 return remoteSones.containsKey(sone.getId());
551 * Returns whether the Sone with the given ID is a remote Sone.
554 * The ID of the Sone to check
555 * @return {@code true} if the Sone with the given ID is a remote Sone,
556 * {@code false} otherwise
558 public boolean isRemoteSone(String id) {
559 synchronized (remoteSones) {
560 return remoteSones.containsKey(id);
565 * Returns whether the Sone with the given ID is a new Sone.
568 * The ID of the sone to check for
569 * @return {@code true} if the given Sone is new, false otherwise
571 public boolean isNewSone(String soneId) {
572 synchronized (newSones) {
573 return !knownSones.contains(soneId) && newSones.contains(soneId);
578 * Returns whether the given Sone has been modified.
581 * The Sone to check for modifications
582 * @return {@code true} if a modification has been detected in the Sone,
583 * {@code false} otherwise
585 public boolean isModifiedSone(Sone sone) {
586 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
590 * Returns whether the target Sone is trusted by the origin Sone.
596 * @return {@code true} if the target Sone is trusted by the origin Sone
598 public boolean isSoneTrusted(Sone origin, Sone target) {
599 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
600 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
604 * Returns the post with the given ID.
607 * The ID of the post to get
608 * @return The post with the given ID, or a new post with the given ID
610 public Post getPost(String postId) {
611 return getPost(postId, true);
615 * Returns the post with the given ID, optionally creating a new post.
618 * The ID of the post to get
620 * {@code true} it create a new post if no post with the given ID
621 * exists, {@code false} to return {@code null}
622 * @return The post, or {@code null} if there is no such post
625 public Post getPost(String postId, boolean create) {
626 synchronized (posts) {
627 Post post = posts.get(postId);
628 if ((post == null) && create) {
629 post = new Post(postId);
630 posts.put(postId, post);
637 * Returns whether the given post ID is new.
641 * @return {@code true} if the post is considered to be new, {@code false}
644 public boolean isNewPost(String postId) {
645 synchronized (newPosts) {
646 return !knownPosts.contains(postId) && newPosts.contains(postId);
651 * Returns all posts that have the given Sone as recipient.
653 * @see Post#getRecipient()
655 * The recipient of the posts
656 * @return All posts that have the given Sone as recipient
658 public Set<Post> getDirectedPosts(Sone recipient) {
659 Validation.begin().isNotNull("Recipient", recipient).check();
660 Set<Post> directedPosts = new HashSet<Post>();
661 synchronized (posts) {
662 for (Post post : posts.values()) {
663 if (recipient.equals(post.getRecipient())) {
664 directedPosts.add(post);
668 return directedPosts;
672 * Returns the reply with the given ID. If there is no reply with the given
673 * ID yet, a new one is created.
676 * The ID of the reply to get
679 public Reply getReply(String replyId) {
680 return getReply(replyId, true);
684 * Returns the reply with the given ID. If there is no reply with the given
685 * ID yet, a new one is created, unless {@code create} is false in which
686 * case {@code null} is returned.
689 * The ID of the reply to get
691 * {@code true} to always return a {@link Reply}, {@code false}
692 * to return {@code null} if no reply can be found
693 * @return The reply, or {@code null} if there is no such reply
695 public Reply getReply(String replyId, boolean create) {
696 synchronized (replies) {
697 Reply reply = replies.get(replyId);
698 if (create && (reply == null)) {
699 reply = new Reply(replyId);
700 replies.put(replyId, reply);
707 * Returns all replies for the given post, order ascending by time.
710 * The post to get all replies for
711 * @return All replies for the given post
713 public List<Reply> getReplies(Post post) {
714 Set<Sone> sones = getSones();
715 List<Reply> replies = new ArrayList<Reply>();
716 for (Sone sone : sones) {
717 for (Reply reply : sone.getReplies()) {
718 if (reply.getPost().equals(post)) {
723 Collections.sort(replies, Reply.TIME_COMPARATOR);
728 * Returns whether the reply with the given ID is new.
731 * The ID of the reply to check
732 * @return {@code true} if the reply is considered to be new, {@code false}
735 public boolean isNewReply(String replyId) {
736 synchronized (newReplies) {
737 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
742 * Returns all Sones that have liked the given post.
745 * The post to get the liking Sones for
746 * @return The Sones that like the given post
748 public Set<Sone> getLikes(Post post) {
749 Set<Sone> sones = new HashSet<Sone>();
750 for (Sone sone : getSones()) {
751 if (sone.getLikedPostIds().contains(post.getId())) {
759 * Returns all Sones that have liked the given reply.
762 * The reply to get the liking Sones for
763 * @return The Sones that like the given reply
765 public Set<Sone> getLikes(Reply reply) {
766 Set<Sone> sones = new HashSet<Sone>();
767 for (Sone sone : getSones()) {
768 if (sone.getLikedReplyIds().contains(reply.getId())) {
776 * Returns whether the given post is bookmarked.
780 * @return {@code true} if the given post is bookmarked, {@code false}
783 public boolean isBookmarked(Post post) {
784 return isPostBookmarked(post.getId());
788 * Returns whether the post with the given ID is bookmarked.
791 * The ID of the post to check
792 * @return {@code true} if the post with the given ID is bookmarked,
793 * {@code false} otherwise
795 public boolean isPostBookmarked(String id) {
796 synchronized (bookmarkedPosts) {
797 return bookmarkedPosts.contains(id);
802 * Returns all currently known bookmarked posts.
804 * @return All bookmarked posts
806 public Set<Post> getBookmarkedPosts() {
807 Set<Post> posts = new HashSet<Post>();
808 synchronized (bookmarkedPosts) {
809 for (String bookmarkedPostId : bookmarkedPosts) {
810 Post post = getPost(bookmarkedPostId, false);
820 * Returns the album with the given ID, creating a new album if no album
821 * with the given ID can be found.
824 * The ID of the album
825 * @return The album with the given ID
827 public Album getAlbum(String albumId) {
828 return getAlbum(albumId, true);
832 * Returns the album with the given ID, optionally creating a new album if
833 * an album with the given ID can not be found.
836 * The ID of the album
838 * {@code true} to create a new album if none exists for the
840 * @return The album with the given ID, or {@code null} if no album with the
841 * given ID exists and {@code create} is {@code false}
843 public Album getAlbum(String albumId, boolean create) {
844 synchronized (albums) {
845 Album album = albums.get(albumId);
846 if (create && (album == null)) {
847 album = new Album(albumId);
848 albums.put(albumId, album);
855 * Returns the image with the given ID, creating it if necessary.
858 * The ID of the image
859 * @return The image with the given ID
861 public Image getImage(String imageId) {
862 return getImage(imageId, true);
866 * Returns the image with the given ID, optionally creating it if it does
870 * The ID of the image
872 * {@code true} to create an image if none exists with the given
874 * @return The image with the given ID, or {@code null} if none exists and
877 public Image getImage(String imageId, boolean create) {
878 synchronized (images) {
879 Image image = images.get(imageId);
880 if (create && (image == null)) {
881 image = new Image(imageId);
882 images.put(imageId, image);
889 * Returns the temporary image with the given ID.
892 * The ID of the temporary image
893 * @return The temporary image, or {@code null} if there is no temporary
894 * image with the given ID
896 public TemporaryImage getTemporaryImage(String imageId) {
897 synchronized (temporaryImages) {
898 return temporaryImages.get(imageId);
907 * Locks the given Sone. A locked Sone will not be inserted by
908 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
914 public void lockSone(Sone sone) {
915 synchronized (lockedSones) {
916 if (lockedSones.add(sone)) {
917 coreListenerManager.fireSoneLocked(sone);
923 * Unlocks the given Sone.
925 * @see #lockSone(Sone)
929 public void unlockSone(Sone sone) {
930 synchronized (lockedSones) {
931 if (lockedSones.remove(sone)) {
932 coreListenerManager.fireSoneUnlocked(sone);
938 * Adds a local Sone from the given ID which has to be the ID of an own
942 * The ID of an own identity to add a Sone for
943 * @return The added (or already existing) Sone
945 public Sone addLocalSone(String id) {
946 synchronized (localSones) {
947 if (localSones.containsKey(id)) {
948 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
949 return localSones.get(id);
951 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
952 if (ownIdentity == null) {
953 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
956 return addLocalSone(ownIdentity);
961 * Adds a local Sone from the given own identity.
964 * The own identity to create a Sone from
965 * @return The added (or already existing) Sone
967 public Sone addLocalSone(OwnIdentity ownIdentity) {
968 if (ownIdentity == null) {
969 logger.log(Level.WARNING, "Given OwnIdentity is null!");
972 synchronized (localSones) {
975 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
976 } catch (MalformedURLException mue1) {
977 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
980 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
981 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
982 /* TODO - load posts ’n stuff */
983 localSones.put(ownIdentity.getId(), sone);
984 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
985 soneInserter.addSoneInsertListener(this);
986 soneInserters.put(sone, soneInserter);
987 setSoneStatus(sone, SoneStatus.idle);
989 soneInserter.start();
995 * Creates a new Sone for the given own identity.
998 * The own identity to create a Sone for
999 * @return The created Sone
1001 public Sone createSone(OwnIdentity ownIdentity) {
1003 ownIdentity.addContext("Sone");
1004 } catch (WebOfTrustException wote1) {
1005 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
1008 Sone sone = addLocalSone(ownIdentity);
1009 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1010 sone.addFriend("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
1011 touchConfiguration();
1016 * Adds the Sone of the given identity.
1019 * The identity whose Sone to add
1020 * @return The added or already existing Sone
1022 public Sone addRemoteSone(Identity identity) {
1023 if (identity == null) {
1024 logger.log(Level.WARNING, "Given Identity is null!");
1027 synchronized (remoteSones) {
1028 final Sone sone = getRemoteSone(identity.getId()).setIdentity(identity);
1029 boolean newSone = sone.getRequestUri() == null;
1030 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
1031 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
1033 synchronized (newSones) {
1034 newSone = !knownSones.contains(sone.getId());
1036 newSones.add(sone.getId());
1040 coreListenerManager.fireNewSoneFound(sone);
1041 for (Sone localSone : getLocalSones()) {
1042 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
1043 localSone.addFriend(sone.getId());
1044 touchConfiguration();
1049 remoteSones.put(identity.getId(), sone);
1050 soneDownloader.addSone(sone);
1051 setSoneStatus(sone, SoneStatus.unknown);
1052 soneDownloaders.execute(new Runnable() {
1055 @SuppressWarnings("synthetic-access")
1057 soneDownloader.fetchSone(sone, sone.getRequestUri());
1066 * Retrieves the trust relationship from the origin to the target. If the
1067 * trust relationship can not be retrieved, {@code null} is returned.
1069 * @see Identity#getTrust(OwnIdentity)
1071 * The origin of the trust tree
1073 * The target of the trust
1074 * @return The trust relationship
1076 public Trust getTrust(Sone origin, Sone target) {
1077 if (!isLocalSone(origin)) {
1078 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1081 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1085 * Sets the trust value of the given origin Sone for the target Sone.
1092 * The trust value (from {@code -100} to {@code 100})
1094 public void setTrust(Sone origin, Sone target, int trustValue) {
1095 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();
1097 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1098 } catch (WebOfTrustException wote1) {
1099 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1104 * Removes any trust assignment for the given target Sone.
1111 public void removeTrust(Sone origin, Sone target) {
1112 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1114 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1115 } catch (WebOfTrustException wote1) {
1116 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1121 * Assigns the configured positive trust value for the given target.
1128 public void trustSone(Sone origin, Sone target) {
1129 setTrust(origin, target, preferences.getPositiveTrust());
1133 * Assigns the configured negative trust value for the given target.
1140 public void distrustSone(Sone origin, Sone target) {
1141 setTrust(origin, target, preferences.getNegativeTrust());
1145 * Removes the trust assignment for the given target.
1152 public void untrustSone(Sone origin, Sone target) {
1153 removeTrust(origin, target);
1157 * Updates the stored Sone with the given Sone.
1162 public void updateSone(Sone sone) {
1163 updateSone(sone, false);
1167 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1168 * {@code true}, an older Sone than the current Sone can be given to restore
1172 * The Sone to update
1173 * @param soneRescueMode
1174 * {@code true} if the stored Sone should be updated regardless
1175 * of the age of the given Sone
1177 public void updateSone(Sone sone, boolean soneRescueMode) {
1178 if (hasSone(sone.getId())) {
1179 Sone storedSone = getSone(sone.getId());
1180 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1181 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1184 synchronized (posts) {
1185 if (!soneRescueMode) {
1186 for (Post post : storedSone.getPosts()) {
1187 posts.remove(post.getId());
1188 if (!sone.getPosts().contains(post)) {
1189 coreListenerManager.firePostRemoved(post);
1193 List<Post> storedPosts = storedSone.getPosts();
1194 synchronized (newPosts) {
1195 for (Post post : sone.getPosts()) {
1196 post.setSone(storedSone);
1197 if (!storedPosts.contains(post) && !knownPosts.contains(post.getId())) {
1198 newPosts.add(post.getId());
1199 coreListenerManager.fireNewPostFound(post);
1201 posts.put(post.getId(), post);
1205 synchronized (replies) {
1206 if (!soneRescueMode) {
1207 for (Reply reply : storedSone.getReplies()) {
1208 replies.remove(reply.getId());
1209 if (!sone.getReplies().contains(reply)) {
1210 coreListenerManager.fireReplyRemoved(reply);
1214 Set<Reply> storedReplies = storedSone.getReplies();
1215 synchronized (newReplies) {
1216 for (Reply reply : sone.getReplies()) {
1217 reply.setSone(storedSone);
1218 if (!storedReplies.contains(reply) && !knownReplies.contains(reply.getId())) {
1219 newReplies.add(reply.getId());
1220 coreListenerManager.fireNewReplyFound(reply);
1222 replies.put(reply.getId(), reply);
1226 synchronized (storedSone) {
1227 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1228 storedSone.setTime(sone.getTime());
1230 storedSone.setClient(sone.getClient());
1231 storedSone.setProfile(sone.getProfile());
1232 if (soneRescueMode) {
1233 for (Post post : sone.getPosts()) {
1234 storedSone.addPost(post);
1236 for (Reply reply : sone.getReplies()) {
1237 storedSone.addReply(reply);
1239 for (String likedPostId : sone.getLikedPostIds()) {
1240 storedSone.addLikedPostId(likedPostId);
1242 for (String likedReplyId : sone.getLikedReplyIds()) {
1243 storedSone.addLikedReplyId(likedReplyId);
1246 storedSone.setPosts(sone.getPosts());
1247 storedSone.setReplies(sone.getReplies());
1248 storedSone.setLikePostIds(sone.getLikedPostIds());
1249 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1250 storedSone.setAlbums(sone.getAlbums());
1252 storedSone.setLatestEdition(sone.getLatestEdition());
1258 * Deletes the given Sone. This will remove the Sone from the
1259 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1260 * and remove the context from its identity.
1263 * The Sone to delete
1265 public void deleteSone(Sone sone) {
1266 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1267 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1270 synchronized (localSones) {
1271 if (!localSones.containsKey(sone.getId())) {
1272 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1275 localSones.remove(sone.getId());
1276 SoneInserter soneInserter = soneInserters.remove(sone);
1277 soneInserter.removeSoneInsertListener(this);
1278 soneInserter.stop();
1281 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1282 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1283 } catch (WebOfTrustException wote1) {
1284 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1287 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1288 } catch (ConfigurationException ce1) {
1289 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1294 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1295 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1298 * The Sone to mark as known
1300 public void markSoneKnown(Sone sone) {
1301 synchronized (newSones) {
1302 if (newSones.remove(sone.getId())) {
1303 knownSones.add(sone.getId());
1304 coreListenerManager.fireMarkSoneKnown(sone);
1305 touchConfiguration();
1311 * Loads and updates the given Sone from the configuration. If any error is
1312 * encountered, loading is aborted and the given Sone is not changed.
1315 * The Sone to load and update
1317 public void loadSone(Sone sone) {
1318 if (!isLocalSone(sone)) {
1319 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1323 /* initialize options. */
1324 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1325 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1328 String sonePrefix = "Sone/" + sone.getId();
1329 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1330 if (soneTime == null) {
1331 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1334 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1337 Profile profile = new Profile();
1338 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1339 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1340 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1341 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1342 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1343 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1345 /* load profile fields. */
1347 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1348 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1349 if (fieldName == null) {
1352 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1353 profile.addField(fieldName).setValue(fieldValue);
1357 Set<Post> posts = new HashSet<Post>();
1359 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1360 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1361 if (postId == null) {
1364 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1365 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1366 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1367 if ((postTime == 0) || (postText == null)) {
1368 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1371 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1372 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1373 post.setRecipient(getSone(postRecipientId));
1379 Set<Reply> replies = new HashSet<Reply>();
1381 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1382 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1383 if (replyId == null) {
1386 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1387 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1388 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1389 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1390 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1393 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1396 /* load post likes. */
1397 Set<String> likedPostIds = new HashSet<String>();
1399 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1400 if (likedPostId == null) {
1403 likedPostIds.add(likedPostId);
1406 /* load reply likes. */
1407 Set<String> likedReplyIds = new HashSet<String>();
1409 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1410 if (likedReplyId == null) {
1413 likedReplyIds.add(likedReplyId);
1417 Set<String> friends = new HashSet<String>();
1419 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1420 if (friendId == null) {
1423 friends.add(friendId);
1427 List<Album> topLevelAlbums = new ArrayList<Album>();
1428 int albumCounter = 0;
1430 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1431 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1432 if (albumId == null) {
1435 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1436 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1437 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1438 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1439 if ((albumTitle == null) || (albumDescription == null)) {
1440 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1443 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1444 if (albumParentId != null) {
1445 Album parentAlbum = getAlbum(albumParentId, false);
1446 if (parentAlbum == null) {
1447 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1450 parentAlbum.addAlbum(album);
1452 topLevelAlbums.add(album);
1457 int imageCounter = 0;
1459 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1460 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1461 if (imageId == null) {
1464 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1465 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1466 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1467 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1468 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1469 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1470 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1471 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1472 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1475 Album album = getAlbum(albumId, false);
1476 if (album == null) {
1477 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1480 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1481 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1482 album.addImage(image);
1486 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1487 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1489 /* if we’re still here, Sone was loaded successfully. */
1490 synchronized (sone) {
1491 sone.setTime(soneTime);
1492 sone.setProfile(profile);
1493 sone.setPosts(posts);
1494 sone.setReplies(replies);
1495 sone.setLikePostIds(likedPostIds);
1496 sone.setLikeReplyIds(likedReplyIds);
1497 sone.setFriends(friends);
1498 sone.setAlbums(topLevelAlbums);
1499 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1501 synchronized (newSones) {
1502 for (String friend : friends) {
1503 knownSones.add(friend);
1506 synchronized (newPosts) {
1507 for (Post post : posts) {
1508 knownPosts.add(post.getId());
1511 synchronized (newReplies) {
1512 for (Reply reply : replies) {
1513 knownReplies.add(reply.getId());
1519 * Creates a new post.
1522 * The Sone that creates the post
1524 * The text of the post
1525 * @return The created post
1527 public Post createPost(Sone sone, String text) {
1528 return createPost(sone, System.currentTimeMillis(), text);
1532 * Creates a new post.
1535 * The Sone that creates the post
1537 * The time of the post
1539 * The text of the post
1540 * @return The created post
1542 public Post createPost(Sone sone, long time, String text) {
1543 return createPost(sone, null, time, text);
1547 * Creates a new post.
1550 * The Sone that creates the post
1552 * The recipient Sone, or {@code null} if this post does not have
1555 * The text of the post
1556 * @return The created post
1558 public Post createPost(Sone sone, Sone recipient, String text) {
1559 return createPost(sone, recipient, System.currentTimeMillis(), text);
1563 * Creates a new post.
1566 * The Sone that creates the post
1568 * The recipient Sone, or {@code null} if this post does not have
1571 * The time of the post
1573 * The text of the post
1574 * @return The created post
1576 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1577 if (!isLocalSone(sone)) {
1578 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1581 final Post post = new Post(sone, time, text);
1582 if (recipient != null) {
1583 post.setRecipient(recipient);
1585 synchronized (posts) {
1586 posts.put(post.getId(), post);
1588 synchronized (newPosts) {
1589 newPosts.add(post.getId());
1590 coreListenerManager.fireNewPostFound(post);
1593 touchConfiguration();
1594 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1601 markPostKnown(post);
1603 }, "Mark " + post + " read.");
1608 * Deletes the given post.
1611 * The post to delete
1613 public void deletePost(Post post) {
1614 if (!isLocalSone(post.getSone())) {
1615 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1618 post.getSone().removePost(post);
1619 synchronized (posts) {
1620 posts.remove(post.getId());
1622 coreListenerManager.firePostRemoved(post);
1623 synchronized (newPosts) {
1624 markPostKnown(post);
1625 knownPosts.remove(post.getId());
1627 touchConfiguration();
1631 * Marks the given post as known, if it is currently a new post (according
1632 * to {@link #isNewPost(String)}).
1635 * The post to mark as known
1637 public void markPostKnown(Post post) {
1638 synchronized (newPosts) {
1639 if (newPosts.remove(post.getId())) {
1640 knownPosts.add(post.getId());
1641 coreListenerManager.fireMarkPostKnown(post);
1642 touchConfiguration();
1648 * Bookmarks the given post.
1651 * The post to bookmark
1653 public void bookmark(Post post) {
1654 bookmarkPost(post.getId());
1658 * Bookmarks the post with the given ID.
1661 * The ID of the post to bookmark
1663 public void bookmarkPost(String id) {
1664 synchronized (bookmarkedPosts) {
1665 bookmarkedPosts.add(id);
1670 * Removes the given post from the bookmarks.
1673 * The post to unbookmark
1675 public void unbookmark(Post post) {
1676 unbookmarkPost(post.getId());
1680 * Removes the post with the given ID from the bookmarks.
1683 * The ID of the post to unbookmark
1685 public void unbookmarkPost(String id) {
1686 synchronized (bookmarkedPosts) {
1687 bookmarkedPosts.remove(id);
1692 * Creates a new reply.
1695 * The Sone that creates the reply
1697 * The post that this reply refers to
1699 * The text of the reply
1700 * @return The created reply
1702 public Reply createReply(Sone sone, Post post, String text) {
1703 return createReply(sone, post, System.currentTimeMillis(), text);
1707 * Creates a new reply.
1710 * The Sone that creates the reply
1712 * The post that this reply refers to
1714 * The time of the reply
1716 * The text of the reply
1717 * @return The created reply
1719 public Reply createReply(Sone sone, Post post, long time, String text) {
1720 if (!isLocalSone(sone)) {
1721 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1724 final Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
1725 synchronized (replies) {
1726 replies.put(reply.getId(), reply);
1728 synchronized (newReplies) {
1729 newReplies.add(reply.getId());
1730 coreListenerManager.fireNewReplyFound(reply);
1732 sone.addReply(reply);
1733 touchConfiguration();
1734 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1741 markReplyKnown(reply);
1743 }, "Mark " + reply + " read.");
1748 * Deletes the given reply.
1751 * The reply to delete
1753 public void deleteReply(Reply reply) {
1754 Sone sone = reply.getSone();
1755 if (!isLocalSone(sone)) {
1756 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1759 synchronized (replies) {
1760 replies.remove(reply.getId());
1762 synchronized (newReplies) {
1763 markReplyKnown(reply);
1764 knownReplies.remove(reply.getId());
1766 sone.removeReply(reply);
1767 touchConfiguration();
1771 * Marks the given reply as known, if it is currently a new reply (according
1772 * to {@link #isNewReply(String)}).
1775 * The reply to mark as known
1777 public void markReplyKnown(Reply reply) {
1778 synchronized (newReplies) {
1779 if (newReplies.remove(reply.getId())) {
1780 knownReplies.add(reply.getId());
1781 coreListenerManager.fireMarkReplyKnown(reply);
1782 touchConfiguration();
1788 * Creates a new top-level album for the given Sone.
1791 * The Sone to create the album for
1792 * @return The new album
1794 public Album createAlbum(Sone sone) {
1795 return createAlbum(sone, null);
1799 * Creates a new album for the given Sone.
1802 * The Sone to create the album for
1804 * The parent of the album (may be {@code null} to create a
1806 * @return The new album
1808 public Album createAlbum(Sone sone, Album parent) {
1809 Album album = new Album();
1810 synchronized (albums) {
1811 albums.put(album.getId(), album);
1813 album.setSone(sone);
1814 if (parent != null) {
1815 parent.addAlbum(album);
1817 sone.addAlbum(album);
1823 * Deletes the given album. The owner of the album has to be a local Sone,
1824 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1827 * The album to remove
1829 public void deleteAlbum(Album album) {
1830 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1831 if (!album.isEmpty()) {
1834 if (album.getParent() == null) {
1835 album.getSone().removeAlbum(album);
1837 album.getParent().removeAlbum(album);
1839 synchronized (albums) {
1840 albums.remove(album.getId());
1842 saveSone(album.getSone());
1846 * Creates a new image.
1849 * The Sone creating the image
1851 * The album the image will be inserted into
1852 * @param temporaryImage
1853 * The temporary image to create the image from
1854 * @return The newly created image
1856 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1857 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();
1858 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1859 album.addImage(image);
1860 synchronized (images) {
1861 images.put(image.getId(), image);
1863 imageInserter.insertImage(temporaryImage, image);
1868 * Deletes the given image. This method will also delete a matching
1871 * @see #deleteTemporaryImage(TemporaryImage)
1873 * The image to delete
1875 public void deleteImage(Image image) {
1876 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1877 deleteTemporaryImage(image.getId());
1878 image.getAlbum().removeImage(image);
1879 synchronized (images) {
1880 images.remove(image.getId());
1882 saveSone(image.getSone());
1886 * Creates a new temporary image.
1889 * The MIME type of the temporary image
1891 * The encoded data of the image
1892 * @return The temporary image
1894 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1895 TemporaryImage temporaryImage = new TemporaryImage();
1896 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1897 synchronized (temporaryImages) {
1898 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1900 return temporaryImage;
1904 * Deletes the given temporary image.
1906 * @param temporaryImage
1907 * The temporary image to delete
1909 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1910 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1911 deleteTemporaryImage(temporaryImage.getId());
1915 * Deletes the temporary image with the given ID.
1918 * The ID of the temporary image to delete
1920 public void deleteTemporaryImage(String imageId) {
1921 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1922 synchronized (temporaryImages) {
1923 temporaryImages.remove(imageId);
1925 Image image = getImage(imageId, false);
1926 if (image != null) {
1927 imageInserter.cancelImageInsert(image);
1932 * Notifies the core that the configuration, either of the core or of a
1933 * single local Sone, has changed, and that the configuration should be
1936 public void touchConfiguration() {
1937 lastConfigurationUpdate = System.currentTimeMillis();
1948 public void serviceStart() {
1949 loadConfiguration();
1950 updateChecker.addUpdateListener(this);
1951 updateChecker.start();
1958 public void serviceRun() {
1959 long lastSaved = System.currentTimeMillis();
1960 while (!shouldStop()) {
1962 long now = System.currentTimeMillis();
1963 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1964 for (Sone localSone : getLocalSones()) {
1965 saveSone(localSone);
1967 saveConfiguration();
1977 public void serviceStop() {
1978 synchronized (localSones) {
1979 for (SoneInserter soneInserter : soneInserters.values()) {
1980 soneInserter.removeSoneInsertListener(this);
1981 soneInserter.stop();
1984 updateChecker.stop();
1985 updateChecker.removeUpdateListener(this);
1986 soneDownloader.stop();
1994 * Saves the given Sone. This will persist all local settings for the given
1995 * Sone, such as the friends list and similar, private options.
2000 private synchronized void saveSone(Sone sone) {
2001 if (!isLocalSone(sone)) {
2002 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2005 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2006 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2010 logger.log(Level.INFO, "Saving Sone: %s", sone);
2012 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2014 /* save Sone into configuration. */
2015 String sonePrefix = "Sone/" + sone.getId();
2016 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2017 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2020 Profile profile = sone.getProfile();
2021 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2022 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2023 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2024 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2025 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2026 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2028 /* save profile fields. */
2029 int fieldCounter = 0;
2030 for (Field profileField : profile.getFields()) {
2031 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2032 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2033 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2035 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2038 int postCounter = 0;
2039 for (Post post : sone.getPosts()) {
2040 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2041 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2042 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2043 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2044 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2046 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2049 int replyCounter = 0;
2050 for (Reply reply : sone.getReplies()) {
2051 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2052 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2053 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2054 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2055 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2057 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2059 /* save post likes. */
2060 int postLikeCounter = 0;
2061 for (String postId : sone.getLikedPostIds()) {
2062 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2064 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2066 /* save reply likes. */
2067 int replyLikeCounter = 0;
2068 for (String replyId : sone.getLikedReplyIds()) {
2069 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2071 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2074 int friendCounter = 0;
2075 for (String friendId : sone.getFriends()) {
2076 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2078 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2080 /* save albums. first, collect in a flat structure, top-level first. */
2081 List<Album> albums = Sone.flattenAlbums(sone.getAlbums());
2083 int albumCounter = 0;
2084 for (Album album : albums) {
2085 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2086 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2087 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2088 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2089 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2090 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2092 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2095 int imageCounter = 0;
2096 for (Album album : albums) {
2097 for (Image image : album.getImages()) {
2098 if (!image.isInserted()) {
2101 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2102 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2103 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2104 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2105 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2106 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2107 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2108 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2109 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2112 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2115 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2116 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2118 configuration.save();
2119 logger.log(Level.INFO, "Sone %s saved.", sone);
2120 } catch (ConfigurationException ce1) {
2121 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2122 } catch (WebOfTrustException wote1) {
2123 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2128 * Saves the current options.
2130 private void saveConfiguration() {
2131 synchronized (configuration) {
2132 if (storingConfiguration) {
2133 logger.log(Level.FINE, "Already storing configuration…");
2136 storingConfiguration = true;
2139 /* store the options first. */
2141 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2142 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2143 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2144 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2145 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2146 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2147 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2148 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2149 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2150 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2151 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2152 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2153 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2155 /* save known Sones. */
2156 int soneCounter = 0;
2157 synchronized (newSones) {
2158 for (String knownSoneId : knownSones) {
2159 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2161 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2164 /* save known posts. */
2165 int postCounter = 0;
2166 synchronized (newPosts) {
2167 for (String knownPostId : knownPosts) {
2168 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2170 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2173 /* save known replies. */
2174 int replyCounter = 0;
2175 synchronized (newReplies) {
2176 for (String knownReplyId : knownReplies) {
2177 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2179 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2182 /* save bookmarked posts. */
2183 int bookmarkedPostCounter = 0;
2184 synchronized (bookmarkedPosts) {
2185 for (String bookmarkedPostId : bookmarkedPosts) {
2186 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2189 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2192 configuration.save();
2194 } catch (ConfigurationException ce1) {
2195 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2197 synchronized (configuration) {
2198 storingConfiguration = false;
2204 * Loads the configuration.
2206 @SuppressWarnings("unchecked")
2207 private void loadConfiguration() {
2208 /* create options. */
2209 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2212 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2213 SoneInserter.setInsertionDelay(newValue);
2217 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2218 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2219 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2220 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2221 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2222 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2223 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2226 @SuppressWarnings("synthetic-access")
2227 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2228 fcpInterface.setActive(newValue);
2231 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2234 @SuppressWarnings("synthetic-access")
2235 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2236 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2240 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2241 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2242 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2244 /* read options from configuration. */
2245 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2246 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2247 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2248 options.getBooleanOption("ClearOnNextRestart").set(null);
2249 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2250 if (clearConfiguration) {
2251 /* stop loading the configuration. */
2255 loadConfigurationValue("InsertionDelay");
2256 loadConfigurationValue("PostsPerPage");
2257 loadConfigurationValue("CharactersPerPost");
2258 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2259 loadConfigurationValue("PositiveTrust");
2260 loadConfigurationValue("NegativeTrust");
2261 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2262 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2263 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2264 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2266 /* load known Sones. */
2267 int soneCounter = 0;
2269 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2270 if (knownSoneId == null) {
2273 synchronized (newSones) {
2274 knownSones.add(knownSoneId);
2278 /* load known posts. */
2279 int postCounter = 0;
2281 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2282 if (knownPostId == null) {
2285 synchronized (newPosts) {
2286 knownPosts.add(knownPostId);
2290 /* load known replies. */
2291 int replyCounter = 0;
2293 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2294 if (knownReplyId == null) {
2297 synchronized (newReplies) {
2298 knownReplies.add(knownReplyId);
2302 /* load bookmarked posts. */
2303 int bookmarkedPostCounter = 0;
2305 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2306 if (bookmarkedPostId == null) {
2309 synchronized (bookmarkedPosts) {
2310 bookmarkedPosts.add(bookmarkedPostId);
2317 * Loads an {@link Integer} configuration value for the option with the
2318 * given name, logging validation failures.
2321 * The name of the option to load
2323 private void loadConfigurationValue(String optionName) {
2325 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2326 } catch (IllegalArgumentException iae1) {
2327 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2332 * Generate a Sone URI from the given URI and latest edition.
2335 * The URI to derive the Sone URI from
2336 * @return The derived URI
2338 private FreenetURI getSoneUri(String uriString) {
2340 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2342 } catch (MalformedURLException mue1) {
2343 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2349 // INTERFACE IdentityListener
2356 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2357 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2358 if (ownIdentity.hasContext("Sone")) {
2359 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2360 addLocalSone(ownIdentity);
2368 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2369 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2370 trustedIdentities.remove(ownIdentity);
2377 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2378 logger.log(Level.FINEST, "Adding Identity: " + identity);
2379 trustedIdentities.get(ownIdentity).add(identity);
2380 addRemoteSone(identity);
2387 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2388 new Thread(new Runnable() {
2391 @SuppressWarnings("synthetic-access")
2393 Sone sone = getRemoteSone(identity.getId());
2394 sone.setIdentity(identity);
2395 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2396 soneDownloader.addSone(sone);
2397 soneDownloader.fetchSone(sone);
2406 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2407 trustedIdentities.get(ownIdentity).remove(identity);
2408 boolean foundIdentity = false;
2409 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2410 if (trustedIdentity.getKey().equals(ownIdentity)) {
2413 if (trustedIdentity.getValue().contains(identity)) {
2414 foundIdentity = true;
2417 if (foundIdentity) {
2418 /* some local identity still trusts this identity, don’t remove. */
2421 Sone sone = getSone(identity.getId(), false);
2423 /* TODO - we don’t have the Sone anymore. should this happen? */
2426 synchronized (posts) {
2427 synchronized (newPosts) {
2428 for (Post post : sone.getPosts()) {
2429 posts.remove(post.getId());
2430 newPosts.remove(post.getId());
2431 coreListenerManager.firePostRemoved(post);
2435 synchronized (replies) {
2436 synchronized (newReplies) {
2437 for (Reply reply : sone.getReplies()) {
2438 replies.remove(reply.getId());
2439 newReplies.remove(reply.getId());
2440 coreListenerManager.fireReplyRemoved(reply);
2444 synchronized (remoteSones) {
2445 remoteSones.remove(identity.getId());
2447 synchronized (newSones) {
2448 newSones.remove(identity.getId());
2449 coreListenerManager.fireSoneRemoved(sone);
2454 // INTERFACE UpdateListener
2461 public void updateFound(Version version, long releaseTime, long latestEdition) {
2462 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2466 // INTERFACE ImageInsertListener
2473 public void insertStarted(Sone sone) {
2474 coreListenerManager.fireSoneInserting(sone);
2481 public void insertFinished(Sone sone, long insertDuration) {
2482 coreListenerManager.fireSoneInserted(sone, insertDuration);
2489 public void insertAborted(Sone sone, Throwable cause) {
2490 coreListenerManager.fireSoneInsertAborted(sone, cause);
2494 // SONEINSERTLISTENER METHODS
2501 public void imageInsertStarted(Image image) {
2502 logger.log(Level.WARNING, "Image insert started for " + image);
2503 coreListenerManager.fireImageInsertStarted(image);
2510 public void imageInsertAborted(Image image) {
2511 logger.log(Level.WARNING, "Image insert aborted for " + image);
2512 coreListenerManager.fireImageInsertAborted(image);
2519 public void imageInsertFinished(Image image, FreenetURI key) {
2520 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2521 image.setKey(key.toString());
2522 deleteTemporaryImage(image.getId());
2523 saveSone(image.getSone());
2524 coreListenerManager.fireImageInsertFinished(image);
2531 public void imageInsertFailed(Image image, Throwable cause) {
2532 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2533 coreListenerManager.fireImageInsertFailed(image, cause);
2537 * Convenience interface for external classes that want to access the core’s
2540 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2542 public static class Preferences {
2544 /** The wrapped options. */
2545 private final Options options;
2548 * Creates a new preferences object wrapped around the given options.
2551 * The options to wrap
2553 public Preferences(Options options) {
2554 this.options = options;
2558 * Returns the insertion delay.
2560 * @return The insertion delay
2562 public int getInsertionDelay() {
2563 return options.getIntegerOption("InsertionDelay").get();
2567 * Validates the given insertion delay.
2569 * @param insertionDelay
2570 * The insertion delay to validate
2571 * @return {@code true} if the given insertion delay was valid, {@code
2574 public boolean validateInsertionDelay(Integer insertionDelay) {
2575 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2579 * Sets the insertion delay
2581 * @param insertionDelay
2582 * The new insertion delay, or {@code null} to restore it to
2584 * @return This preferences
2586 public Preferences setInsertionDelay(Integer insertionDelay) {
2587 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2592 * Returns the number of posts to show per page.
2594 * @return The number of posts to show per page
2596 public int getPostsPerPage() {
2597 return options.getIntegerOption("PostsPerPage").get();
2601 * Validates the number of posts per page.
2603 * @param postsPerPage
2604 * The number of posts per page
2605 * @return {@code true} if the number of posts per page was valid,
2606 * {@code false} otherwise
2608 public boolean validatePostsPerPage(Integer postsPerPage) {
2609 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2613 * Sets the number of posts to show per page.
2615 * @param postsPerPage
2616 * The number of posts to show per page
2617 * @return This preferences object
2619 public Preferences setPostsPerPage(Integer postsPerPage) {
2620 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2625 * Returns the number of characters per post, or <code>-1</code> if the
2626 * posts should not be cut off.
2628 * @return The numbers of characters per post
2630 public int getCharactersPerPost() {
2631 return options.getIntegerOption("CharactersPerPost").get();
2635 * Validates the number of characters per post.
2637 * @param charactersPerPost
2638 * The number of characters per post
2639 * @return {@code true} if the number of characters per post was valid,
2640 * {@code false} otherwise
2642 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2643 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2647 * Sets the number of characters per post.
2649 * @param charactersPerPost
2650 * The number of characters per post, or <code>-1</code> to
2651 * not cut off the posts
2652 * @return This preferences objects
2654 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2655 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2660 * Returns whether Sone requires full access to be even visible.
2662 * @return {@code true} if Sone requires full access, {@code false}
2665 public boolean isRequireFullAccess() {
2666 return options.getBooleanOption("RequireFullAccess").get();
2670 * Sets whether Sone requires full access to be even visible.
2672 * @param requireFullAccess
2673 * {@code true} if Sone requires full access, {@code false}
2676 public void setRequireFullAccess(Boolean requireFullAccess) {
2677 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2681 * Returns the positive trust.
2683 * @return The positive trust
2685 public int getPositiveTrust() {
2686 return options.getIntegerOption("PositiveTrust").get();
2690 * Validates the positive trust.
2692 * @param positiveTrust
2693 * The positive trust to validate
2694 * @return {@code true} if the positive trust was valid, {@code false}
2697 public boolean validatePositiveTrust(Integer positiveTrust) {
2698 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2702 * Sets the positive trust.
2704 * @param positiveTrust
2705 * The new positive trust, or {@code null} to restore it to
2707 * @return This preferences
2709 public Preferences setPositiveTrust(Integer positiveTrust) {
2710 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2715 * Returns the negative trust.
2717 * @return The negative trust
2719 public int getNegativeTrust() {
2720 return options.getIntegerOption("NegativeTrust").get();
2724 * Validates the negative trust.
2726 * @param negativeTrust
2727 * The negative trust to validate
2728 * @return {@code true} if the negative trust was valid, {@code false}
2731 public boolean validateNegativeTrust(Integer negativeTrust) {
2732 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2736 * Sets the negative trust.
2738 * @param negativeTrust
2739 * The negative trust, or {@code null} to restore it to the
2741 * @return The preferences
2743 public Preferences setNegativeTrust(Integer negativeTrust) {
2744 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2749 * Returns the trust comment. This is the comment that is set in the web
2750 * of trust when a trust value is assigned to an identity.
2752 * @return The trust comment
2754 public String getTrustComment() {
2755 return options.getStringOption("TrustComment").get();
2759 * Sets the trust comment.
2761 * @param trustComment
2762 * The trust comment, or {@code null} to restore it to the
2764 * @return This preferences
2766 public Preferences setTrustComment(String trustComment) {
2767 options.getStringOption("TrustComment").set(trustComment);
2772 * Returns whether the {@link FcpInterface FCP interface} is currently
2775 * @see FcpInterface#setActive(boolean)
2776 * @return {@code true} if the FCP interface is currently active,
2777 * {@code false} otherwise
2779 public boolean isFcpInterfaceActive() {
2780 return options.getBooleanOption("ActivateFcpInterface").get();
2784 * Sets whether the {@link FcpInterface FCP interface} is currently
2787 * @see FcpInterface#setActive(boolean)
2788 * @param fcpInterfaceActive
2789 * {@code true} to activate the FCP interface, {@code false}
2790 * to deactivate the FCP interface
2791 * @return This preferences object
2793 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2794 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2799 * Returns the action level for which full access to the FCP interface
2802 * @return The action level for which full access to the FCP interface
2805 public FullAccessRequired getFcpFullAccessRequired() {
2806 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2810 * Sets the action level for which full access to the FCP interface is
2813 * @param fcpFullAccessRequired
2815 * @return This preferences
2817 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2818 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2823 * Returns whether Sone should clear its settings on the next restart.
2824 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2825 * to return {@code true} as well!
2827 * @return {@code true} if Sone should clear its settings on the next
2828 * restart, {@code false} otherwise
2830 public boolean isClearOnNextRestart() {
2831 return options.getBooleanOption("ClearOnNextRestart").get();
2835 * Sets whether Sone will clear its settings on the next restart.
2837 * @param clearOnNextRestart
2838 * {@code true} if Sone should clear its settings on the next
2839 * restart, {@code false} otherwise
2840 * @return This preferences
2842 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2843 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2848 * Returns whether Sone should really clear its settings on next
2849 * restart. This is a confirmation option that needs to be set in
2850 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2851 * settings on the next restart.
2853 * @return {@code true} if Sone should really clear its settings on the
2854 * next restart, {@code false} otherwise
2856 public boolean isReallyClearOnNextRestart() {
2857 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2861 * Sets whether Sone should really clear its settings on the next
2864 * @param reallyClearOnNextRestart
2865 * {@code true} if Sone should really clear its settings on
2866 * the next restart, {@code false} otherwise
2867 * @return This preferences
2869 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2870 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);