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", sone.isLocal()).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.getSone(id, false) != null;
360 * Returns all local Sones.
362 * @return All local Sones
364 public Collection<Sone> getLocalSones() {
365 return database.getLocalSones();
369 * Returns the local Sone with the given ID.
372 * The ID of the Sone to get
373 * @return The Sone with the given ID
375 public Sone getLocalSone(String id) {
376 return getLocalSone(id, true);
380 * Returns the local Sone with the given ID, optionally creating a new Sone.
385 * {@code true} to create a new Sone if none exists,
386 * {@code false} to return null if none exists
387 * @return The Sone with the given ID, or {@code null}
389 public Sone getLocalSone(String id, boolean create) {
390 return database.getLocalSone(id, create);
394 * Returns all remote Sones.
396 * @return All remote Sones
398 public Collection<Sone> getRemoteSones() {
399 return database.getRemoteSones();
403 * Returns the remote Sone with the given ID.
406 * The ID of the remote Sone to get
408 * {@code true} to always create a Sone, {@code false} to return
409 * {@code null} if no Sone with the given ID exists
410 * @return The Sone with the given ID
412 public Sone getRemoteSone(String id, boolean create) {
413 return database.getRemoteSone(id, create);
417 * Returns whether the given Sone has been modified.
420 * The Sone to check for modifications
421 * @return {@code true} if a modification has been detected in the Sone,
422 * {@code false} otherwise
424 public boolean isModifiedSone(Sone sone) {
425 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
429 * Returns the time when the given was first followed by any local Sone.
432 * The Sone to get the time for
433 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
434 * been followed, or {@link Long#MAX_VALUE}
436 public long getSoneFollowingTime(Sone sone) {
437 synchronized (soneFollowingTimes) {
438 if (soneFollowingTimes.containsKey(sone)) {
439 return soneFollowingTimes.get(sone);
441 return Long.MAX_VALUE;
446 * Returns whether the target Sone is trusted by the origin Sone.
452 * @return {@code true} if the target Sone is trusted by the origin Sone
454 public boolean isSoneTrusted(Sone origin, Sone target) {
455 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
456 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
460 * Returns the post with the given ID.
463 * The ID of the post to get
464 * @return The post with the given ID, or a new post with the given ID
466 public Post getPost(String postId) {
467 return getPost(postId, true);
471 * Returns the post with the given ID, optionally creating a new post.
474 * The ID of the post to get
476 * {@code true} it create a new post if no post with the given ID
477 * exists, {@code false} to return {@code null}
478 * @return The post, or {@code null} if there is no such post
481 public Post getPost(String postId, boolean create) {
482 synchronized (posts) {
483 Post post = posts.get(postId);
484 if ((post == null) && create) {
485 post = new Post(postId);
486 posts.put(postId, post);
493 * Returns all posts that have the given Sone as recipient.
495 * @see Post#getRecipient()
497 * The recipient of the posts
498 * @return All posts that have the given Sone as recipient
500 public Set<Post> getDirectedPosts(Sone recipient) {
501 Validation.begin().isNotNull("Recipient", recipient).check();
502 Set<Post> directedPosts = new HashSet<Post>();
503 synchronized (posts) {
504 for (Post post : posts.values()) {
505 if (recipient.equals(post.getRecipient())) {
506 directedPosts.add(post);
510 return directedPosts;
514 * Returns the reply with the given ID. If there is no reply with the given
515 * ID yet, a new one is created.
518 * The ID of the reply to get
521 public PostReply getReply(String replyId) {
522 return getReply(replyId, true);
526 * Returns the reply with the given ID. If there is no reply with the given
527 * ID yet, a new one is created, unless {@code create} is false in which
528 * case {@code null} is returned.
531 * The ID of the reply to get
533 * {@code true} to always return a {@link Reply}, {@code false}
534 * to return {@code null} if no reply can be found
535 * @return The reply, or {@code null} if there is no such reply
537 public PostReply getReply(String replyId, boolean create) {
538 synchronized (replies) {
539 PostReply reply = replies.get(replyId);
540 if (create && (reply == null)) {
541 reply = new PostReply(replyId);
542 replies.put(replyId, reply);
549 * Returns all replies for the given post, order ascending by time.
552 * The post to get all replies for
553 * @return All replies for the given post
555 public List<PostReply> getReplies(Post post) {
556 Collection<Sone> sones = getSones();
557 List<PostReply> replies = new ArrayList<PostReply>();
558 for (Sone sone : sones) {
559 for (PostReply reply : sone.getReplies()) {
560 if (reply.getPost().equals(post)) {
565 Collections.sort(replies, Reply.TIME_COMPARATOR);
570 * Returns all Sones that have liked the given post.
573 * The post to get the liking Sones for
574 * @return The Sones that like the given post
576 public Set<Sone> getLikes(Post post) {
577 Set<Sone> sones = new HashSet<Sone>();
578 for (Sone sone : getSones()) {
579 if (sone.getLikedPostIds().contains(post.getId())) {
587 * Returns all Sones that have liked the given reply.
590 * The reply to get the liking Sones for
591 * @return The Sones that like the given reply
593 public Set<Sone> getLikes(PostReply reply) {
594 Set<Sone> sones = new HashSet<Sone>();
595 for (Sone sone : getSones()) {
596 if (sone.getLikedReplyIds().contains(reply.getId())) {
604 * Returns whether the given post is bookmarked.
608 * @return {@code true} if the given post is bookmarked, {@code false}
611 public boolean isBookmarked(Post post) {
612 return isPostBookmarked(post.getId());
616 * Returns whether the post with the given ID is bookmarked.
619 * The ID of the post to check
620 * @return {@code true} if the post with the given ID is bookmarked,
621 * {@code false} otherwise
623 public boolean isPostBookmarked(String id) {
624 synchronized (bookmarkedPosts) {
625 return bookmarkedPosts.contains(id);
630 * Returns all currently known bookmarked posts.
632 * @return All bookmarked posts
634 public Set<Post> getBookmarkedPosts() {
635 Set<Post> posts = new HashSet<Post>();
636 synchronized (bookmarkedPosts) {
637 for (String bookmarkedPostId : bookmarkedPosts) {
638 Post post = getPost(bookmarkedPostId, false);
648 * Returns the album with the given ID, creating a new album if no album
649 * with the given ID can be found.
652 * The ID of the album
653 * @return The album with the given ID
655 public Album getAlbum(String albumId) {
656 return getAlbum(albumId, true);
660 * Returns the album with the given ID, optionally creating a new album if
661 * an album with the given ID can not be found.
664 * The ID of the album
666 * {@code true} to create a new album if none exists for the
668 * @return The album with the given ID, or {@code null} if no album with the
669 * given ID exists and {@code create} is {@code false}
671 public Album getAlbum(String albumId, boolean create) {
672 synchronized (albums) {
673 Album album = albums.get(albumId);
674 if (create && (album == null)) {
675 album = new Album(albumId);
676 albums.put(albumId, album);
683 * Returns the image with the given ID, creating it if necessary.
686 * The ID of the image
687 * @return The image with the given ID
689 public Image getImage(String imageId) {
690 return getImage(imageId, true);
694 * Returns the image with the given ID, optionally creating it if it does
698 * The ID of the image
700 * {@code true} to create an image if none exists with the given
702 * @return The image with the given ID, or {@code null} if none exists and
705 public Image getImage(String imageId, boolean create) {
706 synchronized (images) {
707 Image image = images.get(imageId);
708 if (create && (image == null)) {
709 image = new Image(imageId);
710 images.put(imageId, image);
717 * Returns the temporary image with the given ID.
720 * The ID of the temporary image
721 * @return The temporary image, or {@code null} if there is no temporary
722 * image with the given ID
724 public TemporaryImage getTemporaryImage(String imageId) {
725 synchronized (temporaryImages) {
726 return temporaryImages.get(imageId);
735 * Locks the given Sone. A locked Sone will not be inserted by
736 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
742 public void lockSone(Sone sone) {
743 synchronized (lockedSones) {
744 if (lockedSones.add(sone)) {
745 coreListenerManager.fireSoneLocked(sone);
751 * Unlocks the given Sone.
753 * @see #lockSone(Sone)
757 public void unlockSone(Sone sone) {
758 synchronized (lockedSones) {
759 if (lockedSones.remove(sone)) {
760 coreListenerManager.fireSoneUnlocked(sone);
768 * Adds a local Sone from the given ID which has to be the ID of an own
772 * The ID of an own identity to add a Sone for
773 * @return The added (or already existing) Sone
775 public Sone addLocalSone(String id) {
776 if (database.getLocalSone(id, false) != null) {
777 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
778 return database.getLocalSone(id, false);
780 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
781 if (ownIdentity == null) {
782 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
785 return addLocalSone(ownIdentity);
789 >>>>>>> 4f36598... Store locality of a Sone in the Sone itself, remove related methods from Database.
790 * Adds a local Sone from the given own identity.
793 * The own identity to create a Sone from
794 * @return The added (or already existing) Sone
796 public Sone addLocalSone(OwnIdentity ownIdentity) {
797 if (ownIdentity == null) {
798 logger.log(Level.WARNING, "Given OwnIdentity is null!");
803 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
804 } catch (MalformedURLException mue1) {
805 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
808 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
809 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
811 /* TODO - load posts ’n stuff */
812 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
813 soneInserter.addSoneInsertListener(this);
814 soneInserters.put(sone, soneInserter);
815 sone.setStatus(SoneStatus.idle);
817 soneInserter.start();
818 database.saveSone(sone);
823 * Creates a new Sone for the given own identity.
826 * The own identity to create a Sone for
827 * @return The created Sone
829 public Sone createSone(OwnIdentity ownIdentity) {
831 ownIdentity.addContext("Sone");
832 } catch (WebOfTrustException wote1) {
833 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity), wote1);
836 Sone sone = addLocalSone(ownIdentity);
837 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
838 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
839 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
840 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
841 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
842 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
844 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
845 touchConfiguration();
850 * Adds the Sone of the given identity.
853 * The identity whose Sone to add
854 * @return The added or already existing Sone
856 public Sone addRemoteSone(Identity identity) {
857 if (identity == null) {
858 logger.log(Level.WARNING, "Given Identity is null!");
861 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
862 boolean newSone = sone.getRequestUri() == null;
863 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
864 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
866 synchronized (knownSones) {
867 newSone = !knownSones.contains(sone.getId());
869 sone.setKnown(!newSone);
871 coreListenerManager.fireNewSoneFound(sone);
872 for (Sone localSone : getLocalSones()) {
873 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
874 followSone(localSone, sone);
879 soneDownloader.addSone(sone);
880 soneDownloaders.execute(new Runnable() {
883 @SuppressWarnings("synthetic-access")
885 soneDownloader.fetchSone(sone, sone.getRequestUri());
889 database.saveSone(sone);
894 * Lets the given local Sone follow the Sone with the given ID.
897 * The local Sone that should follow another Sone
899 * The ID of the Sone to follow
901 public void followSone(Sone sone, String soneId) {
902 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
903 Sone followedSone = getSone(soneId, true);
904 if (followedSone == null) {
905 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
908 followSone(sone, getSone(soneId));
912 * Lets the given local Sone follow the other given Sone. If the given Sone
913 * was not followed by any local Sone before, this will mark all elements of
914 * the followed Sone as read that have been created before the current
918 * The local Sone that should follow the other Sone
919 * @param followedSone
920 * The Sone that should be followed
922 public void followSone(Sone sone, Sone followedSone) {
923 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
924 sone.addFriend(followedSone.getId());
925 synchronized (soneFollowingTimes) {
926 if (!soneFollowingTimes.containsKey(followedSone)) {
927 long now = System.currentTimeMillis();
928 soneFollowingTimes.put(followedSone, now);
929 for (Post post : followedSone.getPosts()) {
930 if (post.getTime() < now) {
934 for (PostReply reply : followedSone.getReplies()) {
935 if (reply.getTime() < now) {
936 markReplyKnown(reply);
941 touchConfiguration();
945 * Lets the given local Sone unfollow the Sone with the given ID.
948 * The local Sone that should unfollow another Sone
950 * The ID of the Sone being unfollowed
952 public void unfollowSone(Sone sone, String soneId) {
953 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
954 unfollowSone(sone, getSone(soneId, false));
958 * Lets the given local Sone unfollow the other given Sone. If the given
959 * local Sone is the last local Sone that followed the given Sone, its
960 * following time will be removed.
963 * The local Sone that should unfollow another Sone
964 * @param unfollowedSone
965 * The Sone being unfollowed
967 public void unfollowSone(Sone sone, Sone unfollowedSone) {
968 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
969 sone.removeFriend(unfollowedSone.getId());
970 boolean unfollowedSoneStillFollowed = false;
971 for (Sone localSone : getLocalSones()) {
972 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
974 if (!unfollowedSoneStillFollowed) {
975 synchronized (soneFollowingTimes) {
976 soneFollowingTimes.remove(unfollowedSone);
979 touchConfiguration();
983 * Retrieves the trust relationship from the origin to the target. If the
984 * trust relationship can not be retrieved, {@code null} is returned.
986 * @see Identity#getTrust(OwnIdentity)
988 * The origin of the trust tree
990 * The target of the trust
991 * @return The trust relationship
993 public Trust getTrust(Sone origin, Sone target) {
994 if (!origin.isLocal()) {
995 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
998 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1002 * Sets the trust value of the given origin Sone for the target Sone.
1009 * The trust value (from {@code -100} to {@code 100})
1011 public void setTrust(Sone origin, Sone target, int trustValue) {
1012 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();
1014 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1015 } catch (WebOfTrustException wote1) {
1016 logger.log(Level.WARNING, String.format("Could not set trust for Sone: %s", target), wote1);
1021 * Removes any trust assignment for the given target Sone.
1028 public void removeTrust(Sone origin, Sone target) {
1029 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1031 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1032 } catch (WebOfTrustException wote1) {
1033 logger.log(Level.WARNING, String.format("Could not remove trust for Sone: %s", target), wote1);
1038 * Assigns the configured positive trust value for the given target.
1045 public void trustSone(Sone origin, Sone target) {
1046 setTrust(origin, target, preferences.getPositiveTrust());
1050 * Assigns the configured negative trust value for the given target.
1057 public void distrustSone(Sone origin, Sone target) {
1058 setTrust(origin, target, preferences.getNegativeTrust());
1062 * Removes the trust assignment for the given target.
1069 public void untrustSone(Sone origin, Sone target) {
1070 removeTrust(origin, target);
1074 * Updates the stored Sone with the given Sone.
1079 public void updateSone(Sone sone) {
1080 updateSone(sone, false);
1084 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1085 * {@code true}, an older Sone than the current Sone can be given to restore
1089 * The Sone to update
1090 * @param soneRescueMode
1091 * {@code true} if the stored Sone should be updated regardless
1092 * of the age of the given Sone
1094 public void updateSone(Sone sone, boolean soneRescueMode) {
1095 if (hasSone(sone.getId())) {
1096 Sone storedSone = getSone(sone.getId());
1097 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1098 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1101 synchronized (posts) {
1102 if (!soneRescueMode) {
1103 for (Post post : storedSone.getPosts()) {
1104 posts.remove(post.getId());
1105 if (!sone.getPosts().contains(post)) {
1106 coreListenerManager.firePostRemoved(post);
1110 List<Post> storedPosts = storedSone.getPosts();
1111 synchronized (knownPosts) {
1112 for (Post post : sone.getPosts()) {
1113 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1114 if (!storedPosts.contains(post)) {
1115 if (post.getTime() < getSoneFollowingTime(sone)) {
1116 knownPosts.add(post.getId());
1117 } else if (!knownPosts.contains(post.getId())) {
1118 sone.setKnown(false);
1119 coreListenerManager.fireNewPostFound(post);
1122 posts.put(post.getId(), post);
1126 synchronized (replies) {
1127 if (!soneRescueMode) {
1128 for (PostReply reply : storedSone.getReplies()) {
1129 replies.remove(reply.getId());
1130 if (!sone.getReplies().contains(reply)) {
1131 coreListenerManager.fireReplyRemoved(reply);
1135 Set<PostReply> storedReplies = storedSone.getReplies();
1136 synchronized (knownReplies) {
1137 for (PostReply reply : sone.getReplies()) {
1138 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1139 if (!storedReplies.contains(reply)) {
1140 if (reply.getTime() < getSoneFollowingTime(sone)) {
1141 knownReplies.add(reply.getId());
1142 } else if (!knownReplies.contains(reply.getId())) {
1143 reply.setKnown(false);
1144 coreListenerManager.fireNewReplyFound(reply);
1147 replies.put(reply.getId(), reply);
1151 synchronized (albums) {
1152 synchronized (images) {
1153 for (Album album : storedSone.getAlbums()) {
1154 albums.remove(album.getId());
1155 for (Image image : album.getImages()) {
1156 images.remove(image.getId());
1159 for (Album album : sone.getAlbums()) {
1160 albums.put(album.getId(), album);
1161 for (Image image : album.getImages()) {
1162 images.put(image.getId(), image);
1167 synchronized (storedSone) {
1168 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1169 storedSone.setTime(sone.getTime());
1171 storedSone.setClient(sone.getClient());
1172 storedSone.setProfile(sone.getProfile());
1173 if (soneRescueMode) {
1174 for (Post post : sone.getPosts()) {
1175 storedSone.addPost(post);
1177 for (PostReply reply : sone.getReplies()) {
1178 storedSone.addReply(reply);
1180 for (String likedPostId : sone.getLikedPostIds()) {
1181 storedSone.addLikedPostId(likedPostId);
1183 for (String likedReplyId : sone.getLikedReplyIds()) {
1184 storedSone.addLikedReplyId(likedReplyId);
1186 for (Album album : sone.getAlbums()) {
1187 storedSone.addAlbum(album);
1190 storedSone.setPosts(sone.getPosts());
1191 storedSone.setReplies(sone.getReplies());
1192 storedSone.setLikePostIds(sone.getLikedPostIds());
1193 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1194 storedSone.setAlbums(sone.getAlbums());
1196 storedSone.setLatestEdition(sone.getLatestEdition());
1202 * Deletes the given Sone. This will remove the Sone from the
1203 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1204 * and remove the context from its identity.
1207 * The Sone to delete
1209 public void deleteSone(Sone sone) {
1210 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1211 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1214 if (!sone.isLocal()) {
1215 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1218 database.removeSone(sone.getId());
1219 SoneInserter soneInserter = soneInserters.remove(sone);
1220 soneInserter.removeSoneInsertListener(this);
1221 soneInserter.stop();
1223 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1224 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1225 } catch (WebOfTrustException wote1) {
1226 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1229 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1230 } catch (ConfigurationException ce1) {
1231 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1236 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1237 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1240 * The Sone to mark as known
1242 public void markSoneKnown(Sone sone) {
1243 if (!sone.isKnown()) {
1244 sone.setKnown(true);
1245 synchronized (knownSones) {
1246 knownSones.add(sone.getId());
1248 coreListenerManager.fireMarkSoneKnown(sone);
1249 touchConfiguration();
1254 * Loads and updates the given Sone from the configuration. If any error is
1255 * encountered, loading is aborted and the given Sone is not changed.
1258 * The Sone to load and update
1260 public void loadSone(Sone sone) {
1261 if (!sone.isLocal()) {
1262 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1266 /* initialize options. */
1267 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1268 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1269 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1270 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1271 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1272 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1275 String sonePrefix = "Sone/" + sone.getId();
1276 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1277 if (soneTime == null) {
1278 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1281 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1284 Profile profile = new Profile(sone);
1285 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1286 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1287 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1288 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1289 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1290 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1292 /* load profile fields. */
1294 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1295 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1296 if (fieldName == null) {
1299 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1300 profile.addField(fieldName).setValue(fieldValue);
1304 Set<Post> posts = new HashSet<Post>();
1306 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1307 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1308 if (postId == null) {
1311 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1312 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1313 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1314 if ((postTime == 0) || (postText == null)) {
1315 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1318 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1319 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1320 post.setRecipient(getSone(postRecipientId));
1326 Set<PostReply> replies = new HashSet<PostReply>();
1328 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1329 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1330 if (replyId == null) {
1333 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1334 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1335 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1336 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1337 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1340 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1343 /* load post likes. */
1344 Set<String> likedPostIds = new HashSet<String>();
1346 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1347 if (likedPostId == null) {
1350 likedPostIds.add(likedPostId);
1353 /* load reply likes. */
1354 Set<String> likedReplyIds = new HashSet<String>();
1356 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1357 if (likedReplyId == null) {
1360 likedReplyIds.add(likedReplyId);
1364 Set<String> friends = new HashSet<String>();
1366 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1367 if (friendId == null) {
1370 friends.add(friendId);
1374 List<Album> topLevelAlbums = new ArrayList<Album>();
1375 int albumCounter = 0;
1377 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1378 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1379 if (albumId == null) {
1382 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1383 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1384 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1385 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1386 if ((albumTitle == null) || (albumDescription == null)) {
1387 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1390 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1391 if (albumParentId != null) {
1392 Album parentAlbum = getAlbum(albumParentId, false);
1393 if (parentAlbum == null) {
1394 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1397 parentAlbum.addAlbum(album);
1399 if (!topLevelAlbums.contains(album)) {
1400 topLevelAlbums.add(album);
1406 int imageCounter = 0;
1408 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1409 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1410 if (imageId == null) {
1413 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1414 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1415 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1416 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1417 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1418 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1419 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1420 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1421 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1424 Album album = getAlbum(albumId, false);
1425 if (album == null) {
1426 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1429 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1430 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1431 album.addImage(image);
1435 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1436 if (avatarId != null) {
1437 profile.setAvatar(getImage(avatarId, false));
1441 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1442 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1443 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1444 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1445 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1446 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1448 /* if we’re still here, Sone was loaded successfully. */
1449 synchronized (sone) {
1450 sone.setTime(soneTime);
1451 sone.setProfile(profile);
1452 sone.setPosts(posts);
1453 sone.setReplies(replies);
1454 sone.setLikePostIds(likedPostIds);
1455 sone.setLikeReplyIds(likedReplyIds);
1456 for (String friendId : friends) {
1457 followSone(sone, friendId);
1459 sone.setAlbums(topLevelAlbums);
1460 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1462 synchronized (knownSones) {
1463 for (String friend : friends) {
1464 knownSones.add(friend);
1467 synchronized (knownPosts) {
1468 for (Post post : posts) {
1469 knownPosts.add(post.getId());
1472 synchronized (knownReplies) {
1473 for (PostReply reply : replies) {
1474 knownReplies.add(reply.getId());
1480 * Creates a new post.
1483 * The Sone that creates the post
1485 * The recipient Sone, or {@code null} if this post does not have
1488 * The time of the post
1490 * The text of the post
1491 * @return The created post
1493 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1494 if (!sone.isLocal()) {
1495 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1498 final Post post = new Post(sone, time, text);
1499 if (recipient != null) {
1500 post.setRecipient(recipient);
1502 synchronized (posts) {
1503 posts.put(post.getId(), post);
1505 coreListenerManager.fireNewPostFound(post);
1507 touchConfiguration();
1508 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1515 markPostKnown(post);
1517 }, "Mark " + post + " read.");
1522 * Deletes the given post.
1525 * The post to delete
1527 public void deletePost(Post post) {
1528 if (!post.getSone().isLocal()) {
1529 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1532 post.getSone().removePost(post);
1533 synchronized (posts) {
1534 posts.remove(post.getId());
1536 coreListenerManager.firePostRemoved(post);
1537 markPostKnown(post);
1538 touchConfiguration();
1542 * Marks the given post as known, if it is currently not a known post
1543 * (according to {@link Post#isKnown()}).
1546 * The post to mark as known
1548 public void markPostKnown(Post post) {
1549 post.setKnown(true);
1550 synchronized (knownPosts) {
1551 coreListenerManager.fireMarkPostKnown(post);
1552 if (knownPosts.add(post.getId())) {
1553 touchConfiguration();
1556 for (PostReply reply : getReplies(post)) {
1557 markReplyKnown(reply);
1562 * Bookmarks the given post.
1565 * The post to bookmark
1567 public void bookmark(Post post) {
1568 bookmarkPost(post.getId());
1572 * Bookmarks the post with the given ID.
1575 * The ID of the post to bookmark
1577 public void bookmarkPost(String id) {
1578 synchronized (bookmarkedPosts) {
1579 bookmarkedPosts.add(id);
1584 * Removes the given post from the bookmarks.
1587 * The post to unbookmark
1589 public void unbookmark(Post post) {
1590 unbookmarkPost(post.getId());
1594 * Removes the post with the given ID from the bookmarks.
1597 * The ID of the post to unbookmark
1599 public void unbookmarkPost(String id) {
1600 synchronized (bookmarkedPosts) {
1601 bookmarkedPosts.remove(id);
1606 * Creates a new reply.
1609 * The Sone that creates the reply
1611 * The post that this reply refers to
1613 * The text of the reply
1614 * @return The created reply
1616 public PostReply createReply(Sone sone, Post post, String text) {
1617 return createReply(sone, post, System.currentTimeMillis(), text);
1621 * Creates a new reply.
1624 * The Sone that creates the reply
1626 * The post that this reply refers to
1628 * The time of the reply
1630 * The text of the reply
1631 * @return The created reply
1633 public PostReply createReply(Sone sone, Post post, long time, String text) {
1634 if (!sone.isLocal()) {
1635 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1638 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1639 synchronized (replies) {
1640 replies.put(reply.getId(), reply);
1642 synchronized (knownReplies) {
1643 coreListenerManager.fireNewReplyFound(reply);
1645 sone.addReply(reply);
1646 touchConfiguration();
1647 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1654 markReplyKnown(reply);
1656 }, "Mark " + reply + " read.");
1661 * Deletes the given reply.
1664 * The reply to delete
1666 public void deleteReply(PostReply reply) {
1667 Sone sone = reply.getSone();
1668 if (!sone.isLocal()) {
1669 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1672 synchronized (replies) {
1673 replies.remove(reply.getId());
1675 synchronized (knownReplies) {
1676 markReplyKnown(reply);
1677 knownReplies.remove(reply.getId());
1679 sone.removeReply(reply);
1680 touchConfiguration();
1684 * Marks the given reply as known, if it is currently not a known reply
1685 * (according to {@link Reply#isKnown()}).
1688 * The reply to mark as known
1690 public void markReplyKnown(PostReply reply) {
1691 reply.setKnown(true);
1692 synchronized (knownReplies) {
1693 coreListenerManager.fireMarkReplyKnown(reply);
1694 if (knownReplies.add(reply.getId())) {
1695 touchConfiguration();
1701 * Creates a new top-level album for the given Sone.
1704 * The Sone to create the album for
1705 * @return The new album
1707 public Album createAlbum(Sone sone) {
1708 return createAlbum(sone, null);
1712 * Creates a new album for the given Sone.
1715 * The Sone to create the album for
1717 * The parent of the album (may be {@code null} to create a
1719 * @return The new album
1721 public Album createAlbum(Sone sone, Album parent) {
1722 Album album = new Album();
1723 synchronized (albums) {
1724 albums.put(album.getId(), album);
1726 album.setSone(sone);
1727 if (parent != null) {
1728 parent.addAlbum(album);
1730 sone.addAlbum(album);
1736 * Deletes the given album. The owner of the album has to be a local Sone,
1737 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1740 * The album to remove
1742 public void deleteAlbum(Album album) {
1743 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1744 if (!album.isEmpty()) {
1747 if (album.getParent() == null) {
1748 album.getSone().removeAlbum(album);
1750 album.getParent().removeAlbum(album);
1752 synchronized (albums) {
1753 albums.remove(album.getId());
1755 saveSone(album.getSone());
1759 * Creates a new image.
1762 * The Sone creating the image
1764 * The album the image will be inserted into
1765 * @param temporaryImage
1766 * The temporary image to create the image from
1767 * @return The newly created image
1769 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1770 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();
1771 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1772 album.addImage(image);
1773 synchronized (images) {
1774 images.put(image.getId(), image);
1776 imageInserter.insertImage(temporaryImage, image);
1781 * Deletes the given image. This method will also delete a matching
1784 * @see #deleteTemporaryImage(TemporaryImage)
1786 * The image to delete
1788 public void deleteImage(Image image) {
1789 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1790 deleteTemporaryImage(image.getId());
1791 image.getAlbum().removeImage(image);
1792 synchronized (images) {
1793 images.remove(image.getId());
1795 saveSone(image.getSone());
1799 * Creates a new temporary image.
1802 * The MIME type of the temporary image
1804 * The encoded data of the image
1805 * @return The temporary image
1807 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1808 TemporaryImage temporaryImage = new TemporaryImage();
1809 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1810 synchronized (temporaryImages) {
1811 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1813 return temporaryImage;
1817 * Deletes the given temporary image.
1819 * @param temporaryImage
1820 * The temporary image to delete
1822 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1823 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1824 deleteTemporaryImage(temporaryImage.getId());
1828 * Deletes the temporary image with the given ID.
1831 * The ID of the temporary image to delete
1833 public void deleteTemporaryImage(String imageId) {
1834 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1835 synchronized (temporaryImages) {
1836 temporaryImages.remove(imageId);
1838 Image image = getImage(imageId, false);
1839 if (image != null) {
1840 imageInserter.cancelImageInsert(image);
1845 * Notifies the core that the configuration, either of the core or of a
1846 * single local Sone, has changed, and that the configuration should be
1849 public void touchConfiguration() {
1850 lastConfigurationUpdate = System.currentTimeMillis();
1861 public void serviceStart() {
1862 loadConfiguration();
1863 updateChecker.addUpdateListener(this);
1864 updateChecker.start();
1871 public void serviceRun() {
1872 long lastSaved = System.currentTimeMillis();
1873 while (!shouldStop()) {
1875 long now = System.currentTimeMillis();
1876 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1877 for (Sone localSone : getLocalSones()) {
1878 saveSone(localSone);
1880 saveConfiguration();
1890 public void serviceStop() {
1891 for (SoneInserter soneInserter : soneInserters.values()) {
1892 soneInserter.removeSoneInsertListener(this);
1893 soneInserter.stop();
1895 updateChecker.stop();
1896 updateChecker.removeUpdateListener(this);
1897 soneDownloader.stop();
1905 * Saves the given Sone. This will persist all local settings for the given
1906 * Sone, such as the friends list and similar, private options.
1911 private synchronized void saveSone(Sone sone) {
1912 if (!sone.isLocal()) {
1913 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1916 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1917 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1921 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1923 /* save Sone into configuration. */
1924 String sonePrefix = "Sone/" + sone.getId();
1925 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1926 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1929 Profile profile = sone.getProfile();
1930 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1931 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1932 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1933 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1934 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1935 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1936 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1938 /* save profile fields. */
1939 int fieldCounter = 0;
1940 for (Field profileField : profile.getFields()) {
1941 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1942 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1943 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1945 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1948 int postCounter = 0;
1949 for (Post post : sone.getPosts()) {
1950 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1951 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1952 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1953 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1954 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1956 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1959 int replyCounter = 0;
1960 for (PostReply reply : sone.getReplies()) {
1961 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1962 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1963 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1964 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1965 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1967 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1969 /* save post likes. */
1970 int postLikeCounter = 0;
1971 for (String postId : sone.getLikedPostIds()) {
1972 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1974 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1976 /* save reply likes. */
1977 int replyLikeCounter = 0;
1978 for (String replyId : sone.getLikedReplyIds()) {
1979 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1981 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1984 int friendCounter = 0;
1985 for (String friendId : sone.getFriends()) {
1986 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1988 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1990 /* save albums. first, collect in a flat structure, top-level first. */
1991 List<Album> albums = sone.getAllAlbums();
1993 int albumCounter = 0;
1994 for (Album album : albums) {
1995 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1996 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1997 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1998 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1999 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2000 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2002 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2005 int imageCounter = 0;
2006 for (Album album : albums) {
2007 for (Image image : album.getImages()) {
2008 if (!image.isInserted()) {
2011 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2012 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2013 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2014 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2015 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2016 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2017 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2018 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2019 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2022 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2025 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2026 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2027 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2028 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2029 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2030 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2032 configuration.save();
2034 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2036 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2037 } catch (ConfigurationException ce1) {
2038 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2039 } catch (WebOfTrustException wote1) {
2040 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2045 * Saves the current options.
2047 private void saveConfiguration() {
2048 synchronized (configuration) {
2049 if (storingConfiguration) {
2050 logger.log(Level.FINE, "Already storing configuration…");
2053 storingConfiguration = true;
2056 /* store the options first. */
2058 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2059 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2060 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2061 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2062 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2063 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2064 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2065 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2066 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2067 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2068 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2069 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2070 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2071 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2073 /* save known Sones. */
2074 int soneCounter = 0;
2075 synchronized (knownSones) {
2076 for (String knownSoneId : knownSones) {
2077 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2079 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2082 /* save Sone following times. */
2084 synchronized (soneFollowingTimes) {
2085 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2086 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2087 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2090 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2093 /* save known posts. */
2094 int postCounter = 0;
2095 synchronized (knownPosts) {
2096 for (String knownPostId : knownPosts) {
2097 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2099 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2102 /* save known replies. */
2103 int replyCounter = 0;
2104 synchronized (knownReplies) {
2105 for (String knownReplyId : knownReplies) {
2106 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2108 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2111 /* save bookmarked posts. */
2112 int bookmarkedPostCounter = 0;
2113 synchronized (bookmarkedPosts) {
2114 for (String bookmarkedPostId : bookmarkedPosts) {
2115 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2118 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2121 configuration.save();
2123 } catch (ConfigurationException ce1) {
2124 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2126 synchronized (configuration) {
2127 storingConfiguration = false;
2133 * Loads the configuration.
2135 @SuppressWarnings("unchecked")
2136 private void loadConfiguration() {
2137 /* create options. */
2138 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2141 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2142 SoneInserter.setInsertionDelay(newValue);
2146 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2147 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2148 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2149 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2150 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2151 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2152 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2153 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2156 @SuppressWarnings("synthetic-access")
2157 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2158 fcpInterface.setActive(newValue);
2161 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2164 @SuppressWarnings("synthetic-access")
2165 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2166 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2170 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2171 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2172 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2174 /* read options from configuration. */
2175 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2176 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2177 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2178 options.getBooleanOption("ClearOnNextRestart").set(null);
2179 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2180 if (clearConfiguration) {
2181 /* stop loading the configuration. */
2185 loadConfigurationValue("InsertionDelay");
2186 loadConfigurationValue("PostsPerPage");
2187 loadConfigurationValue("CharactersPerPost");
2188 loadConfigurationValue("PostCutOffLength");
2189 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2190 loadConfigurationValue("PositiveTrust");
2191 loadConfigurationValue("NegativeTrust");
2192 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2193 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2194 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2195 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2197 /* load known Sones. */
2198 int soneCounter = 0;
2200 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2201 if (knownSoneId == null) {
2204 synchronized (knownSones) {
2205 knownSones.add(knownSoneId);
2209 /* load Sone following times. */
2212 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2213 if (soneId == null) {
2216 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2217 Sone followedSone = getSone(soneId);
2218 if (followedSone == null) {
2219 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2221 synchronized (soneFollowingTimes) {
2222 soneFollowingTimes.put(getSone(soneId), time);
2228 /* load known posts. */
2229 int postCounter = 0;
2231 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2232 if (knownPostId == null) {
2235 synchronized (knownPosts) {
2236 knownPosts.add(knownPostId);
2240 /* load known replies. */
2241 int replyCounter = 0;
2243 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2244 if (knownReplyId == null) {
2247 synchronized (knownReplies) {
2248 knownReplies.add(knownReplyId);
2252 /* load bookmarked posts. */
2253 int bookmarkedPostCounter = 0;
2255 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2256 if (bookmarkedPostId == null) {
2259 synchronized (bookmarkedPosts) {
2260 bookmarkedPosts.add(bookmarkedPostId);
2267 * Loads an {@link Integer} configuration value for the option with the
2268 * given name, logging validation failures.
2271 * The name of the option to load
2273 private void loadConfigurationValue(String optionName) {
2275 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2276 } catch (IllegalArgumentException iae1) {
2277 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2282 * Generate a Sone URI from the given URI and latest edition.
2285 * The URI to derive the Sone URI from
2286 * @return The derived URI
2288 private FreenetURI getSoneUri(String uriString) {
2290 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2292 } catch (MalformedURLException mue1) {
2293 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2299 // INTERFACE IdentityListener
2306 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2307 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2308 if (ownIdentity.hasContext("Sone")) {
2309 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2310 addLocalSone(ownIdentity);
2318 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2319 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2320 trustedIdentities.remove(ownIdentity);
2327 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2328 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2329 trustedIdentities.get(ownIdentity).add(identity);
2330 addRemoteSone(identity);
2337 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2338 new Thread(new Runnable() {
2341 @SuppressWarnings("synthetic-access")
2343 Sone sone = getRemoteSone(identity.getId(), false);
2344 sone.setIdentity(identity);
2345 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2346 soneDownloader.addSone(sone);
2347 soneDownloader.fetchSone(sone);
2356 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2357 trustedIdentities.get(ownIdentity).remove(identity);
2358 boolean foundIdentity = false;
2359 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2360 if (trustedIdentity.getKey().equals(ownIdentity)) {
2363 if (trustedIdentity.getValue().contains(identity)) {
2364 foundIdentity = true;
2367 if (foundIdentity) {
2368 /* some local identity still trusts this identity, don’t remove. */
2371 Sone sone = getSone(identity.getId(), false);
2373 /* TODO - we don’t have the Sone anymore. should this happen? */
2376 synchronized (posts) {
2377 synchronized (knownPosts) {
2378 for (Post post : sone.getPosts()) {
2379 posts.remove(post.getId());
2380 coreListenerManager.firePostRemoved(post);
2384 synchronized (replies) {
2385 synchronized (knownReplies) {
2386 for (PostReply reply : sone.getReplies()) {
2387 replies.remove(reply.getId());
2388 coreListenerManager.fireReplyRemoved(reply);
2392 database.removeSone(identity.getId());
2393 coreListenerManager.fireSoneRemoved(sone);
2397 // INTERFACE UpdateListener
2404 public void updateFound(Version version, long releaseTime, long latestEdition) {
2405 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2409 // INTERFACE ImageInsertListener
2416 public void insertStarted(Sone sone) {
2417 coreListenerManager.fireSoneInserting(sone);
2424 public void insertFinished(Sone sone, long insertDuration) {
2425 coreListenerManager.fireSoneInserted(sone, insertDuration);
2432 public void insertAborted(Sone sone, Throwable cause) {
2433 coreListenerManager.fireSoneInsertAborted(sone, cause);
2437 // SONEINSERTLISTENER METHODS
2444 public void imageInsertStarted(Image image) {
2445 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2446 coreListenerManager.fireImageInsertStarted(image);
2453 public void imageInsertAborted(Image image) {
2454 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2455 coreListenerManager.fireImageInsertAborted(image);
2462 public void imageInsertFinished(Image image, FreenetURI key) {
2463 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2464 image.setKey(key.toString());
2465 deleteTemporaryImage(image.getId());
2466 saveSone(image.getSone());
2467 coreListenerManager.fireImageInsertFinished(image);
2474 public void imageInsertFailed(Image image, Throwable cause) {
2475 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2476 coreListenerManager.fireImageInsertFailed(image, cause);
2480 * Convenience interface for external classes that want to access the core’s
2483 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2485 public static class Preferences {
2487 /** The wrapped options. */
2488 private final Options options;
2491 * Creates a new preferences object wrapped around the given options.
2494 * The options to wrap
2496 public Preferences(Options options) {
2497 this.options = options;
2501 * Returns the insertion delay.
2503 * @return The insertion delay
2505 public int getInsertionDelay() {
2506 return options.getIntegerOption("InsertionDelay").get();
2510 * Validates the given insertion delay.
2512 * @param insertionDelay
2513 * The insertion delay to validate
2514 * @return {@code true} if the given insertion delay was valid,
2515 * {@code false} otherwise
2517 public boolean validateInsertionDelay(Integer insertionDelay) {
2518 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2522 * Sets the insertion delay
2524 * @param insertionDelay
2525 * The new insertion delay, or {@code null} to restore it to
2527 * @return This preferences
2529 public Preferences setInsertionDelay(Integer insertionDelay) {
2530 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2535 * Returns the number of posts to show per page.
2537 * @return The number of posts to show per page
2539 public int getPostsPerPage() {
2540 return options.getIntegerOption("PostsPerPage").get();
2544 * Validates the number of posts per page.
2546 * @param postsPerPage
2547 * The number of posts per page
2548 * @return {@code true} if the number of posts per page was valid,
2549 * {@code false} otherwise
2551 public boolean validatePostsPerPage(Integer postsPerPage) {
2552 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2556 * Sets the number of posts to show per page.
2558 * @param postsPerPage
2559 * The number of posts to show per page
2560 * @return This preferences object
2562 public Preferences setPostsPerPage(Integer postsPerPage) {
2563 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2568 * Returns the number of characters per post, or <code>-1</code> if the
2569 * posts should not be cut off.
2571 * @return The numbers of characters per post
2573 public int getCharactersPerPost() {
2574 return options.getIntegerOption("CharactersPerPost").get();
2578 * Validates the number of characters per post.
2580 * @param charactersPerPost
2581 * The number of characters per post
2582 * @return {@code true} if the number of characters per post was valid,
2583 * {@code false} otherwise
2585 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2586 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2590 * Sets the number of characters per post.
2592 * @param charactersPerPost
2593 * The number of characters per post, or <code>-1</code> to
2594 * not cut off the posts
2595 * @return This preferences objects
2597 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2598 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2603 * Returns the number of characters the shortened post should have.
2605 * @return The number of characters of the snippet
2607 public int getPostCutOffLength() {
2608 return options.getIntegerOption("PostCutOffLength").get();
2612 * Validates the number of characters after which to cut off the post.
2614 * @param postCutOffLength
2615 * The number of characters of the snippet
2616 * @return {@code true} if the number of characters of the snippet is
2617 * valid, {@code false} otherwise
2619 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2620 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2624 * Sets the number of characters the shortened post should have.
2626 * @param postCutOffLength
2627 * The number of characters of the snippet
2628 * @return This preferences
2630 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2631 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2636 * Returns whether Sone requires full access to be even visible.
2638 * @return {@code true} if Sone requires full access, {@code false}
2641 public boolean isRequireFullAccess() {
2642 return options.getBooleanOption("RequireFullAccess").get();
2646 * Sets whether Sone requires full access to be even visible.
2648 * @param requireFullAccess
2649 * {@code true} if Sone requires full access, {@code false}
2652 public void setRequireFullAccess(Boolean requireFullAccess) {
2653 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2657 * Returns the positive trust.
2659 * @return The positive trust
2661 public int getPositiveTrust() {
2662 return options.getIntegerOption("PositiveTrust").get();
2666 * Validates the positive trust.
2668 * @param positiveTrust
2669 * The positive trust to validate
2670 * @return {@code true} if the positive trust was valid, {@code false}
2673 public boolean validatePositiveTrust(Integer positiveTrust) {
2674 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2678 * Sets the positive trust.
2680 * @param positiveTrust
2681 * The new positive trust, or {@code null} to restore it to
2683 * @return This preferences
2685 public Preferences setPositiveTrust(Integer positiveTrust) {
2686 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2691 * Returns the negative trust.
2693 * @return The negative trust
2695 public int getNegativeTrust() {
2696 return options.getIntegerOption("NegativeTrust").get();
2700 * Validates the negative trust.
2702 * @param negativeTrust
2703 * The negative trust to validate
2704 * @return {@code true} if the negative trust was valid, {@code false}
2707 public boolean validateNegativeTrust(Integer negativeTrust) {
2708 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2712 * Sets the negative trust.
2714 * @param negativeTrust
2715 * The negative trust, or {@code null} to restore it to the
2717 * @return The preferences
2719 public Preferences setNegativeTrust(Integer negativeTrust) {
2720 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2725 * Returns the trust comment. This is the comment that is set in the web
2726 * of trust when a trust value is assigned to an identity.
2728 * @return The trust comment
2730 public String getTrustComment() {
2731 return options.getStringOption("TrustComment").get();
2735 * Sets the trust comment.
2737 * @param trustComment
2738 * The trust comment, or {@code null} to restore it to the
2740 * @return This preferences
2742 public Preferences setTrustComment(String trustComment) {
2743 options.getStringOption("TrustComment").set(trustComment);
2748 * Returns whether the {@link FcpInterface FCP interface} is currently
2751 * @see FcpInterface#setActive(boolean)
2752 * @return {@code true} if the FCP interface is currently active,
2753 * {@code false} otherwise
2755 public boolean isFcpInterfaceActive() {
2756 return options.getBooleanOption("ActivateFcpInterface").get();
2760 * Sets whether the {@link FcpInterface FCP interface} is currently
2763 * @see FcpInterface#setActive(boolean)
2764 * @param fcpInterfaceActive
2765 * {@code true} to activate the FCP interface, {@code false}
2766 * to deactivate the FCP interface
2767 * @return This preferences object
2769 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2770 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2775 * Returns the action level for which full access to the FCP interface
2778 * @return The action level for which full access to the FCP interface
2781 public FullAccessRequired getFcpFullAccessRequired() {
2782 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2786 * Sets the action level for which full access to the FCP interface is
2789 * @param fcpFullAccessRequired
2791 * @return This preferences
2793 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2794 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2799 * Returns whether Sone should clear its settings on the next restart.
2800 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2801 * to return {@code true} as well!
2803 * @return {@code true} if Sone should clear its settings on the next
2804 * restart, {@code false} otherwise
2806 public boolean isClearOnNextRestart() {
2807 return options.getBooleanOption("ClearOnNextRestart").get();
2811 * Sets whether Sone will clear its settings on the next restart.
2813 * @param clearOnNextRestart
2814 * {@code true} if Sone should clear its settings on the next
2815 * restart, {@code false} otherwise
2816 * @return This preferences
2818 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2819 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2824 * Returns whether Sone should really clear its settings on next
2825 * restart. This is a confirmation option that needs to be set in
2826 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2827 * settings on the next restart.
2829 * @return {@code true} if Sone should really clear its settings on the
2830 * next restart, {@code false} otherwise
2832 public boolean isReallyClearOnNextRestart() {
2833 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2837 * Sets whether Sone should really clear its settings on the next
2840 * @param reallyClearOnNextRestart
2841 * {@code true} if Sone should really clear its settings on
2842 * the next restart, {@code false} otherwise
2843 * @return This preferences
2845 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2846 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);