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.database.Database;
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.freenet.wot.Trust;
58 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
59 import net.pterodactylus.sone.main.SonePlugin;
60 import net.pterodactylus.util.config.Configuration;
61 import net.pterodactylus.util.config.ConfigurationException;
62 import net.pterodactylus.util.logging.Logging;
63 import net.pterodactylus.util.number.Numbers;
64 import net.pterodactylus.util.service.AbstractService;
65 import net.pterodactylus.util.thread.Ticker;
66 import net.pterodactylus.util.validation.EqualityValidator;
67 import net.pterodactylus.util.validation.IntegerRangeValidator;
68 import net.pterodactylus.util.validation.OrValidator;
69 import net.pterodactylus.util.validation.Validation;
70 import net.pterodactylus.util.version.Version;
71 import freenet.keys.FreenetURI;
76 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
81 private static final Logger logger = Logging.getLogger(Core.class);
84 private final Options options = new Options();
86 /** The preferences. */
87 private final Preferences preferences = new Preferences(options);
89 /** The core listener manager. */
90 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
92 /** The configuration. */
93 private Configuration configuration;
95 /** Whether we’re currently saving the configuration. */
96 private boolean storingConfiguration = false;
99 private Database database;
101 /** The identity manager. */
102 private final IdentityManager identityManager;
104 /** Interface to freenet. */
105 private final FreenetInterface freenetInterface;
107 /** The Sone downloader. */
108 private final SoneDownloader soneDownloader;
110 /** The image inserter. */
111 private final ImageInserter imageInserter;
113 /** Sone downloader thread-pool. */
114 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
116 /** The update checker. */
117 private final UpdateChecker updateChecker;
119 /** The FCP interface. */
120 private volatile FcpInterface fcpInterface;
122 /** The times Sones were followed. */
123 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
125 /** Locked local Sones. */
126 /* synchronize on itself. */
127 private final Set<Sone> lockedSones = new HashSet<Sone>();
129 /** Sone inserters. */
130 /* synchronize access on this on localSones. */
131 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
133 /** Sone rescuers. */
134 /* synchronize access on this on localSones. */
135 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
137 /** All known Sones. */
138 private final Set<String> knownSones = new HashSet<String>();
141 private final Map<String, Post> posts = new HashMap<String, Post>();
143 /** All known posts. */
144 private final Set<String> knownPosts = new HashSet<String>();
147 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
149 /** All known replies. */
150 private final Set<String> knownReplies = new HashSet<String>();
152 /** All bookmarked posts. */
153 /* synchronize access on itself. */
154 private final Set<String> bookmarkedPosts = new HashSet<String>();
156 /** Trusted identities, sorted by own identities. */
157 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
159 /** All known albums. */
160 private final Map<String, Album> albums = new HashMap<String, Album>();
162 /** All known images. */
163 private final Map<String, Image> images = new HashMap<String, Image>();
165 /** All temporary images. */
166 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
168 /** Ticker for threads that mark own elements as known. */
169 private final Ticker localElementTicker = new Ticker();
171 /** The time the configuration was last touched. */
172 private volatile long lastConfigurationUpdate;
175 * Creates a new core.
177 * @param configuration
178 * The configuration of the core
180 * The database to use
181 * @param freenetInterface
182 * The freenet interface
183 * @param identityManager
184 * The identity manager
186 public Core(Configuration configuration, Database database, FreenetInterface freenetInterface, IdentityManager identityManager) {
188 this.configuration = configuration;
189 this.database = database;
190 this.freenetInterface = freenetInterface;
191 this.identityManager = identityManager;
192 this.soneDownloader = new SoneDownloader(this, freenetInterface);
193 this.imageInserter = new ImageInserter(this, freenetInterface);
194 this.updateChecker = new UpdateChecker(freenetInterface);
198 // LISTENER MANAGEMENT
202 * Adds a new core listener.
204 * @param coreListener
205 * The listener to add
207 public void addCoreListener(CoreListener coreListener) {
208 coreListenerManager.addListener(coreListener);
212 * Removes a core listener.
214 * @param coreListener
215 * The listener to remove
217 public void removeCoreListener(CoreListener coreListener) {
218 coreListenerManager.removeListener(coreListener);
226 * Sets the configuration to use. This will automatically save the current
227 * configuration to the given configuration.
229 * @param configuration
230 * The new configuration to use
232 public void setConfiguration(Configuration configuration) {
233 this.configuration = configuration;
234 touchConfiguration();
238 * Returns the options used by the core.
240 * @return The options of the core
242 public Preferences getPreferences() {
247 * Returns the identity manager used by the core.
249 * @return The identity manager
251 public IdentityManager getIdentityManager() {
252 return identityManager;
256 * Returns the update checker.
258 * @return The update checker
260 public UpdateChecker getUpdateChecker() {
261 return updateChecker;
265 * Sets the FCP interface to use.
267 * @param fcpInterface
268 * The FCP interface to use
270 public void setFcpInterface(FcpInterface fcpInterface) {
271 this.fcpInterface = fcpInterface;
275 * Returns the Sone rescuer for the given local Sone.
278 * The local Sone to get the rescuer for
279 * @return The Sone rescuer for the given Sone
281 public SoneRescuer getSoneRescuer(Sone sone) {
282 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
283 synchronized (soneRescuers) {
284 SoneRescuer soneRescuer = soneRescuers.get(sone);
285 if (soneRescuer == null) {
286 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
287 soneRescuers.put(sone, soneRescuer);
295 * Returns whether the given Sone is currently locked.
299 * @return {@code true} if the Sone is locked, {@code false} if it is not
301 public boolean isLocked(Sone sone) {
302 synchronized (lockedSones) {
303 return lockedSones.contains(sone);
308 * Returns all Sones, remote and local.
312 public Collection<Sone> getSones() {
313 return database.getSones();
317 * Returns the Sone with the given ID, regardless whether it’s local or
321 * The ID of the Sone to get
322 * @return The Sone with the given ID, or {@code null} if there is no such
325 public Sone getSone(String id) {
326 return getSone(id, true);
330 * Returns the Sone with the given ID, regardless whether it’s local or
334 * The ID of the Sone to get
336 * {@code true} to create a new Sone if none exists,
337 * {@code false} to return {@code null} if a Sone with the given
339 * @return The Sone with the given ID, or {@code null} if there is no such
343 public Sone getSone(String id, boolean create) {
344 return database.getSone(id, create);
348 * Checks whether the core knows a Sone with the given ID.
352 * @return {@code true} if there is a Sone with the given ID, {@code false}
355 public boolean hasSone(String id) {
356 return database.isLocalSone(id) || database.isRemoteSone(id);
360 * Returns whether the given Sone is a local Sone.
363 * The Sone to check for its locality
364 * @return {@code true} if the given Sone is local, {@code false} otherwise
366 public boolean isLocalSone(Sone sone) {
367 return database.isLocalSone(sone);
371 * Returns whether the given ID is the ID of a local Sone.
374 * The Sone ID to check for its locality
375 * @return {@code true} if the given ID is a local Sone, {@code false}
378 public boolean isLocalSone(String id) {
379 return database.isLocalSone(id);
383 * Returns all local Sones.
385 * @return All local Sones
387 public Collection<Sone> getLocalSones() {
388 return database.getLocalSones();
392 * Returns the local Sone with the given ID.
395 * The ID of the Sone to get
396 * @return The Sone with the given ID
398 public Sone getLocalSone(String id) {
399 return getLocalSone(id, true);
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 return database.getLocalSone(id, create);
417 * Returns all remote Sones.
419 * @return All remote Sones
421 public Collection<Sone> getRemoteSones() {
422 return database.getRemoteSones();
426 * Returns the remote Sone with the given ID.
429 * The ID of the remote Sone to get
431 * {@code true} to always create a Sone, {@code false} to return
432 * {@code null} if no Sone with the given ID exists
433 * @return The Sone with the given ID
435 public Sone getRemoteSone(String id, boolean create) {
436 return database.getRemoteSone(id, create);
440 * Returns whether the given Sone is a remote Sone.
444 * @return {@code true} if the given Sone is a remote Sone, {@code false}
447 public boolean isRemoteSone(Sone sone) {
448 return database.isRemoteSone(sone);
452 * Returns whether the Sone with the given ID is a remote Sone.
455 * The ID of the Sone to check
456 * @return {@code true} if the Sone with the given ID is a remote Sone,
457 * {@code false} otherwise
459 public boolean isRemoteSone(String id) {
460 return database.isRemoteSone(id);
464 * Returns whether the given Sone has been modified.
467 * The Sone to check for modifications
468 * @return {@code true} if a modification has been detected in the Sone,
469 * {@code false} otherwise
471 public boolean isModifiedSone(Sone sone) {
472 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
476 * Returns the time when the given was first followed by any local Sone.
479 * The Sone to get the time for
480 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
481 * been followed, or {@link Long#MAX_VALUE}
483 public long getSoneFollowingTime(Sone sone) {
484 synchronized (soneFollowingTimes) {
485 if (soneFollowingTimes.containsKey(sone)) {
486 return soneFollowingTimes.get(sone);
488 return Long.MAX_VALUE;
493 * Returns whether the target Sone is trusted by the origin Sone.
499 * @return {@code true} if the target Sone is trusted by the origin Sone
501 public boolean isSoneTrusted(Sone origin, Sone target) {
502 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
503 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
507 * Returns the post with the given ID.
510 * The ID of the post to get
511 * @return The post with the given ID, or a new post with the given ID
513 public Post getPost(String postId) {
514 return getPost(postId, true);
518 * Returns the post with the given ID, optionally creating a new post.
521 * The ID of the post to get
523 * {@code true} it create a new post if no post with the given ID
524 * exists, {@code false} to return {@code null}
525 * @return The post, or {@code null} if there is no such post
528 public Post getPost(String postId, boolean create) {
529 synchronized (posts) {
530 Post post = posts.get(postId);
531 if ((post == null) && create) {
532 post = new Post(postId);
533 posts.put(postId, post);
540 * Returns all posts that have the given Sone as recipient.
542 * @see Post#getRecipient()
544 * The recipient of the posts
545 * @return All posts that have the given Sone as recipient
547 public Set<Post> getDirectedPosts(Sone recipient) {
548 Validation.begin().isNotNull("Recipient", recipient).check();
549 Set<Post> directedPosts = new HashSet<Post>();
550 synchronized (posts) {
551 for (Post post : posts.values()) {
552 if (recipient.equals(post.getRecipient())) {
553 directedPosts.add(post);
557 return directedPosts;
561 * Returns the reply with the given ID. If there is no reply with the given
562 * ID yet, a new one is created.
565 * The ID of the reply to get
568 public PostReply getReply(String replyId) {
569 return getReply(replyId, true);
573 * Returns the reply with the given ID. If there is no reply with the given
574 * ID yet, a new one is created, unless {@code create} is false in which
575 * case {@code null} is returned.
578 * The ID of the reply to get
580 * {@code true} to always return a {@link Reply}, {@code false}
581 * to return {@code null} if no reply can be found
582 * @return The reply, or {@code null} if there is no such reply
584 public PostReply getReply(String replyId, boolean create) {
585 synchronized (replies) {
586 PostReply reply = replies.get(replyId);
587 if (create && (reply == null)) {
588 reply = new PostReply(replyId);
589 replies.put(replyId, reply);
596 * Returns all replies for the given post, order ascending by time.
599 * The post to get all replies for
600 * @return All replies for the given post
602 public List<PostReply> getReplies(Post post) {
603 Collection<Sone> sones = getSones();
604 List<PostReply> replies = new ArrayList<PostReply>();
605 for (Sone sone : sones) {
606 for (PostReply reply : sone.getReplies()) {
607 if (reply.getPost().equals(post)) {
612 Collections.sort(replies, Reply.TIME_COMPARATOR);
617 * Returns all Sones that have liked the given post.
620 * The post to get the liking Sones for
621 * @return The Sones that like the given post
623 public Set<Sone> getLikes(Post post) {
624 Set<Sone> sones = new HashSet<Sone>();
625 for (Sone sone : getSones()) {
626 if (sone.getLikedPostIds().contains(post.getId())) {
634 * Returns all Sones that have liked the given reply.
637 * The reply to get the liking Sones for
638 * @return The Sones that like the given reply
640 public Set<Sone> getLikes(PostReply reply) {
641 Set<Sone> sones = new HashSet<Sone>();
642 for (Sone sone : getSones()) {
643 if (sone.getLikedReplyIds().contains(reply.getId())) {
651 * Returns whether the given post is bookmarked.
655 * @return {@code true} if the given post is bookmarked, {@code false}
658 public boolean isBookmarked(Post post) {
659 return isPostBookmarked(post.getId());
663 * Returns whether the post with the given ID is bookmarked.
666 * The ID of the post to check
667 * @return {@code true} if the post with the given ID is bookmarked,
668 * {@code false} otherwise
670 public boolean isPostBookmarked(String id) {
671 synchronized (bookmarkedPosts) {
672 return bookmarkedPosts.contains(id);
677 * Returns all currently known bookmarked posts.
679 * @return All bookmarked posts
681 public Set<Post> getBookmarkedPosts() {
682 Set<Post> posts = new HashSet<Post>();
683 synchronized (bookmarkedPosts) {
684 for (String bookmarkedPostId : bookmarkedPosts) {
685 Post post = getPost(bookmarkedPostId, false);
695 * Returns the album with the given ID, creating a new album if no album
696 * with the given ID can be found.
699 * The ID of the album
700 * @return The album with the given ID
702 public Album getAlbum(String albumId) {
703 return getAlbum(albumId, true);
707 * Returns the album with the given ID, optionally creating a new album if
708 * an album with the given ID can not be found.
711 * The ID of the album
713 * {@code true} to create a new album if none exists for the
715 * @return The album with the given ID, or {@code null} if no album with the
716 * given ID exists and {@code create} is {@code false}
718 public Album getAlbum(String albumId, boolean create) {
719 synchronized (albums) {
720 Album album = albums.get(albumId);
721 if (create && (album == null)) {
722 album = new Album(albumId);
723 albums.put(albumId, album);
730 * Returns the image with the given ID, creating it if necessary.
733 * The ID of the image
734 * @return The image with the given ID
736 public Image getImage(String imageId) {
737 return getImage(imageId, true);
741 * Returns the image with the given ID, optionally creating it if it does
745 * The ID of the image
747 * {@code true} to create an image if none exists with the given
749 * @return The image with the given ID, or {@code null} if none exists and
752 public Image getImage(String imageId, boolean create) {
753 synchronized (images) {
754 Image image = images.get(imageId);
755 if (create && (image == null)) {
756 image = new Image(imageId);
757 images.put(imageId, image);
764 * Returns the temporary image with the given ID.
767 * The ID of the temporary image
768 * @return The temporary image, or {@code null} if there is no temporary
769 * image with the given ID
771 public TemporaryImage getTemporaryImage(String imageId) {
772 synchronized (temporaryImages) {
773 return temporaryImages.get(imageId);
782 * Locks the given Sone. A locked Sone will not be inserted by
783 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
789 public void lockSone(Sone sone) {
790 synchronized (lockedSones) {
791 if (lockedSones.add(sone)) {
792 coreListenerManager.fireSoneLocked(sone);
798 * Unlocks the given Sone.
800 * @see #lockSone(Sone)
804 public void unlockSone(Sone sone) {
805 synchronized (lockedSones) {
806 if (lockedSones.remove(sone)) {
807 coreListenerManager.fireSoneUnlocked(sone);
813 * Adds a local Sone from the given own identity.
816 * The own identity to create a Sone from
817 * @return The added (or already existing) Sone
819 public Sone addLocalSone(OwnIdentity ownIdentity) {
820 if (ownIdentity == null) {
821 logger.log(Level.WARNING, "Given OwnIdentity is null!");
826 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
827 } catch (MalformedURLException mue1) {
828 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
831 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
832 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
834 /* TODO - load posts ’n stuff */
835 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
836 soneInserter.addSoneInsertListener(this);
837 soneInserters.put(sone, soneInserter);
838 sone.setStatus(SoneStatus.idle);
840 soneInserter.start();
841 database.saveSone(sone);
846 * Creates a new Sone for the given own identity.
849 * The own identity to create a Sone for
850 * @return The created Sone
852 public Sone createSone(OwnIdentity ownIdentity) {
854 ownIdentity.addContext("Sone");
855 } catch (WebOfTrustException wote1) {
856 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity), wote1);
859 Sone sone = addLocalSone(ownIdentity);
860 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
861 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
862 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
863 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
864 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
865 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
867 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
868 touchConfiguration();
873 * Adds the Sone of the given identity.
876 * The identity whose Sone to add
877 * @return The added or already existing Sone
879 public Sone addRemoteSone(Identity identity) {
880 if (identity == null) {
881 logger.log(Level.WARNING, "Given Identity is null!");
884 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
885 boolean newSone = sone.getRequestUri() == null;
886 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
887 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
889 synchronized (knownSones) {
890 newSone = !knownSones.contains(sone.getId());
892 sone.setKnown(!newSone);
894 coreListenerManager.fireNewSoneFound(sone);
895 for (Sone localSone : getLocalSones()) {
896 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
897 followSone(localSone, sone);
902 soneDownloader.addSone(sone);
903 soneDownloaders.execute(new Runnable() {
906 @SuppressWarnings("synthetic-access")
908 soneDownloader.fetchSone(sone, sone.getRequestUri());
912 database.saveSone(sone);
917 * Lets the given local Sone follow the Sone with the given ID.
920 * The local Sone that should follow another Sone
922 * The ID of the Sone to follow
924 public void followSone(Sone sone, String soneId) {
925 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
926 Sone followedSone = getSone(soneId, true);
927 if (followedSone == null) {
928 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
931 followSone(sone, getSone(soneId));
935 * Lets the given local Sone follow the other given Sone. If the given Sone
936 * was not followed by any local Sone before, this will mark all elements of
937 * the followed Sone as read that have been created before the current
941 * The local Sone that should follow the other Sone
942 * @param followedSone
943 * The Sone that should be followed
945 public void followSone(Sone sone, Sone followedSone) {
946 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
947 sone.addFriend(followedSone.getId());
948 synchronized (soneFollowingTimes) {
949 if (!soneFollowingTimes.containsKey(followedSone)) {
950 long now = System.currentTimeMillis();
951 soneFollowingTimes.put(followedSone, now);
952 for (Post post : followedSone.getPosts()) {
953 if (post.getTime() < now) {
957 for (PostReply reply : followedSone.getReplies()) {
958 if (reply.getTime() < now) {
959 markReplyKnown(reply);
964 touchConfiguration();
968 * Lets the given local Sone unfollow the Sone with the given ID.
971 * The local Sone that should unfollow another Sone
973 * The ID of the Sone being unfollowed
975 public void unfollowSone(Sone sone, String soneId) {
976 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
977 unfollowSone(sone, getSone(soneId, false));
981 * Lets the given local Sone unfollow the other given Sone. If the given
982 * local Sone is the last local Sone that followed the given Sone, its
983 * following time will be removed.
986 * The local Sone that should unfollow another Sone
987 * @param unfollowedSone
988 * The Sone being unfollowed
990 public void unfollowSone(Sone sone, Sone unfollowedSone) {
991 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
992 sone.removeFriend(unfollowedSone.getId());
993 boolean unfollowedSoneStillFollowed = false;
994 for (Sone localSone : getLocalSones()) {
995 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
997 if (!unfollowedSoneStillFollowed) {
998 synchronized (soneFollowingTimes) {
999 soneFollowingTimes.remove(unfollowedSone);
1002 touchConfiguration();
1006 * Retrieves the trust relationship from the origin to the target. If the
1007 * trust relationship can not be retrieved, {@code null} is returned.
1009 * @see Identity#getTrust(OwnIdentity)
1011 * The origin of the trust tree
1013 * The target of the trust
1014 * @return The trust relationship
1016 public Trust getTrust(Sone origin, Sone target) {
1017 if (!isLocalSone(origin)) {
1018 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
1021 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1025 * Sets the trust value of the given origin Sone for the target Sone.
1032 * The trust value (from {@code -100} to {@code 100})
1034 public void setTrust(Sone origin, Sone target, int trustValue) {
1035 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();
1037 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1038 } catch (WebOfTrustException wote1) {
1039 logger.log(Level.WARNING, String.format("Could not set trust for Sone: %s", target), wote1);
1044 * Removes any trust assignment for the given target Sone.
1051 public void removeTrust(Sone origin, Sone target) {
1052 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1054 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1055 } catch (WebOfTrustException wote1) {
1056 logger.log(Level.WARNING, String.format("Could not remove trust for Sone: %s", target), wote1);
1061 * Assigns the configured positive trust value for the given target.
1068 public void trustSone(Sone origin, Sone target) {
1069 setTrust(origin, target, preferences.getPositiveTrust());
1073 * Assigns the configured negative trust value for the given target.
1080 public void distrustSone(Sone origin, Sone target) {
1081 setTrust(origin, target, preferences.getNegativeTrust());
1085 * Removes the trust assignment for the given target.
1092 public void untrustSone(Sone origin, Sone target) {
1093 removeTrust(origin, target);
1097 * Updates the stored Sone with the given Sone.
1102 public void updateSone(Sone sone) {
1103 updateSone(sone, false);
1107 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1108 * {@code true}, an older Sone than the current Sone can be given to restore
1112 * The Sone to update
1113 * @param soneRescueMode
1114 * {@code true} if the stored Sone should be updated regardless
1115 * of the age of the given Sone
1117 public void updateSone(Sone sone, boolean soneRescueMode) {
1118 if (hasSone(sone.getId())) {
1119 Sone storedSone = getSone(sone.getId());
1120 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1121 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1124 synchronized (posts) {
1125 if (!soneRescueMode) {
1126 for (Post post : storedSone.getPosts()) {
1127 posts.remove(post.getId());
1128 if (!sone.getPosts().contains(post)) {
1129 coreListenerManager.firePostRemoved(post);
1133 List<Post> storedPosts = storedSone.getPosts();
1134 synchronized (knownPosts) {
1135 for (Post post : sone.getPosts()) {
1136 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1137 if (!storedPosts.contains(post)) {
1138 if (post.getTime() < getSoneFollowingTime(sone)) {
1139 knownPosts.add(post.getId());
1140 } else if (!knownPosts.contains(post.getId())) {
1141 sone.setKnown(false);
1142 coreListenerManager.fireNewPostFound(post);
1145 posts.put(post.getId(), post);
1149 synchronized (replies) {
1150 if (!soneRescueMode) {
1151 for (PostReply reply : storedSone.getReplies()) {
1152 replies.remove(reply.getId());
1153 if (!sone.getReplies().contains(reply)) {
1154 coreListenerManager.fireReplyRemoved(reply);
1158 Set<PostReply> storedReplies = storedSone.getReplies();
1159 synchronized (knownReplies) {
1160 for (PostReply reply : sone.getReplies()) {
1161 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1162 if (!storedReplies.contains(reply)) {
1163 if (reply.getTime() < getSoneFollowingTime(sone)) {
1164 knownReplies.add(reply.getId());
1165 } else if (!knownReplies.contains(reply.getId())) {
1166 reply.setKnown(false);
1167 coreListenerManager.fireNewReplyFound(reply);
1170 replies.put(reply.getId(), reply);
1174 synchronized (albums) {
1175 synchronized (images) {
1176 for (Album album : storedSone.getAlbums()) {
1177 albums.remove(album.getId());
1178 for (Image image : album.getImages()) {
1179 images.remove(image.getId());
1182 for (Album album : sone.getAlbums()) {
1183 albums.put(album.getId(), album);
1184 for (Image image : album.getImages()) {
1185 images.put(image.getId(), image);
1190 synchronized (storedSone) {
1191 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1192 storedSone.setTime(sone.getTime());
1194 storedSone.setClient(sone.getClient());
1195 storedSone.setProfile(sone.getProfile());
1196 if (soneRescueMode) {
1197 for (Post post : sone.getPosts()) {
1198 storedSone.addPost(post);
1200 for (PostReply reply : sone.getReplies()) {
1201 storedSone.addReply(reply);
1203 for (String likedPostId : sone.getLikedPostIds()) {
1204 storedSone.addLikedPostId(likedPostId);
1206 for (String likedReplyId : sone.getLikedReplyIds()) {
1207 storedSone.addLikedReplyId(likedReplyId);
1209 for (Album album : sone.getAlbums()) {
1210 storedSone.addAlbum(album);
1213 storedSone.setPosts(sone.getPosts());
1214 storedSone.setReplies(sone.getReplies());
1215 storedSone.setLikePostIds(sone.getLikedPostIds());
1216 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1217 storedSone.setAlbums(sone.getAlbums());
1219 storedSone.setLatestEdition(sone.getLatestEdition());
1225 * Deletes the given Sone. This will remove the Sone from the
1226 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1227 * and remove the context from its identity.
1230 * The Sone to delete
1232 public void deleteSone(Sone sone) {
1233 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1234 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1237 if (!database.isLocalSone(sone)) {
1238 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1241 database.removeSone(sone.getId());
1242 SoneInserter soneInserter = soneInserters.remove(sone);
1243 soneInserter.removeSoneInsertListener(this);
1244 soneInserter.stop();
1246 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1247 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1248 } catch (WebOfTrustException wote1) {
1249 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1252 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1253 } catch (ConfigurationException ce1) {
1254 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1259 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1260 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1263 * The Sone to mark as known
1265 public void markSoneKnown(Sone sone) {
1266 if (!sone.isKnown()) {
1267 sone.setKnown(true);
1268 synchronized (knownSones) {
1269 knownSones.add(sone.getId());
1271 coreListenerManager.fireMarkSoneKnown(sone);
1272 touchConfiguration();
1277 * Loads and updates the given Sone from the configuration. If any error is
1278 * encountered, loading is aborted and the given Sone is not changed.
1281 * The Sone to load and update
1283 public void loadSone(Sone sone) {
1284 if (!isLocalSone(sone)) {
1285 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1289 /* initialize options. */
1290 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1291 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1292 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1293 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1294 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1295 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1298 String sonePrefix = "Sone/" + sone.getId();
1299 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1300 if (soneTime == null) {
1301 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1304 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1307 Profile profile = new Profile(sone);
1308 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1309 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1310 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1311 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1312 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1313 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1315 /* load profile fields. */
1317 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1318 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1319 if (fieldName == null) {
1322 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1323 profile.addField(fieldName).setValue(fieldValue);
1327 Set<Post> posts = new HashSet<Post>();
1329 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1330 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1331 if (postId == null) {
1334 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1335 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1336 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1337 if ((postTime == 0) || (postText == null)) {
1338 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1341 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1342 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1343 post.setRecipient(getSone(postRecipientId));
1349 Set<PostReply> replies = new HashSet<PostReply>();
1351 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1352 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1353 if (replyId == null) {
1356 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1357 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1358 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1359 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1360 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1363 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1366 /* load post likes. */
1367 Set<String> likedPostIds = new HashSet<String>();
1369 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1370 if (likedPostId == null) {
1373 likedPostIds.add(likedPostId);
1376 /* load reply likes. */
1377 Set<String> likedReplyIds = new HashSet<String>();
1379 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1380 if (likedReplyId == null) {
1383 likedReplyIds.add(likedReplyId);
1387 Set<String> friends = new HashSet<String>();
1389 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1390 if (friendId == null) {
1393 friends.add(friendId);
1397 List<Album> topLevelAlbums = new ArrayList<Album>();
1398 int albumCounter = 0;
1400 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1401 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1402 if (albumId == null) {
1405 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1406 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1407 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1408 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1409 if ((albumTitle == null) || (albumDescription == null)) {
1410 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1413 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1414 if (albumParentId != null) {
1415 Album parentAlbum = getAlbum(albumParentId, false);
1416 if (parentAlbum == null) {
1417 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1420 parentAlbum.addAlbum(album);
1422 if (!topLevelAlbums.contains(album)) {
1423 topLevelAlbums.add(album);
1429 int imageCounter = 0;
1431 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1432 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1433 if (imageId == null) {
1436 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1437 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1438 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1439 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1440 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1441 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1442 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1443 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1444 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1447 Album album = getAlbum(albumId, false);
1448 if (album == null) {
1449 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1452 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1453 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1454 album.addImage(image);
1458 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1459 if (avatarId != null) {
1460 profile.setAvatar(getImage(avatarId, false));
1464 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1465 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1466 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1467 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1468 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1469 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1471 /* if we’re still here, Sone was loaded successfully. */
1472 synchronized (sone) {
1473 sone.setTime(soneTime);
1474 sone.setProfile(profile);
1475 sone.setPosts(posts);
1476 sone.setReplies(replies);
1477 sone.setLikePostIds(likedPostIds);
1478 sone.setLikeReplyIds(likedReplyIds);
1479 for (String friendId : friends) {
1480 followSone(sone, friendId);
1482 sone.setAlbums(topLevelAlbums);
1483 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1485 synchronized (knownSones) {
1486 for (String friend : friends) {
1487 knownSones.add(friend);
1490 synchronized (knownPosts) {
1491 for (Post post : posts) {
1492 knownPosts.add(post.getId());
1495 synchronized (knownReplies) {
1496 for (PostReply reply : replies) {
1497 knownReplies.add(reply.getId());
1503 * Creates a new post.
1506 * The Sone that creates the post
1508 * The text of the post
1509 * @return The created post
1511 public Post createPost(Sone sone, String text) {
1512 return createPost(sone, System.currentTimeMillis(), text);
1516 * Creates a new post.
1519 * The Sone that creates the post
1521 * The time of the post
1523 * The text of the post
1524 * @return The created post
1526 public Post createPost(Sone sone, long time, String text) {
1527 return createPost(sone, null, time, text);
1531 * Creates a new post.
1534 * The Sone that creates the post
1536 * The recipient Sone, or {@code null} if this post does not have
1539 * The text of the post
1540 * @return The created post
1542 public Post createPost(Sone sone, Sone recipient, String text) {
1543 return createPost(sone, recipient, System.currentTimeMillis(), text);
1547 * Creates a new post.
1550 * The Sone that creates the post
1552 * The recipient Sone, or {@code null} if this post does not have
1555 * The time of the post
1557 * The text of the post
1558 * @return The created post
1560 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1561 if (!isLocalSone(sone)) {
1562 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1565 final Post post = new Post(sone, time, text);
1566 if (recipient != null) {
1567 post.setRecipient(recipient);
1569 synchronized (posts) {
1570 posts.put(post.getId(), post);
1572 coreListenerManager.fireNewPostFound(post);
1574 touchConfiguration();
1575 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1582 markPostKnown(post);
1584 }, "Mark " + post + " read.");
1589 * Deletes the given post.
1592 * The post to delete
1594 public void deletePost(Post post) {
1595 if (!isLocalSone(post.getSone())) {
1596 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1599 post.getSone().removePost(post);
1600 synchronized (posts) {
1601 posts.remove(post.getId());
1603 coreListenerManager.firePostRemoved(post);
1604 markPostKnown(post);
1605 touchConfiguration();
1609 * Marks the given post as known, if it is currently not a known post
1610 * (according to {@link Post#isKnown()}).
1613 * The post to mark as known
1615 public void markPostKnown(Post post) {
1616 post.setKnown(true);
1617 synchronized (knownPosts) {
1618 coreListenerManager.fireMarkPostKnown(post);
1619 if (knownPosts.add(post.getId())) {
1620 touchConfiguration();
1623 for (PostReply reply : getReplies(post)) {
1624 markReplyKnown(reply);
1629 * Bookmarks the given post.
1632 * The post to bookmark
1634 public void bookmark(Post post) {
1635 bookmarkPost(post.getId());
1639 * Bookmarks the post with the given ID.
1642 * The ID of the post to bookmark
1644 public void bookmarkPost(String id) {
1645 synchronized (bookmarkedPosts) {
1646 bookmarkedPosts.add(id);
1651 * Removes the given post from the bookmarks.
1654 * The post to unbookmark
1656 public void unbookmark(Post post) {
1657 unbookmarkPost(post.getId());
1661 * Removes the post with the given ID from the bookmarks.
1664 * The ID of the post to unbookmark
1666 public void unbookmarkPost(String id) {
1667 synchronized (bookmarkedPosts) {
1668 bookmarkedPosts.remove(id);
1673 * Creates a new reply.
1676 * The Sone that creates the reply
1678 * The post that this reply refers to
1680 * The text of the reply
1681 * @return The created reply
1683 public PostReply createReply(Sone sone, Post post, String text) {
1684 return createReply(sone, post, System.currentTimeMillis(), text);
1688 * Creates a new reply.
1691 * The Sone that creates the reply
1693 * The post that this reply refers to
1695 * The time of the reply
1697 * The text of the reply
1698 * @return The created reply
1700 public PostReply createReply(Sone sone, Post post, long time, String text) {
1701 if (!isLocalSone(sone)) {
1702 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1705 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1706 synchronized (replies) {
1707 replies.put(reply.getId(), reply);
1709 synchronized (knownReplies) {
1710 coreListenerManager.fireNewReplyFound(reply);
1712 sone.addReply(reply);
1713 touchConfiguration();
1714 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1721 markReplyKnown(reply);
1723 }, "Mark " + reply + " read.");
1728 * Deletes the given reply.
1731 * The reply to delete
1733 public void deleteReply(PostReply reply) {
1734 Sone sone = reply.getSone();
1735 if (!isLocalSone(sone)) {
1736 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1739 synchronized (replies) {
1740 replies.remove(reply.getId());
1742 synchronized (knownReplies) {
1743 markReplyKnown(reply);
1744 knownReplies.remove(reply.getId());
1746 sone.removeReply(reply);
1747 touchConfiguration();
1751 * Marks the given reply as known, if it is currently not a known reply
1752 * (according to {@link Reply#isKnown()}).
1755 * The reply to mark as known
1757 public void markReplyKnown(PostReply reply) {
1758 reply.setKnown(true);
1759 synchronized (knownReplies) {
1760 coreListenerManager.fireMarkReplyKnown(reply);
1761 if (knownReplies.add(reply.getId())) {
1762 touchConfiguration();
1768 * Creates a new top-level album for the given Sone.
1771 * The Sone to create the album for
1772 * @return The new album
1774 public Album createAlbum(Sone sone) {
1775 return createAlbum(sone, null);
1779 * Creates a new album for the given Sone.
1782 * The Sone to create the album for
1784 * The parent of the album (may be {@code null} to create a
1786 * @return The new album
1788 public Album createAlbum(Sone sone, Album parent) {
1789 Album album = new Album();
1790 synchronized (albums) {
1791 albums.put(album.getId(), album);
1793 album.setSone(sone);
1794 if (parent != null) {
1795 parent.addAlbum(album);
1797 sone.addAlbum(album);
1803 * Deletes the given album. The owner of the album has to be a local Sone,
1804 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1807 * The album to remove
1809 public void deleteAlbum(Album album) {
1810 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1811 if (!album.isEmpty()) {
1814 if (album.getParent() == null) {
1815 album.getSone().removeAlbum(album);
1817 album.getParent().removeAlbum(album);
1819 synchronized (albums) {
1820 albums.remove(album.getId());
1822 saveSone(album.getSone());
1826 * Creates a new image.
1829 * The Sone creating the image
1831 * The album the image will be inserted into
1832 * @param temporaryImage
1833 * The temporary image to create the image from
1834 * @return The newly created image
1836 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1837 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();
1838 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1839 album.addImage(image);
1840 synchronized (images) {
1841 images.put(image.getId(), image);
1843 imageInserter.insertImage(temporaryImage, image);
1848 * Deletes the given image. This method will also delete a matching
1851 * @see #deleteTemporaryImage(TemporaryImage)
1853 * The image to delete
1855 public void deleteImage(Image image) {
1856 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1857 deleteTemporaryImage(image.getId());
1858 image.getAlbum().removeImage(image);
1859 synchronized (images) {
1860 images.remove(image.getId());
1862 saveSone(image.getSone());
1866 * Creates a new temporary image.
1869 * The MIME type of the temporary image
1871 * The encoded data of the image
1872 * @return The temporary image
1874 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1875 TemporaryImage temporaryImage = new TemporaryImage();
1876 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1877 synchronized (temporaryImages) {
1878 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1880 return temporaryImage;
1884 * Deletes the given temporary image.
1886 * @param temporaryImage
1887 * The temporary image to delete
1889 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1890 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1891 deleteTemporaryImage(temporaryImage.getId());
1895 * Deletes the temporary image with the given ID.
1898 * The ID of the temporary image to delete
1900 public void deleteTemporaryImage(String imageId) {
1901 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1902 synchronized (temporaryImages) {
1903 temporaryImages.remove(imageId);
1905 Image image = getImage(imageId, false);
1906 if (image != null) {
1907 imageInserter.cancelImageInsert(image);
1912 * Notifies the core that the configuration, either of the core or of a
1913 * single local Sone, has changed, and that the configuration should be
1916 public void touchConfiguration() {
1917 lastConfigurationUpdate = System.currentTimeMillis();
1928 public void serviceStart() {
1929 loadConfiguration();
1930 updateChecker.addUpdateListener(this);
1931 updateChecker.start();
1938 public void serviceRun() {
1939 long lastSaved = System.currentTimeMillis();
1940 while (!shouldStop()) {
1942 long now = System.currentTimeMillis();
1943 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1944 for (Sone localSone : getLocalSones()) {
1945 saveSone(localSone);
1947 saveConfiguration();
1957 public void serviceStop() {
1958 for (SoneInserter soneInserter : soneInserters.values()) {
1959 soneInserter.removeSoneInsertListener(this);
1960 soneInserter.stop();
1962 updateChecker.stop();
1963 updateChecker.removeUpdateListener(this);
1964 soneDownloader.stop();
1972 * Saves the given Sone. This will persist all local settings for the given
1973 * Sone, such as the friends list and similar, private options.
1978 private synchronized void saveSone(Sone sone) {
1979 if (!isLocalSone(sone)) {
1980 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1983 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1984 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1988 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1990 /* save Sone into configuration. */
1991 String sonePrefix = "Sone/" + sone.getId();
1992 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1993 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1996 Profile profile = sone.getProfile();
1997 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1998 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1999 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2000 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2001 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2002 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2003 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2005 /* save profile fields. */
2006 int fieldCounter = 0;
2007 for (Field profileField : profile.getFields()) {
2008 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2009 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2010 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2012 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2015 int postCounter = 0;
2016 for (Post post : sone.getPosts()) {
2017 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2018 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2019 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2020 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2021 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2023 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2026 int replyCounter = 0;
2027 for (PostReply reply : sone.getReplies()) {
2028 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2029 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2030 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2031 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2032 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2034 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2036 /* save post likes. */
2037 int postLikeCounter = 0;
2038 for (String postId : sone.getLikedPostIds()) {
2039 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2041 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2043 /* save reply likes. */
2044 int replyLikeCounter = 0;
2045 for (String replyId : sone.getLikedReplyIds()) {
2046 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2048 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2051 int friendCounter = 0;
2052 for (String friendId : sone.getFriends()) {
2053 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2055 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2057 /* save albums. first, collect in a flat structure, top-level first. */
2058 List<Album> albums = sone.getAllAlbums();
2060 int albumCounter = 0;
2061 for (Album album : albums) {
2062 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2063 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2064 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2065 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2066 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2067 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2069 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2072 int imageCounter = 0;
2073 for (Album album : albums) {
2074 for (Image image : album.getImages()) {
2075 if (!image.isInserted()) {
2078 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2079 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2080 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2081 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2082 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2083 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2084 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2085 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2086 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2089 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2092 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2093 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2094 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2095 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2096 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2097 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2099 configuration.save();
2101 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2103 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2104 } catch (ConfigurationException ce1) {
2105 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2106 } catch (WebOfTrustException wote1) {
2107 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2112 * Saves the current options.
2114 private void saveConfiguration() {
2115 synchronized (configuration) {
2116 if (storingConfiguration) {
2117 logger.log(Level.FINE, "Already storing configuration…");
2120 storingConfiguration = true;
2123 /* store the options first. */
2125 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2126 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2127 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2128 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2129 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2130 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2131 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2132 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2133 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2134 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2135 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2136 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2137 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2138 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2140 /* save known Sones. */
2141 int soneCounter = 0;
2142 synchronized (knownSones) {
2143 for (String knownSoneId : knownSones) {
2144 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2146 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2149 /* save Sone following times. */
2151 synchronized (soneFollowingTimes) {
2152 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2153 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2154 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2157 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2160 /* save known posts. */
2161 int postCounter = 0;
2162 synchronized (knownPosts) {
2163 for (String knownPostId : knownPosts) {
2164 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2166 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2169 /* save known replies. */
2170 int replyCounter = 0;
2171 synchronized (knownReplies) {
2172 for (String knownReplyId : knownReplies) {
2173 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2175 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2178 /* save bookmarked posts. */
2179 int bookmarkedPostCounter = 0;
2180 synchronized (bookmarkedPosts) {
2181 for (String bookmarkedPostId : bookmarkedPosts) {
2182 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2185 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2188 configuration.save();
2190 } catch (ConfigurationException ce1) {
2191 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2193 synchronized (configuration) {
2194 storingConfiguration = false;
2200 * Loads the configuration.
2202 @SuppressWarnings("unchecked")
2203 private void loadConfiguration() {
2204 /* create options. */
2205 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2208 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2209 SoneInserter.setInsertionDelay(newValue);
2213 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2214 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2215 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2216 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2217 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2218 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2219 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2220 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2223 @SuppressWarnings("synthetic-access")
2224 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2225 fcpInterface.setActive(newValue);
2228 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2231 @SuppressWarnings("synthetic-access")
2232 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2233 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2237 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2238 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2239 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2241 /* read options from configuration. */
2242 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2243 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2244 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2245 options.getBooleanOption("ClearOnNextRestart").set(null);
2246 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2247 if (clearConfiguration) {
2248 /* stop loading the configuration. */
2252 loadConfigurationValue("InsertionDelay");
2253 loadConfigurationValue("PostsPerPage");
2254 loadConfigurationValue("CharactersPerPost");
2255 loadConfigurationValue("PostCutOffLength");
2256 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2257 loadConfigurationValue("PositiveTrust");
2258 loadConfigurationValue("NegativeTrust");
2259 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2260 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2261 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2262 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2264 /* load known Sones. */
2265 int soneCounter = 0;
2267 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2268 if (knownSoneId == null) {
2271 synchronized (knownSones) {
2272 knownSones.add(knownSoneId);
2276 /* load Sone following times. */
2279 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2280 if (soneId == null) {
2283 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2284 Sone followedSone = getSone(soneId);
2285 if (followedSone == null) {
2286 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2288 synchronized (soneFollowingTimes) {
2289 soneFollowingTimes.put(getSone(soneId), time);
2295 /* load known posts. */
2296 int postCounter = 0;
2298 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2299 if (knownPostId == null) {
2302 synchronized (knownPosts) {
2303 knownPosts.add(knownPostId);
2307 /* load known replies. */
2308 int replyCounter = 0;
2310 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2311 if (knownReplyId == null) {
2314 synchronized (knownReplies) {
2315 knownReplies.add(knownReplyId);
2319 /* load bookmarked posts. */
2320 int bookmarkedPostCounter = 0;
2322 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2323 if (bookmarkedPostId == null) {
2326 synchronized (bookmarkedPosts) {
2327 bookmarkedPosts.add(bookmarkedPostId);
2334 * Loads an {@link Integer} configuration value for the option with the
2335 * given name, logging validation failures.
2338 * The name of the option to load
2340 private void loadConfigurationValue(String optionName) {
2342 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2343 } catch (IllegalArgumentException iae1) {
2344 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2349 * Generate a Sone URI from the given URI and latest edition.
2352 * The URI to derive the Sone URI from
2353 * @return The derived URI
2355 private FreenetURI getSoneUri(String uriString) {
2357 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2359 } catch (MalformedURLException mue1) {
2360 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2366 // INTERFACE IdentityListener
2373 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2374 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2375 if (ownIdentity.hasContext("Sone")) {
2376 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2377 addLocalSone(ownIdentity);
2385 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2386 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2387 trustedIdentities.remove(ownIdentity);
2394 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2395 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2396 trustedIdentities.get(ownIdentity).add(identity);
2397 addRemoteSone(identity);
2404 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2405 new Thread(new Runnable() {
2408 @SuppressWarnings("synthetic-access")
2410 Sone sone = getRemoteSone(identity.getId(), false);
2411 sone.setIdentity(identity);
2412 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2413 soneDownloader.addSone(sone);
2414 soneDownloader.fetchSone(sone);
2423 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2424 trustedIdentities.get(ownIdentity).remove(identity);
2425 boolean foundIdentity = false;
2426 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2427 if (trustedIdentity.getKey().equals(ownIdentity)) {
2430 if (trustedIdentity.getValue().contains(identity)) {
2431 foundIdentity = true;
2434 if (foundIdentity) {
2435 /* some local identity still trusts this identity, don’t remove. */
2438 Sone sone = getSone(identity.getId(), false);
2440 /* TODO - we don’t have the Sone anymore. should this happen? */
2443 synchronized (posts) {
2444 synchronized (knownPosts) {
2445 for (Post post : sone.getPosts()) {
2446 posts.remove(post.getId());
2447 coreListenerManager.firePostRemoved(post);
2451 synchronized (replies) {
2452 synchronized (knownReplies) {
2453 for (PostReply reply : sone.getReplies()) {
2454 replies.remove(reply.getId());
2455 coreListenerManager.fireReplyRemoved(reply);
2459 database.removeSone(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 saveSone(image.getSone());
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 characters per post, or <code>-1</code> if the
2636 * posts should not be cut off.
2638 * @return The numbers of characters per post
2640 public int getCharactersPerPost() {
2641 return options.getIntegerOption("CharactersPerPost").get();
2645 * Validates the number of characters per post.
2647 * @param charactersPerPost
2648 * The number of characters per post
2649 * @return {@code true} if the number of characters per post was valid,
2650 * {@code false} otherwise
2652 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2653 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2657 * Sets the number of characters per post.
2659 * @param charactersPerPost
2660 * The number of characters per post, or <code>-1</code> to
2661 * not cut off the posts
2662 * @return This preferences objects
2664 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2665 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2670 * Returns the number of characters the shortened post should have.
2672 * @return The number of characters of the snippet
2674 public int getPostCutOffLength() {
2675 return options.getIntegerOption("PostCutOffLength").get();
2679 * Validates the number of characters after which to cut off the post.
2681 * @param postCutOffLength
2682 * The number of characters of the snippet
2683 * @return {@code true} if the number of characters of the snippet is
2684 * valid, {@code false} otherwise
2686 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2687 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2691 * Sets the number of characters the shortened post should have.
2693 * @param postCutOffLength
2694 * The number of characters of the snippet
2695 * @return This preferences
2697 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2698 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2703 * Returns whether Sone requires full access to be even visible.
2705 * @return {@code true} if Sone requires full access, {@code false}
2708 public boolean isRequireFullAccess() {
2709 return options.getBooleanOption("RequireFullAccess").get();
2713 * Sets whether Sone requires full access to be even visible.
2715 * @param requireFullAccess
2716 * {@code true} if Sone requires full access, {@code false}
2719 public void setRequireFullAccess(Boolean requireFullAccess) {
2720 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2724 * Returns the positive trust.
2726 * @return The positive trust
2728 public int getPositiveTrust() {
2729 return options.getIntegerOption("PositiveTrust").get();
2733 * Validates the positive trust.
2735 * @param positiveTrust
2736 * The positive trust to validate
2737 * @return {@code true} if the positive trust was valid, {@code false}
2740 public boolean validatePositiveTrust(Integer positiveTrust) {
2741 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2745 * Sets the positive trust.
2747 * @param positiveTrust
2748 * The new positive trust, or {@code null} to restore it to
2750 * @return This preferences
2752 public Preferences setPositiveTrust(Integer positiveTrust) {
2753 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2758 * Returns the negative trust.
2760 * @return The negative trust
2762 public int getNegativeTrust() {
2763 return options.getIntegerOption("NegativeTrust").get();
2767 * Validates the negative trust.
2769 * @param negativeTrust
2770 * The negative trust to validate
2771 * @return {@code true} if the negative trust was valid, {@code false}
2774 public boolean validateNegativeTrust(Integer negativeTrust) {
2775 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2779 * Sets the negative trust.
2781 * @param negativeTrust
2782 * The negative trust, or {@code null} to restore it to the
2784 * @return The preferences
2786 public Preferences setNegativeTrust(Integer negativeTrust) {
2787 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2792 * Returns the trust comment. This is the comment that is set in the web
2793 * of trust when a trust value is assigned to an identity.
2795 * @return The trust comment
2797 public String getTrustComment() {
2798 return options.getStringOption("TrustComment").get();
2802 * Sets the trust comment.
2804 * @param trustComment
2805 * The trust comment, or {@code null} to restore it to the
2807 * @return This preferences
2809 public Preferences setTrustComment(String trustComment) {
2810 options.getStringOption("TrustComment").set(trustComment);
2815 * Returns whether the {@link FcpInterface FCP interface} is currently
2818 * @see FcpInterface#setActive(boolean)
2819 * @return {@code true} if the FCP interface is currently active,
2820 * {@code false} otherwise
2822 public boolean isFcpInterfaceActive() {
2823 return options.getBooleanOption("ActivateFcpInterface").get();
2827 * Sets whether the {@link FcpInterface FCP interface} is currently
2830 * @see FcpInterface#setActive(boolean)
2831 * @param fcpInterfaceActive
2832 * {@code true} to activate the FCP interface, {@code false}
2833 * to deactivate the FCP interface
2834 * @return This preferences object
2836 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2837 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2842 * Returns the action level for which full access to the FCP interface
2845 * @return The action level for which full access to the FCP interface
2848 public FullAccessRequired getFcpFullAccessRequired() {
2849 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2853 * Sets the action level for which full access to the FCP interface is
2856 * @param fcpFullAccessRequired
2858 * @return This preferences
2860 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2861 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2866 * Returns whether Sone should clear its settings on the next restart.
2867 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2868 * to return {@code true} as well!
2870 * @return {@code true} if Sone should clear its settings on the next
2871 * restart, {@code false} otherwise
2873 public boolean isClearOnNextRestart() {
2874 return options.getBooleanOption("ClearOnNextRestart").get();
2878 * Sets whether Sone will clear its settings on the next restart.
2880 * @param clearOnNextRestart
2881 * {@code true} if Sone should clear its settings on the next
2882 * restart, {@code false} otherwise
2883 * @return This preferences
2885 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2886 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2891 * Returns whether Sone should really clear its settings on next
2892 * restart. This is a confirmation option that needs to be set in
2893 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2894 * settings on the next restart.
2896 * @return {@code true} if Sone should really clear its settings on the
2897 * next restart, {@code false} otherwise
2899 public boolean isReallyClearOnNextRestart() {
2900 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2904 * Sets whether Sone should really clear its settings on the next
2907 * @param reallyClearOnNextRestart
2908 * {@code true} if Sone should really clear its settings on
2909 * the next restart, {@code false} otherwise
2910 * @return This preferences
2912 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2913 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);