2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Profile.Field;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.data.TemporaryImage;
49 import net.pterodactylus.sone.data.impl.PostImpl;
50 import net.pterodactylus.sone.fcp.FcpInterface;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.sone.freenet.wot.IdentityListener;
54 import net.pterodactylus.sone.freenet.wot.IdentityManager;
55 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
56 import net.pterodactylus.sone.main.SonePlugin;
57 import net.pterodactylus.util.config.Configuration;
58 import net.pterodactylus.util.config.ConfigurationException;
59 import net.pterodactylus.util.logging.Logging;
60 import net.pterodactylus.util.number.Numbers;
61 import net.pterodactylus.util.service.AbstractService;
62 import net.pterodactylus.util.thread.Ticker;
63 import net.pterodactylus.util.validation.EqualityValidator;
64 import net.pterodactylus.util.validation.IntegerRangeValidator;
65 import net.pterodactylus.util.validation.OrValidator;
66 import net.pterodactylus.util.validation.Validation;
67 import net.pterodactylus.util.version.Version;
68 import freenet.keys.FreenetURI;
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
78 private static final Logger logger = Logging.getLogger(Core.class);
81 private final Options options = new Options();
83 /** The preferences. */
84 private final Preferences preferences = new Preferences(options);
86 /** The core listener manager. */
87 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
89 /** The configuration. */
90 private Configuration configuration;
92 /** Whether we’re currently saving the configuration. */
93 private boolean storingConfiguration = false;
95 /** The identity manager. */
96 private final IdentityManager identityManager;
98 /** Interface to freenet. */
99 private final FreenetInterface freenetInterface;
101 /** The Sone downloader. */
102 private final SoneDownloader soneDownloader;
104 /** The image inserter. */
105 private final ImageInserter imageInserter;
107 /** Sone downloader thread-pool. */
108 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
110 /** The update checker. */
111 private final UpdateChecker updateChecker;
113 /** The trust updater. */
114 private final WebOfTrustUpdater webOfTrustUpdater;
116 /** The FCP interface. */
117 private volatile FcpInterface fcpInterface;
119 /** The times Sones were followed. */
120 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
122 /** Locked local Sones. */
123 /* synchronize on itself. */
124 private final Set<Sone> lockedSones = new HashSet<Sone>();
126 /** Sone inserters. */
127 /* synchronize access on this on localSones. */
128 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
130 /** Sone rescuers. */
131 /* synchronize access on this on localSones. */
132 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
134 /** All local Sones. */
135 /* synchronize access on this on itself. */
136 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
138 /** All remote Sones. */
139 /* synchronize access on this on itself. */
140 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
142 /** All known Sones. */
143 private final Set<String> knownSones = new HashSet<String>();
146 private final Map<String, Post> posts = new HashMap<String, Post>();
148 /** All known posts. */
149 private final Set<String> knownPosts = new HashSet<String>();
152 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
154 /** All known replies. */
155 private final Set<String> knownReplies = new HashSet<String>();
157 /** All bookmarked posts. */
158 /* synchronize access on itself. */
159 private final Set<String> bookmarkedPosts = new HashSet<String>();
161 /** Trusted identities, sorted by own identities. */
162 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
164 /** All known albums. */
165 private final Map<String, Album> albums = new HashMap<String, Album>();
167 /** All known images. */
168 private final Map<String, Image> images = new HashMap<String, Image>();
170 /** All temporary images. */
171 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
173 /** Ticker for threads that mark own elements as known. */
174 private final Ticker localElementTicker = new Ticker();
176 /** The time the configuration was last touched. */
177 private volatile long lastConfigurationUpdate;
180 * Creates a new core.
182 * @param configuration
183 * The configuration of the core
184 * @param freenetInterface
185 * The freenet interface
186 * @param identityManager
187 * The identity manager
188 * @param webOfTrustUpdater
189 * The WebOfTrust updater
191 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
193 this.configuration = configuration;
194 this.freenetInterface = freenetInterface;
195 this.identityManager = identityManager;
196 this.soneDownloader = new SoneDownloader(this, freenetInterface);
197 this.imageInserter = new ImageInserter(this, freenetInterface);
198 this.updateChecker = new UpdateChecker(freenetInterface);
199 this.webOfTrustUpdater = webOfTrustUpdater;
203 // LISTENER MANAGEMENT
207 * Adds a new core listener.
209 * @param coreListener
210 * The listener to add
212 public void addCoreListener(CoreListener coreListener) {
213 coreListenerManager.addListener(coreListener);
217 * Removes a core listener.
219 * @param coreListener
220 * The listener to remove
222 public void removeCoreListener(CoreListener coreListener) {
223 coreListenerManager.removeListener(coreListener);
231 * Sets the configuration to use. This will automatically save the current
232 * configuration to the given configuration.
234 * @param configuration
235 * The new configuration to use
237 public void setConfiguration(Configuration configuration) {
238 this.configuration = configuration;
239 touchConfiguration();
243 * Returns the options used by the core.
245 * @return The options of the core
247 public Preferences getPreferences() {
252 * Returns the identity manager used by the core.
254 * @return The identity manager
256 public IdentityManager getIdentityManager() {
257 return identityManager;
261 * Returns the update checker.
263 * @return The update checker
265 public UpdateChecker getUpdateChecker() {
266 return updateChecker;
270 * Sets the FCP interface to use.
272 * @param fcpInterface
273 * The FCP interface to use
275 public void setFcpInterface(FcpInterface fcpInterface) {
276 this.fcpInterface = fcpInterface;
280 * Returns the Sone rescuer for the given local Sone.
283 * The local Sone to get the rescuer for
284 * @return The Sone rescuer for the given Sone
286 public SoneRescuer getSoneRescuer(Sone sone) {
287 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
288 synchronized (localSones) {
289 SoneRescuer soneRescuer = soneRescuers.get(sone);
290 if (soneRescuer == null) {
291 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
292 soneRescuers.put(sone, soneRescuer);
300 * Returns whether the given Sone is currently locked.
304 * @return {@code true} if the Sone is locked, {@code false} if it is not
306 public boolean isLocked(Sone sone) {
307 synchronized (lockedSones) {
308 return lockedSones.contains(sone);
313 * Returns all Sones, remote and local.
317 public Set<Sone> getSones() {
318 Set<Sone> allSones = new HashSet<Sone>();
319 allSones.addAll(getLocalSones());
320 allSones.addAll(getRemoteSones());
325 * Returns the Sone with the given ID, regardless whether it’s local or
329 * The ID of the Sone to get
330 * @return The Sone with the given ID, or {@code null} if there is no such
333 public Sone getSone(String id) {
334 return getSone(id, true);
338 * Returns the Sone with the given ID, regardless whether it’s local or
342 * The ID of the Sone to get
344 * {@code true} to create a new Sone if none exists,
345 * {@code false} to return {@code null} if a Sone with the given
347 * @return The Sone with the given ID, or {@code null} if there is no such
351 public Sone getSone(String id, boolean create) {
352 if (isLocalSone(id)) {
353 return getLocalSone(id);
355 return getRemoteSone(id, create);
359 * Checks whether the core knows a Sone with the given ID.
363 * @return {@code true} if there is a Sone with the given ID, {@code false}
366 public boolean hasSone(String id) {
367 return isLocalSone(id) || isRemoteSone(id);
371 * Returns whether the given Sone is a local Sone.
374 * The Sone to check for its locality
375 * @return {@code true} if the given Sone is local, {@code false} otherwise
377 public boolean isLocalSone(Sone sone) {
378 synchronized (localSones) {
379 return localSones.containsKey(sone.getId());
384 * Returns whether the given ID is the ID of a local Sone.
387 * The Sone ID to check for its locality
388 * @return {@code true} if the given ID is a local Sone, {@code false}
391 public boolean isLocalSone(String id) {
392 synchronized (localSones) {
393 return localSones.containsKey(id);
398 * Returns all local Sones.
400 * @return All local Sones
402 public Set<Sone> getLocalSones() {
403 synchronized (localSones) {
404 return new HashSet<Sone>(localSones.values());
409 * Returns the local Sone with the given ID.
412 * The ID of the Sone to get
413 * @return The Sone with the given ID
415 public Sone getLocalSone(String id) {
416 return getLocalSone(id, true);
420 * Returns the local Sone with the given ID, optionally creating a new Sone.
425 * {@code true} to create a new Sone if none exists,
426 * {@code false} to return null if none exists
427 * @return The Sone with the given ID, or {@code null}
429 public Sone getLocalSone(String id, boolean create) {
430 synchronized (localSones) {
431 Sone sone = localSones.get(id);
432 if ((sone == null) && create) {
434 localSones.put(id, sone);
441 * Returns all remote Sones.
443 * @return All remote Sones
445 public Set<Sone> getRemoteSones() {
446 synchronized (remoteSones) {
447 return new HashSet<Sone>(remoteSones.values());
452 * Returns the remote Sone with the given ID.
455 * The ID of the remote Sone to get
457 * {@code true} to always create a Sone, {@code false} to return
458 * {@code null} if no Sone with the given ID exists
459 * @return The Sone with the given ID
461 public Sone getRemoteSone(String id, boolean create) {
462 synchronized (remoteSones) {
463 Sone sone = remoteSones.get(id);
464 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
466 remoteSones.put(id, sone);
473 * Returns whether the given Sone is a remote Sone.
477 * @return {@code true} if the given Sone is a remote Sone, {@code false}
480 public boolean isRemoteSone(Sone sone) {
481 synchronized (remoteSones) {
482 return remoteSones.containsKey(sone.getId());
487 * Returns whether the Sone with the given ID is a remote Sone.
490 * The ID of the Sone to check
491 * @return {@code true} if the Sone with the given ID is a remote Sone,
492 * {@code false} otherwise
494 public boolean isRemoteSone(String id) {
495 synchronized (remoteSones) {
496 return remoteSones.containsKey(id);
501 * Returns whether the given Sone has been modified.
504 * The Sone to check for modifications
505 * @return {@code true} if a modification has been detected in the Sone,
506 * {@code false} otherwise
508 public boolean isModifiedSone(Sone sone) {
509 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
513 * Returns the time when the given was first followed by any local Sone.
516 * The Sone to get the time for
517 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
518 * been followed, or {@link Long#MAX_VALUE}
520 public long getSoneFollowingTime(Sone sone) {
521 synchronized (soneFollowingTimes) {
522 if (soneFollowingTimes.containsKey(sone)) {
523 return soneFollowingTimes.get(sone);
525 return Long.MAX_VALUE;
530 * Returns whether the target Sone is trusted by the origin Sone.
536 * @return {@code true} if the target Sone is trusted by the origin Sone
538 public boolean isSoneTrusted(Sone origin, Sone target) {
539 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
540 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
544 * Returns the post with the given ID.
547 * The ID of the post to get
548 * @return The post with the given ID, or a new post with the given ID
550 public Post getPost(String postId) {
551 return getPost(postId, true);
555 * Returns the post with the given ID, optionally creating a new post.
558 * The ID of the post to get
560 * {@code true} it create a new post if no post with the given ID
561 * exists, {@code false} to return {@code null}
562 * @return The post, or {@code null} if there is no such post
565 public Post getPost(String postId, boolean create) {
566 synchronized (posts) {
567 Post post = posts.get(postId);
568 if ((post == null) && create) {
569 post = new PostImpl(postId);
570 posts.put(postId, post);
577 * Returns all posts that have the given Sone as recipient.
579 * @see Post#getRecipient()
581 * The recipient of the posts
582 * @return All posts that have the given Sone as recipient
584 public Set<Post> getDirectedPosts(Sone recipient) {
585 Validation.begin().isNotNull("Recipient", recipient).check();
586 Set<Post> directedPosts = new HashSet<Post>();
587 synchronized (posts) {
588 for (Post post : posts.values()) {
589 if (recipient.equals(post.getRecipient())) {
590 directedPosts.add(post);
594 return directedPosts;
598 * Returns the reply with the given ID. If there is no reply with the given
599 * ID yet, a new one is created.
602 * The ID of the reply to get
605 public PostReply getReply(String replyId) {
606 return getReply(replyId, true);
610 * Returns the reply with the given ID. If there is no reply with the given
611 * ID yet, a new one is created, unless {@code create} is false in which
612 * case {@code null} is returned.
615 * The ID of the reply to get
617 * {@code true} to always return a {@link Reply}, {@code false}
618 * to return {@code null} if no reply can be found
619 * @return The reply, or {@code null} if there is no such reply
621 public PostReply getReply(String replyId, boolean create) {
622 synchronized (replies) {
623 PostReply reply = replies.get(replyId);
624 if (create && (reply == null)) {
625 reply = new PostReply(replyId);
626 replies.put(replyId, reply);
633 * Returns all replies for the given post, order ascending by time.
636 * The post to get all replies for
637 * @return All replies for the given post
639 public List<PostReply> getReplies(Post post) {
640 Set<Sone> sones = getSones();
641 List<PostReply> replies = new ArrayList<PostReply>();
642 for (Sone sone : sones) {
643 for (PostReply reply : sone.getReplies()) {
644 if (reply.getPost().equals(post)) {
649 Collections.sort(replies, Reply.TIME_COMPARATOR);
654 * Returns all Sones that have liked the given post.
657 * The post to get the liking Sones for
658 * @return The Sones that like the given post
660 public Set<Sone> getLikes(Post post) {
661 Set<Sone> sones = new HashSet<Sone>();
662 for (Sone sone : getSones()) {
663 if (sone.getLikedPostIds().contains(post.getId())) {
671 * Returns all Sones that have liked the given reply.
674 * The reply to get the liking Sones for
675 * @return The Sones that like the given reply
677 public Set<Sone> getLikes(PostReply reply) {
678 Set<Sone> sones = new HashSet<Sone>();
679 for (Sone sone : getSones()) {
680 if (sone.getLikedReplyIds().contains(reply.getId())) {
688 * Returns whether the given post is bookmarked.
692 * @return {@code true} if the given post is bookmarked, {@code false}
695 public boolean isBookmarked(Post post) {
696 return isPostBookmarked(post.getId());
700 * Returns whether the post with the given ID is bookmarked.
703 * The ID of the post to check
704 * @return {@code true} if the post with the given ID is bookmarked,
705 * {@code false} otherwise
707 public boolean isPostBookmarked(String id) {
708 synchronized (bookmarkedPosts) {
709 return bookmarkedPosts.contains(id);
714 * Returns all currently known bookmarked posts.
716 * @return All bookmarked posts
718 public Set<Post> getBookmarkedPosts() {
719 Set<Post> posts = new HashSet<Post>();
720 synchronized (bookmarkedPosts) {
721 for (String bookmarkedPostId : bookmarkedPosts) {
722 Post post = getPost(bookmarkedPostId, false);
732 * Returns the album with the given ID, creating a new album if no album
733 * with the given ID can be found.
736 * The ID of the album
737 * @return The album with the given ID
739 public Album getAlbum(String albumId) {
740 return getAlbum(albumId, true);
744 * Returns the album with the given ID, optionally creating a new album if
745 * an album with the given ID can not be found.
748 * The ID of the album
750 * {@code true} to create a new album if none exists for the
752 * @return The album with the given ID, or {@code null} if no album with the
753 * given ID exists and {@code create} is {@code false}
755 public Album getAlbum(String albumId, boolean create) {
756 synchronized (albums) {
757 Album album = albums.get(albumId);
758 if (create && (album == null)) {
759 album = new Album(albumId);
760 albums.put(albumId, album);
767 * Returns the image with the given ID, creating it if necessary.
770 * The ID of the image
771 * @return The image with the given ID
773 public Image getImage(String imageId) {
774 return getImage(imageId, true);
778 * Returns the image with the given ID, optionally creating it if it does
782 * The ID of the image
784 * {@code true} to create an image if none exists with the given
786 * @return The image with the given ID, or {@code null} if none exists and
789 public Image getImage(String imageId, boolean create) {
790 synchronized (images) {
791 Image image = images.get(imageId);
792 if (create && (image == null)) {
793 image = new Image(imageId);
794 images.put(imageId, image);
801 * Returns the temporary image with the given ID.
804 * The ID of the temporary image
805 * @return The temporary image, or {@code null} if there is no temporary
806 * image with the given ID
808 public TemporaryImage getTemporaryImage(String imageId) {
809 synchronized (temporaryImages) {
810 return temporaryImages.get(imageId);
819 * Locks the given Sone. A locked Sone will not be inserted by
820 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
826 public void lockSone(Sone sone) {
827 synchronized (lockedSones) {
828 if (lockedSones.add(sone)) {
829 coreListenerManager.fireSoneLocked(sone);
835 * Unlocks the given Sone.
837 * @see #lockSone(Sone)
841 public void unlockSone(Sone sone) {
842 synchronized (lockedSones) {
843 if (lockedSones.remove(sone)) {
844 coreListenerManager.fireSoneUnlocked(sone);
850 * Adds a local Sone from the given own identity.
853 * The own identity to create a Sone from
854 * @return The added (or already existing) Sone
856 public Sone addLocalSone(OwnIdentity ownIdentity) {
857 if (ownIdentity == null) {
858 logger.log(Level.WARNING, "Given OwnIdentity is null!");
861 synchronized (localSones) {
864 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
865 } catch (MalformedURLException mue1) {
866 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
869 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
870 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
872 /* TODO - load posts ’n stuff */
873 localSones.put(ownIdentity.getId(), sone);
874 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
875 soneInserter.addSoneInsertListener(this);
876 soneInserters.put(sone, soneInserter);
877 sone.setStatus(SoneStatus.idle);
879 soneInserter.start();
885 * Creates a new Sone for the given own identity.
888 * The own identity to create a Sone for
889 * @return The created Sone
891 public Sone createSone(OwnIdentity ownIdentity) {
892 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
893 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
896 Sone sone = addLocalSone(ownIdentity);
897 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
898 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
899 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
900 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
901 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
902 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
904 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
905 touchConfiguration();
910 * Adds the Sone of the given identity.
913 * The identity whose Sone to add
914 * @return The added or already existing Sone
916 public Sone addRemoteSone(Identity identity) {
917 if (identity == null) {
918 logger.log(Level.WARNING, "Given Identity is null!");
921 synchronized (remoteSones) {
922 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
923 boolean newSone = sone.getRequestUri() == null;
924 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
925 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
927 synchronized (knownSones) {
928 newSone = !knownSones.contains(sone.getId());
930 sone.setKnown(!newSone);
932 coreListenerManager.fireNewSoneFound(sone);
933 for (Sone localSone : getLocalSones()) {
934 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
935 followSone(localSone, sone);
940 soneDownloader.addSone(sone);
941 soneDownloaders.execute(new Runnable() {
944 @SuppressWarnings("synthetic-access")
946 soneDownloader.fetchSone(sone, sone.getRequestUri());
955 * Lets the given local Sone follow the Sone with the given ID.
958 * The local Sone that should follow another Sone
960 * The ID of the Sone to follow
962 public void followSone(Sone sone, String soneId) {
963 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
964 Sone followedSone = getSone(soneId, true);
965 if (followedSone == null) {
966 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
969 followSone(sone, getSone(soneId));
973 * Lets the given local Sone follow the other given Sone. If the given Sone
974 * was not followed by any local Sone before, this will mark all elements of
975 * the followed Sone as read that have been created before the current
979 * The local Sone that should follow the other Sone
980 * @param followedSone
981 * The Sone that should be followed
983 public void followSone(Sone sone, Sone followedSone) {
984 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
985 sone.addFriend(followedSone.getId());
986 synchronized (soneFollowingTimes) {
987 if (!soneFollowingTimes.containsKey(followedSone)) {
988 long now = System.currentTimeMillis();
989 soneFollowingTimes.put(followedSone, now);
990 for (Post post : followedSone.getPosts()) {
991 if (post.getTime() < now) {
995 for (PostReply reply : followedSone.getReplies()) {
996 if (reply.getTime() < now) {
997 markReplyKnown(reply);
1002 touchConfiguration();
1006 * Lets the given local Sone unfollow the Sone with the given ID.
1009 * The local Sone that should unfollow another Sone
1011 * The ID of the Sone being unfollowed
1013 public void unfollowSone(Sone sone, String soneId) {
1014 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1015 unfollowSone(sone, getSone(soneId, false));
1019 * Lets the given local Sone unfollow the other given Sone. If the given
1020 * local Sone is the last local Sone that followed the given Sone, its
1021 * following time will be removed.
1024 * The local Sone that should unfollow another Sone
1025 * @param unfollowedSone
1026 * The Sone being unfollowed
1028 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1029 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1030 sone.removeFriend(unfollowedSone.getId());
1031 boolean unfollowedSoneStillFollowed = false;
1032 for (Sone localSone : getLocalSones()) {
1033 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1035 if (!unfollowedSoneStillFollowed) {
1036 synchronized (soneFollowingTimes) {
1037 soneFollowingTimes.remove(unfollowedSone);
1040 touchConfiguration();
1044 * Sets the trust value of the given origin Sone for the target Sone.
1051 * The trust value (from {@code -100} to {@code 100})
1053 public void setTrust(Sone origin, Sone target, int trustValue) {
1054 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();
1055 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1059 * Removes any trust assignment for the given target Sone.
1066 public void removeTrust(Sone origin, Sone target) {
1067 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1068 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1072 * Assigns the configured positive trust value for the given target.
1079 public void trustSone(Sone origin, Sone target) {
1080 setTrust(origin, target, preferences.getPositiveTrust());
1084 * Assigns the configured negative trust value for the given target.
1091 public void distrustSone(Sone origin, Sone target) {
1092 setTrust(origin, target, preferences.getNegativeTrust());
1096 * Removes the trust assignment for the given target.
1103 public void untrustSone(Sone origin, Sone target) {
1104 removeTrust(origin, target);
1108 * Updates the stored Sone with the given Sone.
1113 public void updateSone(Sone sone) {
1114 updateSone(sone, false);
1118 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1119 * {@code true}, an older Sone than the current Sone can be given to restore
1123 * The Sone to update
1124 * @param soneRescueMode
1125 * {@code true} if the stored Sone should be updated regardless
1126 * of the age of the given Sone
1128 public void updateSone(Sone sone, boolean soneRescueMode) {
1129 if (hasSone(sone.getId())) {
1130 Sone storedSone = getSone(sone.getId());
1131 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1132 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1135 synchronized (posts) {
1136 if (!soneRescueMode) {
1137 for (Post post : storedSone.getPosts()) {
1138 posts.remove(post.getId());
1139 if (!sone.getPosts().contains(post)) {
1140 coreListenerManager.firePostRemoved(post);
1144 List<Post> storedPosts = storedSone.getPosts();
1145 synchronized (knownPosts) {
1146 for (Post post : sone.getPosts()) {
1147 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1148 if (!storedPosts.contains(post)) {
1149 if (post.getTime() < getSoneFollowingTime(sone)) {
1150 knownPosts.add(post.getId());
1151 } else if (!knownPosts.contains(post.getId())) {
1152 sone.setKnown(false);
1153 coreListenerManager.fireNewPostFound(post);
1156 posts.put(post.getId(), post);
1160 synchronized (replies) {
1161 if (!soneRescueMode) {
1162 for (PostReply reply : storedSone.getReplies()) {
1163 replies.remove(reply.getId());
1164 if (!sone.getReplies().contains(reply)) {
1165 coreListenerManager.fireReplyRemoved(reply);
1169 Set<PostReply> storedReplies = storedSone.getReplies();
1170 synchronized (knownReplies) {
1171 for (PostReply reply : sone.getReplies()) {
1172 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1173 if (!storedReplies.contains(reply)) {
1174 if (reply.getTime() < getSoneFollowingTime(sone)) {
1175 knownReplies.add(reply.getId());
1176 } else if (!knownReplies.contains(reply.getId())) {
1177 reply.setKnown(false);
1178 coreListenerManager.fireNewReplyFound(reply);
1181 replies.put(reply.getId(), reply);
1185 synchronized (albums) {
1186 synchronized (images) {
1187 for (Album album : storedSone.getAlbums()) {
1188 albums.remove(album.getId());
1189 for (Image image : album.getImages()) {
1190 images.remove(image.getId());
1193 for (Album album : sone.getAlbums()) {
1194 albums.put(album.getId(), album);
1195 for (Image image : album.getImages()) {
1196 images.put(image.getId(), image);
1201 synchronized (storedSone) {
1202 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1203 storedSone.setTime(sone.getTime());
1205 storedSone.setClient(sone.getClient());
1206 storedSone.setProfile(sone.getProfile());
1207 if (soneRescueMode) {
1208 for (Post post : sone.getPosts()) {
1209 storedSone.addPost(post);
1211 for (PostReply reply : sone.getReplies()) {
1212 storedSone.addReply(reply);
1214 for (String likedPostId : sone.getLikedPostIds()) {
1215 storedSone.addLikedPostId(likedPostId);
1217 for (String likedReplyId : sone.getLikedReplyIds()) {
1218 storedSone.addLikedReplyId(likedReplyId);
1220 for (Album album : sone.getAlbums()) {
1221 storedSone.addAlbum(album);
1224 storedSone.setPosts(sone.getPosts());
1225 storedSone.setReplies(sone.getReplies());
1226 storedSone.setLikePostIds(sone.getLikedPostIds());
1227 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1228 storedSone.setAlbums(sone.getAlbums());
1230 storedSone.setLatestEdition(sone.getLatestEdition());
1236 * Deletes the given Sone. This will remove the Sone from the
1237 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1238 * and remove the context from its identity.
1241 * The Sone to delete
1243 public void deleteSone(Sone sone) {
1244 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1245 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1248 synchronized (localSones) {
1249 if (!localSones.containsKey(sone.getId())) {
1250 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1253 localSones.remove(sone.getId());
1254 SoneInserter soneInserter = soneInserters.remove(sone);
1255 soneInserter.removeSoneInsertListener(this);
1256 soneInserter.stop();
1258 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1259 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1261 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1262 } catch (ConfigurationException ce1) {
1263 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1268 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1269 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1272 * The Sone to mark as known
1274 public void markSoneKnown(Sone sone) {
1275 if (!sone.isKnown()) {
1276 sone.setKnown(true);
1277 synchronized (knownSones) {
1278 knownSones.add(sone.getId());
1280 coreListenerManager.fireMarkSoneKnown(sone);
1281 touchConfiguration();
1286 * Loads and updates the given Sone from the configuration. If any error is
1287 * encountered, loading is aborted and the given Sone is not changed.
1290 * The Sone to load and update
1292 public void loadSone(Sone sone) {
1293 if (!isLocalSone(sone)) {
1294 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1298 /* initialize options. */
1299 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1300 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1301 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1302 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1303 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1304 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1307 String sonePrefix = "Sone/" + sone.getId();
1308 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1309 if (soneTime == null) {
1310 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1313 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1316 Profile profile = new Profile(sone);
1317 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1318 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1319 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1320 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1321 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1322 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1324 /* load profile fields. */
1326 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1327 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1328 if (fieldName == null) {
1331 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1332 profile.addField(fieldName).setValue(fieldValue);
1336 Set<Post> posts = new HashSet<Post>();
1338 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1339 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1340 if (postId == null) {
1343 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1344 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1345 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1346 if ((postTime == 0) || (postText == null)) {
1347 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1350 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1351 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1352 post.setRecipient(getSone(postRecipientId));
1358 Set<PostReply> replies = new HashSet<PostReply>();
1360 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1361 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1362 if (replyId == null) {
1365 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1366 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1367 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1368 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1369 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1372 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1375 /* load post likes. */
1376 Set<String> likedPostIds = new HashSet<String>();
1378 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1379 if (likedPostId == null) {
1382 likedPostIds.add(likedPostId);
1385 /* load reply likes. */
1386 Set<String> likedReplyIds = new HashSet<String>();
1388 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1389 if (likedReplyId == null) {
1392 likedReplyIds.add(likedReplyId);
1396 Set<String> friends = new HashSet<String>();
1398 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1399 if (friendId == null) {
1402 friends.add(friendId);
1406 List<Album> topLevelAlbums = new ArrayList<Album>();
1407 int albumCounter = 0;
1409 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1410 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1411 if (albumId == null) {
1414 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1415 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1416 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1417 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1418 if ((albumTitle == null) || (albumDescription == null)) {
1419 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1422 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1423 if (albumParentId != null) {
1424 Album parentAlbum = getAlbum(albumParentId, false);
1425 if (parentAlbum == null) {
1426 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1429 parentAlbum.addAlbum(album);
1431 if (!topLevelAlbums.contains(album)) {
1432 topLevelAlbums.add(album);
1438 int imageCounter = 0;
1440 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1441 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1442 if (imageId == null) {
1445 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1446 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1447 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1448 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1449 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1450 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1451 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1452 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1453 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1456 Album album = getAlbum(albumId, false);
1457 if (album == null) {
1458 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1461 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1462 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1463 album.addImage(image);
1467 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1468 if (avatarId != null) {
1469 profile.setAvatar(getImage(avatarId, false));
1473 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1474 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1475 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1476 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1477 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1478 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1480 /* if we’re still here, Sone was loaded successfully. */
1481 synchronized (sone) {
1482 sone.setTime(soneTime);
1483 sone.setProfile(profile);
1484 sone.setPosts(posts);
1485 sone.setReplies(replies);
1486 sone.setLikePostIds(likedPostIds);
1487 sone.setLikeReplyIds(likedReplyIds);
1488 for (String friendId : friends) {
1489 followSone(sone, friendId);
1491 sone.setAlbums(topLevelAlbums);
1492 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1494 synchronized (knownSones) {
1495 for (String friend : friends) {
1496 knownSones.add(friend);
1499 synchronized (knownPosts) {
1500 for (Post post : posts) {
1501 knownPosts.add(post.getId());
1504 synchronized (knownReplies) {
1505 for (PostReply reply : replies) {
1506 knownReplies.add(reply.getId());
1512 * Creates a new post.
1515 * The Sone that creates the post
1517 * The text of the post
1518 * @return The created post
1520 public Post createPost(Sone sone, String text) {
1521 return createPost(sone, System.currentTimeMillis(), text);
1525 * Creates a new post.
1528 * The Sone that creates the post
1530 * The time of the post
1532 * The text of the post
1533 * @return The created post
1535 public Post createPost(Sone sone, long time, String text) {
1536 return createPost(sone, null, time, text);
1540 * Creates a new post.
1543 * The Sone that creates the post
1545 * The recipient Sone, or {@code null} if this post does not have
1548 * The text of the post
1549 * @return The created post
1551 public Post createPost(Sone sone, Sone recipient, String text) {
1552 return createPost(sone, recipient, System.currentTimeMillis(), text);
1556 * Creates a new post.
1559 * The Sone that creates the post
1561 * The recipient Sone, or {@code null} if this post does not have
1564 * The time of the post
1566 * The text of the post
1567 * @return The created post
1569 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1570 if (!isLocalSone(sone)) {
1571 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1574 final Post post = new PostImpl(sone, time, text);
1575 if (recipient != null) {
1576 post.setRecipient(recipient);
1578 synchronized (posts) {
1579 posts.put(post.getId(), post);
1581 coreListenerManager.fireNewPostFound(post);
1583 touchConfiguration();
1584 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1591 markPostKnown(post);
1593 }, "Mark " + post + " read.");
1598 * Deletes the given post.
1601 * The post to delete
1603 public void deletePost(Post post) {
1604 if (!isLocalSone(post.getSone())) {
1605 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1608 post.getSone().removePost(post);
1609 synchronized (posts) {
1610 posts.remove(post.getId());
1612 coreListenerManager.firePostRemoved(post);
1613 markPostKnown(post);
1614 touchConfiguration();
1618 * Marks the given post as known, if it is currently not a known post
1619 * (according to {@link Post#isKnown()}).
1622 * The post to mark as known
1624 public void markPostKnown(Post post) {
1625 post.setKnown(true);
1626 synchronized (knownPosts) {
1627 coreListenerManager.fireMarkPostKnown(post);
1628 if (knownPosts.add(post.getId())) {
1629 touchConfiguration();
1632 for (PostReply reply : getReplies(post)) {
1633 markReplyKnown(reply);
1638 * Bookmarks the given post.
1641 * The post to bookmark
1643 public void bookmark(Post post) {
1644 bookmarkPost(post.getId());
1648 * Bookmarks the post with the given ID.
1651 * The ID of the post to bookmark
1653 public void bookmarkPost(String id) {
1654 synchronized (bookmarkedPosts) {
1655 bookmarkedPosts.add(id);
1660 * Removes the given post from the bookmarks.
1663 * The post to unbookmark
1665 public void unbookmark(Post post) {
1666 unbookmarkPost(post.getId());
1670 * Removes the post with the given ID from the bookmarks.
1673 * The ID of the post to unbookmark
1675 public void unbookmarkPost(String id) {
1676 synchronized (bookmarkedPosts) {
1677 bookmarkedPosts.remove(id);
1682 * Creates a new reply.
1685 * The Sone that creates the reply
1687 * The post that this reply refers to
1689 * The text of the reply
1690 * @return The created reply
1692 public PostReply createReply(Sone sone, Post post, String text) {
1693 return createReply(sone, post, System.currentTimeMillis(), text);
1697 * Creates a new reply.
1700 * The Sone that creates the reply
1702 * The post that this reply refers to
1704 * The time of the reply
1706 * The text of the reply
1707 * @return The created reply
1709 public PostReply createReply(Sone sone, Post post, long time, String text) {
1710 if (!isLocalSone(sone)) {
1711 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1714 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1715 synchronized (replies) {
1716 replies.put(reply.getId(), reply);
1718 synchronized (knownReplies) {
1719 coreListenerManager.fireNewReplyFound(reply);
1721 sone.addReply(reply);
1722 touchConfiguration();
1723 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1730 markReplyKnown(reply);
1732 }, "Mark " + reply + " read.");
1737 * Deletes the given reply.
1740 * The reply to delete
1742 public void deleteReply(PostReply reply) {
1743 Sone sone = reply.getSone();
1744 if (!isLocalSone(sone)) {
1745 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1748 synchronized (replies) {
1749 replies.remove(reply.getId());
1751 synchronized (knownReplies) {
1752 markReplyKnown(reply);
1753 knownReplies.remove(reply.getId());
1755 sone.removeReply(reply);
1756 touchConfiguration();
1760 * Marks the given reply as known, if it is currently not a known reply
1761 * (according to {@link Reply#isKnown()}).
1764 * The reply to mark as known
1766 public void markReplyKnown(PostReply reply) {
1767 reply.setKnown(true);
1768 synchronized (knownReplies) {
1769 coreListenerManager.fireMarkReplyKnown(reply);
1770 if (knownReplies.add(reply.getId())) {
1771 touchConfiguration();
1777 * Creates a new top-level album for the given Sone.
1780 * The Sone to create the album for
1781 * @return The new album
1783 public Album createAlbum(Sone sone) {
1784 return createAlbum(sone, null);
1788 * Creates a new album for the given Sone.
1791 * The Sone to create the album for
1793 * The parent of the album (may be {@code null} to create a
1795 * @return The new album
1797 public Album createAlbum(Sone sone, Album parent) {
1798 Album album = new Album();
1799 synchronized (albums) {
1800 albums.put(album.getId(), album);
1802 album.setSone(sone);
1803 if (parent != null) {
1804 parent.addAlbum(album);
1806 sone.addAlbum(album);
1812 * Deletes the given album. The owner of the album has to be a local Sone,
1813 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1816 * The album to remove
1818 public void deleteAlbum(Album album) {
1819 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1820 if (!album.isEmpty()) {
1823 if (album.getParent() == null) {
1824 album.getSone().removeAlbum(album);
1826 album.getParent().removeAlbum(album);
1828 synchronized (albums) {
1829 albums.remove(album.getId());
1831 touchConfiguration();
1835 * Creates a new image.
1838 * The Sone creating the image
1840 * The album the image will be inserted into
1841 * @param temporaryImage
1842 * The temporary image to create the image from
1843 * @return The newly created image
1845 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1846 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();
1847 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1848 album.addImage(image);
1849 synchronized (images) {
1850 images.put(image.getId(), image);
1852 imageInserter.insertImage(temporaryImage, image);
1857 * Deletes the given image. This method will also delete a matching
1860 * @see #deleteTemporaryImage(TemporaryImage)
1862 * The image to delete
1864 public void deleteImage(Image image) {
1865 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1866 deleteTemporaryImage(image.getId());
1867 image.getAlbum().removeImage(image);
1868 synchronized (images) {
1869 images.remove(image.getId());
1871 touchConfiguration();
1875 * Creates a new temporary image.
1878 * The MIME type of the temporary image
1880 * The encoded data of the image
1881 * @return The temporary image
1883 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1884 TemporaryImage temporaryImage = new TemporaryImage();
1885 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1886 synchronized (temporaryImages) {
1887 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1889 return temporaryImage;
1893 * Deletes the given temporary image.
1895 * @param temporaryImage
1896 * The temporary image to delete
1898 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1899 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1900 deleteTemporaryImage(temporaryImage.getId());
1904 * Deletes the temporary image with the given ID.
1907 * The ID of the temporary image to delete
1909 public void deleteTemporaryImage(String imageId) {
1910 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1911 synchronized (temporaryImages) {
1912 temporaryImages.remove(imageId);
1914 Image image = getImage(imageId, false);
1915 if (image != null) {
1916 imageInserter.cancelImageInsert(image);
1921 * Notifies the core that the configuration, either of the core or of a
1922 * single local Sone, has changed, and that the configuration should be
1925 public void touchConfiguration() {
1926 lastConfigurationUpdate = System.currentTimeMillis();
1937 public void serviceStart() {
1938 loadConfiguration();
1939 updateChecker.addUpdateListener(this);
1940 updateChecker.start();
1941 webOfTrustUpdater.start();
1948 public void serviceRun() {
1949 long lastSaved = System.currentTimeMillis();
1950 while (!shouldStop()) {
1952 long now = System.currentTimeMillis();
1953 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1954 for (Sone localSone : getLocalSones()) {
1955 saveSone(localSone);
1957 saveConfiguration();
1967 public void serviceStop() {
1968 synchronized (localSones) {
1969 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1970 soneInserter.getValue().removeSoneInsertListener(this);
1971 soneInserter.getValue().stop();
1972 saveSone(soneInserter.getKey());
1975 saveConfiguration();
1976 webOfTrustUpdater.stop();
1977 updateChecker.stop();
1978 updateChecker.removeUpdateListener(this);
1979 soneDownloader.stop();
1987 * Saves the given Sone. This will persist all local settings for the given
1988 * Sone, such as the friends list and similar, private options.
1993 private synchronized void saveSone(Sone sone) {
1994 if (!isLocalSone(sone)) {
1995 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1998 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1999 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2003 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2005 /* save Sone into configuration. */
2006 String sonePrefix = "Sone/" + sone.getId();
2007 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2008 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2011 Profile profile = sone.getProfile();
2012 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2013 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2014 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2015 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2016 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2017 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2018 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2020 /* save profile fields. */
2021 int fieldCounter = 0;
2022 for (Field profileField : profile.getFields()) {
2023 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2024 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2025 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2027 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2030 int postCounter = 0;
2031 for (Post post : sone.getPosts()) {
2032 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2033 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2034 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2035 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2036 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2038 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2041 int replyCounter = 0;
2042 for (PostReply reply : sone.getReplies()) {
2043 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2044 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2045 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2046 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2047 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2049 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2051 /* save post likes. */
2052 int postLikeCounter = 0;
2053 for (String postId : sone.getLikedPostIds()) {
2054 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2056 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2058 /* save reply likes. */
2059 int replyLikeCounter = 0;
2060 for (String replyId : sone.getLikedReplyIds()) {
2061 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2063 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2066 int friendCounter = 0;
2067 for (String friendId : sone.getFriends()) {
2068 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2070 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2072 /* save albums. first, collect in a flat structure, top-level first. */
2073 List<Album> albums = sone.getAllAlbums();
2075 int albumCounter = 0;
2076 for (Album album : albums) {
2077 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2078 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2079 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2080 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2081 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2082 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2084 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2087 int imageCounter = 0;
2088 for (Album album : albums) {
2089 for (Image image : album.getImages()) {
2090 if (!image.isInserted()) {
2093 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2094 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2095 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2096 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2097 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2098 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2099 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2100 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2101 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2104 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2107 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2108 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2109 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2110 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2111 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2112 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2114 configuration.save();
2116 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2118 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2119 } catch (ConfigurationException ce1) {
2120 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2125 * Saves the current options.
2127 private void saveConfiguration() {
2128 synchronized (configuration) {
2129 if (storingConfiguration) {
2130 logger.log(Level.FINE, "Already storing configuration…");
2133 storingConfiguration = true;
2136 /* store the options first. */
2138 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2139 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2140 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2141 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2142 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2143 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2144 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2145 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2146 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2147 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2148 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2149 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2151 /* save known Sones. */
2152 int soneCounter = 0;
2153 synchronized (knownSones) {
2154 for (String knownSoneId : knownSones) {
2155 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2157 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2160 /* save Sone following times. */
2162 synchronized (soneFollowingTimes) {
2163 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2164 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2165 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2168 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2171 /* save known posts. */
2172 int postCounter = 0;
2173 synchronized (knownPosts) {
2174 for (String knownPostId : knownPosts) {
2175 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2177 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2180 /* save known replies. */
2181 int replyCounter = 0;
2182 synchronized (knownReplies) {
2183 for (String knownReplyId : knownReplies) {
2184 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2186 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2189 /* save bookmarked posts. */
2190 int bookmarkedPostCounter = 0;
2191 synchronized (bookmarkedPosts) {
2192 for (String bookmarkedPostId : bookmarkedPosts) {
2193 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2196 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2199 configuration.save();
2201 } catch (ConfigurationException ce1) {
2202 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2204 synchronized (configuration) {
2205 storingConfiguration = false;
2211 * Loads the configuration.
2213 @SuppressWarnings("unchecked")
2214 private void loadConfiguration() {
2215 /* create options. */
2216 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2219 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2220 SoneInserter.setInsertionDelay(newValue);
2224 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2225 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2226 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2227 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2228 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2229 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2230 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2231 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2232 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2235 @SuppressWarnings("synthetic-access")
2236 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2237 fcpInterface.setActive(newValue);
2240 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2243 @SuppressWarnings("synthetic-access")
2244 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2245 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2250 loadConfigurationValue("InsertionDelay");
2251 loadConfigurationValue("PostsPerPage");
2252 loadConfigurationValue("ImagesPerPage");
2253 loadConfigurationValue("CharactersPerPost");
2254 loadConfigurationValue("PostCutOffLength");
2255 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2256 loadConfigurationValue("PositiveTrust");
2257 loadConfigurationValue("NegativeTrust");
2258 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2259 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2260 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2262 /* load known Sones. */
2263 int soneCounter = 0;
2265 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2266 if (knownSoneId == null) {
2269 synchronized (knownSones) {
2270 knownSones.add(knownSoneId);
2274 /* load Sone following times. */
2277 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2278 if (soneId == null) {
2281 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2282 Sone followedSone = getSone(soneId);
2283 if (followedSone == null) {
2284 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2286 synchronized (soneFollowingTimes) {
2287 soneFollowingTimes.put(getSone(soneId), time);
2293 /* load known posts. */
2294 int postCounter = 0;
2296 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2297 if (knownPostId == null) {
2300 synchronized (knownPosts) {
2301 knownPosts.add(knownPostId);
2305 /* load known replies. */
2306 int replyCounter = 0;
2308 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2309 if (knownReplyId == null) {
2312 synchronized (knownReplies) {
2313 knownReplies.add(knownReplyId);
2317 /* load bookmarked posts. */
2318 int bookmarkedPostCounter = 0;
2320 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2321 if (bookmarkedPostId == null) {
2324 synchronized (bookmarkedPosts) {
2325 bookmarkedPosts.add(bookmarkedPostId);
2332 * Loads an {@link Integer} configuration value for the option with the
2333 * given name, logging validation failures.
2336 * The name of the option to load
2338 private void loadConfigurationValue(String optionName) {
2340 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2341 } catch (IllegalArgumentException iae1) {
2342 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2347 * Generate a Sone URI from the given URI and latest edition.
2350 * The URI to derive the Sone URI from
2351 * @return The derived URI
2353 private static FreenetURI getSoneUri(String uriString) {
2355 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2357 } catch (MalformedURLException mue1) {
2358 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2364 // INTERFACE IdentityListener
2371 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2372 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2373 if (ownIdentity.hasContext("Sone")) {
2374 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2375 addLocalSone(ownIdentity);
2383 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2384 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2385 trustedIdentities.remove(ownIdentity);
2392 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2393 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2394 trustedIdentities.get(ownIdentity).add(identity);
2395 addRemoteSone(identity);
2402 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2403 new Thread(new Runnable() {
2406 @SuppressWarnings("synthetic-access")
2408 Sone sone = getRemoteSone(identity.getId(), false);
2409 sone.setIdentity(identity);
2410 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2411 soneDownloader.addSone(sone);
2412 soneDownloader.fetchSone(sone);
2421 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2422 trustedIdentities.get(ownIdentity).remove(identity);
2423 boolean foundIdentity = false;
2424 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2425 if (trustedIdentity.getKey().equals(ownIdentity)) {
2428 if (trustedIdentity.getValue().contains(identity)) {
2429 foundIdentity = true;
2432 if (foundIdentity) {
2433 /* some local identity still trusts this identity, don’t remove. */
2436 Sone sone = getSone(identity.getId(), false);
2438 /* TODO - we don’t have the Sone anymore. should this happen? */
2441 synchronized (posts) {
2442 synchronized (knownPosts) {
2443 for (Post post : sone.getPosts()) {
2444 posts.remove(post.getId());
2445 coreListenerManager.firePostRemoved(post);
2449 synchronized (replies) {
2450 synchronized (knownReplies) {
2451 for (PostReply reply : sone.getReplies()) {
2452 replies.remove(reply.getId());
2453 coreListenerManager.fireReplyRemoved(reply);
2457 synchronized (remoteSones) {
2458 remoteSones.remove(identity.getId());
2460 coreListenerManager.fireSoneRemoved(sone);
2464 // INTERFACE UpdateListener
2471 public void updateFound(Version version, long releaseTime, long latestEdition) {
2472 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2476 // INTERFACE ImageInsertListener
2483 public void insertStarted(Sone sone) {
2484 coreListenerManager.fireSoneInserting(sone);
2491 public void insertFinished(Sone sone, long insertDuration) {
2492 coreListenerManager.fireSoneInserted(sone, insertDuration);
2499 public void insertAborted(Sone sone, Throwable cause) {
2500 coreListenerManager.fireSoneInsertAborted(sone, cause);
2504 // SONEINSERTLISTENER METHODS
2511 public void imageInsertStarted(Image image) {
2512 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2513 coreListenerManager.fireImageInsertStarted(image);
2520 public void imageInsertAborted(Image image) {
2521 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2522 coreListenerManager.fireImageInsertAborted(image);
2529 public void imageInsertFinished(Image image, FreenetURI key) {
2530 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2531 image.setKey(key.toString());
2532 deleteTemporaryImage(image.getId());
2533 touchConfiguration();
2534 coreListenerManager.fireImageInsertFinished(image);
2541 public void imageInsertFailed(Image image, Throwable cause) {
2542 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2543 coreListenerManager.fireImageInsertFailed(image, cause);
2547 * Convenience interface for external classes that want to access the core’s
2550 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2552 public static class Preferences {
2554 /** The wrapped options. */
2555 private final Options options;
2558 * Creates a new preferences object wrapped around the given options.
2561 * The options to wrap
2563 public Preferences(Options options) {
2564 this.options = options;
2568 * Returns the insertion delay.
2570 * @return The insertion delay
2572 public int getInsertionDelay() {
2573 return options.getIntegerOption("InsertionDelay").get();
2577 * Validates the given insertion delay.
2579 * @param insertionDelay
2580 * The insertion delay to validate
2581 * @return {@code true} if the given insertion delay was valid,
2582 * {@code false} otherwise
2584 public boolean validateInsertionDelay(Integer insertionDelay) {
2585 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2589 * Sets the insertion delay
2591 * @param insertionDelay
2592 * The new insertion delay, or {@code null} to restore it to
2594 * @return This preferences
2596 public Preferences setInsertionDelay(Integer insertionDelay) {
2597 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2602 * Returns the number of posts to show per page.
2604 * @return The number of posts to show per page
2606 public int getPostsPerPage() {
2607 return options.getIntegerOption("PostsPerPage").get();
2611 * Validates the number of posts per page.
2613 * @param postsPerPage
2614 * The number of posts per page
2615 * @return {@code true} if the number of posts per page was valid,
2616 * {@code false} otherwise
2618 public boolean validatePostsPerPage(Integer postsPerPage) {
2619 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2623 * Sets the number of posts to show per page.
2625 * @param postsPerPage
2626 * The number of posts to show per page
2627 * @return This preferences object
2629 public Preferences setPostsPerPage(Integer postsPerPage) {
2630 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2635 * Returns the number of images to show per page.
2637 * @return The number of images to show per page
2639 public int getImagesPerPage() {
2640 return options.getIntegerOption("ImagesPerPage").get();
2644 * Validates the number of images per page.
2646 * @param imagesPerPage
2647 * The number of images per page
2648 * @return {@code true} if the number of images per page was valid,
2649 * {@code false} otherwise
2651 public boolean validateImagesPerPage(Integer imagesPerPage) {
2652 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2656 * Sets the number of images per page.
2658 * @param imagesPerPage
2659 * The number of images per page
2660 * @return This preferences object
2662 public Preferences setImagesPerPage(Integer imagesPerPage) {
2663 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2668 * Returns the number of characters per post, or <code>-1</code> if the
2669 * posts should not be cut off.
2671 * @return The numbers of characters per post
2673 public int getCharactersPerPost() {
2674 return options.getIntegerOption("CharactersPerPost").get();
2678 * Validates the number of characters per post.
2680 * @param charactersPerPost
2681 * The number of characters per post
2682 * @return {@code true} if the number of characters per post was valid,
2683 * {@code false} otherwise
2685 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2686 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2690 * Sets the number of characters per post.
2692 * @param charactersPerPost
2693 * The number of characters per post, or <code>-1</code> to
2694 * not cut off the posts
2695 * @return This preferences objects
2697 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2698 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2703 * Returns the number of characters the shortened post should have.
2705 * @return The number of characters of the snippet
2707 public int getPostCutOffLength() {
2708 return options.getIntegerOption("PostCutOffLength").get();
2712 * Validates the number of characters after which to cut off the post.
2714 * @param postCutOffLength
2715 * The number of characters of the snippet
2716 * @return {@code true} if the number of characters of the snippet is
2717 * valid, {@code false} otherwise
2719 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2720 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2724 * Sets the number of characters the shortened post should have.
2726 * @param postCutOffLength
2727 * The number of characters of the snippet
2728 * @return This preferences
2730 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2731 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2736 * Returns whether Sone requires full access to be even visible.
2738 * @return {@code true} if Sone requires full access, {@code false}
2741 public boolean isRequireFullAccess() {
2742 return options.getBooleanOption("RequireFullAccess").get();
2746 * Sets whether Sone requires full access to be even visible.
2748 * @param requireFullAccess
2749 * {@code true} if Sone requires full access, {@code false}
2752 public void setRequireFullAccess(Boolean requireFullAccess) {
2753 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2757 * Returns the positive trust.
2759 * @return The positive trust
2761 public int getPositiveTrust() {
2762 return options.getIntegerOption("PositiveTrust").get();
2766 * Validates the positive trust.
2768 * @param positiveTrust
2769 * The positive trust to validate
2770 * @return {@code true} if the positive trust was valid, {@code false}
2773 public boolean validatePositiveTrust(Integer positiveTrust) {
2774 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2778 * Sets the positive trust.
2780 * @param positiveTrust
2781 * The new positive trust, or {@code null} to restore it to
2783 * @return This preferences
2785 public Preferences setPositiveTrust(Integer positiveTrust) {
2786 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2791 * Returns the negative trust.
2793 * @return The negative trust
2795 public int getNegativeTrust() {
2796 return options.getIntegerOption("NegativeTrust").get();
2800 * Validates the negative trust.
2802 * @param negativeTrust
2803 * The negative trust to validate
2804 * @return {@code true} if the negative trust was valid, {@code false}
2807 public boolean validateNegativeTrust(Integer negativeTrust) {
2808 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2812 * Sets the negative trust.
2814 * @param negativeTrust
2815 * The negative trust, or {@code null} to restore it to the
2817 * @return The preferences
2819 public Preferences setNegativeTrust(Integer negativeTrust) {
2820 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2825 * Returns the trust comment. This is the comment that is set in the web
2826 * of trust when a trust value is assigned to an identity.
2828 * @return The trust comment
2830 public String getTrustComment() {
2831 return options.getStringOption("TrustComment").get();
2835 * Sets the trust comment.
2837 * @param trustComment
2838 * The trust comment, or {@code null} to restore it to the
2840 * @return This preferences
2842 public Preferences setTrustComment(String trustComment) {
2843 options.getStringOption("TrustComment").set(trustComment);
2848 * Returns whether the {@link FcpInterface FCP interface} is currently
2851 * @see FcpInterface#setActive(boolean)
2852 * @return {@code true} if the FCP interface is currently active,
2853 * {@code false} otherwise
2855 public boolean isFcpInterfaceActive() {
2856 return options.getBooleanOption("ActivateFcpInterface").get();
2860 * Sets whether the {@link FcpInterface FCP interface} is currently
2863 * @see FcpInterface#setActive(boolean)
2864 * @param fcpInterfaceActive
2865 * {@code true} to activate the FCP interface, {@code false}
2866 * to deactivate the FCP interface
2867 * @return This preferences object
2869 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2870 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2875 * Returns the action level for which full access to the FCP interface
2878 * @return The action level for which full access to the FCP interface
2881 public FullAccessRequired getFcpFullAccessRequired() {
2882 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2886 * Sets the action level for which full access to the FCP interface is
2889 * @param fcpFullAccessRequired
2891 * @return This preferences
2893 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2894 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);