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 text of the post
1486 * @return The created post
1488 public Post createPost(Sone sone, String text) {
1489 return createPost(sone, System.currentTimeMillis(), text);
1493 * Creates a new post.
1496 * The Sone that creates the post
1498 * The time of the post
1500 * The text of the post
1501 * @return The created post
1503 public Post createPost(Sone sone, long time, String text) {
1504 return createPost(sone, null, time, text);
1508 * Creates a new post.
1511 * The Sone that creates the post
1513 * The recipient Sone, or {@code null} if this post does not have
1516 * The text of the post
1517 * @return The created post
1519 public Post createPost(Sone sone, Sone recipient, String text) {
1520 return createPost(sone, recipient, System.currentTimeMillis(), text);
1524 * Creates a new post.
1527 * The Sone that creates the post
1529 * The recipient Sone, or {@code null} if this post does not have
1532 * The time of the post
1534 * The text of the post
1535 * @return The created post
1537 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1538 if (!sone.isLocal()) {
1539 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1542 final Post post = new Post(sone, time, text);
1543 if (recipient != null) {
1544 post.setRecipient(recipient);
1546 synchronized (posts) {
1547 posts.put(post.getId(), post);
1549 coreListenerManager.fireNewPostFound(post);
1551 touchConfiguration();
1552 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1559 markPostKnown(post);
1561 }, "Mark " + post + " read.");
1566 * Deletes the given post.
1569 * The post to delete
1571 public void deletePost(Post post) {
1572 if (!post.getSone().isLocal()) {
1573 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1576 post.getSone().removePost(post);
1577 synchronized (posts) {
1578 posts.remove(post.getId());
1580 coreListenerManager.firePostRemoved(post);
1581 markPostKnown(post);
1582 touchConfiguration();
1586 * Marks the given post as known, if it is currently not a known post
1587 * (according to {@link Post#isKnown()}).
1590 * The post to mark as known
1592 public void markPostKnown(Post post) {
1593 post.setKnown(true);
1594 synchronized (knownPosts) {
1595 coreListenerManager.fireMarkPostKnown(post);
1596 if (knownPosts.add(post.getId())) {
1597 touchConfiguration();
1600 for (PostReply reply : getReplies(post)) {
1601 markReplyKnown(reply);
1606 * Bookmarks the given post.
1609 * The post to bookmark
1611 public void bookmark(Post post) {
1612 bookmarkPost(post.getId());
1616 * Bookmarks the post with the given ID.
1619 * The ID of the post to bookmark
1621 public void bookmarkPost(String id) {
1622 synchronized (bookmarkedPosts) {
1623 bookmarkedPosts.add(id);
1628 * Removes the given post from the bookmarks.
1631 * The post to unbookmark
1633 public void unbookmark(Post post) {
1634 unbookmarkPost(post.getId());
1638 * Removes the post with the given ID from the bookmarks.
1641 * The ID of the post to unbookmark
1643 public void unbookmarkPost(String id) {
1644 synchronized (bookmarkedPosts) {
1645 bookmarkedPosts.remove(id);
1650 * Creates a new reply.
1653 * The Sone that creates the reply
1655 * The post that this reply refers to
1657 * The text of the reply
1658 * @return The created reply
1660 public PostReply createReply(Sone sone, Post post, String text) {
1661 return createReply(sone, post, System.currentTimeMillis(), text);
1665 * Creates a new reply.
1668 * The Sone that creates the reply
1670 * The post that this reply refers to
1672 * The time of the reply
1674 * The text of the reply
1675 * @return The created reply
1677 public PostReply createReply(Sone sone, Post post, long time, String text) {
1678 if (!sone.isLocal()) {
1679 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1682 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1683 synchronized (replies) {
1684 replies.put(reply.getId(), reply);
1686 synchronized (knownReplies) {
1687 coreListenerManager.fireNewReplyFound(reply);
1689 sone.addReply(reply);
1690 touchConfiguration();
1691 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1698 markReplyKnown(reply);
1700 }, "Mark " + reply + " read.");
1705 * Deletes the given reply.
1708 * The reply to delete
1710 public void deleteReply(PostReply reply) {
1711 Sone sone = reply.getSone();
1712 if (!sone.isLocal()) {
1713 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1716 synchronized (replies) {
1717 replies.remove(reply.getId());
1719 synchronized (knownReplies) {
1720 markReplyKnown(reply);
1721 knownReplies.remove(reply.getId());
1723 sone.removeReply(reply);
1724 touchConfiguration();
1728 * Marks the given reply as known, if it is currently not a known reply
1729 * (according to {@link Reply#isKnown()}).
1732 * The reply to mark as known
1734 public void markReplyKnown(PostReply reply) {
1735 reply.setKnown(true);
1736 synchronized (knownReplies) {
1737 coreListenerManager.fireMarkReplyKnown(reply);
1738 if (knownReplies.add(reply.getId())) {
1739 touchConfiguration();
1745 * Creates a new top-level album for the given Sone.
1748 * The Sone to create the album for
1749 * @return The new album
1751 public Album createAlbum(Sone sone) {
1752 return createAlbum(sone, null);
1756 * Creates a new album for the given Sone.
1759 * The Sone to create the album for
1761 * The parent of the album (may be {@code null} to create a
1763 * @return The new album
1765 public Album createAlbum(Sone sone, Album parent) {
1766 Album album = new Album();
1767 synchronized (albums) {
1768 albums.put(album.getId(), album);
1770 album.setSone(sone);
1771 if (parent != null) {
1772 parent.addAlbum(album);
1774 sone.addAlbum(album);
1780 * Deletes the given album. The owner of the album has to be a local Sone,
1781 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1784 * The album to remove
1786 public void deleteAlbum(Album album) {
1787 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1788 if (!album.isEmpty()) {
1791 if (album.getParent() == null) {
1792 album.getSone().removeAlbum(album);
1794 album.getParent().removeAlbum(album);
1796 synchronized (albums) {
1797 albums.remove(album.getId());
1799 saveSone(album.getSone());
1803 * Creates a new image.
1806 * The Sone creating the image
1808 * The album the image will be inserted into
1809 * @param temporaryImage
1810 * The temporary image to create the image from
1811 * @return The newly created image
1813 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1814 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();
1815 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1816 album.addImage(image);
1817 synchronized (images) {
1818 images.put(image.getId(), image);
1820 imageInserter.insertImage(temporaryImage, image);
1825 * Deletes the given image. This method will also delete a matching
1828 * @see #deleteTemporaryImage(TemporaryImage)
1830 * The image to delete
1832 public void deleteImage(Image image) {
1833 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1834 deleteTemporaryImage(image.getId());
1835 image.getAlbum().removeImage(image);
1836 synchronized (images) {
1837 images.remove(image.getId());
1839 saveSone(image.getSone());
1843 * Creates a new temporary image.
1846 * The MIME type of the temporary image
1848 * The encoded data of the image
1849 * @return The temporary image
1851 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1852 TemporaryImage temporaryImage = new TemporaryImage();
1853 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1854 synchronized (temporaryImages) {
1855 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1857 return temporaryImage;
1861 * Deletes the given temporary image.
1863 * @param temporaryImage
1864 * The temporary image to delete
1866 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1867 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1868 deleteTemporaryImage(temporaryImage.getId());
1872 * Deletes the temporary image with the given ID.
1875 * The ID of the temporary image to delete
1877 public void deleteTemporaryImage(String imageId) {
1878 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1879 synchronized (temporaryImages) {
1880 temporaryImages.remove(imageId);
1882 Image image = getImage(imageId, false);
1883 if (image != null) {
1884 imageInserter.cancelImageInsert(image);
1889 * Notifies the core that the configuration, either of the core or of a
1890 * single local Sone, has changed, and that the configuration should be
1893 public void touchConfiguration() {
1894 lastConfigurationUpdate = System.currentTimeMillis();
1905 public void serviceStart() {
1906 loadConfiguration();
1907 updateChecker.addUpdateListener(this);
1908 updateChecker.start();
1915 public void serviceRun() {
1916 long lastSaved = System.currentTimeMillis();
1917 while (!shouldStop()) {
1919 long now = System.currentTimeMillis();
1920 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1921 for (Sone localSone : getLocalSones()) {
1922 saveSone(localSone);
1924 saveConfiguration();
1934 public void serviceStop() {
1935 for (SoneInserter soneInserter : soneInserters.values()) {
1936 soneInserter.removeSoneInsertListener(this);
1937 soneInserter.stop();
1939 updateChecker.stop();
1940 updateChecker.removeUpdateListener(this);
1941 soneDownloader.stop();
1949 * Saves the given Sone. This will persist all local settings for the given
1950 * Sone, such as the friends list and similar, private options.
1955 private synchronized void saveSone(Sone sone) {
1956 if (!sone.isLocal()) {
1957 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1960 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1961 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1965 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1967 /* save Sone into configuration. */
1968 String sonePrefix = "Sone/" + sone.getId();
1969 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1970 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1973 Profile profile = sone.getProfile();
1974 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1975 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1976 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1977 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1978 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1979 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1980 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1982 /* save profile fields. */
1983 int fieldCounter = 0;
1984 for (Field profileField : profile.getFields()) {
1985 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1986 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1987 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1989 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1992 int postCounter = 0;
1993 for (Post post : sone.getPosts()) {
1994 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1995 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1996 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1997 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1998 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2000 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2003 int replyCounter = 0;
2004 for (PostReply reply : sone.getReplies()) {
2005 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2006 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2007 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2008 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2009 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2011 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2013 /* save post likes. */
2014 int postLikeCounter = 0;
2015 for (String postId : sone.getLikedPostIds()) {
2016 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2018 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2020 /* save reply likes. */
2021 int replyLikeCounter = 0;
2022 for (String replyId : sone.getLikedReplyIds()) {
2023 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2025 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2028 int friendCounter = 0;
2029 for (String friendId : sone.getFriends()) {
2030 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2032 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2034 /* save albums. first, collect in a flat structure, top-level first. */
2035 List<Album> albums = sone.getAllAlbums();
2037 int albumCounter = 0;
2038 for (Album album : albums) {
2039 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2040 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2041 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2042 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2043 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2044 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2046 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2049 int imageCounter = 0;
2050 for (Album album : albums) {
2051 for (Image image : album.getImages()) {
2052 if (!image.isInserted()) {
2055 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2056 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2057 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2058 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2059 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2060 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2061 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2062 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2063 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2066 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2069 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2070 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2071 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2072 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2073 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2074 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2076 configuration.save();
2078 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2080 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2081 } catch (ConfigurationException ce1) {
2082 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2083 } catch (WebOfTrustException wote1) {
2084 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2089 * Saves the current options.
2091 private void saveConfiguration() {
2092 synchronized (configuration) {
2093 if (storingConfiguration) {
2094 logger.log(Level.FINE, "Already storing configuration…");
2097 storingConfiguration = true;
2100 /* store the options first. */
2102 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2103 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2104 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2105 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2106 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2107 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2108 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2109 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2110 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2111 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2112 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2113 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2114 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2115 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2117 /* save known Sones. */
2118 int soneCounter = 0;
2119 synchronized (knownSones) {
2120 for (String knownSoneId : knownSones) {
2121 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2123 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2126 /* save Sone following times. */
2128 synchronized (soneFollowingTimes) {
2129 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2130 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2131 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2134 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2137 /* save known posts. */
2138 int postCounter = 0;
2139 synchronized (knownPosts) {
2140 for (String knownPostId : knownPosts) {
2141 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2143 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2146 /* save known replies. */
2147 int replyCounter = 0;
2148 synchronized (knownReplies) {
2149 for (String knownReplyId : knownReplies) {
2150 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2152 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2155 /* save bookmarked posts. */
2156 int bookmarkedPostCounter = 0;
2157 synchronized (bookmarkedPosts) {
2158 for (String bookmarkedPostId : bookmarkedPosts) {
2159 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2162 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2165 configuration.save();
2167 } catch (ConfigurationException ce1) {
2168 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2170 synchronized (configuration) {
2171 storingConfiguration = false;
2177 * Loads the configuration.
2179 @SuppressWarnings("unchecked")
2180 private void loadConfiguration() {
2181 /* create options. */
2182 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2185 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2186 SoneInserter.setInsertionDelay(newValue);
2190 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2191 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2192 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2193 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2194 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2195 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2196 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2197 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2200 @SuppressWarnings("synthetic-access")
2201 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2202 fcpInterface.setActive(newValue);
2205 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2208 @SuppressWarnings("synthetic-access")
2209 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2210 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2214 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2215 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2216 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2218 /* read options from configuration. */
2219 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2220 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2221 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2222 options.getBooleanOption("ClearOnNextRestart").set(null);
2223 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2224 if (clearConfiguration) {
2225 /* stop loading the configuration. */
2229 loadConfigurationValue("InsertionDelay");
2230 loadConfigurationValue("PostsPerPage");
2231 loadConfigurationValue("CharactersPerPost");
2232 loadConfigurationValue("PostCutOffLength");
2233 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2234 loadConfigurationValue("PositiveTrust");
2235 loadConfigurationValue("NegativeTrust");
2236 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2237 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2238 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2239 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2241 /* load known Sones. */
2242 int soneCounter = 0;
2244 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2245 if (knownSoneId == null) {
2248 synchronized (knownSones) {
2249 knownSones.add(knownSoneId);
2253 /* load Sone following times. */
2256 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2257 if (soneId == null) {
2260 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2261 Sone followedSone = getSone(soneId);
2262 if (followedSone == null) {
2263 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2265 synchronized (soneFollowingTimes) {
2266 soneFollowingTimes.put(getSone(soneId), time);
2272 /* load known posts. */
2273 int postCounter = 0;
2275 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2276 if (knownPostId == null) {
2279 synchronized (knownPosts) {
2280 knownPosts.add(knownPostId);
2284 /* load known replies. */
2285 int replyCounter = 0;
2287 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2288 if (knownReplyId == null) {
2291 synchronized (knownReplies) {
2292 knownReplies.add(knownReplyId);
2296 /* load bookmarked posts. */
2297 int bookmarkedPostCounter = 0;
2299 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2300 if (bookmarkedPostId == null) {
2303 synchronized (bookmarkedPosts) {
2304 bookmarkedPosts.add(bookmarkedPostId);
2311 * Loads an {@link Integer} configuration value for the option with the
2312 * given name, logging validation failures.
2315 * The name of the option to load
2317 private void loadConfigurationValue(String optionName) {
2319 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2320 } catch (IllegalArgumentException iae1) {
2321 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2326 * Generate a Sone URI from the given URI and latest edition.
2329 * The URI to derive the Sone URI from
2330 * @return The derived URI
2332 private FreenetURI getSoneUri(String uriString) {
2334 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2336 } catch (MalformedURLException mue1) {
2337 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2343 // INTERFACE IdentityListener
2350 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2351 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2352 if (ownIdentity.hasContext("Sone")) {
2353 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2354 addLocalSone(ownIdentity);
2362 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2363 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2364 trustedIdentities.remove(ownIdentity);
2371 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2372 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2373 trustedIdentities.get(ownIdentity).add(identity);
2374 addRemoteSone(identity);
2381 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2382 new Thread(new Runnable() {
2385 @SuppressWarnings("synthetic-access")
2387 Sone sone = getRemoteSone(identity.getId(), false);
2388 sone.setIdentity(identity);
2389 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2390 soneDownloader.addSone(sone);
2391 soneDownloader.fetchSone(sone);
2400 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2401 trustedIdentities.get(ownIdentity).remove(identity);
2402 boolean foundIdentity = false;
2403 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2404 if (trustedIdentity.getKey().equals(ownIdentity)) {
2407 if (trustedIdentity.getValue().contains(identity)) {
2408 foundIdentity = true;
2411 if (foundIdentity) {
2412 /* some local identity still trusts this identity, don’t remove. */
2415 Sone sone = getSone(identity.getId(), false);
2417 /* TODO - we don’t have the Sone anymore. should this happen? */
2420 synchronized (posts) {
2421 synchronized (knownPosts) {
2422 for (Post post : sone.getPosts()) {
2423 posts.remove(post.getId());
2424 coreListenerManager.firePostRemoved(post);
2428 synchronized (replies) {
2429 synchronized (knownReplies) {
2430 for (PostReply reply : sone.getReplies()) {
2431 replies.remove(reply.getId());
2432 coreListenerManager.fireReplyRemoved(reply);
2436 database.removeSone(identity.getId());
2437 coreListenerManager.fireSoneRemoved(sone);
2441 // INTERFACE UpdateListener
2448 public void updateFound(Version version, long releaseTime, long latestEdition) {
2449 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2453 // INTERFACE ImageInsertListener
2460 public void insertStarted(Sone sone) {
2461 coreListenerManager.fireSoneInserting(sone);
2468 public void insertFinished(Sone sone, long insertDuration) {
2469 coreListenerManager.fireSoneInserted(sone, insertDuration);
2476 public void insertAborted(Sone sone, Throwable cause) {
2477 coreListenerManager.fireSoneInsertAborted(sone, cause);
2481 // SONEINSERTLISTENER METHODS
2488 public void imageInsertStarted(Image image) {
2489 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2490 coreListenerManager.fireImageInsertStarted(image);
2497 public void imageInsertAborted(Image image) {
2498 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2499 coreListenerManager.fireImageInsertAborted(image);
2506 public void imageInsertFinished(Image image, FreenetURI key) {
2507 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2508 image.setKey(key.toString());
2509 deleteTemporaryImage(image.getId());
2510 saveSone(image.getSone());
2511 coreListenerManager.fireImageInsertFinished(image);
2518 public void imageInsertFailed(Image image, Throwable cause) {
2519 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2520 coreListenerManager.fireImageInsertFailed(image, cause);
2524 * Convenience interface for external classes that want to access the core’s
2527 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2529 public static class Preferences {
2531 /** The wrapped options. */
2532 private final Options options;
2535 * Creates a new preferences object wrapped around the given options.
2538 * The options to wrap
2540 public Preferences(Options options) {
2541 this.options = options;
2545 * Returns the insertion delay.
2547 * @return The insertion delay
2549 public int getInsertionDelay() {
2550 return options.getIntegerOption("InsertionDelay").get();
2554 * Validates the given insertion delay.
2556 * @param insertionDelay
2557 * The insertion delay to validate
2558 * @return {@code true} if the given insertion delay was valid,
2559 * {@code false} otherwise
2561 public boolean validateInsertionDelay(Integer insertionDelay) {
2562 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2566 * Sets the insertion delay
2568 * @param insertionDelay
2569 * The new insertion delay, or {@code null} to restore it to
2571 * @return This preferences
2573 public Preferences setInsertionDelay(Integer insertionDelay) {
2574 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2579 * Returns the number of posts to show per page.
2581 * @return The number of posts to show per page
2583 public int getPostsPerPage() {
2584 return options.getIntegerOption("PostsPerPage").get();
2588 * Validates the number of posts per page.
2590 * @param postsPerPage
2591 * The number of posts per page
2592 * @return {@code true} if the number of posts per page was valid,
2593 * {@code false} otherwise
2595 public boolean validatePostsPerPage(Integer postsPerPage) {
2596 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2600 * Sets the number of posts to show per page.
2602 * @param postsPerPage
2603 * The number of posts to show per page
2604 * @return This preferences object
2606 public Preferences setPostsPerPage(Integer postsPerPage) {
2607 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2612 * Returns the number of characters per post, or <code>-1</code> if the
2613 * posts should not be cut off.
2615 * @return The numbers of characters per post
2617 public int getCharactersPerPost() {
2618 return options.getIntegerOption("CharactersPerPost").get();
2622 * Validates the number of characters per post.
2624 * @param charactersPerPost
2625 * The number of characters per post
2626 * @return {@code true} if the number of characters per post was valid,
2627 * {@code false} otherwise
2629 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2630 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2634 * Sets the number of characters per post.
2636 * @param charactersPerPost
2637 * The number of characters per post, or <code>-1</code> to
2638 * not cut off the posts
2639 * @return This preferences objects
2641 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2642 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2647 * Returns the number of characters the shortened post should have.
2649 * @return The number of characters of the snippet
2651 public int getPostCutOffLength() {
2652 return options.getIntegerOption("PostCutOffLength").get();
2656 * Validates the number of characters after which to cut off the post.
2658 * @param postCutOffLength
2659 * The number of characters of the snippet
2660 * @return {@code true} if the number of characters of the snippet is
2661 * valid, {@code false} otherwise
2663 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2664 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2668 * Sets the number of characters the shortened post should have.
2670 * @param postCutOffLength
2671 * The number of characters of the snippet
2672 * @return This preferences
2674 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2675 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2680 * Returns whether Sone requires full access to be even visible.
2682 * @return {@code true} if Sone requires full access, {@code false}
2685 public boolean isRequireFullAccess() {
2686 return options.getBooleanOption("RequireFullAccess").get();
2690 * Sets whether Sone requires full access to be even visible.
2692 * @param requireFullAccess
2693 * {@code true} if Sone requires full access, {@code false}
2696 public void setRequireFullAccess(Boolean requireFullAccess) {
2697 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2701 * Returns the positive trust.
2703 * @return The positive trust
2705 public int getPositiveTrust() {
2706 return options.getIntegerOption("PositiveTrust").get();
2710 * Validates the positive trust.
2712 * @param positiveTrust
2713 * The positive trust to validate
2714 * @return {@code true} if the positive trust was valid, {@code false}
2717 public boolean validatePositiveTrust(Integer positiveTrust) {
2718 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2722 * Sets the positive trust.
2724 * @param positiveTrust
2725 * The new positive trust, or {@code null} to restore it to
2727 * @return This preferences
2729 public Preferences setPositiveTrust(Integer positiveTrust) {
2730 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2735 * Returns the negative trust.
2737 * @return The negative trust
2739 public int getNegativeTrust() {
2740 return options.getIntegerOption("NegativeTrust").get();
2744 * Validates the negative trust.
2746 * @param negativeTrust
2747 * The negative trust to validate
2748 * @return {@code true} if the negative trust was valid, {@code false}
2751 public boolean validateNegativeTrust(Integer negativeTrust) {
2752 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2756 * Sets the negative trust.
2758 * @param negativeTrust
2759 * The negative trust, or {@code null} to restore it to the
2761 * @return The preferences
2763 public Preferences setNegativeTrust(Integer negativeTrust) {
2764 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2769 * Returns the trust comment. This is the comment that is set in the web
2770 * of trust when a trust value is assigned to an identity.
2772 * @return The trust comment
2774 public String getTrustComment() {
2775 return options.getStringOption("TrustComment").get();
2779 * Sets the trust comment.
2781 * @param trustComment
2782 * The trust comment, or {@code null} to restore it to the
2784 * @return This preferences
2786 public Preferences setTrustComment(String trustComment) {
2787 options.getStringOption("TrustComment").set(trustComment);
2792 * Returns whether the {@link FcpInterface FCP interface} is currently
2795 * @see FcpInterface#setActive(boolean)
2796 * @return {@code true} if the FCP interface is currently active,
2797 * {@code false} otherwise
2799 public boolean isFcpInterfaceActive() {
2800 return options.getBooleanOption("ActivateFcpInterface").get();
2804 * Sets whether the {@link FcpInterface FCP interface} is currently
2807 * @see FcpInterface#setActive(boolean)
2808 * @param fcpInterfaceActive
2809 * {@code true} to activate the FCP interface, {@code false}
2810 * to deactivate the FCP interface
2811 * @return This preferences object
2813 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2814 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2819 * Returns the action level for which full access to the FCP interface
2822 * @return The action level for which full access to the FCP interface
2825 public FullAccessRequired getFcpFullAccessRequired() {
2826 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2830 * Sets the action level for which full access to the FCP interface is
2833 * @param fcpFullAccessRequired
2835 * @return This preferences
2837 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2838 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2843 * Returns whether Sone should clear its settings on the next restart.
2844 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2845 * to return {@code true} as well!
2847 * @return {@code true} if Sone should clear its settings on the next
2848 * restart, {@code false} otherwise
2850 public boolean isClearOnNextRestart() {
2851 return options.getBooleanOption("ClearOnNextRestart").get();
2855 * Sets whether Sone will clear its settings on the next restart.
2857 * @param clearOnNextRestart
2858 * {@code true} if Sone should clear its settings on the next
2859 * restart, {@code false} otherwise
2860 * @return This preferences
2862 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2863 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2868 * Returns whether Sone should really clear its settings on next
2869 * restart. This is a confirmation option that needs to be set in
2870 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2871 * settings on the next restart.
2873 * @return {@code true} if Sone should really clear its settings on the
2874 * next restart, {@code false} otherwise
2876 public boolean isReallyClearOnNextRestart() {
2877 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2881 * Sets whether Sone should really clear its settings on the next
2884 * @param reallyClearOnNextRestart
2885 * {@code true} if Sone should really clear its settings on
2886 * the next restart, {@code false} otherwise
2887 * @return This preferences
2889 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2890 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);