2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Profile.Field;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.data.TemporaryImage;
49 import net.pterodactylus.sone.data.impl.PostImpl;
50 import net.pterodactylus.sone.fcp.FcpInterface;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.sone.freenet.wot.IdentityListener;
54 import net.pterodactylus.sone.freenet.wot.IdentityManager;
55 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
56 import net.pterodactylus.sone.freenet.wot.Trust;
57 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
58 import net.pterodactylus.sone.main.SonePlugin;
59 import net.pterodactylus.util.config.Configuration;
60 import net.pterodactylus.util.config.ConfigurationException;
61 import net.pterodactylus.util.logging.Logging;
62 import net.pterodactylus.util.number.Numbers;
63 import net.pterodactylus.util.service.AbstractService;
64 import net.pterodactylus.util.thread.Ticker;
65 import net.pterodactylus.util.validation.EqualityValidator;
66 import net.pterodactylus.util.validation.IntegerRangeValidator;
67 import net.pterodactylus.util.validation.OrValidator;
68 import net.pterodactylus.util.validation.Validation;
69 import net.pterodactylus.util.version.Version;
70 import freenet.keys.FreenetURI;
75 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
80 private static final Logger logger = Logging.getLogger(Core.class);
83 private final Options options = new Options();
85 /** The preferences. */
86 private final Preferences preferences = new Preferences(options);
88 /** The core listener manager. */
89 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
91 /** The configuration. */
92 private Configuration configuration;
94 /** Whether we’re currently saving the configuration. */
95 private boolean storingConfiguration = false;
97 /** The identity manager. */
98 private final IdentityManager identityManager;
100 /** Interface to freenet. */
101 private final FreenetInterface freenetInterface;
103 /** The Sone downloader. */
104 private final SoneDownloader soneDownloader;
106 /** The image inserter. */
107 private final ImageInserter imageInserter;
109 /** Sone downloader thread-pool. */
110 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
112 /** The update checker. */
113 private final UpdateChecker updateChecker;
115 /** The trust updater. */
116 private final TrustUpdater trustUpdater;
118 /** The FCP interface. */
119 private volatile FcpInterface fcpInterface;
121 /** The times Sones were followed. */
122 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
124 /** Locked local Sones. */
125 /* synchronize on itself. */
126 private final Set<Sone> lockedSones = new HashSet<Sone>();
128 /** Sone inserters. */
129 /* synchronize access on this on localSones. */
130 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
132 /** Sone rescuers. */
133 /* synchronize access on this on localSones. */
134 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
136 /** All local Sones. */
137 /* synchronize access on this on itself. */
138 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
140 /** All remote Sones. */
141 /* synchronize access on this on itself. */
142 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
144 /** All known Sones. */
145 private final Set<String> knownSones = new HashSet<String>();
148 private final Map<String, Post> posts = new HashMap<String, Post>();
150 /** All known posts. */
151 private final Set<String> knownPosts = new HashSet<String>();
154 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
156 /** All known replies. */
157 private final Set<String> knownReplies = new HashSet<String>();
159 /** All bookmarked posts. */
160 /* synchronize access on itself. */
161 private final Set<String> bookmarkedPosts = new HashSet<String>();
163 /** Trusted identities, sorted by own identities. */
164 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
166 /** All known albums. */
167 private final Map<String, Album> albums = new HashMap<String, Album>();
169 /** All known images. */
170 private final Map<String, Image> images = new HashMap<String, Image>();
172 /** All temporary images. */
173 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
175 /** Ticker for threads that mark own elements as known. */
176 private final Ticker localElementTicker = new Ticker();
178 /** The time the configuration was last touched. */
179 private volatile long lastConfigurationUpdate;
182 * Creates a new core.
184 * @param configuration
185 * The configuration of the core
186 * @param freenetInterface
187 * The freenet interface
188 * @param identityManager
189 * The identity manager
191 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, TrustUpdater trustUpdater) {
193 this.configuration = configuration;
194 this.freenetInterface = freenetInterface;
195 this.identityManager = identityManager;
196 this.soneDownloader = new SoneDownloader(this, freenetInterface);
197 this.imageInserter = new ImageInserter(this, freenetInterface);
198 this.updateChecker = new UpdateChecker(freenetInterface);
199 this.trustUpdater = trustUpdater;
203 // LISTENER MANAGEMENT
207 * Adds a new core listener.
209 * @param coreListener
210 * The listener to add
212 public void addCoreListener(CoreListener coreListener) {
213 coreListenerManager.addListener(coreListener);
217 * Removes a core listener.
219 * @param coreListener
220 * The listener to remove
222 public void removeCoreListener(CoreListener coreListener) {
223 coreListenerManager.removeListener(coreListener);
231 * Sets the configuration to use. This will automatically save the current
232 * configuration to the given configuration.
234 * @param configuration
235 * The new configuration to use
237 public void setConfiguration(Configuration configuration) {
238 this.configuration = configuration;
239 touchConfiguration();
243 * Returns the options used by the core.
245 * @return The options of the core
247 public Preferences getPreferences() {
252 * Returns the identity manager used by the core.
254 * @return The identity manager
256 public IdentityManager getIdentityManager() {
257 return identityManager;
261 * Returns the update checker.
263 * @return The update checker
265 public UpdateChecker getUpdateChecker() {
266 return updateChecker;
270 * Sets the FCP interface to use.
272 * @param fcpInterface
273 * The FCP interface to use
275 public void setFcpInterface(FcpInterface fcpInterface) {
276 this.fcpInterface = fcpInterface;
280 * Returns the Sone rescuer for the given local Sone.
283 * The local Sone to get the rescuer for
284 * @return The Sone rescuer for the given Sone
286 public SoneRescuer getSoneRescuer(Sone sone) {
287 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
288 synchronized (localSones) {
289 SoneRescuer soneRescuer = soneRescuers.get(sone);
290 if (soneRescuer == null) {
291 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
292 soneRescuers.put(sone, soneRescuer);
300 * Returns whether the given Sone is currently locked.
304 * @return {@code true} if the Sone is locked, {@code false} if it is not
306 public boolean isLocked(Sone sone) {
307 synchronized (lockedSones) {
308 return lockedSones.contains(sone);
313 * Returns all Sones, remote and local.
317 public Set<Sone> getSones() {
318 Set<Sone> allSones = new HashSet<Sone>();
319 allSones.addAll(getLocalSones());
320 allSones.addAll(getRemoteSones());
325 * Returns the Sone with the given ID, regardless whether it’s local or
329 * The ID of the Sone to get
330 * @return The Sone with the given ID, or {@code null} if there is no such
333 public Sone getSone(String id) {
334 return getSone(id, true);
338 * Returns the Sone with the given ID, regardless whether it’s local or
342 * The ID of the Sone to get
344 * {@code true} to create a new Sone if none exists,
345 * {@code false} to return {@code null} if a Sone with the given
347 * @return The Sone with the given ID, or {@code null} if there is no such
351 public Sone getSone(String id, boolean create) {
352 if (isLocalSone(id)) {
353 return getLocalSone(id);
355 return getRemoteSone(id, create);
359 * Checks whether the core knows a Sone with the given ID.
363 * @return {@code true} if there is a Sone with the given ID, {@code false}
366 public boolean hasSone(String id) {
367 return isLocalSone(id) || isRemoteSone(id);
371 * Returns whether the given Sone is a local Sone.
374 * The Sone to check for its locality
375 * @return {@code true} if the given Sone is local, {@code false} otherwise
377 public boolean isLocalSone(Sone sone) {
378 synchronized (localSones) {
379 return localSones.containsKey(sone.getId());
384 * Returns whether the given ID is the ID of a local Sone.
387 * The Sone ID to check for its locality
388 * @return {@code true} if the given ID is a local Sone, {@code false}
391 public boolean isLocalSone(String id) {
392 synchronized (localSones) {
393 return localSones.containsKey(id);
398 * Returns all local Sones.
400 * @return All local Sones
402 public Set<Sone> getLocalSones() {
403 synchronized (localSones) {
404 return new HashSet<Sone>(localSones.values());
409 * Returns the local Sone with the given ID.
412 * The ID of the Sone to get
413 * @return The Sone with the given ID
415 public Sone getLocalSone(String id) {
416 return getLocalSone(id, true);
420 * Returns the local Sone with the given ID, optionally creating a new Sone.
425 * {@code true} to create a new Sone if none exists,
426 * {@code false} to return null if none exists
427 * @return The Sone with the given ID, or {@code null}
429 public Sone getLocalSone(String id, boolean create) {
430 synchronized (localSones) {
431 Sone sone = localSones.get(id);
432 if ((sone == null) && create) {
434 localSones.put(id, sone);
441 * Returns all remote Sones.
443 * @return All remote Sones
445 public Set<Sone> getRemoteSones() {
446 synchronized (remoteSones) {
447 return new HashSet<Sone>(remoteSones.values());
452 * Returns the remote Sone with the given ID.
455 * The ID of the remote Sone to get
457 * {@code true} to always create a Sone, {@code false} to return
458 * {@code null} if no Sone with the given ID exists
459 * @return The Sone with the given ID
461 public Sone getRemoteSone(String id, boolean create) {
462 synchronized (remoteSones) {
463 Sone sone = remoteSones.get(id);
464 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
466 remoteSones.put(id, sone);
473 * Returns whether the given Sone is a remote Sone.
477 * @return {@code true} if the given Sone is a remote Sone, {@code false}
480 public boolean isRemoteSone(Sone sone) {
481 synchronized (remoteSones) {
482 return remoteSones.containsKey(sone.getId());
487 * Returns whether the Sone with the given ID is a remote Sone.
490 * The ID of the Sone to check
491 * @return {@code true} if the Sone with the given ID is a remote Sone,
492 * {@code false} otherwise
494 public boolean isRemoteSone(String id) {
495 synchronized (remoteSones) {
496 return remoteSones.containsKey(id);
501 * Returns whether the given Sone has been modified.
504 * The Sone to check for modifications
505 * @return {@code true} if a modification has been detected in the Sone,
506 * {@code false} otherwise
508 public boolean isModifiedSone(Sone sone) {
509 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
513 * Returns the time when the given was first followed by any local Sone.
516 * The Sone to get the time for
517 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
518 * been followed, or {@link Long#MAX_VALUE}
520 public long getSoneFollowingTime(Sone sone) {
521 synchronized (soneFollowingTimes) {
522 if (soneFollowingTimes.containsKey(sone)) {
523 return soneFollowingTimes.get(sone);
525 return Long.MAX_VALUE;
530 * Returns whether the target Sone is trusted by the origin Sone.
536 * @return {@code true} if the target Sone is trusted by the origin Sone
538 public boolean isSoneTrusted(Sone origin, Sone target) {
539 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
540 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
544 * Returns the post with the given ID.
547 * The ID of the post to get
548 * @return The post with the given ID, or a new post with the given ID
550 public Post getPost(String postId) {
551 return getPost(postId, true);
555 * Returns the post with the given ID, optionally creating a new post.
558 * The ID of the post to get
560 * {@code true} it create a new post if no post with the given ID
561 * exists, {@code false} to return {@code null}
562 * @return The post, or {@code null} if there is no such post
565 public Post getPost(String postId, boolean create) {
566 synchronized (posts) {
567 Post post = posts.get(postId);
568 if ((post == null) && create) {
569 post = new PostImpl(postId);
570 posts.put(postId, post);
577 * Returns all posts that have the given Sone as recipient.
579 * @see Post#getRecipient()
581 * The recipient of the posts
582 * @return All posts that have the given Sone as recipient
584 public Set<Post> getDirectedPosts(Sone recipient) {
585 Validation.begin().isNotNull("Recipient", recipient).check();
586 Set<Post> directedPosts = new HashSet<Post>();
587 synchronized (posts) {
588 for (Post post : posts.values()) {
589 if (recipient.equals(post.getRecipient())) {
590 directedPosts.add(post);
594 return directedPosts;
598 * Returns the reply with the given ID. If there is no reply with the given
599 * ID yet, a new one is created.
602 * The ID of the reply to get
605 public PostReply getReply(String replyId) {
606 return getReply(replyId, true);
610 * Returns the reply with the given ID. If there is no reply with the given
611 * ID yet, a new one is created, unless {@code create} is false in which
612 * case {@code null} is returned.
615 * The ID of the reply to get
617 * {@code true} to always return a {@link Reply}, {@code false}
618 * to return {@code null} if no reply can be found
619 * @return The reply, or {@code null} if there is no such reply
621 public PostReply getReply(String replyId, boolean create) {
622 synchronized (replies) {
623 PostReply reply = replies.get(replyId);
624 if (create && (reply == null)) {
625 reply = new PostReply(replyId);
626 replies.put(replyId, reply);
633 * Returns all replies for the given post, order ascending by time.
636 * The post to get all replies for
637 * @return All replies for the given post
639 public List<PostReply> getReplies(Post post) {
640 Set<Sone> sones = getSones();
641 List<PostReply> replies = new ArrayList<PostReply>();
642 for (Sone sone : sones) {
643 for (PostReply reply : sone.getReplies()) {
644 if (reply.getPost().equals(post)) {
649 Collections.sort(replies, Reply.TIME_COMPARATOR);
654 * Returns all Sones that have liked the given post.
657 * The post to get the liking Sones for
658 * @return The Sones that like the given post
660 public Set<Sone> getLikes(Post post) {
661 Set<Sone> sones = new HashSet<Sone>();
662 for (Sone sone : getSones()) {
663 if (sone.getLikedPostIds().contains(post.getId())) {
671 * Returns all Sones that have liked the given reply.
674 * The reply to get the liking Sones for
675 * @return The Sones that like the given reply
677 public Set<Sone> getLikes(PostReply reply) {
678 Set<Sone> sones = new HashSet<Sone>();
679 for (Sone sone : getSones()) {
680 if (sone.getLikedReplyIds().contains(reply.getId())) {
688 * Returns whether the given post is bookmarked.
692 * @return {@code true} if the given post is bookmarked, {@code false}
695 public boolean isBookmarked(Post post) {
696 return isPostBookmarked(post.getId());
700 * Returns whether the post with the given ID is bookmarked.
703 * The ID of the post to check
704 * @return {@code true} if the post with the given ID is bookmarked,
705 * {@code false} otherwise
707 public boolean isPostBookmarked(String id) {
708 synchronized (bookmarkedPosts) {
709 return bookmarkedPosts.contains(id);
714 * Returns all currently known bookmarked posts.
716 * @return All bookmarked posts
718 public Set<Post> getBookmarkedPosts() {
719 Set<Post> posts = new HashSet<Post>();
720 synchronized (bookmarkedPosts) {
721 for (String bookmarkedPostId : bookmarkedPosts) {
722 Post post = getPost(bookmarkedPostId, false);
732 * Returns the album with the given ID, creating a new album if no album
733 * with the given ID can be found.
736 * The ID of the album
737 * @return The album with the given ID
739 public Album getAlbum(String albumId) {
740 return getAlbum(albumId, true);
744 * Returns the album with the given ID, optionally creating a new album if
745 * an album with the given ID can not be found.
748 * The ID of the album
750 * {@code true} to create a new album if none exists for the
752 * @return The album with the given ID, or {@code null} if no album with the
753 * given ID exists and {@code create} is {@code false}
755 public Album getAlbum(String albumId, boolean create) {
756 synchronized (albums) {
757 Album album = albums.get(albumId);
758 if (create && (album == null)) {
759 album = new Album(albumId);
760 albums.put(albumId, album);
767 * Returns the image with the given ID, creating it if necessary.
770 * The ID of the image
771 * @return The image with the given ID
773 public Image getImage(String imageId) {
774 return getImage(imageId, true);
778 * Returns the image with the given ID, optionally creating it if it does
782 * The ID of the image
784 * {@code true} to create an image if none exists with the given
786 * @return The image with the given ID, or {@code null} if none exists and
789 public Image getImage(String imageId, boolean create) {
790 synchronized (images) {
791 Image image = images.get(imageId);
792 if (create && (image == null)) {
793 image = new Image(imageId);
794 images.put(imageId, image);
801 * Returns the temporary image with the given ID.
804 * The ID of the temporary image
805 * @return The temporary image, or {@code null} if there is no temporary
806 * image with the given ID
808 public TemporaryImage getTemporaryImage(String imageId) {
809 synchronized (temporaryImages) {
810 return temporaryImages.get(imageId);
819 * Locks the given Sone. A locked Sone will not be inserted by
820 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
826 public void lockSone(Sone sone) {
827 synchronized (lockedSones) {
828 if (lockedSones.add(sone)) {
829 coreListenerManager.fireSoneLocked(sone);
835 * Unlocks the given Sone.
837 * @see #lockSone(Sone)
841 public void unlockSone(Sone sone) {
842 synchronized (lockedSones) {
843 if (lockedSones.remove(sone)) {
844 coreListenerManager.fireSoneUnlocked(sone);
850 * Adds a local Sone from the given own identity.
853 * The own identity to create a Sone from
854 * @return The added (or already existing) Sone
856 public Sone addLocalSone(OwnIdentity ownIdentity) {
857 if (ownIdentity == null) {
858 logger.log(Level.WARNING, "Given OwnIdentity is null!");
861 synchronized (localSones) {
864 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
865 } catch (MalformedURLException mue1) {
866 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
869 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
870 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
872 /* TODO - load posts ’n stuff */
873 localSones.put(ownIdentity.getId(), sone);
874 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
875 soneInserter.addSoneInsertListener(this);
876 soneInserters.put(sone, soneInserter);
877 sone.setStatus(SoneStatus.idle);
879 soneInserter.start();
885 * Creates a new Sone for the given own identity.
888 * The own identity to create a Sone for
889 * @return The created Sone
891 public Sone createSone(OwnIdentity ownIdentity) {
893 ownIdentity.addContext("Sone");
894 } catch (WebOfTrustException wote1) {
895 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity), wote1);
898 Sone sone = addLocalSone(ownIdentity);
899 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
900 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
901 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
902 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
903 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
904 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
906 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
907 touchConfiguration();
912 * Adds the Sone of the given identity.
915 * The identity whose Sone to add
916 * @return The added or already existing Sone
918 public Sone addRemoteSone(Identity identity) {
919 if (identity == null) {
920 logger.log(Level.WARNING, "Given Identity is null!");
923 synchronized (remoteSones) {
924 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
925 boolean newSone = sone.getRequestUri() == null;
926 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
927 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
929 synchronized (knownSones) {
930 newSone = !knownSones.contains(sone.getId());
932 sone.setKnown(!newSone);
934 coreListenerManager.fireNewSoneFound(sone);
935 for (Sone localSone : getLocalSones()) {
936 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
937 followSone(localSone, sone);
942 soneDownloader.addSone(sone);
943 soneDownloaders.execute(new Runnable() {
946 @SuppressWarnings("synthetic-access")
948 soneDownloader.fetchSone(sone, sone.getRequestUri());
957 * Lets the given local Sone follow the Sone with the given ID.
960 * The local Sone that should follow another Sone
962 * The ID of the Sone to follow
964 public void followSone(Sone sone, String soneId) {
965 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
966 Sone followedSone = getSone(soneId, true);
967 if (followedSone == null) {
968 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
971 followSone(sone, getSone(soneId));
975 * Lets the given local Sone follow the other given Sone. If the given Sone
976 * was not followed by any local Sone before, this will mark all elements of
977 * the followed Sone as read that have been created before the current
981 * The local Sone that should follow the other Sone
982 * @param followedSone
983 * The Sone that should be followed
985 public void followSone(Sone sone, Sone followedSone) {
986 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
987 sone.addFriend(followedSone.getId());
988 synchronized (soneFollowingTimes) {
989 if (!soneFollowingTimes.containsKey(followedSone)) {
990 long now = System.currentTimeMillis();
991 soneFollowingTimes.put(followedSone, now);
992 for (Post post : followedSone.getPosts()) {
993 if (post.getTime() < now) {
997 for (PostReply reply : followedSone.getReplies()) {
998 if (reply.getTime() < now) {
999 markReplyKnown(reply);
1004 touchConfiguration();
1008 * Lets the given local Sone unfollow the Sone with the given ID.
1011 * The local Sone that should unfollow another Sone
1013 * The ID of the Sone being unfollowed
1015 public void unfollowSone(Sone sone, String soneId) {
1016 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1017 unfollowSone(sone, getSone(soneId, false));
1021 * Lets the given local Sone unfollow the other given Sone. If the given
1022 * local Sone is the last local Sone that followed the given Sone, its
1023 * following time will be removed.
1026 * The local Sone that should unfollow another Sone
1027 * @param unfollowedSone
1028 * The Sone being unfollowed
1030 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1031 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1032 sone.removeFriend(unfollowedSone.getId());
1033 boolean unfollowedSoneStillFollowed = false;
1034 for (Sone localSone : getLocalSones()) {
1035 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1037 if (!unfollowedSoneStillFollowed) {
1038 synchronized (soneFollowingTimes) {
1039 soneFollowingTimes.remove(unfollowedSone);
1042 touchConfiguration();
1046 * Retrieves the trust relationship from the origin to the target. If the
1047 * trust relationship can not be retrieved, {@code null} is returned.
1049 * @see Identity#getTrust(OwnIdentity)
1051 * The origin of the trust tree
1053 * The target of the trust
1054 * @return The trust relationship
1056 public Trust getTrust(Sone origin, Sone target) {
1057 if (!isLocalSone(origin)) {
1058 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
1061 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1065 * Sets the trust value of the given origin Sone for the target Sone.
1072 * The trust value (from {@code -100} to {@code 100})
1074 public void setTrust(Sone origin, Sone target, int trustValue) {
1075 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();
1077 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1078 } catch (WebOfTrustException wote1) {
1079 logger.log(Level.WARNING, String.format("Could not set trust for Sone: %s", target), wote1);
1084 * Removes any trust assignment for the given target Sone.
1091 public void removeTrust(Sone origin, Sone target) {
1092 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1094 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1095 } catch (WebOfTrustException wote1) {
1096 logger.log(Level.WARNING, String.format("Could not remove trust for Sone: %s", target), wote1);
1101 * Assigns the configured positive trust value for the given target.
1108 public void trustSone(Sone origin, Sone target) {
1109 setTrust(origin, target, preferences.getPositiveTrust());
1113 * Assigns the configured negative trust value for the given target.
1120 public void distrustSone(Sone origin, Sone target) {
1121 setTrust(origin, target, preferences.getNegativeTrust());
1125 * Removes the trust assignment for the given target.
1132 public void untrustSone(Sone origin, Sone target) {
1133 removeTrust(origin, target);
1137 * Updates the stored Sone with the given Sone.
1142 public void updateSone(Sone sone) {
1143 updateSone(sone, false);
1147 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1148 * {@code true}, an older Sone than the current Sone can be given to restore
1152 * The Sone to update
1153 * @param soneRescueMode
1154 * {@code true} if the stored Sone should be updated regardless
1155 * of the age of the given Sone
1157 public void updateSone(Sone sone, boolean soneRescueMode) {
1158 if (hasSone(sone.getId())) {
1159 Sone storedSone = getSone(sone.getId());
1160 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1161 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1164 synchronized (posts) {
1165 if (!soneRescueMode) {
1166 for (Post post : storedSone.getPosts()) {
1167 posts.remove(post.getId());
1168 if (!sone.getPosts().contains(post)) {
1169 coreListenerManager.firePostRemoved(post);
1173 List<Post> storedPosts = storedSone.getPosts();
1174 synchronized (knownPosts) {
1175 for (Post post : sone.getPosts()) {
1176 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1177 if (!storedPosts.contains(post)) {
1178 if (post.getTime() < getSoneFollowingTime(sone)) {
1179 knownPosts.add(post.getId());
1180 } else if (!knownPosts.contains(post.getId())) {
1181 sone.setKnown(false);
1182 coreListenerManager.fireNewPostFound(post);
1185 posts.put(post.getId(), post);
1189 synchronized (replies) {
1190 if (!soneRescueMode) {
1191 for (PostReply reply : storedSone.getReplies()) {
1192 replies.remove(reply.getId());
1193 if (!sone.getReplies().contains(reply)) {
1194 coreListenerManager.fireReplyRemoved(reply);
1198 Set<PostReply> storedReplies = storedSone.getReplies();
1199 synchronized (knownReplies) {
1200 for (PostReply reply : sone.getReplies()) {
1201 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1202 if (!storedReplies.contains(reply)) {
1203 if (reply.getTime() < getSoneFollowingTime(sone)) {
1204 knownReplies.add(reply.getId());
1205 } else if (!knownReplies.contains(reply.getId())) {
1206 reply.setKnown(false);
1207 coreListenerManager.fireNewReplyFound(reply);
1210 replies.put(reply.getId(), reply);
1214 synchronized (albums) {
1215 synchronized (images) {
1216 for (Album album : storedSone.getAlbums()) {
1217 albums.remove(album.getId());
1218 for (Image image : album.getImages()) {
1219 images.remove(image.getId());
1222 for (Album album : sone.getAlbums()) {
1223 albums.put(album.getId(), album);
1224 for (Image image : album.getImages()) {
1225 images.put(image.getId(), image);
1230 synchronized (storedSone) {
1231 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1232 storedSone.setTime(sone.getTime());
1234 storedSone.setClient(sone.getClient());
1235 storedSone.setProfile(sone.getProfile());
1236 if (soneRescueMode) {
1237 for (Post post : sone.getPosts()) {
1238 storedSone.addPost(post);
1240 for (PostReply reply : sone.getReplies()) {
1241 storedSone.addReply(reply);
1243 for (String likedPostId : sone.getLikedPostIds()) {
1244 storedSone.addLikedPostId(likedPostId);
1246 for (String likedReplyId : sone.getLikedReplyIds()) {
1247 storedSone.addLikedReplyId(likedReplyId);
1249 for (Album album : sone.getAlbums()) {
1250 storedSone.addAlbum(album);
1253 storedSone.setPosts(sone.getPosts());
1254 storedSone.setReplies(sone.getReplies());
1255 storedSone.setLikePostIds(sone.getLikedPostIds());
1256 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1257 storedSone.setAlbums(sone.getAlbums());
1259 storedSone.setLatestEdition(sone.getLatestEdition());
1265 * Deletes the given Sone. This will remove the Sone from the
1266 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1267 * and remove the context from its identity.
1270 * The Sone to delete
1272 public void deleteSone(Sone sone) {
1273 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1274 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1277 synchronized (localSones) {
1278 if (!localSones.containsKey(sone.getId())) {
1279 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1282 localSones.remove(sone.getId());
1283 SoneInserter soneInserter = soneInserters.remove(sone);
1284 soneInserter.removeSoneInsertListener(this);
1285 soneInserter.stop();
1288 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1289 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1290 } catch (WebOfTrustException wote1) {
1291 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1294 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1295 } catch (ConfigurationException ce1) {
1296 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1301 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1302 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1305 * The Sone to mark as known
1307 public void markSoneKnown(Sone sone) {
1308 if (!sone.isKnown()) {
1309 sone.setKnown(true);
1310 synchronized (knownSones) {
1311 knownSones.add(sone.getId());
1313 coreListenerManager.fireMarkSoneKnown(sone);
1314 touchConfiguration();
1319 * Loads and updates the given Sone from the configuration. If any error is
1320 * encountered, loading is aborted and the given Sone is not changed.
1323 * The Sone to load and update
1325 public void loadSone(Sone sone) {
1326 if (!isLocalSone(sone)) {
1327 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1331 /* initialize options. */
1332 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1333 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1334 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1335 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1336 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1337 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1340 String sonePrefix = "Sone/" + sone.getId();
1341 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1342 if (soneTime == null) {
1343 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1346 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1349 Profile profile = new Profile(sone);
1350 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1351 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1352 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1353 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1354 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1355 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1357 /* load profile fields. */
1359 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1360 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1361 if (fieldName == null) {
1364 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1365 profile.addField(fieldName).setValue(fieldValue);
1369 Set<Post> posts = new HashSet<Post>();
1371 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1372 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1373 if (postId == null) {
1376 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1377 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1378 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1379 if ((postTime == 0) || (postText == null)) {
1380 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1383 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1384 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1385 post.setRecipient(getSone(postRecipientId));
1391 Set<PostReply> replies = new HashSet<PostReply>();
1393 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1394 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1395 if (replyId == null) {
1398 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1399 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1400 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1401 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1402 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1405 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1408 /* load post likes. */
1409 Set<String> likedPostIds = new HashSet<String>();
1411 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1412 if (likedPostId == null) {
1415 likedPostIds.add(likedPostId);
1418 /* load reply likes. */
1419 Set<String> likedReplyIds = new HashSet<String>();
1421 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1422 if (likedReplyId == null) {
1425 likedReplyIds.add(likedReplyId);
1429 Set<String> friends = new HashSet<String>();
1431 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1432 if (friendId == null) {
1435 friends.add(friendId);
1439 List<Album> topLevelAlbums = new ArrayList<Album>();
1440 int albumCounter = 0;
1442 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1443 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1444 if (albumId == null) {
1447 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1448 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1449 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1450 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1451 if ((albumTitle == null) || (albumDescription == null)) {
1452 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1455 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1456 if (albumParentId != null) {
1457 Album parentAlbum = getAlbum(albumParentId, false);
1458 if (parentAlbum == null) {
1459 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1462 parentAlbum.addAlbum(album);
1464 if (!topLevelAlbums.contains(album)) {
1465 topLevelAlbums.add(album);
1471 int imageCounter = 0;
1473 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1474 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1475 if (imageId == null) {
1478 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1479 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1480 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1481 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1482 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1483 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1484 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1485 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1486 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1489 Album album = getAlbum(albumId, false);
1490 if (album == null) {
1491 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1494 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1495 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1496 album.addImage(image);
1500 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1501 if (avatarId != null) {
1502 profile.setAvatar(getImage(avatarId, false));
1506 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1507 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1508 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1509 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1510 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1511 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1513 /* if we’re still here, Sone was loaded successfully. */
1514 synchronized (sone) {
1515 sone.setTime(soneTime);
1516 sone.setProfile(profile);
1517 sone.setPosts(posts);
1518 sone.setReplies(replies);
1519 sone.setLikePostIds(likedPostIds);
1520 sone.setLikeReplyIds(likedReplyIds);
1521 for (String friendId : friends) {
1522 followSone(sone, friendId);
1524 sone.setAlbums(topLevelAlbums);
1525 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1527 synchronized (knownSones) {
1528 for (String friend : friends) {
1529 knownSones.add(friend);
1532 synchronized (knownPosts) {
1533 for (Post post : posts) {
1534 knownPosts.add(post.getId());
1537 synchronized (knownReplies) {
1538 for (PostReply reply : replies) {
1539 knownReplies.add(reply.getId());
1545 * Creates a new post.
1548 * The Sone that creates the post
1550 * The text of the post
1551 * @return The created post
1553 public Post createPost(Sone sone, String text) {
1554 return createPost(sone, System.currentTimeMillis(), text);
1558 * Creates a new post.
1561 * The Sone that creates the post
1563 * The time of the post
1565 * The text of the post
1566 * @return The created post
1568 public Post createPost(Sone sone, long time, String text) {
1569 return createPost(sone, null, time, text);
1573 * Creates a new post.
1576 * The Sone that creates the post
1578 * The recipient Sone, or {@code null} if this post does not have
1581 * The text of the post
1582 * @return The created post
1584 public Post createPost(Sone sone, Sone recipient, String text) {
1585 return createPost(sone, recipient, System.currentTimeMillis(), text);
1589 * Creates a new post.
1592 * The Sone that creates the post
1594 * The recipient Sone, or {@code null} if this post does not have
1597 * The time of the post
1599 * The text of the post
1600 * @return The created post
1602 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1603 if (!isLocalSone(sone)) {
1604 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1607 final Post post = new PostImpl(sone, time, text);
1608 if (recipient != null) {
1609 post.setRecipient(recipient);
1611 synchronized (posts) {
1612 posts.put(post.getId(), post);
1614 coreListenerManager.fireNewPostFound(post);
1616 touchConfiguration();
1617 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1624 markPostKnown(post);
1626 }, "Mark " + post + " read.");
1631 * Deletes the given post.
1634 * The post to delete
1636 public void deletePost(Post post) {
1637 if (!isLocalSone(post.getSone())) {
1638 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1641 post.getSone().removePost(post);
1642 synchronized (posts) {
1643 posts.remove(post.getId());
1645 coreListenerManager.firePostRemoved(post);
1646 markPostKnown(post);
1647 touchConfiguration();
1651 * Marks the given post as known, if it is currently not a known post
1652 * (according to {@link Post#isKnown()}).
1655 * The post to mark as known
1657 public void markPostKnown(Post post) {
1658 post.setKnown(true);
1659 synchronized (knownPosts) {
1660 coreListenerManager.fireMarkPostKnown(post);
1661 if (knownPosts.add(post.getId())) {
1662 touchConfiguration();
1665 for (PostReply reply : getReplies(post)) {
1666 markReplyKnown(reply);
1671 * Bookmarks the given post.
1674 * The post to bookmark
1676 public void bookmark(Post post) {
1677 bookmarkPost(post.getId());
1681 * Bookmarks the post with the given ID.
1684 * The ID of the post to bookmark
1686 public void bookmarkPost(String id) {
1687 synchronized (bookmarkedPosts) {
1688 bookmarkedPosts.add(id);
1693 * Removes the given post from the bookmarks.
1696 * The post to unbookmark
1698 public void unbookmark(Post post) {
1699 unbookmarkPost(post.getId());
1703 * Removes the post with the given ID from the bookmarks.
1706 * The ID of the post to unbookmark
1708 public void unbookmarkPost(String id) {
1709 synchronized (bookmarkedPosts) {
1710 bookmarkedPosts.remove(id);
1715 * Creates a new reply.
1718 * The Sone that creates the reply
1720 * The post that this reply refers to
1722 * The text of the reply
1723 * @return The created reply
1725 public PostReply createReply(Sone sone, Post post, String text) {
1726 return createReply(sone, post, System.currentTimeMillis(), text);
1730 * Creates a new reply.
1733 * The Sone that creates the reply
1735 * The post that this reply refers to
1737 * The time of the reply
1739 * The text of the reply
1740 * @return The created reply
1742 public PostReply createReply(Sone sone, Post post, long time, String text) {
1743 if (!isLocalSone(sone)) {
1744 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1747 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1748 synchronized (replies) {
1749 replies.put(reply.getId(), reply);
1751 synchronized (knownReplies) {
1752 coreListenerManager.fireNewReplyFound(reply);
1754 sone.addReply(reply);
1755 touchConfiguration();
1756 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1763 markReplyKnown(reply);
1765 }, "Mark " + reply + " read.");
1770 * Deletes the given reply.
1773 * The reply to delete
1775 public void deleteReply(PostReply reply) {
1776 Sone sone = reply.getSone();
1777 if (!isLocalSone(sone)) {
1778 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1781 synchronized (replies) {
1782 replies.remove(reply.getId());
1784 synchronized (knownReplies) {
1785 markReplyKnown(reply);
1786 knownReplies.remove(reply.getId());
1788 sone.removeReply(reply);
1789 touchConfiguration();
1793 * Marks the given reply as known, if it is currently not a known reply
1794 * (according to {@link Reply#isKnown()}).
1797 * The reply to mark as known
1799 public void markReplyKnown(PostReply reply) {
1800 reply.setKnown(true);
1801 synchronized (knownReplies) {
1802 coreListenerManager.fireMarkReplyKnown(reply);
1803 if (knownReplies.add(reply.getId())) {
1804 touchConfiguration();
1810 * Creates a new top-level album for the given Sone.
1813 * The Sone to create the album for
1814 * @return The new album
1816 public Album createAlbum(Sone sone) {
1817 return createAlbum(sone, null);
1821 * Creates a new album for the given Sone.
1824 * The Sone to create the album for
1826 * The parent of the album (may be {@code null} to create a
1828 * @return The new album
1830 public Album createAlbum(Sone sone, Album parent) {
1831 Album album = new Album();
1832 synchronized (albums) {
1833 albums.put(album.getId(), album);
1835 album.setSone(sone);
1836 if (parent != null) {
1837 parent.addAlbum(album);
1839 sone.addAlbum(album);
1845 * Deletes the given album. The owner of the album has to be a local Sone,
1846 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1849 * The album to remove
1851 public void deleteAlbum(Album album) {
1852 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1853 if (!album.isEmpty()) {
1856 if (album.getParent() == null) {
1857 album.getSone().removeAlbum(album);
1859 album.getParent().removeAlbum(album);
1861 synchronized (albums) {
1862 albums.remove(album.getId());
1864 saveSone(album.getSone());
1868 * Creates a new image.
1871 * The Sone creating the image
1873 * The album the image will be inserted into
1874 * @param temporaryImage
1875 * The temporary image to create the image from
1876 * @return The newly created image
1878 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1879 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", isLocalSone(sone)).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1880 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1881 album.addImage(image);
1882 synchronized (images) {
1883 images.put(image.getId(), image);
1885 imageInserter.insertImage(temporaryImage, image);
1890 * Deletes the given image. This method will also delete a matching
1893 * @see #deleteTemporaryImage(TemporaryImage)
1895 * The image to delete
1897 public void deleteImage(Image image) {
1898 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1899 deleteTemporaryImage(image.getId());
1900 image.getAlbum().removeImage(image);
1901 synchronized (images) {
1902 images.remove(image.getId());
1904 saveSone(image.getSone());
1908 * Creates a new temporary image.
1911 * The MIME type of the temporary image
1913 * The encoded data of the image
1914 * @return The temporary image
1916 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1917 TemporaryImage temporaryImage = new TemporaryImage();
1918 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1919 synchronized (temporaryImages) {
1920 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1922 return temporaryImage;
1926 * Deletes the given temporary image.
1928 * @param temporaryImage
1929 * The temporary image to delete
1931 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1932 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1933 deleteTemporaryImage(temporaryImage.getId());
1937 * Deletes the temporary image with the given ID.
1940 * The ID of the temporary image to delete
1942 public void deleteTemporaryImage(String imageId) {
1943 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1944 synchronized (temporaryImages) {
1945 temporaryImages.remove(imageId);
1947 Image image = getImage(imageId, false);
1948 if (image != null) {
1949 imageInserter.cancelImageInsert(image);
1954 * Notifies the core that the configuration, either of the core or of a
1955 * single local Sone, has changed, and that the configuration should be
1958 public void touchConfiguration() {
1959 lastConfigurationUpdate = System.currentTimeMillis();
1970 public void serviceStart() {
1971 loadConfiguration();
1972 updateChecker.addUpdateListener(this);
1973 updateChecker.start();
1974 trustUpdater.start();
1981 public void serviceRun() {
1982 long lastSaved = System.currentTimeMillis();
1983 while (!shouldStop()) {
1985 long now = System.currentTimeMillis();
1986 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1987 for (Sone localSone : getLocalSones()) {
1988 saveSone(localSone);
1990 saveConfiguration();
2000 public void serviceStop() {
2001 synchronized (localSones) {
2002 for (SoneInserter soneInserter : soneInserters.values()) {
2003 soneInserter.removeSoneInsertListener(this);
2004 soneInserter.stop();
2007 trustUpdater.stop();
2008 updateChecker.stop();
2009 updateChecker.removeUpdateListener(this);
2010 soneDownloader.stop();
2018 * Saves the given Sone. This will persist all local settings for the given
2019 * Sone, such as the friends list and similar, private options.
2024 private synchronized void saveSone(Sone sone) {
2025 if (!isLocalSone(sone)) {
2026 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2029 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2030 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2034 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2036 /* save Sone into configuration. */
2037 String sonePrefix = "Sone/" + sone.getId();
2038 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2039 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2042 Profile profile = sone.getProfile();
2043 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2044 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2045 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2046 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2047 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2048 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2049 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2051 /* save profile fields. */
2052 int fieldCounter = 0;
2053 for (Field profileField : profile.getFields()) {
2054 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2055 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2056 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2058 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2061 int postCounter = 0;
2062 for (Post post : sone.getPosts()) {
2063 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2064 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2065 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2066 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2067 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2069 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2072 int replyCounter = 0;
2073 for (PostReply reply : sone.getReplies()) {
2074 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2075 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2076 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2077 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2078 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2080 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2082 /* save post likes. */
2083 int postLikeCounter = 0;
2084 for (String postId : sone.getLikedPostIds()) {
2085 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2087 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2089 /* save reply likes. */
2090 int replyLikeCounter = 0;
2091 for (String replyId : sone.getLikedReplyIds()) {
2092 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2094 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2097 int friendCounter = 0;
2098 for (String friendId : sone.getFriends()) {
2099 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2101 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2103 /* save albums. first, collect in a flat structure, top-level first. */
2104 List<Album> albums = sone.getAllAlbums();
2106 int albumCounter = 0;
2107 for (Album album : albums) {
2108 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2109 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2110 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2111 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2112 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2113 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2115 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2118 int imageCounter = 0;
2119 for (Album album : albums) {
2120 for (Image image : album.getImages()) {
2121 if (!image.isInserted()) {
2124 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2125 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2126 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2127 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2128 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2129 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2130 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2131 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2132 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2135 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2138 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2139 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2140 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2141 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2142 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2143 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2145 configuration.save();
2147 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2149 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2150 } catch (ConfigurationException ce1) {
2151 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2152 } catch (WebOfTrustException wote1) {
2153 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2158 * Saves the current options.
2160 private void saveConfiguration() {
2161 synchronized (configuration) {
2162 if (storingConfiguration) {
2163 logger.log(Level.FINE, "Already storing configuration…");
2166 storingConfiguration = true;
2169 /* store the options first. */
2171 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2172 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2173 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2174 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2175 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2176 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2177 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2178 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2179 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2180 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2181 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2182 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2183 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2184 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2185 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2187 /* save known Sones. */
2188 int soneCounter = 0;
2189 synchronized (knownSones) {
2190 for (String knownSoneId : knownSones) {
2191 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2193 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2196 /* save Sone following times. */
2198 synchronized (soneFollowingTimes) {
2199 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2200 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2201 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2204 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2207 /* save known posts. */
2208 int postCounter = 0;
2209 synchronized (knownPosts) {
2210 for (String knownPostId : knownPosts) {
2211 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2213 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2216 /* save known replies. */
2217 int replyCounter = 0;
2218 synchronized (knownReplies) {
2219 for (String knownReplyId : knownReplies) {
2220 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2222 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2225 /* save bookmarked posts. */
2226 int bookmarkedPostCounter = 0;
2227 synchronized (bookmarkedPosts) {
2228 for (String bookmarkedPostId : bookmarkedPosts) {
2229 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2232 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2235 configuration.save();
2237 } catch (ConfigurationException ce1) {
2238 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2240 synchronized (configuration) {
2241 storingConfiguration = false;
2247 * Loads the configuration.
2249 @SuppressWarnings("unchecked")
2250 private void loadConfiguration() {
2251 /* create options. */
2252 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2255 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2256 SoneInserter.setInsertionDelay(newValue);
2260 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2261 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2262 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2263 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2264 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2265 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2266 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2267 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2268 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2271 @SuppressWarnings("synthetic-access")
2272 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2273 fcpInterface.setActive(newValue);
2276 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2279 @SuppressWarnings("synthetic-access")
2280 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2281 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2285 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2286 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2287 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2289 /* read options from configuration. */
2290 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2291 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2292 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2293 options.getBooleanOption("ClearOnNextRestart").set(null);
2294 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2295 if (clearConfiguration) {
2296 /* stop loading the configuration. */
2300 loadConfigurationValue("InsertionDelay");
2301 loadConfigurationValue("PostsPerPage");
2302 loadConfigurationValue("ImagesPerPage");
2303 loadConfigurationValue("CharactersPerPost");
2304 loadConfigurationValue("PostCutOffLength");
2305 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2306 loadConfigurationValue("PositiveTrust");
2307 loadConfigurationValue("NegativeTrust");
2308 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2309 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2310 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2311 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2313 /* load known Sones. */
2314 int soneCounter = 0;
2316 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2317 if (knownSoneId == null) {
2320 synchronized (knownSones) {
2321 knownSones.add(knownSoneId);
2325 /* load Sone following times. */
2328 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2329 if (soneId == null) {
2332 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2333 Sone followedSone = getSone(soneId);
2334 if (followedSone == null) {
2335 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2337 synchronized (soneFollowingTimes) {
2338 soneFollowingTimes.put(getSone(soneId), time);
2344 /* load known posts. */
2345 int postCounter = 0;
2347 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2348 if (knownPostId == null) {
2351 synchronized (knownPosts) {
2352 knownPosts.add(knownPostId);
2356 /* load known replies. */
2357 int replyCounter = 0;
2359 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2360 if (knownReplyId == null) {
2363 synchronized (knownReplies) {
2364 knownReplies.add(knownReplyId);
2368 /* load bookmarked posts. */
2369 int bookmarkedPostCounter = 0;
2371 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2372 if (bookmarkedPostId == null) {
2375 synchronized (bookmarkedPosts) {
2376 bookmarkedPosts.add(bookmarkedPostId);
2383 * Loads an {@link Integer} configuration value for the option with the
2384 * given name, logging validation failures.
2387 * The name of the option to load
2389 private void loadConfigurationValue(String optionName) {
2391 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2392 } catch (IllegalArgumentException iae1) {
2393 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2398 * Generate a Sone URI from the given URI and latest edition.
2401 * The URI to derive the Sone URI from
2402 * @return The derived URI
2404 private FreenetURI getSoneUri(String uriString) {
2406 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2408 } catch (MalformedURLException mue1) {
2409 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2415 // INTERFACE IdentityListener
2422 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2423 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2424 if (ownIdentity.hasContext("Sone")) {
2425 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2426 addLocalSone(ownIdentity);
2434 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2435 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2436 trustedIdentities.remove(ownIdentity);
2443 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2444 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2445 trustedIdentities.get(ownIdentity).add(identity);
2446 addRemoteSone(identity);
2453 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2454 new Thread(new Runnable() {
2457 @SuppressWarnings("synthetic-access")
2459 Sone sone = getRemoteSone(identity.getId(), false);
2460 sone.setIdentity(identity);
2461 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2462 soneDownloader.addSone(sone);
2463 soneDownloader.fetchSone(sone);
2472 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2473 trustedIdentities.get(ownIdentity).remove(identity);
2474 boolean foundIdentity = false;
2475 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2476 if (trustedIdentity.getKey().equals(ownIdentity)) {
2479 if (trustedIdentity.getValue().contains(identity)) {
2480 foundIdentity = true;
2483 if (foundIdentity) {
2484 /* some local identity still trusts this identity, don’t remove. */
2487 Sone sone = getSone(identity.getId(), false);
2489 /* TODO - we don’t have the Sone anymore. should this happen? */
2492 synchronized (posts) {
2493 synchronized (knownPosts) {
2494 for (Post post : sone.getPosts()) {
2495 posts.remove(post.getId());
2496 coreListenerManager.firePostRemoved(post);
2500 synchronized (replies) {
2501 synchronized (knownReplies) {
2502 for (PostReply reply : sone.getReplies()) {
2503 replies.remove(reply.getId());
2504 coreListenerManager.fireReplyRemoved(reply);
2508 synchronized (remoteSones) {
2509 remoteSones.remove(identity.getId());
2511 coreListenerManager.fireSoneRemoved(sone);
2515 // INTERFACE UpdateListener
2522 public void updateFound(Version version, long releaseTime, long latestEdition) {
2523 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2527 // INTERFACE ImageInsertListener
2534 public void insertStarted(Sone sone) {
2535 coreListenerManager.fireSoneInserting(sone);
2542 public void insertFinished(Sone sone, long insertDuration) {
2543 coreListenerManager.fireSoneInserted(sone, insertDuration);
2550 public void insertAborted(Sone sone, Throwable cause) {
2551 coreListenerManager.fireSoneInsertAborted(sone, cause);
2555 // SONEINSERTLISTENER METHODS
2562 public void imageInsertStarted(Image image) {
2563 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2564 coreListenerManager.fireImageInsertStarted(image);
2571 public void imageInsertAborted(Image image) {
2572 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2573 coreListenerManager.fireImageInsertAborted(image);
2580 public void imageInsertFinished(Image image, FreenetURI key) {
2581 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2582 image.setKey(key.toString());
2583 deleteTemporaryImage(image.getId());
2584 saveSone(image.getSone());
2585 coreListenerManager.fireImageInsertFinished(image);
2592 public void imageInsertFailed(Image image, Throwable cause) {
2593 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2594 coreListenerManager.fireImageInsertFailed(image, cause);
2598 * Convenience interface for external classes that want to access the core’s
2601 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2603 public static class Preferences {
2605 /** The wrapped options. */
2606 private final Options options;
2609 * Creates a new preferences object wrapped around the given options.
2612 * The options to wrap
2614 public Preferences(Options options) {
2615 this.options = options;
2619 * Returns the insertion delay.
2621 * @return The insertion delay
2623 public int getInsertionDelay() {
2624 return options.getIntegerOption("InsertionDelay").get();
2628 * Validates the given insertion delay.
2630 * @param insertionDelay
2631 * The insertion delay to validate
2632 * @return {@code true} if the given insertion delay was valid,
2633 * {@code false} otherwise
2635 public boolean validateInsertionDelay(Integer insertionDelay) {
2636 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2640 * Sets the insertion delay
2642 * @param insertionDelay
2643 * The new insertion delay, or {@code null} to restore it to
2645 * @return This preferences
2647 public Preferences setInsertionDelay(Integer insertionDelay) {
2648 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2653 * Returns the number of posts to show per page.
2655 * @return The number of posts to show per page
2657 public int getPostsPerPage() {
2658 return options.getIntegerOption("PostsPerPage").get();
2662 * Validates the number of posts per page.
2664 * @param postsPerPage
2665 * The number of posts per page
2666 * @return {@code true} if the number of posts per page was valid,
2667 * {@code false} otherwise
2669 public boolean validatePostsPerPage(Integer postsPerPage) {
2670 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2674 * Sets the number of posts to show per page.
2676 * @param postsPerPage
2677 * The number of posts to show per page
2678 * @return This preferences object
2680 public Preferences setPostsPerPage(Integer postsPerPage) {
2681 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2686 * Returns the number of images to show per page.
2688 * @return The number of images to show per page
2690 public int getImagesPerPage() {
2691 return options.getIntegerOption("ImagesPerPage").get();
2695 * Validates the number of images per page.
2697 * @param imagesPerPage
2698 * The number of images per page
2699 * @return {@code true} if the number of images per page was valid,
2700 * {@code false} otherwise
2702 public boolean validateImagesPerPage(Integer imagesPerPage) {
2703 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2707 * Sets the number of images per page.
2709 * @param imagesPerPage
2710 * The number of images per page
2711 * @return This preferences object
2713 public Preferences setImagesPerPage(Integer imagesPerPage) {
2714 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2719 * Returns the number of characters per post, or <code>-1</code> if the
2720 * posts should not be cut off.
2722 * @return The numbers of characters per post
2724 public int getCharactersPerPost() {
2725 return options.getIntegerOption("CharactersPerPost").get();
2729 * Validates the number of characters per post.
2731 * @param charactersPerPost
2732 * The number of characters per post
2733 * @return {@code true} if the number of characters per post was valid,
2734 * {@code false} otherwise
2736 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2737 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2741 * Sets the number of characters per post.
2743 * @param charactersPerPost
2744 * The number of characters per post, or <code>-1</code> to
2745 * not cut off the posts
2746 * @return This preferences objects
2748 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2749 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2754 * Returns the number of characters the shortened post should have.
2756 * @return The number of characters of the snippet
2758 public int getPostCutOffLength() {
2759 return options.getIntegerOption("PostCutOffLength").get();
2763 * Validates the number of characters after which to cut off the post.
2765 * @param postCutOffLength
2766 * The number of characters of the snippet
2767 * @return {@code true} if the number of characters of the snippet is
2768 * valid, {@code false} otherwise
2770 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2771 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2775 * Sets the number of characters the shortened post should have.
2777 * @param postCutOffLength
2778 * The number of characters of the snippet
2779 * @return This preferences
2781 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2782 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2787 * Returns whether Sone requires full access to be even visible.
2789 * @return {@code true} if Sone requires full access, {@code false}
2792 public boolean isRequireFullAccess() {
2793 return options.getBooleanOption("RequireFullAccess").get();
2797 * Sets whether Sone requires full access to be even visible.
2799 * @param requireFullAccess
2800 * {@code true} if Sone requires full access, {@code false}
2803 public void setRequireFullAccess(Boolean requireFullAccess) {
2804 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2808 * Returns the positive trust.
2810 * @return The positive trust
2812 public int getPositiveTrust() {
2813 return options.getIntegerOption("PositiveTrust").get();
2817 * Validates the positive trust.
2819 * @param positiveTrust
2820 * The positive trust to validate
2821 * @return {@code true} if the positive trust was valid, {@code false}
2824 public boolean validatePositiveTrust(Integer positiveTrust) {
2825 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2829 * Sets the positive trust.
2831 * @param positiveTrust
2832 * The new positive trust, or {@code null} to restore it to
2834 * @return This preferences
2836 public Preferences setPositiveTrust(Integer positiveTrust) {
2837 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2842 * Returns the negative trust.
2844 * @return The negative trust
2846 public int getNegativeTrust() {
2847 return options.getIntegerOption("NegativeTrust").get();
2851 * Validates the negative trust.
2853 * @param negativeTrust
2854 * The negative trust to validate
2855 * @return {@code true} if the negative trust was valid, {@code false}
2858 public boolean validateNegativeTrust(Integer negativeTrust) {
2859 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2863 * Sets the negative trust.
2865 * @param negativeTrust
2866 * The negative trust, or {@code null} to restore it to the
2868 * @return The preferences
2870 public Preferences setNegativeTrust(Integer negativeTrust) {
2871 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2876 * Returns the trust comment. This is the comment that is set in the web
2877 * of trust when a trust value is assigned to an identity.
2879 * @return The trust comment
2881 public String getTrustComment() {
2882 return options.getStringOption("TrustComment").get();
2886 * Sets the trust comment.
2888 * @param trustComment
2889 * The trust comment, or {@code null} to restore it to the
2891 * @return This preferences
2893 public Preferences setTrustComment(String trustComment) {
2894 options.getStringOption("TrustComment").set(trustComment);
2899 * Returns whether the {@link FcpInterface FCP interface} is currently
2902 * @see FcpInterface#setActive(boolean)
2903 * @return {@code true} if the FCP interface is currently active,
2904 * {@code false} otherwise
2906 public boolean isFcpInterfaceActive() {
2907 return options.getBooleanOption("ActivateFcpInterface").get();
2911 * Sets whether the {@link FcpInterface FCP interface} is currently
2914 * @see FcpInterface#setActive(boolean)
2915 * @param fcpInterfaceActive
2916 * {@code true} to activate the FCP interface, {@code false}
2917 * to deactivate the FCP interface
2918 * @return This preferences object
2920 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2921 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2926 * Returns the action level for which full access to the FCP interface
2929 * @return The action level for which full access to the FCP interface
2932 public FullAccessRequired getFcpFullAccessRequired() {
2933 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2937 * Sets the action level for which full access to the FCP interface is
2940 * @param fcpFullAccessRequired
2942 * @return This preferences
2944 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2945 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2950 * Returns whether Sone should clear its settings on the next restart.
2951 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2952 * to return {@code true} as well!
2954 * @return {@code true} if Sone should clear its settings on the next
2955 * restart, {@code false} otherwise
2957 public boolean isClearOnNextRestart() {
2958 return options.getBooleanOption("ClearOnNextRestart").get();
2962 * Sets whether Sone will clear its settings on the next restart.
2964 * @param clearOnNextRestart
2965 * {@code true} if Sone should clear its settings on the next
2966 * restart, {@code false} otherwise
2967 * @return This preferences
2969 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2970 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2975 * Returns whether Sone should really clear its settings on next
2976 * restart. This is a confirmation option that needs to be set in
2977 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2978 * settings on the next restart.
2980 * @return {@code true} if Sone should really clear its settings on the
2981 * next restart, {@code false} otherwise
2983 public boolean isReallyClearOnNextRestart() {
2984 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2988 * Sets whether Sone should really clear its settings on the next
2991 * @param reallyClearOnNextRestart
2992 * {@code true} if Sone should really clear its settings on
2993 * the next restart, {@code false} otherwise
2994 * @return This preferences
2996 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2997 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);