2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.data.Album;
39 import net.pterodactylus.sone.data.Client;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Profile;
44 import net.pterodactylus.sone.data.Profile.Field;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.data.TemporaryImage;
50 import net.pterodactylus.sone.data.impl.PostImpl;
51 import net.pterodactylus.sone.fcp.FcpInterface;
52 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
53 import net.pterodactylus.sone.freenet.wot.Identity;
54 import net.pterodactylus.sone.freenet.wot.IdentityListener;
55 import net.pterodactylus.sone.freenet.wot.IdentityManager;
56 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
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.NamedThreadFactory;
64 import net.pterodactylus.util.thread.Ticker;
65 import net.pterodactylus.util.validation.EqualityValidator;
66 import net.pterodactylus.util.validation.IntegerRangeValidator;
67 import net.pterodactylus.util.validation.OrValidator;
68 import net.pterodactylus.util.validation.Validation;
69 import net.pterodactylus.util.version.Version;
71 import com.google.common.base.Predicate;
72 import com.google.common.collect.Collections2;
73 import freenet.keys.FreenetURI;
78 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
80 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
83 private static final Logger logger = Logging.getLogger(Core.class);
85 /** The start time. */
86 private final long startupTime = System.currentTimeMillis();
89 private final Options options = new Options();
91 /** The preferences. */
92 private final Preferences preferences = new Preferences(options);
94 /** The core listener manager. */
95 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
97 /** The configuration. */
98 private Configuration configuration;
100 /** Whether we’re currently saving the configuration. */
101 private boolean storingConfiguration = false;
103 /** The identity manager. */
104 private final IdentityManager identityManager;
106 /** Interface to freenet. */
107 private final FreenetInterface freenetInterface;
109 /** The Sone downloader. */
110 private final SoneDownloader soneDownloader;
112 /** The image inserter. */
113 private final ImageInserter imageInserter;
115 /** Sone downloader thread-pool. */
116 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
118 /** The update checker. */
119 private final UpdateChecker updateChecker;
121 /** The trust updater. */
122 private final WebOfTrustUpdater webOfTrustUpdater;
124 /** The FCP interface. */
125 private volatile FcpInterface fcpInterface;
127 /** The times Sones were followed. */
128 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
130 /** Locked local Sones. */
131 /* synchronize on itself. */
132 private final Set<Sone> lockedSones = new HashSet<Sone>();
134 /** Sone inserters. */
135 /* synchronize access on this on sones. */
136 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
138 /** Sone rescuers. */
139 /* synchronize access on this on sones. */
140 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
143 /* synchronize access on this on itself. */
144 private final Map<String, Sone> sones = new HashMap<String, Sone>();
146 /** All known Sones. */
147 private final Set<String> knownSones = new HashSet<String>();
150 private final Map<String, Post> posts = new HashMap<String, Post>();
152 /** All known posts. */
153 private final Set<String> knownPosts = new HashSet<String>();
156 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
158 /** All known replies. */
159 private final Set<String> knownReplies = new HashSet<String>();
161 /** All bookmarked posts. */
162 /* synchronize access on itself. */
163 private final Set<String> bookmarkedPosts = new HashSet<String>();
165 /** Trusted identities, sorted by own identities. */
166 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
168 /** All known albums. */
169 private final Map<String, Album> albums = new HashMap<String, Album>();
171 /** All known images. */
172 private final Map<String, Image> images = new HashMap<String, Image>();
174 /** All temporary images. */
175 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
177 /** Ticker for threads that mark own elements as known. */
178 private final Ticker localElementTicker = new Ticker();
180 /** The time the configuration was last touched. */
181 private volatile long lastConfigurationUpdate;
184 * Creates a new core.
186 * @param configuration
187 * The configuration of the core
188 * @param freenetInterface
189 * The freenet interface
190 * @param identityManager
191 * The identity manager
192 * @param webOfTrustUpdater
193 * The WebOfTrust updater
195 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater) {
197 this.configuration = configuration;
198 this.freenetInterface = freenetInterface;
199 this.identityManager = identityManager;
200 this.soneDownloader = new SoneDownloader(this, freenetInterface);
201 this.imageInserter = new ImageInserter(this, freenetInterface);
202 this.updateChecker = new UpdateChecker(freenetInterface);
203 this.webOfTrustUpdater = webOfTrustUpdater;
207 // LISTENER MANAGEMENT
211 * Adds a new core listener.
213 * @param coreListener
214 * The listener to add
216 public void addCoreListener(CoreListener coreListener) {
217 coreListenerManager.addListener(coreListener);
221 * Removes a core listener.
223 * @param coreListener
224 * The listener to remove
226 public void removeCoreListener(CoreListener coreListener) {
227 coreListenerManager.removeListener(coreListener);
235 * Returns the time Sone was started.
237 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
239 public long getStartupTime() {
244 * Sets the configuration to use. This will automatically save the current
245 * configuration to the given configuration.
247 * @param configuration
248 * The new configuration to use
250 public void setConfiguration(Configuration configuration) {
251 this.configuration = configuration;
252 touchConfiguration();
256 * Returns the options used by the core.
258 * @return The options of the core
260 public Preferences getPreferences() {
265 * Returns the identity manager used by the core.
267 * @return The identity manager
269 public IdentityManager getIdentityManager() {
270 return identityManager;
274 * Returns the update checker.
276 * @return The update checker
278 public UpdateChecker getUpdateChecker() {
279 return updateChecker;
283 * Sets the FCP interface to use.
285 * @param fcpInterface
286 * The FCP interface to use
288 public void setFcpInterface(FcpInterface fcpInterface) {
289 this.fcpInterface = fcpInterface;
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
301 synchronized (sones) {
302 SoneRescuer soneRescuer = soneRescuers.get(sone);
303 if (soneRescuer == null) {
304 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
305 soneRescuers.put(sone, soneRescuer);
313 * Returns whether the given Sone is currently locked.
317 * @return {@code true} if the Sone is locked, {@code false} if it is not
319 public boolean isLocked(Sone sone) {
320 synchronized (lockedSones) {
321 return lockedSones.contains(sone);
326 * Returns all Sones, remote and local.
330 public Set<Sone> getSones() {
331 return new HashSet<Sone>(sones.values());
335 * Returns the Sone with the given ID, regardless whether it’s local or
339 * The ID of the Sone to get
340 * @return The Sone with the given ID, or {@code null} if there is no such
343 public Sone getSone(String id) {
344 return getSone(id, true);
348 * Returns the Sone with the given ID, regardless whether it’s local or
352 * The ID of the Sone to get
354 * {@code true} to create a new Sone if none exists,
355 * {@code false} to return {@code null} if a Sone with the given
357 * @return The Sone with the given ID, or {@code null} if there is no such
361 public Sone getSone(String id, boolean create) {
362 synchronized (sones) {
363 if (!sones.containsKey(id)) {
364 Sone sone = new Sone(id, false);
367 return sones.get(id);
372 * Checks whether the core knows a Sone with the given ID.
376 * @return {@code true} if there is a Sone with the given ID, {@code false}
379 public boolean hasSone(String id) {
380 synchronized (sones) {
381 return sones.containsKey(id);
386 * Returns all local Sones.
388 * @return All local Sones
390 public Collection<Sone> getLocalSones() {
391 synchronized (sones) {
392 return Collections2.filter(sones.values(), new Predicate<Sone>() {
395 public boolean apply(Sone sone) {
396 return sone.isLocal();
403 * Returns the local Sone with the given ID, optionally creating a new Sone.
408 * {@code true} to create a new Sone if none exists,
409 * {@code false} to return null if none exists
410 * @return The Sone with the given ID, or {@code null}
412 public Sone getLocalSone(String id, boolean create) {
413 synchronized (sones) {
414 Sone sone = sones.get(id);
415 if ((sone == null) && create) {
416 sone = new Sone(id, true);
419 if (!sone.isLocal()) {
420 sone = new Sone(id, true);
428 * Returns all remote Sones.
430 * @return All remote Sones
432 public Collection<Sone> getRemoteSones() {
433 synchronized (sones) {
434 return Collections2.filter(sones.values(), new Predicate<Sone>() {
437 public boolean apply(Sone sone) {
438 return !sone.isLocal();
445 * Returns the remote Sone with the given ID.
448 * The ID of the remote Sone to get
450 * {@code true} to always create a Sone, {@code false} to return
451 * {@code null} if no Sone with the given ID exists
452 * @return The Sone with the given ID
454 public Sone getRemoteSone(String id, boolean create) {
455 synchronized (sones) {
456 Sone sone = sones.get(id);
457 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
458 sone = new Sone(id, false);
466 * Returns whether the given Sone has been modified.
469 * The Sone to check for modifications
470 * @return {@code true} if a modification has been detected in the Sone,
471 * {@code false} otherwise
473 public boolean isModifiedSone(Sone sone) {
474 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
478 * Returns the time when the given was first followed by any local Sone.
481 * The Sone to get the time for
482 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
483 * been followed, or {@link Long#MAX_VALUE}
485 public long getSoneFollowingTime(Sone sone) {
486 synchronized (soneFollowingTimes) {
487 if (soneFollowingTimes.containsKey(sone)) {
488 return soneFollowingTimes.get(sone);
490 return Long.MAX_VALUE;
495 * Returns whether the target Sone is trusted by the origin Sone.
501 * @return {@code true} if the target Sone is trusted by the origin Sone
503 public boolean isSoneTrusted(Sone origin, Sone target) {
504 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
505 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
509 * Returns the post with the given ID.
512 * The ID of the post to get
513 * @return The post with the given ID, or a new post with the given ID
515 public Post getPost(String postId) {
516 return getPost(postId, true);
520 * Returns the post with the given ID, optionally creating a new post.
523 * The ID of the post to get
525 * {@code true} it create a new post if no post with the given ID
526 * exists, {@code false} to return {@code null}
527 * @return The post, or {@code null} if there is no such post
530 public Post getPost(String postId, boolean create) {
531 synchronized (posts) {
532 Post post = posts.get(postId);
533 if ((post == null) && create) {
534 post = new PostImpl(postId);
535 posts.put(postId, post);
542 * Returns all posts that have the given Sone as recipient.
544 * @see Post#getRecipient()
546 * The recipient of the posts
547 * @return All posts that have the given Sone as recipient
549 public Set<Post> getDirectedPosts(Sone recipient) {
550 Validation.begin().isNotNull("Recipient", recipient).check();
551 Set<Post> directedPosts = new HashSet<Post>();
552 synchronized (posts) {
553 for (Post post : posts.values()) {
554 if (recipient.equals(post.getRecipient())) {
555 directedPosts.add(post);
559 return directedPosts;
563 * Returns the reply with the given ID. If there is no reply with the given
564 * ID yet, a new one is created, unless {@code create} is false in which
565 * case {@code null} is returned.
568 * The ID of the reply to get
570 * {@code true} to always return a {@link Reply}, {@code false}
571 * to return {@code null} if no reply can be found
572 * @return The reply, or {@code null} if there is no such reply
574 public PostReply getPostReply(String replyId, boolean create) {
575 synchronized (replies) {
576 PostReply reply = replies.get(replyId);
577 if (create && (reply == null)) {
578 reply = new PostReply(replyId);
579 replies.put(replyId, reply);
586 * Returns all replies for the given post, order ascending by time.
589 * The post to get all replies for
590 * @return All replies for the given post
592 public List<PostReply> getReplies(Post post) {
593 Set<Sone> sones = getSones();
594 List<PostReply> replies = new ArrayList<PostReply>();
595 for (Sone sone : sones) {
596 for (PostReply reply : sone.getReplies()) {
597 if (reply.getPost().equals(post)) {
602 Collections.sort(replies, Reply.TIME_COMPARATOR);
607 * Returns all Sones that have liked the given post.
610 * The post to get the liking Sones for
611 * @return The Sones that like the given post
613 public Set<Sone> getLikes(Post post) {
614 Set<Sone> sones = new HashSet<Sone>();
615 for (Sone sone : getSones()) {
616 if (sone.getLikedPostIds().contains(post.getId())) {
624 * Returns all Sones that have liked the given reply.
627 * The reply to get the liking Sones for
628 * @return The Sones that like the given reply
630 public Set<Sone> getLikes(PostReply reply) {
631 Set<Sone> sones = new HashSet<Sone>();
632 for (Sone sone : getSones()) {
633 if (sone.getLikedReplyIds().contains(reply.getId())) {
641 * Returns whether the given post is bookmarked.
645 * @return {@code true} if the given post is bookmarked, {@code false}
648 public boolean isBookmarked(Post post) {
649 return isPostBookmarked(post.getId());
653 * Returns whether the post with the given ID is bookmarked.
656 * The ID of the post to check
657 * @return {@code true} if the post with the given ID is bookmarked,
658 * {@code false} otherwise
660 public boolean isPostBookmarked(String id) {
661 synchronized (bookmarkedPosts) {
662 return bookmarkedPosts.contains(id);
667 * Returns all currently known bookmarked posts.
669 * @return All bookmarked posts
671 public Set<Post> getBookmarkedPosts() {
672 Set<Post> posts = new HashSet<Post>();
673 synchronized (bookmarkedPosts) {
674 for (String bookmarkedPostId : bookmarkedPosts) {
675 Post post = getPost(bookmarkedPostId, false);
685 * Returns the album with the given ID, creating a new album if no album
686 * with the given ID can be found.
689 * The ID of the album
690 * @return The album with the given ID
692 public Album getAlbum(String albumId) {
693 return getAlbum(albumId, true);
697 * Returns the album with the given ID, optionally creating a new album if
698 * an album with the given ID can not be found.
701 * The ID of the album
703 * {@code true} to create a new album if none exists for the
705 * @return The album with the given ID, or {@code null} if no album with the
706 * given ID exists and {@code create} is {@code false}
708 public Album getAlbum(String albumId, boolean create) {
709 synchronized (albums) {
710 Album album = albums.get(albumId);
711 if (create && (album == null)) {
712 album = new Album(albumId);
713 albums.put(albumId, album);
720 * Returns the image with the given ID, creating it if necessary.
723 * The ID of the image
724 * @return The image with the given ID
726 public Image getImage(String imageId) {
727 return getImage(imageId, true);
731 * Returns the image with the given ID, optionally creating it if it does
735 * The ID of the image
737 * {@code true} to create an image if none exists with the given
739 * @return The image with the given ID, or {@code null} if none exists and
742 public Image getImage(String imageId, boolean create) {
743 synchronized (images) {
744 Image image = images.get(imageId);
745 if (create && (image == null)) {
746 image = new Image(imageId);
747 images.put(imageId, image);
754 * Returns the temporary image with the given ID.
757 * The ID of the temporary image
758 * @return The temporary image, or {@code null} if there is no temporary
759 * image with the given ID
761 public TemporaryImage getTemporaryImage(String imageId) {
762 synchronized (temporaryImages) {
763 return temporaryImages.get(imageId);
772 * Locks the given Sone. A locked Sone will not be inserted by
773 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
779 public void lockSone(Sone sone) {
780 synchronized (lockedSones) {
781 if (lockedSones.add(sone)) {
782 coreListenerManager.fireSoneLocked(sone);
788 * Unlocks the given Sone.
790 * @see #lockSone(Sone)
794 public void unlockSone(Sone sone) {
795 synchronized (lockedSones) {
796 if (lockedSones.remove(sone)) {
797 coreListenerManager.fireSoneUnlocked(sone);
803 * Adds a local Sone from the given own identity.
806 * The own identity to create a Sone from
807 * @return The added (or already existing) Sone
809 public Sone addLocalSone(OwnIdentity ownIdentity) {
810 if (ownIdentity == null) {
811 logger.log(Level.WARNING, "Given OwnIdentity is null!");
814 synchronized (sones) {
817 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
818 } catch (MalformedURLException mue1) {
819 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
822 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
823 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
825 /* TODO - load posts ’n stuff */
826 sones.put(ownIdentity.getId(), sone);
827 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
828 soneInserter.addSoneInsertListener(this);
829 soneInserters.put(sone, soneInserter);
830 sone.setStatus(SoneStatus.idle);
832 soneInserter.start();
838 * Creates a new Sone for the given own identity.
841 * The own identity to create a Sone for
842 * @return The created Sone
844 public Sone createSone(OwnIdentity ownIdentity) {
845 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
846 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
849 Sone sone = addLocalSone(ownIdentity);
850 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
851 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
852 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
853 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
854 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
855 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
857 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
858 touchConfiguration();
863 * Adds the Sone of the given identity.
866 * The identity whose Sone to add
867 * @return The added or already existing Sone
869 public Sone addRemoteSone(Identity identity) {
870 if (identity == null) {
871 logger.log(Level.WARNING, "Given Identity is null!");
874 synchronized (sones) {
875 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
876 boolean newSone = sone.getRequestUri() == null;
877 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
878 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
880 synchronized (knownSones) {
881 newSone = !knownSones.contains(sone.getId());
883 sone.setKnown(!newSone);
885 coreListenerManager.fireNewSoneFound(sone);
886 for (Sone localSone : getLocalSones()) {
887 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
888 followSone(localSone, sone);
893 soneDownloader.addSone(sone);
894 soneDownloaders.execute(new Runnable() {
897 @SuppressWarnings("synthetic-access")
899 soneDownloader.fetchSone(sone, sone.getRequestUri());
908 * Lets the given local Sone follow the Sone with the given ID.
911 * The local Sone that should follow another Sone
913 * The ID of the Sone to follow
915 public void followSone(Sone sone, String soneId) {
916 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
917 Sone followedSone = getSone(soneId, true);
918 if (followedSone == null) {
919 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
922 followSone(sone, getSone(soneId));
926 * Lets the given local Sone follow the other given Sone. If the given Sone
927 * was not followed by any local Sone before, this will mark all elements of
928 * the followed Sone as read that have been created before the current
932 * The local Sone that should follow the other Sone
933 * @param followedSone
934 * The Sone that should be followed
936 public void followSone(Sone sone, Sone followedSone) {
937 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
938 sone.addFriend(followedSone.getId());
939 synchronized (soneFollowingTimes) {
940 if (!soneFollowingTimes.containsKey(followedSone)) {
941 long now = System.currentTimeMillis();
942 soneFollowingTimes.put(followedSone, now);
943 for (Post post : followedSone.getPosts()) {
944 if (post.getTime() < now) {
948 for (PostReply reply : followedSone.getReplies()) {
949 if (reply.getTime() < now) {
950 markReplyKnown(reply);
955 touchConfiguration();
959 * Lets the given local Sone unfollow the Sone with the given ID.
962 * The local Sone that should unfollow another Sone
964 * The ID of the Sone being unfollowed
966 public void unfollowSone(Sone sone, String soneId) {
967 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
968 unfollowSone(sone, getSone(soneId, false));
972 * Lets the given local Sone unfollow the other given Sone. If the given
973 * local Sone is the last local Sone that followed the given Sone, its
974 * following time will be removed.
977 * The local Sone that should unfollow another Sone
978 * @param unfollowedSone
979 * The Sone being unfollowed
981 public void unfollowSone(Sone sone, Sone unfollowedSone) {
982 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
983 sone.removeFriend(unfollowedSone.getId());
984 boolean unfollowedSoneStillFollowed = false;
985 for (Sone localSone : getLocalSones()) {
986 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
988 if (!unfollowedSoneStillFollowed) {
989 synchronized (soneFollowingTimes) {
990 soneFollowingTimes.remove(unfollowedSone);
993 touchConfiguration();
997 * Sets the trust value of the given origin Sone for the target Sone.
1004 * The trust value (from {@code -100} to {@code 100})
1006 public void setTrust(Sone origin, Sone target, int trustValue) {
1007 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();
1008 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1012 * Removes any trust assignment for the given target Sone.
1019 public void removeTrust(Sone origin, Sone target) {
1020 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1021 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1025 * Assigns the configured positive trust value for the given target.
1032 public void trustSone(Sone origin, Sone target) {
1033 setTrust(origin, target, preferences.getPositiveTrust());
1037 * Assigns the configured negative trust value for the given target.
1044 public void distrustSone(Sone origin, Sone target) {
1045 setTrust(origin, target, preferences.getNegativeTrust());
1049 * Removes the trust assignment for the given target.
1056 public void untrustSone(Sone origin, Sone target) {
1057 removeTrust(origin, target);
1061 * Updates the stored Sone with the given Sone.
1066 public void updateSone(Sone sone) {
1067 updateSone(sone, false);
1071 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1072 * {@code true}, an older Sone than the current Sone can be given to restore
1076 * The Sone to update
1077 * @param soneRescueMode
1078 * {@code true} if the stored Sone should be updated regardless
1079 * of the age of the given Sone
1081 public void updateSone(Sone sone, boolean soneRescueMode) {
1082 if (hasSone(sone.getId())) {
1083 Sone storedSone = getSone(sone.getId());
1084 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1085 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1088 synchronized (posts) {
1089 if (!soneRescueMode) {
1090 for (Post post : storedSone.getPosts()) {
1091 posts.remove(post.getId());
1092 if (!sone.getPosts().contains(post)) {
1093 coreListenerManager.firePostRemoved(post);
1097 List<Post> storedPosts = storedSone.getPosts();
1098 synchronized (knownPosts) {
1099 for (Post post : sone.getPosts()) {
1100 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1101 if (!storedPosts.contains(post)) {
1102 if (post.getTime() < getSoneFollowingTime(sone)) {
1103 knownPosts.add(post.getId());
1104 post.setKnown(true);
1105 } else if (!knownPosts.contains(post.getId())) {
1106 coreListenerManager.fireNewPostFound(post);
1109 posts.put(post.getId(), post);
1113 synchronized (replies) {
1114 if (!soneRescueMode) {
1115 for (PostReply reply : storedSone.getReplies()) {
1116 replies.remove(reply.getId());
1117 if (!sone.getReplies().contains(reply)) {
1118 coreListenerManager.fireReplyRemoved(reply);
1122 Set<PostReply> storedReplies = storedSone.getReplies();
1123 synchronized (knownReplies) {
1124 for (PostReply reply : sone.getReplies()) {
1125 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1126 if (!storedReplies.contains(reply)) {
1127 if (reply.getTime() < getSoneFollowingTime(sone)) {
1128 knownReplies.add(reply.getId());
1129 reply.setKnown(true);
1130 } else if (!knownReplies.contains(reply.getId())) {
1131 coreListenerManager.fireNewReplyFound(reply);
1134 replies.put(reply.getId(), reply);
1138 synchronized (albums) {
1139 synchronized (images) {
1140 for (Album album : storedSone.getAlbums()) {
1141 albums.remove(album.getId());
1142 for (Image image : album.getImages()) {
1143 images.remove(image.getId());
1146 for (Album album : sone.getAlbums()) {
1147 albums.put(album.getId(), album);
1148 for (Image image : album.getImages()) {
1149 images.put(image.getId(), image);
1154 synchronized (storedSone) {
1155 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1156 storedSone.setTime(sone.getTime());
1158 storedSone.setClient(sone.getClient());
1159 storedSone.setProfile(sone.getProfile());
1160 if (soneRescueMode) {
1161 for (Post post : sone.getPosts()) {
1162 storedSone.addPost(post);
1164 for (PostReply reply : sone.getReplies()) {
1165 storedSone.addReply(reply);
1167 for (String likedPostId : sone.getLikedPostIds()) {
1168 storedSone.addLikedPostId(likedPostId);
1170 for (String likedReplyId : sone.getLikedReplyIds()) {
1171 storedSone.addLikedReplyId(likedReplyId);
1173 for (Album album : sone.getAlbums()) {
1174 storedSone.addAlbum(album);
1177 storedSone.setPosts(sone.getPosts());
1178 storedSone.setReplies(sone.getReplies());
1179 storedSone.setLikePostIds(sone.getLikedPostIds());
1180 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1181 storedSone.setAlbums(sone.getAlbums());
1183 storedSone.setLatestEdition(sone.getLatestEdition());
1189 * Deletes the given Sone. This will remove the Sone from the
1190 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1191 * remove the context from its identity.
1194 * The Sone to delete
1196 public void deleteSone(Sone sone) {
1197 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1198 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1201 synchronized (sones) {
1202 if (!getLocalSones().contains(sone)) {
1203 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1206 sones.remove(sone.getId());
1207 SoneInserter soneInserter = soneInserters.remove(sone);
1208 soneInserter.removeSoneInsertListener(this);
1209 soneInserter.stop();
1211 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1212 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1214 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1215 } catch (ConfigurationException ce1) {
1216 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1221 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1222 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1225 * The Sone to mark as known
1227 public void markSoneKnown(Sone sone) {
1228 if (!sone.isKnown()) {
1229 sone.setKnown(true);
1230 synchronized (knownSones) {
1231 knownSones.add(sone.getId());
1233 coreListenerManager.fireMarkSoneKnown(sone);
1234 touchConfiguration();
1239 * Loads and updates the given Sone from the configuration. If any error is
1240 * encountered, loading is aborted and the given Sone is not changed.
1243 * The Sone to load and update
1245 public void loadSone(Sone sone) {
1246 if (!sone.isLocal()) {
1247 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1251 /* initialize options. */
1252 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1253 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1254 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1255 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1256 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1257 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1260 String sonePrefix = "Sone/" + sone.getId();
1261 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1262 if (soneTime == null) {
1263 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1266 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1269 Profile profile = new Profile(sone);
1270 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1271 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1272 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1273 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1274 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1275 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1277 /* load profile fields. */
1279 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1280 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1281 if (fieldName == null) {
1284 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1285 profile.addField(fieldName).setValue(fieldValue);
1289 Set<Post> posts = new HashSet<Post>();
1291 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1292 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1293 if (postId == null) {
1296 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1297 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1298 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1299 if ((postTime == 0) || (postText == null)) {
1300 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1303 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1304 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1305 post.setRecipient(getSone(postRecipientId));
1311 Set<PostReply> replies = new HashSet<PostReply>();
1313 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1314 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1315 if (replyId == null) {
1318 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1319 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1320 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1321 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1322 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1325 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1328 /* load post likes. */
1329 Set<String> likedPostIds = new HashSet<String>();
1331 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1332 if (likedPostId == null) {
1335 likedPostIds.add(likedPostId);
1338 /* load reply likes. */
1339 Set<String> likedReplyIds = new HashSet<String>();
1341 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1342 if (likedReplyId == null) {
1345 likedReplyIds.add(likedReplyId);
1349 Set<String> friends = new HashSet<String>();
1351 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1352 if (friendId == null) {
1355 friends.add(friendId);
1359 List<Album> topLevelAlbums = new ArrayList<Album>();
1360 int albumCounter = 0;
1362 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1363 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1364 if (albumId == null) {
1367 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1368 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1369 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1370 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1371 if ((albumTitle == null) || (albumDescription == null)) {
1372 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1375 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1376 if (albumParentId != null) {
1377 Album parentAlbum = getAlbum(albumParentId, false);
1378 if (parentAlbum == null) {
1379 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1382 parentAlbum.addAlbum(album);
1384 if (!topLevelAlbums.contains(album)) {
1385 topLevelAlbums.add(album);
1391 int imageCounter = 0;
1393 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1394 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1395 if (imageId == null) {
1398 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1399 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1400 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1401 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1402 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1403 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1404 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1405 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1406 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1409 Album album = getAlbum(albumId, false);
1410 if (album == null) {
1411 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1414 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1415 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1416 album.addImage(image);
1420 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1421 if (avatarId != null) {
1422 profile.setAvatar(getImage(avatarId, false));
1426 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1427 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1428 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1429 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1430 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1431 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1433 /* if we’re still here, Sone was loaded successfully. */
1434 synchronized (sone) {
1435 sone.setTime(soneTime);
1436 sone.setProfile(profile);
1437 sone.setPosts(posts);
1438 sone.setReplies(replies);
1439 sone.setLikePostIds(likedPostIds);
1440 sone.setLikeReplyIds(likedReplyIds);
1441 for (String friendId : friends) {
1442 followSone(sone, friendId);
1444 sone.setAlbums(topLevelAlbums);
1445 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1447 synchronized (knownSones) {
1448 for (String friend : friends) {
1449 knownSones.add(friend);
1452 synchronized (knownPosts) {
1453 for (Post post : posts) {
1454 knownPosts.add(post.getId());
1457 synchronized (knownReplies) {
1458 for (PostReply reply : replies) {
1459 knownReplies.add(reply.getId());
1465 * Creates a new post.
1468 * The Sone that creates the post
1470 * The text of the post
1471 * @return The created post
1473 public Post createPost(Sone sone, String text) {
1474 return createPost(sone, System.currentTimeMillis(), text);
1478 * Creates a new post.
1481 * The Sone that creates the post
1483 * The time of the post
1485 * The text of the post
1486 * @return The created post
1488 public Post createPost(Sone sone, long time, String text) {
1489 return createPost(sone, null, time, text);
1493 * Creates a new post.
1496 * The Sone that creates the post
1498 * The recipient Sone, or {@code null} if this post does not have
1501 * The text of the post
1502 * @return The created post
1504 public Post createPost(Sone sone, Sone recipient, String text) {
1505 return createPost(sone, recipient, System.currentTimeMillis(), text);
1509 * Creates a new post.
1512 * The Sone that creates the post
1514 * The recipient Sone, or {@code null} if this post does not have
1517 * The time of the post
1519 * The text of the post
1520 * @return The created post
1522 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1523 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1524 if (!sone.isLocal()) {
1525 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1528 final Post post = new PostImpl(sone, time, text);
1529 if (recipient != null) {
1530 post.setRecipient(recipient);
1532 synchronized (posts) {
1533 posts.put(post.getId(), post);
1535 coreListenerManager.fireNewPostFound(post);
1537 touchConfiguration();
1538 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1545 markPostKnown(post);
1547 }, "Mark " + post + " read.");
1552 * Deletes the given post.
1555 * The post to delete
1557 public void deletePost(Post post) {
1558 if (!post.getSone().isLocal()) {
1559 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1562 post.getSone().removePost(post);
1563 synchronized (posts) {
1564 posts.remove(post.getId());
1566 coreListenerManager.firePostRemoved(post);
1567 markPostKnown(post);
1568 touchConfiguration();
1572 * Marks the given post as known, if it is currently not a known post
1573 * (according to {@link Post#isKnown()}).
1576 * The post to mark as known
1578 public void markPostKnown(Post post) {
1579 post.setKnown(true);
1580 synchronized (knownPosts) {
1581 coreListenerManager.fireMarkPostKnown(post);
1582 if (knownPosts.add(post.getId())) {
1583 touchConfiguration();
1586 for (PostReply reply : getReplies(post)) {
1587 markReplyKnown(reply);
1592 * Bookmarks the given post.
1595 * The post to bookmark
1597 public void bookmark(Post post) {
1598 bookmarkPost(post.getId());
1602 * Bookmarks the post with the given ID.
1605 * The ID of the post to bookmark
1607 public void bookmarkPost(String id) {
1608 synchronized (bookmarkedPosts) {
1609 bookmarkedPosts.add(id);
1614 * Removes the given post from the bookmarks.
1617 * The post to unbookmark
1619 public void unbookmark(Post post) {
1620 unbookmarkPost(post.getId());
1624 * Removes the post with the given ID from the bookmarks.
1627 * The ID of the post to unbookmark
1629 public void unbookmarkPost(String id) {
1630 synchronized (bookmarkedPosts) {
1631 bookmarkedPosts.remove(id);
1636 * Creates a new reply.
1639 * The Sone that creates the reply
1641 * The post that this reply refers to
1643 * The text of the reply
1644 * @return The created reply
1646 public PostReply createReply(Sone sone, Post post, String text) {
1647 return createReply(sone, post, System.currentTimeMillis(), text);
1651 * Creates a new reply.
1654 * The Sone that creates the reply
1656 * The post that this reply refers to
1658 * The time of the reply
1660 * The text of the reply
1661 * @return The created reply
1663 public PostReply createReply(Sone sone, Post post, long time, String text) {
1664 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1665 if (!sone.isLocal()) {
1666 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1669 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1670 synchronized (replies) {
1671 replies.put(reply.getId(), reply);
1673 synchronized (knownReplies) {
1674 coreListenerManager.fireNewReplyFound(reply);
1676 sone.addReply(reply);
1677 touchConfiguration();
1678 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1685 markReplyKnown(reply);
1687 }, "Mark " + reply + " read.");
1692 * Deletes the given reply.
1695 * The reply to delete
1697 public void deleteReply(PostReply reply) {
1698 Sone sone = reply.getSone();
1699 if (!sone.isLocal()) {
1700 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1703 synchronized (replies) {
1704 replies.remove(reply.getId());
1706 synchronized (knownReplies) {
1707 markReplyKnown(reply);
1708 knownReplies.remove(reply.getId());
1710 sone.removeReply(reply);
1711 touchConfiguration();
1715 * Marks the given reply as known, if it is currently not a known reply
1716 * (according to {@link Reply#isKnown()}).
1719 * The reply to mark as known
1721 public void markReplyKnown(PostReply reply) {
1722 reply.setKnown(true);
1723 synchronized (knownReplies) {
1724 coreListenerManager.fireMarkReplyKnown(reply);
1725 if (knownReplies.add(reply.getId())) {
1726 touchConfiguration();
1732 * Creates a new top-level album for the given Sone.
1735 * The Sone to create the album for
1736 * @return The new album
1738 public Album createAlbum(Sone sone) {
1739 return createAlbum(sone, null);
1743 * Creates a new album for the given Sone.
1746 * The Sone to create the album for
1748 * The parent of the album (may be {@code null} to create a
1750 * @return The new album
1752 public Album createAlbum(Sone sone, Album parent) {
1753 Album album = new Album();
1754 synchronized (albums) {
1755 albums.put(album.getId(), album);
1757 album.setSone(sone);
1758 if (parent != null) {
1759 parent.addAlbum(album);
1761 sone.addAlbum(album);
1767 * Deletes the given album. The owner of the album has to be a local Sone,
1768 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1771 * The album to remove
1773 public void deleteAlbum(Album album) {
1774 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1775 if (!album.isEmpty()) {
1778 if (album.getParent() == null) {
1779 album.getSone().removeAlbum(album);
1781 album.getParent().removeAlbum(album);
1783 synchronized (albums) {
1784 albums.remove(album.getId());
1786 touchConfiguration();
1790 * Creates a new image.
1793 * The Sone creating the image
1795 * The album the image will be inserted into
1796 * @param temporaryImage
1797 * The temporary image to create the image from
1798 * @return The newly created image
1800 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1801 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1802 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1803 album.addImage(image);
1804 synchronized (images) {
1805 images.put(image.getId(), image);
1807 imageInserter.insertImage(temporaryImage, image);
1812 * Deletes the given image. This method will also delete a matching
1815 * @see #deleteTemporaryImage(TemporaryImage)
1817 * The image to delete
1819 public void deleteImage(Image image) {
1820 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1821 deleteTemporaryImage(image.getId());
1822 image.getAlbum().removeImage(image);
1823 synchronized (images) {
1824 images.remove(image.getId());
1826 touchConfiguration();
1830 * Creates a new temporary image.
1833 * The MIME type of the temporary image
1835 * The encoded data of the image
1836 * @return The temporary image
1838 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1839 TemporaryImage temporaryImage = new TemporaryImage();
1840 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1841 synchronized (temporaryImages) {
1842 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1844 return temporaryImage;
1848 * Deletes the given temporary image.
1850 * @param temporaryImage
1851 * The temporary image to delete
1853 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1854 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1855 deleteTemporaryImage(temporaryImage.getId());
1859 * Deletes the temporary image with the given ID.
1862 * The ID of the temporary image to delete
1864 public void deleteTemporaryImage(String imageId) {
1865 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1866 synchronized (temporaryImages) {
1867 temporaryImages.remove(imageId);
1869 Image image = getImage(imageId, false);
1870 if (image != null) {
1871 imageInserter.cancelImageInsert(image);
1876 * Notifies the core that the configuration, either of the core or of a
1877 * single local Sone, has changed, and that the configuration should be
1880 public void touchConfiguration() {
1881 lastConfigurationUpdate = System.currentTimeMillis();
1892 public void serviceStart() {
1893 loadConfiguration();
1894 updateChecker.addUpdateListener(this);
1895 updateChecker.start();
1896 webOfTrustUpdater.start();
1903 public void serviceRun() {
1904 long lastSaved = System.currentTimeMillis();
1905 while (!shouldStop()) {
1907 long now = System.currentTimeMillis();
1908 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1909 for (Sone localSone : getLocalSones()) {
1910 saveSone(localSone);
1912 saveConfiguration();
1922 public void serviceStop() {
1923 synchronized (sones) {
1924 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1925 soneInserter.getValue().removeSoneInsertListener(this);
1926 soneInserter.getValue().stop();
1927 saveSone(soneInserter.getKey());
1930 saveConfiguration();
1931 webOfTrustUpdater.stop();
1932 updateChecker.stop();
1933 updateChecker.removeUpdateListener(this);
1934 soneDownloader.stop();
1942 * Saves the given Sone. This will persist all local settings for the given
1943 * Sone, such as the friends list and similar, private options.
1948 private synchronized void saveSone(Sone sone) {
1949 if (!sone.isLocal()) {
1950 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1953 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1954 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1958 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1960 /* save Sone into configuration. */
1961 String sonePrefix = "Sone/" + sone.getId();
1962 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1963 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1966 Profile profile = sone.getProfile();
1967 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1968 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1969 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1970 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1971 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1972 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1973 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1975 /* save profile fields. */
1976 int fieldCounter = 0;
1977 for (Field profileField : profile.getFields()) {
1978 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1979 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1980 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1982 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1985 int postCounter = 0;
1986 for (Post post : sone.getPosts()) {
1987 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1988 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1989 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1990 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1991 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1993 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1996 int replyCounter = 0;
1997 for (PostReply reply : sone.getReplies()) {
1998 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1999 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2000 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2001 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2002 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2004 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2006 /* save post likes. */
2007 int postLikeCounter = 0;
2008 for (String postId : sone.getLikedPostIds()) {
2009 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2011 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2013 /* save reply likes. */
2014 int replyLikeCounter = 0;
2015 for (String replyId : sone.getLikedReplyIds()) {
2016 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2018 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2021 int friendCounter = 0;
2022 for (String friendId : sone.getFriends()) {
2023 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2025 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2027 /* save albums. first, collect in a flat structure, top-level first. */
2028 List<Album> albums = sone.getAllAlbums();
2030 int albumCounter = 0;
2031 for (Album album : albums) {
2032 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2033 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2034 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2035 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2036 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2037 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2039 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2042 int imageCounter = 0;
2043 for (Album album : albums) {
2044 for (Image image : album.getImages()) {
2045 if (!image.isInserted()) {
2048 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2049 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2050 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2051 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2052 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2053 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2054 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2055 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2056 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2059 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2062 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2063 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2064 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2065 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2066 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2067 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2069 configuration.save();
2071 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2073 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2074 } catch (ConfigurationException ce1) {
2075 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2080 * Saves the current options.
2082 private void saveConfiguration() {
2083 synchronized (configuration) {
2084 if (storingConfiguration) {
2085 logger.log(Level.FINE, "Already storing configuration…");
2088 storingConfiguration = true;
2091 /* store the options first. */
2093 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2094 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2095 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2096 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2097 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2098 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2099 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2100 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2101 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2102 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2103 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2104 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2106 /* save known Sones. */
2107 int soneCounter = 0;
2108 synchronized (knownSones) {
2109 for (String knownSoneId : knownSones) {
2110 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2112 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2115 /* save Sone following times. */
2117 synchronized (soneFollowingTimes) {
2118 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2119 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2120 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2123 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2126 /* save known posts. */
2127 int postCounter = 0;
2128 synchronized (knownPosts) {
2129 for (String knownPostId : knownPosts) {
2130 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2132 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2135 /* save known replies. */
2136 int replyCounter = 0;
2137 synchronized (knownReplies) {
2138 for (String knownReplyId : knownReplies) {
2139 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2141 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2144 /* save bookmarked posts. */
2145 int bookmarkedPostCounter = 0;
2146 synchronized (bookmarkedPosts) {
2147 for (String bookmarkedPostId : bookmarkedPosts) {
2148 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2151 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2154 configuration.save();
2156 } catch (ConfigurationException ce1) {
2157 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2159 synchronized (configuration) {
2160 storingConfiguration = false;
2166 * Loads the configuration.
2168 @SuppressWarnings("unchecked")
2169 private void loadConfiguration() {
2170 /* create options. */
2171 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2174 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2175 SoneInserter.setInsertionDelay(newValue);
2179 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2180 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2181 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2182 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2183 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2184 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2185 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2186 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2187 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2190 @SuppressWarnings("synthetic-access")
2191 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2192 fcpInterface.setActive(newValue);
2195 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2198 @SuppressWarnings("synthetic-access")
2199 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2200 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2205 loadConfigurationValue("InsertionDelay");
2206 loadConfigurationValue("PostsPerPage");
2207 loadConfigurationValue("ImagesPerPage");
2208 loadConfigurationValue("CharactersPerPost");
2209 loadConfigurationValue("PostCutOffLength");
2210 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2211 loadConfigurationValue("PositiveTrust");
2212 loadConfigurationValue("NegativeTrust");
2213 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2214 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2215 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2217 /* load known Sones. */
2218 int soneCounter = 0;
2220 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2221 if (knownSoneId == null) {
2224 synchronized (knownSones) {
2225 knownSones.add(knownSoneId);
2229 /* load Sone following times. */
2232 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2233 if (soneId == null) {
2236 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2237 Sone followedSone = getSone(soneId);
2238 if (followedSone == null) {
2239 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2241 synchronized (soneFollowingTimes) {
2242 soneFollowingTimes.put(getSone(soneId), time);
2248 /* load known posts. */
2249 int postCounter = 0;
2251 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2252 if (knownPostId == null) {
2255 synchronized (knownPosts) {
2256 knownPosts.add(knownPostId);
2260 /* load known replies. */
2261 int replyCounter = 0;
2263 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2264 if (knownReplyId == null) {
2267 synchronized (knownReplies) {
2268 knownReplies.add(knownReplyId);
2272 /* load bookmarked posts. */
2273 int bookmarkedPostCounter = 0;
2275 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2276 if (bookmarkedPostId == null) {
2279 synchronized (bookmarkedPosts) {
2280 bookmarkedPosts.add(bookmarkedPostId);
2287 * Loads an {@link Integer} configuration value for the option with the
2288 * given name, logging validation failures.
2291 * The name of the option to load
2293 private void loadConfigurationValue(String optionName) {
2295 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2296 } catch (IllegalArgumentException iae1) {
2297 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2302 * Generate a Sone URI from the given URI and latest edition.
2305 * The URI to derive the Sone URI from
2306 * @return The derived URI
2308 private static FreenetURI getSoneUri(String uriString) {
2310 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2312 } catch (MalformedURLException mue1) {
2313 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2319 // INTERFACE IdentityListener
2326 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2327 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2328 if (ownIdentity.hasContext("Sone")) {
2329 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2330 addLocalSone(ownIdentity);
2338 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2339 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2340 trustedIdentities.remove(ownIdentity);
2347 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2348 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2349 trustedIdentities.get(ownIdentity).add(identity);
2350 addRemoteSone(identity);
2357 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2358 soneDownloaders.execute(new Runnable() {
2361 @SuppressWarnings("synthetic-access")
2363 Sone sone = getRemoteSone(identity.getId(), false);
2364 sone.setIdentity(identity);
2365 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2366 soneDownloader.addSone(sone);
2367 soneDownloader.fetchSone(sone);
2376 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2377 trustedIdentities.get(ownIdentity).remove(identity);
2378 boolean foundIdentity = false;
2379 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2380 if (trustedIdentity.getKey().equals(ownIdentity)) {
2383 if (trustedIdentity.getValue().contains(identity)) {
2384 foundIdentity = true;
2387 if (foundIdentity) {
2388 /* some local identity still trusts this identity, don’t remove. */
2391 Sone sone = getSone(identity.getId(), false);
2393 /* TODO - we don’t have the Sone anymore. should this happen? */
2396 synchronized (posts) {
2397 synchronized (knownPosts) {
2398 for (Post post : sone.getPosts()) {
2399 posts.remove(post.getId());
2400 coreListenerManager.firePostRemoved(post);
2404 synchronized (replies) {
2405 synchronized (knownReplies) {
2406 for (PostReply reply : sone.getReplies()) {
2407 replies.remove(reply.getId());
2408 coreListenerManager.fireReplyRemoved(reply);
2412 synchronized (sones) {
2413 sones.remove(identity.getId());
2415 coreListenerManager.fireSoneRemoved(sone);
2419 // INTERFACE UpdateListener
2426 public void updateFound(Version version, long releaseTime, long latestEdition) {
2427 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2431 // INTERFACE ImageInsertListener
2438 public void insertStarted(Sone sone) {
2439 coreListenerManager.fireSoneInserting(sone);
2446 public void insertFinished(Sone sone, long insertDuration) {
2447 coreListenerManager.fireSoneInserted(sone, insertDuration);
2454 public void insertAborted(Sone sone, Throwable cause) {
2455 coreListenerManager.fireSoneInsertAborted(sone, cause);
2459 // SONEINSERTLISTENER METHODS
2466 public void imageInsertStarted(Image image) {
2467 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2468 coreListenerManager.fireImageInsertStarted(image);
2475 public void imageInsertAborted(Image image) {
2476 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2477 coreListenerManager.fireImageInsertAborted(image);
2484 public void imageInsertFinished(Image image, FreenetURI key) {
2485 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2486 image.setKey(key.toString());
2487 deleteTemporaryImage(image.getId());
2488 touchConfiguration();
2489 coreListenerManager.fireImageInsertFinished(image);
2496 public void imageInsertFailed(Image image, Throwable cause) {
2497 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2498 coreListenerManager.fireImageInsertFailed(image, cause);
2502 * Convenience interface for external classes that want to access the core’s
2505 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2507 public static class Preferences {
2509 /** The wrapped options. */
2510 private final Options options;
2513 * Creates a new preferences object wrapped around the given options.
2516 * The options to wrap
2518 public Preferences(Options options) {
2519 this.options = options;
2523 * Returns the insertion delay.
2525 * @return The insertion delay
2527 public int getInsertionDelay() {
2528 return options.getIntegerOption("InsertionDelay").get();
2532 * Validates the given insertion delay.
2534 * @param insertionDelay
2535 * The insertion delay to validate
2536 * @return {@code true} if the given insertion delay was valid,
2537 * {@code false} otherwise
2539 public boolean validateInsertionDelay(Integer insertionDelay) {
2540 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2544 * Sets the insertion delay
2546 * @param insertionDelay
2547 * The new insertion delay, or {@code null} to restore it to
2549 * @return This preferences
2551 public Preferences setInsertionDelay(Integer insertionDelay) {
2552 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2557 * Returns the number of posts to show per page.
2559 * @return The number of posts to show per page
2561 public int getPostsPerPage() {
2562 return options.getIntegerOption("PostsPerPage").get();
2566 * Validates the number of posts per page.
2568 * @param postsPerPage
2569 * The number of posts per page
2570 * @return {@code true} if the number of posts per page was valid,
2571 * {@code false} otherwise
2573 public boolean validatePostsPerPage(Integer postsPerPage) {
2574 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2578 * Sets the number of posts to show per page.
2580 * @param postsPerPage
2581 * The number of posts to show per page
2582 * @return This preferences object
2584 public Preferences setPostsPerPage(Integer postsPerPage) {
2585 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2590 * Returns the number of images to show per page.
2592 * @return The number of images to show per page
2594 public int getImagesPerPage() {
2595 return options.getIntegerOption("ImagesPerPage").get();
2599 * Validates the number of images per page.
2601 * @param imagesPerPage
2602 * The number of images per page
2603 * @return {@code true} if the number of images per page was valid,
2604 * {@code false} otherwise
2606 public boolean validateImagesPerPage(Integer imagesPerPage) {
2607 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2611 * Sets the number of images per page.
2613 * @param imagesPerPage
2614 * The number of images per page
2615 * @return This preferences object
2617 public Preferences setImagesPerPage(Integer imagesPerPage) {
2618 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2623 * Returns the number of characters per post, or <code>-1</code> if the
2624 * posts should not be cut off.
2626 * @return The numbers of characters per post
2628 public int getCharactersPerPost() {
2629 return options.getIntegerOption("CharactersPerPost").get();
2633 * Validates the number of characters per post.
2635 * @param charactersPerPost
2636 * The number of characters per post
2637 * @return {@code true} if the number of characters per post was valid,
2638 * {@code false} otherwise
2640 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2641 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2645 * Sets the number of characters per post.
2647 * @param charactersPerPost
2648 * The number of characters per post, or <code>-1</code> to
2649 * not cut off the posts
2650 * @return This preferences objects
2652 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2653 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2658 * Returns the number of characters the shortened post should have.
2660 * @return The number of characters of the snippet
2662 public int getPostCutOffLength() {
2663 return options.getIntegerOption("PostCutOffLength").get();
2667 * Validates the number of characters after which to cut off the post.
2669 * @param postCutOffLength
2670 * The number of characters of the snippet
2671 * @return {@code true} if the number of characters of the snippet is
2672 * valid, {@code false} otherwise
2674 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2675 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2679 * Sets the number of characters the shortened post should have.
2681 * @param postCutOffLength
2682 * The number of characters of the snippet
2683 * @return This preferences
2685 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2686 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2691 * Returns whether Sone requires full access to be even visible.
2693 * @return {@code true} if Sone requires full access, {@code false}
2696 public boolean isRequireFullAccess() {
2697 return options.getBooleanOption("RequireFullAccess").get();
2701 * Sets whether Sone requires full access to be even visible.
2703 * @param requireFullAccess
2704 * {@code true} if Sone requires full access, {@code false}
2707 public void setRequireFullAccess(Boolean requireFullAccess) {
2708 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2712 * Returns the positive trust.
2714 * @return The positive trust
2716 public int getPositiveTrust() {
2717 return options.getIntegerOption("PositiveTrust").get();
2721 * Validates the positive trust.
2723 * @param positiveTrust
2724 * The positive trust to validate
2725 * @return {@code true} if the positive trust was valid, {@code false}
2728 public boolean validatePositiveTrust(Integer positiveTrust) {
2729 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2733 * Sets the positive trust.
2735 * @param positiveTrust
2736 * The new positive trust, or {@code null} to restore it to
2738 * @return This preferences
2740 public Preferences setPositiveTrust(Integer positiveTrust) {
2741 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2746 * Returns the negative trust.
2748 * @return The negative trust
2750 public int getNegativeTrust() {
2751 return options.getIntegerOption("NegativeTrust").get();
2755 * Validates the negative trust.
2757 * @param negativeTrust
2758 * The negative trust to validate
2759 * @return {@code true} if the negative trust was valid, {@code false}
2762 public boolean validateNegativeTrust(Integer negativeTrust) {
2763 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2767 * Sets the negative trust.
2769 * @param negativeTrust
2770 * The negative trust, or {@code null} to restore it to the
2772 * @return The preferences
2774 public Preferences setNegativeTrust(Integer negativeTrust) {
2775 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2780 * Returns the trust comment. This is the comment that is set in the web
2781 * of trust when a trust value is assigned to an identity.
2783 * @return The trust comment
2785 public String getTrustComment() {
2786 return options.getStringOption("TrustComment").get();
2790 * Sets the trust comment.
2792 * @param trustComment
2793 * The trust comment, or {@code null} to restore it to the
2795 * @return This preferences
2797 public Preferences setTrustComment(String trustComment) {
2798 options.getStringOption("TrustComment").set(trustComment);
2803 * Returns whether the {@link FcpInterface FCP interface} is currently
2806 * @see FcpInterface#setActive(boolean)
2807 * @return {@code true} if the FCP interface is currently active,
2808 * {@code false} otherwise
2810 public boolean isFcpInterfaceActive() {
2811 return options.getBooleanOption("ActivateFcpInterface").get();
2815 * Sets whether the {@link FcpInterface FCP interface} is currently
2818 * @see FcpInterface#setActive(boolean)
2819 * @param fcpInterfaceActive
2820 * {@code true} to activate the FCP interface, {@code false}
2821 * to deactivate the FCP interface
2822 * @return This preferences object
2824 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2825 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2830 * Returns the action level for which full access to the FCP interface
2833 * @return The action level for which full access to the FCP interface
2836 public FullAccessRequired getFcpFullAccessRequired() {
2837 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2841 * Sets the action level for which full access to the FCP interface is
2844 * @param fcpFullAccessRequired
2846 * @return This preferences
2848 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2849 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);