2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Profile.Field;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.data.TemporaryImage;
49 import net.pterodactylus.sone.data.impl.PostImpl;
50 import net.pterodactylus.sone.fcp.FcpInterface;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.sone.freenet.wot.IdentityListener;
54 import net.pterodactylus.sone.freenet.wot.IdentityManager;
55 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
56 import net.pterodactylus.sone.freenet.wot.Trust;
57 import net.pterodactylus.sone.main.SonePlugin;
58 import net.pterodactylus.util.config.Configuration;
59 import net.pterodactylus.util.config.ConfigurationException;
60 import net.pterodactylus.util.logging.Logging;
61 import net.pterodactylus.util.number.Numbers;
62 import net.pterodactylus.util.service.AbstractService;
63 import net.pterodactylus.util.thread.Ticker;
64 import net.pterodactylus.util.validation.EqualityValidator;
65 import net.pterodactylus.util.validation.IntegerRangeValidator;
66 import net.pterodactylus.util.validation.OrValidator;
67 import net.pterodactylus.util.validation.Validation;
68 import net.pterodactylus.util.version.Version;
69 import freenet.keys.FreenetURI;
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
79 private static final Logger logger = Logging.getLogger(Core.class);
82 private final Options options = new Options();
84 /** The preferences. */
85 private final Preferences preferences = new Preferences(options);
87 /** The core listener manager. */
88 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
90 /** The configuration. */
91 private Configuration configuration;
93 /** Whether we’re currently saving the configuration. */
94 private boolean storingConfiguration = false;
96 /** The identity manager. */
97 private final IdentityManager identityManager;
99 /** Interface to freenet. */
100 private final FreenetInterface freenetInterface;
102 /** The Sone downloader. */
103 private final SoneDownloader soneDownloader;
105 /** The image inserter. */
106 private final ImageInserter imageInserter;
108 /** Sone downloader thread-pool. */
109 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
111 /** The update checker. */
112 private final UpdateChecker updateChecker;
114 /** The trust updater. */
115 private final WebOfTrustUpdater webOfTrustUpdater;
117 /** The FCP interface. */
118 private volatile FcpInterface fcpInterface;
120 /** The times Sones were followed. */
121 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
123 /** Locked local Sones. */
124 /* synchronize on itself. */
125 private final Set<Sone> lockedSones = new HashSet<Sone>();
127 /** Sone inserters. */
128 /* synchronize access on this on localSones. */
129 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
131 /** Sone rescuers. */
132 /* synchronize access on this on localSones. */
133 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
135 /** All local Sones. */
136 /* synchronize access on this on itself. */
137 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
139 /** All remote Sones. */
140 /* synchronize access on this on itself. */
141 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
143 /** All known Sones. */
144 private final Set<String> knownSones = new HashSet<String>();
147 private final Map<String, Post> posts = new HashMap<String, Post>();
149 /** All known posts. */
150 private final Set<String> knownPosts = new HashSet<String>();
153 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
155 /** All known replies. */
156 private final Set<String> knownReplies = new HashSet<String>();
158 /** All bookmarked posts. */
159 /* synchronize access on itself. */
160 private final Set<String> bookmarkedPosts = new HashSet<String>();
162 /** Trusted identities, sorted by own identities. */
163 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
165 /** All known albums. */
166 private final Map<String, Album> albums = new HashMap<String, Album>();
168 /** All known images. */
169 private final Map<String, Image> images = new HashMap<String, Image>();
171 /** All temporary images. */
172 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
174 /** Ticker for threads that mark own elements as known. */
175 private final Ticker localElementTicker = new Ticker();
177 /** The time the configuration was last touched. */
178 private volatile long lastConfigurationUpdate;
181 * Creates a new core.
183 * @param configuration
184 * The configuration of the core
185 * @param freenetInterface
186 * The freenet interface
187 * @param identityManager
188 * The identity manager
189 * @param webOfTrustUpdater
190 * The WebOfTrust updater
192 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
194 this.configuration = configuration;
195 this.freenetInterface = freenetInterface;
196 this.identityManager = identityManager;
197 this.soneDownloader = new SoneDownloader(this, freenetInterface);
198 this.imageInserter = new ImageInserter(this, freenetInterface);
199 this.updateChecker = new UpdateChecker(freenetInterface);
200 this.webOfTrustUpdater = webOfTrustUpdater;
204 // LISTENER MANAGEMENT
208 * Adds a new core listener.
210 * @param coreListener
211 * The listener to add
213 public void addCoreListener(CoreListener coreListener) {
214 coreListenerManager.addListener(coreListener);
218 * Removes a core listener.
220 * @param coreListener
221 * The listener to remove
223 public void removeCoreListener(CoreListener coreListener) {
224 coreListenerManager.removeListener(coreListener);
232 * Sets the configuration to use. This will automatically save the current
233 * configuration to the given configuration.
235 * @param configuration
236 * The new configuration to use
238 public void setConfiguration(Configuration configuration) {
239 this.configuration = configuration;
240 touchConfiguration();
244 * Returns the options used by the core.
246 * @return The options of the core
248 public Preferences getPreferences() {
253 * Returns the identity manager used by the core.
255 * @return The identity manager
257 public IdentityManager getIdentityManager() {
258 return identityManager;
262 * Returns the update checker.
264 * @return The update checker
266 public UpdateChecker getUpdateChecker() {
267 return updateChecker;
271 * Sets the FCP interface to use.
273 * @param fcpInterface
274 * The FCP interface to use
276 public void setFcpInterface(FcpInterface fcpInterface) {
277 this.fcpInterface = fcpInterface;
281 * Returns the Sone rescuer for the given local Sone.
284 * The local Sone to get the rescuer for
285 * @return The Sone rescuer for the given Sone
287 public SoneRescuer getSoneRescuer(Sone sone) {
288 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
289 synchronized (localSones) {
290 SoneRescuer soneRescuer = soneRescuers.get(sone);
291 if (soneRescuer == null) {
292 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
293 soneRescuers.put(sone, soneRescuer);
301 * Returns whether the given Sone is currently locked.
305 * @return {@code true} if the Sone is locked, {@code false} if it is not
307 public boolean isLocked(Sone sone) {
308 synchronized (lockedSones) {
309 return lockedSones.contains(sone);
314 * Returns all Sones, remote and local.
318 public Set<Sone> getSones() {
319 Set<Sone> allSones = new HashSet<Sone>();
320 allSones.addAll(getLocalSones());
321 allSones.addAll(getRemoteSones());
326 * Returns the Sone with the given ID, regardless whether it’s local or
330 * The ID of the Sone to get
331 * @return The Sone with the given ID, or {@code null} if there is no such
334 public Sone getSone(String id) {
335 return getSone(id, true);
339 * Returns the Sone with the given ID, regardless whether it’s local or
343 * The ID of the Sone to get
345 * {@code true} to create a new Sone if none exists,
346 * {@code false} to return {@code null} if a Sone with the given
348 * @return The Sone with the given ID, or {@code null} if there is no such
352 public Sone getSone(String id, boolean create) {
353 if (isLocalSone(id)) {
354 return getLocalSone(id);
356 return getRemoteSone(id, create);
360 * Checks whether the core knows a Sone with the given ID.
364 * @return {@code true} if there is a Sone with the given ID, {@code false}
367 public boolean hasSone(String id) {
368 return isLocalSone(id) || isRemoteSone(id);
372 * Returns whether the given Sone is a local Sone.
375 * The Sone to check for its locality
376 * @return {@code true} if the given Sone is local, {@code false} otherwise
378 public boolean isLocalSone(Sone sone) {
379 synchronized (localSones) {
380 return localSones.containsKey(sone.getId());
385 * Returns whether the given ID is the ID of a local Sone.
388 * The Sone ID to check for its locality
389 * @return {@code true} if the given ID is a local Sone, {@code false}
392 public boolean isLocalSone(String id) {
393 synchronized (localSones) {
394 return localSones.containsKey(id);
399 * Returns all local Sones.
401 * @return All local Sones
403 public Set<Sone> getLocalSones() {
404 synchronized (localSones) {
405 return new HashSet<Sone>(localSones.values());
410 * Returns the local Sone with the given ID.
413 * The ID of the Sone to get
414 * @return The Sone with the given ID
416 public Sone getLocalSone(String id) {
417 return getLocalSone(id, true);
421 * Returns the local Sone with the given ID, optionally creating a new Sone.
426 * {@code true} to create a new Sone if none exists,
427 * {@code false} to return null if none exists
428 * @return The Sone with the given ID, or {@code null}
430 public Sone getLocalSone(String id, boolean create) {
431 synchronized (localSones) {
432 Sone sone = localSones.get(id);
433 if ((sone == null) && create) {
435 localSones.put(id, sone);
442 * Returns all remote Sones.
444 * @return All remote Sones
446 public Set<Sone> getRemoteSones() {
447 synchronized (remoteSones) {
448 return new HashSet<Sone>(remoteSones.values());
453 * Returns the remote Sone with the given ID.
456 * The ID of the remote Sone to get
458 * {@code true} to always create a Sone, {@code false} to return
459 * {@code null} if no Sone with the given ID exists
460 * @return The Sone with the given ID
462 public Sone getRemoteSone(String id, boolean create) {
463 synchronized (remoteSones) {
464 Sone sone = remoteSones.get(id);
465 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
467 remoteSones.put(id, sone);
474 * Returns whether the given Sone is a remote Sone.
478 * @return {@code true} if the given Sone is a remote Sone, {@code false}
481 public boolean isRemoteSone(Sone sone) {
482 synchronized (remoteSones) {
483 return remoteSones.containsKey(sone.getId());
488 * Returns whether the Sone with the given ID is a remote Sone.
491 * The ID of the Sone to check
492 * @return {@code true} if the Sone with the given ID is a remote Sone,
493 * {@code false} otherwise
495 public boolean isRemoteSone(String id) {
496 synchronized (remoteSones) {
497 return remoteSones.containsKey(id);
502 * Returns whether the given Sone has been modified.
505 * The Sone to check for modifications
506 * @return {@code true} if a modification has been detected in the Sone,
507 * {@code false} otherwise
509 public boolean isModifiedSone(Sone sone) {
510 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
514 * Returns the time when the given was first followed by any local Sone.
517 * The Sone to get the time for
518 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
519 * been followed, or {@link Long#MAX_VALUE}
521 public long getSoneFollowingTime(Sone sone) {
522 synchronized (soneFollowingTimes) {
523 if (soneFollowingTimes.containsKey(sone)) {
524 return soneFollowingTimes.get(sone);
526 return Long.MAX_VALUE;
531 * Returns whether the target Sone is trusted by the origin Sone.
537 * @return {@code true} if the target Sone is trusted by the origin Sone
539 public boolean isSoneTrusted(Sone origin, Sone target) {
540 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
541 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
545 * Returns the post with the given ID.
548 * The ID of the post to get
549 * @return The post with the given ID, or a new post with the given ID
551 public Post getPost(String postId) {
552 return getPost(postId, true);
556 * Returns the post with the given ID, optionally creating a new post.
559 * The ID of the post to get
561 * {@code true} it create a new post if no post with the given ID
562 * exists, {@code false} to return {@code null}
563 * @return The post, or {@code null} if there is no such post
566 public Post getPost(String postId, boolean create) {
567 synchronized (posts) {
568 Post post = posts.get(postId);
569 if ((post == null) && create) {
570 post = new PostImpl(postId);
571 posts.put(postId, post);
578 * Returns all posts that have the given Sone as recipient.
580 * @see Post#getRecipient()
582 * The recipient of the posts
583 * @return All posts that have the given Sone as recipient
585 public Set<Post> getDirectedPosts(Sone recipient) {
586 Validation.begin().isNotNull("Recipient", recipient).check();
587 Set<Post> directedPosts = new HashSet<Post>();
588 synchronized (posts) {
589 for (Post post : posts.values()) {
590 if (recipient.equals(post.getRecipient())) {
591 directedPosts.add(post);
595 return directedPosts;
599 * Returns the reply with the given ID. If there is no reply with the given
600 * ID yet, a new one is created.
603 * The ID of the reply to get
606 public PostReply getReply(String replyId) {
607 return getReply(replyId, true);
611 * Returns the reply with the given ID. If there is no reply with the given
612 * ID yet, a new one is created, unless {@code create} is false in which
613 * case {@code null} is returned.
616 * The ID of the reply to get
618 * {@code true} to always return a {@link Reply}, {@code false}
619 * to return {@code null} if no reply can be found
620 * @return The reply, or {@code null} if there is no such reply
622 public PostReply getReply(String replyId, boolean create) {
623 synchronized (replies) {
624 PostReply reply = replies.get(replyId);
625 if (create && (reply == null)) {
626 reply = new PostReply(replyId);
627 replies.put(replyId, reply);
634 * Returns all replies for the given post, order ascending by time.
637 * The post to get all replies for
638 * @return All replies for the given post
640 public List<PostReply> getReplies(Post post) {
641 Set<Sone> sones = getSones();
642 List<PostReply> replies = new ArrayList<PostReply>();
643 for (Sone sone : sones) {
644 for (PostReply reply : sone.getReplies()) {
645 if (reply.getPost().equals(post)) {
650 Collections.sort(replies, Reply.TIME_COMPARATOR);
655 * Returns all Sones that have liked the given post.
658 * The post to get the liking Sones for
659 * @return The Sones that like the given post
661 public Set<Sone> getLikes(Post post) {
662 Set<Sone> sones = new HashSet<Sone>();
663 for (Sone sone : getSones()) {
664 if (sone.getLikedPostIds().contains(post.getId())) {
672 * Returns all Sones that have liked the given reply.
675 * The reply to get the liking Sones for
676 * @return The Sones that like the given reply
678 public Set<Sone> getLikes(PostReply reply) {
679 Set<Sone> sones = new HashSet<Sone>();
680 for (Sone sone : getSones()) {
681 if (sone.getLikedReplyIds().contains(reply.getId())) {
689 * Returns whether the given post is bookmarked.
693 * @return {@code true} if the given post is bookmarked, {@code false}
696 public boolean isBookmarked(Post post) {
697 return isPostBookmarked(post.getId());
701 * Returns whether the post with the given ID is bookmarked.
704 * The ID of the post to check
705 * @return {@code true} if the post with the given ID is bookmarked,
706 * {@code false} otherwise
708 public boolean isPostBookmarked(String id) {
709 synchronized (bookmarkedPosts) {
710 return bookmarkedPosts.contains(id);
715 * Returns all currently known bookmarked posts.
717 * @return All bookmarked posts
719 public Set<Post> getBookmarkedPosts() {
720 Set<Post> posts = new HashSet<Post>();
721 synchronized (bookmarkedPosts) {
722 for (String bookmarkedPostId : bookmarkedPosts) {
723 Post post = getPost(bookmarkedPostId, false);
733 * Returns the album with the given ID, creating a new album if no album
734 * with the given ID can be found.
737 * The ID of the album
738 * @return The album with the given ID
740 public Album getAlbum(String albumId) {
741 return getAlbum(albumId, true);
745 * Returns the album with the given ID, optionally creating a new album if
746 * an album with the given ID can not be found.
749 * The ID of the album
751 * {@code true} to create a new album if none exists for the
753 * @return The album with the given ID, or {@code null} if no album with the
754 * given ID exists and {@code create} is {@code false}
756 public Album getAlbum(String albumId, boolean create) {
757 synchronized (albums) {
758 Album album = albums.get(albumId);
759 if (create && (album == null)) {
760 album = new Album(albumId);
761 albums.put(albumId, album);
768 * Returns the image with the given ID, creating it if necessary.
771 * The ID of the image
772 * @return The image with the given ID
774 public Image getImage(String imageId) {
775 return getImage(imageId, true);
779 * Returns the image with the given ID, optionally creating it if it does
783 * The ID of the image
785 * {@code true} to create an image if none exists with the given
787 * @return The image with the given ID, or {@code null} if none exists and
790 public Image getImage(String imageId, boolean create) {
791 synchronized (images) {
792 Image image = images.get(imageId);
793 if (create && (image == null)) {
794 image = new Image(imageId);
795 images.put(imageId, image);
802 * Returns the temporary image with the given ID.
805 * The ID of the temporary image
806 * @return The temporary image, or {@code null} if there is no temporary
807 * image with the given ID
809 public TemporaryImage getTemporaryImage(String imageId) {
810 synchronized (temporaryImages) {
811 return temporaryImages.get(imageId);
820 * Locks the given Sone. A locked Sone will not be inserted by
821 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
827 public void lockSone(Sone sone) {
828 synchronized (lockedSones) {
829 if (lockedSones.add(sone)) {
830 coreListenerManager.fireSoneLocked(sone);
836 * Unlocks the given Sone.
838 * @see #lockSone(Sone)
842 public void unlockSone(Sone sone) {
843 synchronized (lockedSones) {
844 if (lockedSones.remove(sone)) {
845 coreListenerManager.fireSoneUnlocked(sone);
851 * Adds a local Sone from the given own identity.
854 * The own identity to create a Sone from
855 * @return The added (or already existing) Sone
857 public Sone addLocalSone(OwnIdentity ownIdentity) {
858 if (ownIdentity == null) {
859 logger.log(Level.WARNING, "Given OwnIdentity is null!");
862 synchronized (localSones) {
865 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
866 } catch (MalformedURLException mue1) {
867 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
870 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
871 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
873 /* TODO - load posts ’n stuff */
874 localSones.put(ownIdentity.getId(), sone);
875 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
876 soneInserter.addSoneInsertListener(this);
877 soneInserters.put(sone, soneInserter);
878 sone.setStatus(SoneStatus.idle);
880 soneInserter.start();
886 * Creates a new Sone for the given own identity.
889 * The own identity to create a Sone for
890 * @return The created Sone
892 public Sone createSone(OwnIdentity ownIdentity) {
893 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
894 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
897 Sone sone = addLocalSone(ownIdentity);
898 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
899 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
900 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
901 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
902 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
903 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
905 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
906 touchConfiguration();
911 * Adds the Sone of the given identity.
914 * The identity whose Sone to add
915 * @return The added or already existing Sone
917 public Sone addRemoteSone(Identity identity) {
918 if (identity == null) {
919 logger.log(Level.WARNING, "Given Identity is null!");
922 synchronized (remoteSones) {
923 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
924 boolean newSone = sone.getRequestUri() == null;
925 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
926 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
928 synchronized (knownSones) {
929 newSone = !knownSones.contains(sone.getId());
931 sone.setKnown(!newSone);
933 coreListenerManager.fireNewSoneFound(sone);
934 for (Sone localSone : getLocalSones()) {
935 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
936 followSone(localSone, sone);
941 soneDownloader.addSone(sone);
942 soneDownloaders.execute(new Runnable() {
945 @SuppressWarnings("synthetic-access")
947 soneDownloader.fetchSone(sone, sone.getRequestUri());
956 * Lets the given local Sone follow the Sone with the given ID.
959 * The local Sone that should follow another Sone
961 * The ID of the Sone to follow
963 public void followSone(Sone sone, String soneId) {
964 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
965 Sone followedSone = getSone(soneId, true);
966 if (followedSone == null) {
967 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
970 followSone(sone, getSone(soneId));
974 * Lets the given local Sone follow the other given Sone. If the given Sone
975 * was not followed by any local Sone before, this will mark all elements of
976 * the followed Sone as read that have been created before the current
980 * The local Sone that should follow the other Sone
981 * @param followedSone
982 * The Sone that should be followed
984 public void followSone(Sone sone, Sone followedSone) {
985 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
986 sone.addFriend(followedSone.getId());
987 synchronized (soneFollowingTimes) {
988 if (!soneFollowingTimes.containsKey(followedSone)) {
989 long now = System.currentTimeMillis();
990 soneFollowingTimes.put(followedSone, now);
991 for (Post post : followedSone.getPosts()) {
992 if (post.getTime() < now) {
996 for (PostReply reply : followedSone.getReplies()) {
997 if (reply.getTime() < now) {
998 markReplyKnown(reply);
1003 touchConfiguration();
1007 * Lets the given local Sone unfollow the Sone with the given ID.
1010 * The local Sone that should unfollow another Sone
1012 * The ID of the Sone being unfollowed
1014 public void unfollowSone(Sone sone, String soneId) {
1015 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1016 unfollowSone(sone, getSone(soneId, false));
1020 * Lets the given local Sone unfollow the other given Sone. If the given
1021 * local Sone is the last local Sone that followed the given Sone, its
1022 * following time will be removed.
1025 * The local Sone that should unfollow another Sone
1026 * @param unfollowedSone
1027 * The Sone being unfollowed
1029 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1030 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1031 sone.removeFriend(unfollowedSone.getId());
1032 boolean unfollowedSoneStillFollowed = false;
1033 for (Sone localSone : getLocalSones()) {
1034 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1036 if (!unfollowedSoneStillFollowed) {
1037 synchronized (soneFollowingTimes) {
1038 soneFollowingTimes.remove(unfollowedSone);
1041 touchConfiguration();
1045 * Retrieves the trust relationship from the origin to the target. If the
1046 * trust relationship can not be retrieved, {@code null} is returned.
1048 * @see Identity#getTrust(OwnIdentity)
1050 * The origin of the trust tree
1052 * The target of the trust
1053 * @return The trust relationship
1055 public Trust getTrust(Sone origin, Sone target) {
1056 if (!isLocalSone(origin)) {
1057 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
1060 webOfTrustUpdater.getTrust((OwnIdentity) origin.getIdentity(), target.getIdentity());
1061 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1065 * Sets the trust value of the given origin Sone for the target Sone.
1072 * The trust value (from {@code -100} to {@code 100})
1074 public void setTrust(Sone origin, Sone target, int trustValue) {
1075 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();
1076 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1080 * Removes any trust assignment for the given target Sone.
1087 public void removeTrust(Sone origin, Sone target) {
1088 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1089 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1093 * Assigns the configured positive trust value for the given target.
1100 public void trustSone(Sone origin, Sone target) {
1101 setTrust(origin, target, preferences.getPositiveTrust());
1105 * Assigns the configured negative trust value for the given target.
1112 public void distrustSone(Sone origin, Sone target) {
1113 setTrust(origin, target, preferences.getNegativeTrust());
1117 * Removes the trust assignment for the given target.
1124 public void untrustSone(Sone origin, Sone target) {
1125 removeTrust(origin, target);
1129 * Updates the stored Sone with the given Sone.
1134 public void updateSone(Sone sone) {
1135 updateSone(sone, false);
1139 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1140 * {@code true}, an older Sone than the current Sone can be given to restore
1144 * The Sone to update
1145 * @param soneRescueMode
1146 * {@code true} if the stored Sone should be updated regardless
1147 * of the age of the given Sone
1149 public void updateSone(Sone sone, boolean soneRescueMode) {
1150 if (hasSone(sone.getId())) {
1151 Sone storedSone = getSone(sone.getId());
1152 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1153 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1156 synchronized (posts) {
1157 if (!soneRescueMode) {
1158 for (Post post : storedSone.getPosts()) {
1159 posts.remove(post.getId());
1160 if (!sone.getPosts().contains(post)) {
1161 coreListenerManager.firePostRemoved(post);
1165 List<Post> storedPosts = storedSone.getPosts();
1166 synchronized (knownPosts) {
1167 for (Post post : sone.getPosts()) {
1168 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1169 if (!storedPosts.contains(post)) {
1170 if (post.getTime() < getSoneFollowingTime(sone)) {
1171 knownPosts.add(post.getId());
1172 } else if (!knownPosts.contains(post.getId())) {
1173 sone.setKnown(false);
1174 coreListenerManager.fireNewPostFound(post);
1177 posts.put(post.getId(), post);
1181 synchronized (replies) {
1182 if (!soneRescueMode) {
1183 for (PostReply reply : storedSone.getReplies()) {
1184 replies.remove(reply.getId());
1185 if (!sone.getReplies().contains(reply)) {
1186 coreListenerManager.fireReplyRemoved(reply);
1190 Set<PostReply> storedReplies = storedSone.getReplies();
1191 synchronized (knownReplies) {
1192 for (PostReply reply : sone.getReplies()) {
1193 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1194 if (!storedReplies.contains(reply)) {
1195 if (reply.getTime() < getSoneFollowingTime(sone)) {
1196 knownReplies.add(reply.getId());
1197 } else if (!knownReplies.contains(reply.getId())) {
1198 reply.setKnown(false);
1199 coreListenerManager.fireNewReplyFound(reply);
1202 replies.put(reply.getId(), reply);
1206 synchronized (albums) {
1207 synchronized (images) {
1208 for (Album album : storedSone.getAlbums()) {
1209 albums.remove(album.getId());
1210 for (Image image : album.getImages()) {
1211 images.remove(image.getId());
1214 for (Album album : sone.getAlbums()) {
1215 albums.put(album.getId(), album);
1216 for (Image image : album.getImages()) {
1217 images.put(image.getId(), image);
1222 synchronized (storedSone) {
1223 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1224 storedSone.setTime(sone.getTime());
1226 storedSone.setClient(sone.getClient());
1227 storedSone.setProfile(sone.getProfile());
1228 if (soneRescueMode) {
1229 for (Post post : sone.getPosts()) {
1230 storedSone.addPost(post);
1232 for (PostReply reply : sone.getReplies()) {
1233 storedSone.addReply(reply);
1235 for (String likedPostId : sone.getLikedPostIds()) {
1236 storedSone.addLikedPostId(likedPostId);
1238 for (String likedReplyId : sone.getLikedReplyIds()) {
1239 storedSone.addLikedReplyId(likedReplyId);
1241 for (Album album : sone.getAlbums()) {
1242 storedSone.addAlbum(album);
1245 storedSone.setPosts(sone.getPosts());
1246 storedSone.setReplies(sone.getReplies());
1247 storedSone.setLikePostIds(sone.getLikedPostIds());
1248 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1249 storedSone.setAlbums(sone.getAlbums());
1251 storedSone.setLatestEdition(sone.getLatestEdition());
1257 * Deletes the given Sone. This will remove the Sone from the
1258 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1259 * and remove the context from its identity.
1262 * The Sone to delete
1264 public void deleteSone(Sone sone) {
1265 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1266 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1269 synchronized (localSones) {
1270 if (!localSones.containsKey(sone.getId())) {
1271 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1274 localSones.remove(sone.getId());
1275 SoneInserter soneInserter = soneInserters.remove(sone);
1276 soneInserter.removeSoneInsertListener(this);
1277 soneInserter.stop();
1279 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1280 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1282 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1283 } catch (ConfigurationException ce1) {
1284 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1289 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1290 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1293 * The Sone to mark as known
1295 public void markSoneKnown(Sone sone) {
1296 if (!sone.isKnown()) {
1297 sone.setKnown(true);
1298 synchronized (knownSones) {
1299 knownSones.add(sone.getId());
1301 coreListenerManager.fireMarkSoneKnown(sone);
1302 touchConfiguration();
1307 * Loads and updates the given Sone from the configuration. If any error is
1308 * encountered, loading is aborted and the given Sone is not changed.
1311 * The Sone to load and update
1313 public void loadSone(Sone sone) {
1314 if (!isLocalSone(sone)) {
1315 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1319 /* initialize options. */
1320 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1321 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1322 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1323 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1324 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1325 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
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(sone);
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<PostReply> replies = new HashSet<PostReply>();
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, String.format("Invalid parent album ID: %s", albumParentId));
1450 parentAlbum.addAlbum(album);
1452 if (!topLevelAlbums.contains(album)) {
1453 topLevelAlbums.add(album);
1459 int imageCounter = 0;
1461 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1462 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1463 if (imageId == null) {
1466 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1467 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1468 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1469 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1470 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1471 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1472 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1473 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1474 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1477 Album album = getAlbum(albumId, false);
1478 if (album == null) {
1479 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1482 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1483 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1484 album.addImage(image);
1488 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1489 if (avatarId != null) {
1490 profile.setAvatar(getImage(avatarId, false));
1494 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1495 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1496 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1497 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1498 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1499 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1501 /* if we’re still here, Sone was loaded successfully. */
1502 synchronized (sone) {
1503 sone.setTime(soneTime);
1504 sone.setProfile(profile);
1505 sone.setPosts(posts);
1506 sone.setReplies(replies);
1507 sone.setLikePostIds(likedPostIds);
1508 sone.setLikeReplyIds(likedReplyIds);
1509 for (String friendId : friends) {
1510 followSone(sone, friendId);
1512 sone.setAlbums(topLevelAlbums);
1513 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1515 synchronized (knownSones) {
1516 for (String friend : friends) {
1517 knownSones.add(friend);
1520 synchronized (knownPosts) {
1521 for (Post post : posts) {
1522 knownPosts.add(post.getId());
1525 synchronized (knownReplies) {
1526 for (PostReply reply : replies) {
1527 knownReplies.add(reply.getId());
1533 * Creates a new post.
1536 * The Sone that creates the post
1538 * The text of the post
1539 * @return The created post
1541 public Post createPost(Sone sone, String text) {
1542 return createPost(sone, System.currentTimeMillis(), text);
1546 * Creates a new post.
1549 * The Sone that creates the post
1551 * The time of the post
1553 * The text of the post
1554 * @return The created post
1556 public Post createPost(Sone sone, long time, String text) {
1557 return createPost(sone, null, time, text);
1561 * Creates a new post.
1564 * The Sone that creates the post
1566 * The recipient Sone, or {@code null} if this post does not have
1569 * The text of the post
1570 * @return The created post
1572 public Post createPost(Sone sone, Sone recipient, String text) {
1573 return createPost(sone, recipient, System.currentTimeMillis(), text);
1577 * Creates a new post.
1580 * The Sone that creates the post
1582 * The recipient Sone, or {@code null} if this post does not have
1585 * The time of the post
1587 * The text of the post
1588 * @return The created post
1590 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1591 if (!isLocalSone(sone)) {
1592 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1595 final Post post = new PostImpl(sone, time, text);
1596 if (recipient != null) {
1597 post.setRecipient(recipient);
1599 synchronized (posts) {
1600 posts.put(post.getId(), post);
1602 coreListenerManager.fireNewPostFound(post);
1604 touchConfiguration();
1605 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1612 markPostKnown(post);
1614 }, "Mark " + post + " read.");
1619 * Deletes the given post.
1622 * The post to delete
1624 public void deletePost(Post post) {
1625 if (!isLocalSone(post.getSone())) {
1626 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1629 post.getSone().removePost(post);
1630 synchronized (posts) {
1631 posts.remove(post.getId());
1633 coreListenerManager.firePostRemoved(post);
1634 markPostKnown(post);
1635 touchConfiguration();
1639 * Marks the given post as known, if it is currently not a known post
1640 * (according to {@link Post#isKnown()}).
1643 * The post to mark as known
1645 public void markPostKnown(Post post) {
1646 post.setKnown(true);
1647 synchronized (knownPosts) {
1648 coreListenerManager.fireMarkPostKnown(post);
1649 if (knownPosts.add(post.getId())) {
1650 touchConfiguration();
1653 for (PostReply reply : getReplies(post)) {
1654 markReplyKnown(reply);
1659 * Bookmarks the given post.
1662 * The post to bookmark
1664 public void bookmark(Post post) {
1665 bookmarkPost(post.getId());
1669 * Bookmarks the post with the given ID.
1672 * The ID of the post to bookmark
1674 public void bookmarkPost(String id) {
1675 synchronized (bookmarkedPosts) {
1676 bookmarkedPosts.add(id);
1681 * Removes the given post from the bookmarks.
1684 * The post to unbookmark
1686 public void unbookmark(Post post) {
1687 unbookmarkPost(post.getId());
1691 * Removes the post with the given ID from the bookmarks.
1694 * The ID of the post to unbookmark
1696 public void unbookmarkPost(String id) {
1697 synchronized (bookmarkedPosts) {
1698 bookmarkedPosts.remove(id);
1703 * Creates a new reply.
1706 * The Sone that creates the reply
1708 * The post that this reply refers to
1710 * The text of the reply
1711 * @return The created reply
1713 public PostReply createReply(Sone sone, Post post, String text) {
1714 return createReply(sone, post, System.currentTimeMillis(), text);
1718 * Creates a new reply.
1721 * The Sone that creates the reply
1723 * The post that this reply refers to
1725 * The time of the reply
1727 * The text of the reply
1728 * @return The created reply
1730 public PostReply createReply(Sone sone, Post post, long time, String text) {
1731 if (!isLocalSone(sone)) {
1732 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1735 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1736 synchronized (replies) {
1737 replies.put(reply.getId(), reply);
1739 synchronized (knownReplies) {
1740 coreListenerManager.fireNewReplyFound(reply);
1742 sone.addReply(reply);
1743 touchConfiguration();
1744 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1751 markReplyKnown(reply);
1753 }, "Mark " + reply + " read.");
1758 * Deletes the given reply.
1761 * The reply to delete
1763 public void deleteReply(PostReply reply) {
1764 Sone sone = reply.getSone();
1765 if (!isLocalSone(sone)) {
1766 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1769 synchronized (replies) {
1770 replies.remove(reply.getId());
1772 synchronized (knownReplies) {
1773 markReplyKnown(reply);
1774 knownReplies.remove(reply.getId());
1776 sone.removeReply(reply);
1777 touchConfiguration();
1781 * Marks the given reply as known, if it is currently not a known reply
1782 * (according to {@link Reply#isKnown()}).
1785 * The reply to mark as known
1787 public void markReplyKnown(PostReply reply) {
1788 reply.setKnown(true);
1789 synchronized (knownReplies) {
1790 coreListenerManager.fireMarkReplyKnown(reply);
1791 if (knownReplies.add(reply.getId())) {
1792 touchConfiguration();
1798 * Creates a new top-level album for the given Sone.
1801 * The Sone to create the album for
1802 * @return The new album
1804 public Album createAlbum(Sone sone) {
1805 return createAlbum(sone, null);
1809 * Creates a new album for the given Sone.
1812 * The Sone to create the album for
1814 * The parent of the album (may be {@code null} to create a
1816 * @return The new album
1818 public Album createAlbum(Sone sone, Album parent) {
1819 Album album = new Album();
1820 synchronized (albums) {
1821 albums.put(album.getId(), album);
1823 album.setSone(sone);
1824 if (parent != null) {
1825 parent.addAlbum(album);
1827 sone.addAlbum(album);
1833 * Deletes the given album. The owner of the album has to be a local Sone,
1834 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1837 * The album to remove
1839 public void deleteAlbum(Album album) {
1840 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1841 if (!album.isEmpty()) {
1844 if (album.getParent() == null) {
1845 album.getSone().removeAlbum(album);
1847 album.getParent().removeAlbum(album);
1849 synchronized (albums) {
1850 albums.remove(album.getId());
1852 touchConfiguration();
1856 * Creates a new image.
1859 * The Sone creating the image
1861 * The album the image will be inserted into
1862 * @param temporaryImage
1863 * The temporary image to create the image from
1864 * @return The newly created image
1866 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1867 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();
1868 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1869 album.addImage(image);
1870 synchronized (images) {
1871 images.put(image.getId(), image);
1873 imageInserter.insertImage(temporaryImage, image);
1878 * Deletes the given image. This method will also delete a matching
1881 * @see #deleteTemporaryImage(TemporaryImage)
1883 * The image to delete
1885 public void deleteImage(Image image) {
1886 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1887 deleteTemporaryImage(image.getId());
1888 image.getAlbum().removeImage(image);
1889 synchronized (images) {
1890 images.remove(image.getId());
1892 touchConfiguration();
1896 * Creates a new temporary image.
1899 * The MIME type of the temporary image
1901 * The encoded data of the image
1902 * @return The temporary image
1904 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1905 TemporaryImage temporaryImage = new TemporaryImage();
1906 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1907 synchronized (temporaryImages) {
1908 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1910 return temporaryImage;
1914 * Deletes the given temporary image.
1916 * @param temporaryImage
1917 * The temporary image to delete
1919 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1920 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1921 deleteTemporaryImage(temporaryImage.getId());
1925 * Deletes the temporary image with the given ID.
1928 * The ID of the temporary image to delete
1930 public void deleteTemporaryImage(String imageId) {
1931 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1932 synchronized (temporaryImages) {
1933 temporaryImages.remove(imageId);
1935 Image image = getImage(imageId, false);
1936 if (image != null) {
1937 imageInserter.cancelImageInsert(image);
1942 * Notifies the core that the configuration, either of the core or of a
1943 * single local Sone, has changed, and that the configuration should be
1946 public void touchConfiguration() {
1947 lastConfigurationUpdate = System.currentTimeMillis();
1958 public void serviceStart() {
1959 loadConfiguration();
1960 updateChecker.addUpdateListener(this);
1961 updateChecker.start();
1962 webOfTrustUpdater.start();
1969 public void serviceRun() {
1970 long lastSaved = System.currentTimeMillis();
1971 while (!shouldStop()) {
1973 long now = System.currentTimeMillis();
1974 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1975 for (Sone localSone : getLocalSones()) {
1976 saveSone(localSone);
1978 saveConfiguration();
1988 public void serviceStop() {
1989 synchronized (localSones) {
1990 for (SoneInserter soneInserter : soneInserters.values()) {
1991 soneInserter.removeSoneInsertListener(this);
1992 soneInserter.stop();
1995 webOfTrustUpdater.stop();
1996 updateChecker.stop();
1997 updateChecker.removeUpdateListener(this);
1998 soneDownloader.stop();
2006 * Saves the given Sone. This will persist all local settings for the given
2007 * Sone, such as the friends list and similar, private options.
2012 private synchronized void saveSone(Sone sone) {
2013 if (!isLocalSone(sone)) {
2014 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2017 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2018 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2022 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2024 /* save Sone into configuration. */
2025 String sonePrefix = "Sone/" + sone.getId();
2026 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2027 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2030 Profile profile = sone.getProfile();
2031 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2032 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2033 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2034 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2035 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2036 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2037 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2039 /* save profile fields. */
2040 int fieldCounter = 0;
2041 for (Field profileField : profile.getFields()) {
2042 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2043 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2044 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2046 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2049 int postCounter = 0;
2050 for (Post post : sone.getPosts()) {
2051 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2052 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2053 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2054 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2055 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2057 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2060 int replyCounter = 0;
2061 for (PostReply reply : sone.getReplies()) {
2062 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2063 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2064 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2065 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2066 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2068 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2070 /* save post likes. */
2071 int postLikeCounter = 0;
2072 for (String postId : sone.getLikedPostIds()) {
2073 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2075 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2077 /* save reply likes. */
2078 int replyLikeCounter = 0;
2079 for (String replyId : sone.getLikedReplyIds()) {
2080 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2082 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2085 int friendCounter = 0;
2086 for (String friendId : sone.getFriends()) {
2087 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2089 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2091 /* save albums. first, collect in a flat structure, top-level first. */
2092 List<Album> albums = sone.getAllAlbums();
2094 int albumCounter = 0;
2095 for (Album album : albums) {
2096 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2097 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2098 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2099 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2100 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2101 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2103 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2106 int imageCounter = 0;
2107 for (Album album : albums) {
2108 for (Image image : album.getImages()) {
2109 if (!image.isInserted()) {
2112 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2113 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2114 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2115 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2116 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2117 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2118 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2119 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2120 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2123 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2126 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2127 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2128 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2129 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2130 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2131 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2133 configuration.save();
2135 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2137 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2138 } catch (ConfigurationException ce1) {
2139 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2144 * Saves the current options.
2146 private void saveConfiguration() {
2147 synchronized (configuration) {
2148 if (storingConfiguration) {
2149 logger.log(Level.FINE, "Already storing configuration…");
2152 storingConfiguration = true;
2155 /* store the options first. */
2157 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2158 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2159 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2160 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2161 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2162 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2163 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2164 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2165 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2166 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2167 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2168 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2170 /* save known Sones. */
2171 int soneCounter = 0;
2172 synchronized (knownSones) {
2173 for (String knownSoneId : knownSones) {
2174 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2176 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2179 /* save Sone following times. */
2181 synchronized (soneFollowingTimes) {
2182 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2183 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2184 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2187 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2190 /* save known posts. */
2191 int postCounter = 0;
2192 synchronized (knownPosts) {
2193 for (String knownPostId : knownPosts) {
2194 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2196 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2199 /* save known replies. */
2200 int replyCounter = 0;
2201 synchronized (knownReplies) {
2202 for (String knownReplyId : knownReplies) {
2203 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2205 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2208 /* save bookmarked posts. */
2209 int bookmarkedPostCounter = 0;
2210 synchronized (bookmarkedPosts) {
2211 for (String bookmarkedPostId : bookmarkedPosts) {
2212 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2215 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2218 configuration.save();
2220 } catch (ConfigurationException ce1) {
2221 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2223 synchronized (configuration) {
2224 storingConfiguration = false;
2230 * Loads the configuration.
2232 @SuppressWarnings("unchecked")
2233 private void loadConfiguration() {
2234 /* create options. */
2235 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2238 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2239 SoneInserter.setInsertionDelay(newValue);
2243 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2244 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2245 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2246 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2247 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2248 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2249 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2250 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2251 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2254 @SuppressWarnings("synthetic-access")
2255 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2256 fcpInterface.setActive(newValue);
2259 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2262 @SuppressWarnings("synthetic-access")
2263 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2264 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2269 loadConfigurationValue("InsertionDelay");
2270 loadConfigurationValue("PostsPerPage");
2271 loadConfigurationValue("ImagesPerPage");
2272 loadConfigurationValue("CharactersPerPost");
2273 loadConfigurationValue("PostCutOffLength");
2274 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2275 loadConfigurationValue("PositiveTrust");
2276 loadConfigurationValue("NegativeTrust");
2277 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2278 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2279 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2281 /* load known Sones. */
2282 int soneCounter = 0;
2284 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2285 if (knownSoneId == null) {
2288 synchronized (knownSones) {
2289 knownSones.add(knownSoneId);
2293 /* load Sone following times. */
2296 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2297 if (soneId == null) {
2300 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2301 Sone followedSone = getSone(soneId);
2302 if (followedSone == null) {
2303 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2305 synchronized (soneFollowingTimes) {
2306 soneFollowingTimes.put(getSone(soneId), time);
2312 /* load known posts. */
2313 int postCounter = 0;
2315 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2316 if (knownPostId == null) {
2319 synchronized (knownPosts) {
2320 knownPosts.add(knownPostId);
2324 /* load known replies. */
2325 int replyCounter = 0;
2327 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2328 if (knownReplyId == null) {
2331 synchronized (knownReplies) {
2332 knownReplies.add(knownReplyId);
2336 /* load bookmarked posts. */
2337 int bookmarkedPostCounter = 0;
2339 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2340 if (bookmarkedPostId == null) {
2343 synchronized (bookmarkedPosts) {
2344 bookmarkedPosts.add(bookmarkedPostId);
2351 * Loads an {@link Integer} configuration value for the option with the
2352 * given name, logging validation failures.
2355 * The name of the option to load
2357 private void loadConfigurationValue(String optionName) {
2359 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2360 } catch (IllegalArgumentException iae1) {
2361 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2366 * Generate a Sone URI from the given URI and latest edition.
2369 * The URI to derive the Sone URI from
2370 * @return The derived URI
2372 private FreenetURI getSoneUri(String uriString) {
2374 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2376 } catch (MalformedURLException mue1) {
2377 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2383 // INTERFACE IdentityListener
2390 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2391 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2392 if (ownIdentity.hasContext("Sone")) {
2393 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2394 addLocalSone(ownIdentity);
2402 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2403 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2404 trustedIdentities.remove(ownIdentity);
2411 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2412 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2413 trustedIdentities.get(ownIdentity).add(identity);
2414 addRemoteSone(identity);
2421 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2422 new Thread(new Runnable() {
2425 @SuppressWarnings("synthetic-access")
2427 Sone sone = getRemoteSone(identity.getId(), false);
2428 sone.setIdentity(identity);
2429 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2430 soneDownloader.addSone(sone);
2431 soneDownloader.fetchSone(sone);
2440 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2441 trustedIdentities.get(ownIdentity).remove(identity);
2442 boolean foundIdentity = false;
2443 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2444 if (trustedIdentity.getKey().equals(ownIdentity)) {
2447 if (trustedIdentity.getValue().contains(identity)) {
2448 foundIdentity = true;
2451 if (foundIdentity) {
2452 /* some local identity still trusts this identity, don’t remove. */
2455 Sone sone = getSone(identity.getId(), false);
2457 /* TODO - we don’t have the Sone anymore. should this happen? */
2460 synchronized (posts) {
2461 synchronized (knownPosts) {
2462 for (Post post : sone.getPosts()) {
2463 posts.remove(post.getId());
2464 coreListenerManager.firePostRemoved(post);
2468 synchronized (replies) {
2469 synchronized (knownReplies) {
2470 for (PostReply reply : sone.getReplies()) {
2471 replies.remove(reply.getId());
2472 coreListenerManager.fireReplyRemoved(reply);
2476 synchronized (remoteSones) {
2477 remoteSones.remove(identity.getId());
2479 coreListenerManager.fireSoneRemoved(sone);
2483 // INTERFACE UpdateListener
2490 public void updateFound(Version version, long releaseTime, long latestEdition) {
2491 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2495 // INTERFACE ImageInsertListener
2502 public void insertStarted(Sone sone) {
2503 coreListenerManager.fireSoneInserting(sone);
2510 public void insertFinished(Sone sone, long insertDuration) {
2511 coreListenerManager.fireSoneInserted(sone, insertDuration);
2518 public void insertAborted(Sone sone, Throwable cause) {
2519 coreListenerManager.fireSoneInsertAborted(sone, cause);
2523 // SONEINSERTLISTENER METHODS
2530 public void imageInsertStarted(Image image) {
2531 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2532 coreListenerManager.fireImageInsertStarted(image);
2539 public void imageInsertAborted(Image image) {
2540 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2541 coreListenerManager.fireImageInsertAborted(image);
2548 public void imageInsertFinished(Image image, FreenetURI key) {
2549 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2550 image.setKey(key.toString());
2551 deleteTemporaryImage(image.getId());
2552 touchConfiguration();
2553 coreListenerManager.fireImageInsertFinished(image);
2560 public void imageInsertFailed(Image image, Throwable cause) {
2561 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2562 coreListenerManager.fireImageInsertFailed(image, cause);
2566 * Convenience interface for external classes that want to access the core’s
2569 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2571 public static class Preferences {
2573 /** The wrapped options. */
2574 private final Options options;
2577 * Creates a new preferences object wrapped around the given options.
2580 * The options to wrap
2582 public Preferences(Options options) {
2583 this.options = options;
2587 * Returns the insertion delay.
2589 * @return The insertion delay
2591 public int getInsertionDelay() {
2592 return options.getIntegerOption("InsertionDelay").get();
2596 * Validates the given insertion delay.
2598 * @param insertionDelay
2599 * The insertion delay to validate
2600 * @return {@code true} if the given insertion delay was valid,
2601 * {@code false} otherwise
2603 public boolean validateInsertionDelay(Integer insertionDelay) {
2604 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2608 * Sets the insertion delay
2610 * @param insertionDelay
2611 * The new insertion delay, or {@code null} to restore it to
2613 * @return This preferences
2615 public Preferences setInsertionDelay(Integer insertionDelay) {
2616 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2621 * Returns the number of posts to show per page.
2623 * @return The number of posts to show per page
2625 public int getPostsPerPage() {
2626 return options.getIntegerOption("PostsPerPage").get();
2630 * Validates the number of posts per page.
2632 * @param postsPerPage
2633 * The number of posts per page
2634 * @return {@code true} if the number of posts per page was valid,
2635 * {@code false} otherwise
2637 public boolean validatePostsPerPage(Integer postsPerPage) {
2638 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2642 * Sets the number of posts to show per page.
2644 * @param postsPerPage
2645 * The number of posts to show per page
2646 * @return This preferences object
2648 public Preferences setPostsPerPage(Integer postsPerPage) {
2649 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2654 * Returns the number of images to show per page.
2656 * @return The number of images to show per page
2658 public int getImagesPerPage() {
2659 return options.getIntegerOption("ImagesPerPage").get();
2663 * Validates the number of images per page.
2665 * @param imagesPerPage
2666 * The number of images per page
2667 * @return {@code true} if the number of images per page was valid,
2668 * {@code false} otherwise
2670 public boolean validateImagesPerPage(Integer imagesPerPage) {
2671 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2675 * Sets the number of images per page.
2677 * @param imagesPerPage
2678 * The number of images per page
2679 * @return This preferences object
2681 public Preferences setImagesPerPage(Integer imagesPerPage) {
2682 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2687 * Returns the number of characters per post, or <code>-1</code> if the
2688 * posts should not be cut off.
2690 * @return The numbers of characters per post
2692 public int getCharactersPerPost() {
2693 return options.getIntegerOption("CharactersPerPost").get();
2697 * Validates the number of characters per post.
2699 * @param charactersPerPost
2700 * The number of characters per post
2701 * @return {@code true} if the number of characters per post was valid,
2702 * {@code false} otherwise
2704 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2705 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2709 * Sets the number of characters per post.
2711 * @param charactersPerPost
2712 * The number of characters per post, or <code>-1</code> to
2713 * not cut off the posts
2714 * @return This preferences objects
2716 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2717 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2722 * Returns the number of characters the shortened post should have.
2724 * @return The number of characters of the snippet
2726 public int getPostCutOffLength() {
2727 return options.getIntegerOption("PostCutOffLength").get();
2731 * Validates the number of characters after which to cut off the post.
2733 * @param postCutOffLength
2734 * The number of characters of the snippet
2735 * @return {@code true} if the number of characters of the snippet is
2736 * valid, {@code false} otherwise
2738 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2739 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2743 * Sets the number of characters the shortened post should have.
2745 * @param postCutOffLength
2746 * The number of characters of the snippet
2747 * @return This preferences
2749 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2750 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2755 * Returns whether Sone requires full access to be even visible.
2757 * @return {@code true} if Sone requires full access, {@code false}
2760 public boolean isRequireFullAccess() {
2761 return options.getBooleanOption("RequireFullAccess").get();
2765 * Sets whether Sone requires full access to be even visible.
2767 * @param requireFullAccess
2768 * {@code true} if Sone requires full access, {@code false}
2771 public void setRequireFullAccess(Boolean requireFullAccess) {
2772 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2776 * Returns the positive trust.
2778 * @return The positive trust
2780 public int getPositiveTrust() {
2781 return options.getIntegerOption("PositiveTrust").get();
2785 * Validates the positive trust.
2787 * @param positiveTrust
2788 * The positive trust to validate
2789 * @return {@code true} if the positive trust was valid, {@code false}
2792 public boolean validatePositiveTrust(Integer positiveTrust) {
2793 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2797 * Sets the positive trust.
2799 * @param positiveTrust
2800 * The new positive trust, or {@code null} to restore it to
2802 * @return This preferences
2804 public Preferences setPositiveTrust(Integer positiveTrust) {
2805 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2810 * Returns the negative trust.
2812 * @return The negative trust
2814 public int getNegativeTrust() {
2815 return options.getIntegerOption("NegativeTrust").get();
2819 * Validates the negative trust.
2821 * @param negativeTrust
2822 * The negative trust to validate
2823 * @return {@code true} if the negative trust was valid, {@code false}
2826 public boolean validateNegativeTrust(Integer negativeTrust) {
2827 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2831 * Sets the negative trust.
2833 * @param negativeTrust
2834 * The negative trust, or {@code null} to restore it to the
2836 * @return The preferences
2838 public Preferences setNegativeTrust(Integer negativeTrust) {
2839 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2844 * Returns the trust comment. This is the comment that is set in the web
2845 * of trust when a trust value is assigned to an identity.
2847 * @return The trust comment
2849 public String getTrustComment() {
2850 return options.getStringOption("TrustComment").get();
2854 * Sets the trust comment.
2856 * @param trustComment
2857 * The trust comment, or {@code null} to restore it to the
2859 * @return This preferences
2861 public Preferences setTrustComment(String trustComment) {
2862 options.getStringOption("TrustComment").set(trustComment);
2867 * Returns whether the {@link FcpInterface FCP interface} is currently
2870 * @see FcpInterface#setActive(boolean)
2871 * @return {@code true} if the FCP interface is currently active,
2872 * {@code false} otherwise
2874 public boolean isFcpInterfaceActive() {
2875 return options.getBooleanOption("ActivateFcpInterface").get();
2879 * Sets whether the {@link FcpInterface FCP interface} is currently
2882 * @see FcpInterface#setActive(boolean)
2883 * @param fcpInterfaceActive
2884 * {@code true} to activate the FCP interface, {@code false}
2885 * to deactivate the FCP interface
2886 * @return This preferences object
2888 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2889 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2894 * Returns the action level for which full access to the FCP interface
2897 * @return The action level for which full access to the FCP interface
2900 public FullAccessRequired getFcpFullAccessRequired() {
2901 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2905 * Sets the action level for which full access to the FCP interface is
2908 * @param fcpFullAccessRequired
2910 * @return This preferences
2912 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2913 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);