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 trustUpdater.getTrust((OwnIdentity) origin.getIdentity(), target.getIdentity());
1062 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1066 * Sets the trust value of the given origin Sone for the target Sone.
1073 * The trust value (from {@code -100} to {@code 100})
1075 public void setTrust(Sone origin, Sone target, int trustValue) {
1076 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 trustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1081 * Removes any trust assignment for the given target Sone.
1088 public void removeTrust(Sone origin, Sone target) {
1089 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1090 trustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1094 * Assigns the configured positive trust value for the given target.
1101 public void trustSone(Sone origin, Sone target) {
1102 setTrust(origin, target, preferences.getPositiveTrust());
1106 * Assigns the configured negative trust value for the given target.
1113 public void distrustSone(Sone origin, Sone target) {
1114 setTrust(origin, target, preferences.getNegativeTrust());
1118 * Removes the trust assignment for the given target.
1125 public void untrustSone(Sone origin, Sone target) {
1126 removeTrust(origin, target);
1130 * Updates the stored Sone with the given Sone.
1135 public void updateSone(Sone sone) {
1136 updateSone(sone, false);
1140 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1141 * {@code true}, an older Sone than the current Sone can be given to restore
1145 * The Sone to update
1146 * @param soneRescueMode
1147 * {@code true} if the stored Sone should be updated regardless
1148 * of the age of the given Sone
1150 public void updateSone(Sone sone, boolean soneRescueMode) {
1151 if (hasSone(sone.getId())) {
1152 Sone storedSone = getSone(sone.getId());
1153 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1154 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1157 synchronized (posts) {
1158 if (!soneRescueMode) {
1159 for (Post post : storedSone.getPosts()) {
1160 posts.remove(post.getId());
1161 if (!sone.getPosts().contains(post)) {
1162 coreListenerManager.firePostRemoved(post);
1166 List<Post> storedPosts = storedSone.getPosts();
1167 synchronized (knownPosts) {
1168 for (Post post : sone.getPosts()) {
1169 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1170 if (!storedPosts.contains(post)) {
1171 if (post.getTime() < getSoneFollowingTime(sone)) {
1172 knownPosts.add(post.getId());
1173 } else if (!knownPosts.contains(post.getId())) {
1174 sone.setKnown(false);
1175 coreListenerManager.fireNewPostFound(post);
1178 posts.put(post.getId(), post);
1182 synchronized (replies) {
1183 if (!soneRescueMode) {
1184 for (PostReply reply : storedSone.getReplies()) {
1185 replies.remove(reply.getId());
1186 if (!sone.getReplies().contains(reply)) {
1187 coreListenerManager.fireReplyRemoved(reply);
1191 Set<PostReply> storedReplies = storedSone.getReplies();
1192 synchronized (knownReplies) {
1193 for (PostReply reply : sone.getReplies()) {
1194 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1195 if (!storedReplies.contains(reply)) {
1196 if (reply.getTime() < getSoneFollowingTime(sone)) {
1197 knownReplies.add(reply.getId());
1198 } else if (!knownReplies.contains(reply.getId())) {
1199 reply.setKnown(false);
1200 coreListenerManager.fireNewReplyFound(reply);
1203 replies.put(reply.getId(), reply);
1207 synchronized (albums) {
1208 synchronized (images) {
1209 for (Album album : storedSone.getAlbums()) {
1210 albums.remove(album.getId());
1211 for (Image image : album.getImages()) {
1212 images.remove(image.getId());
1215 for (Album album : sone.getAlbums()) {
1216 albums.put(album.getId(), album);
1217 for (Image image : album.getImages()) {
1218 images.put(image.getId(), image);
1223 synchronized (storedSone) {
1224 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1225 storedSone.setTime(sone.getTime());
1227 storedSone.setClient(sone.getClient());
1228 storedSone.setProfile(sone.getProfile());
1229 if (soneRescueMode) {
1230 for (Post post : sone.getPosts()) {
1231 storedSone.addPost(post);
1233 for (PostReply reply : sone.getReplies()) {
1234 storedSone.addReply(reply);
1236 for (String likedPostId : sone.getLikedPostIds()) {
1237 storedSone.addLikedPostId(likedPostId);
1239 for (String likedReplyId : sone.getLikedReplyIds()) {
1240 storedSone.addLikedReplyId(likedReplyId);
1242 for (Album album : sone.getAlbums()) {
1243 storedSone.addAlbum(album);
1246 storedSone.setPosts(sone.getPosts());
1247 storedSone.setReplies(sone.getReplies());
1248 storedSone.setLikePostIds(sone.getLikedPostIds());
1249 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1250 storedSone.setAlbums(sone.getAlbums());
1252 storedSone.setLatestEdition(sone.getLatestEdition());
1258 * Deletes the given Sone. This will remove the Sone from the
1259 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1260 * and remove the context from its identity.
1263 * The Sone to delete
1265 public void deleteSone(Sone sone) {
1266 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1267 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1270 synchronized (localSones) {
1271 if (!localSones.containsKey(sone.getId())) {
1272 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1275 localSones.remove(sone.getId());
1276 SoneInserter soneInserter = soneInserters.remove(sone);
1277 soneInserter.removeSoneInsertListener(this);
1278 soneInserter.stop();
1281 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1282 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1283 } catch (WebOfTrustException wote1) {
1284 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1287 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1288 } catch (ConfigurationException ce1) {
1289 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1294 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1295 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1298 * The Sone to mark as known
1300 public void markSoneKnown(Sone sone) {
1301 if (!sone.isKnown()) {
1302 sone.setKnown(true);
1303 synchronized (knownSones) {
1304 knownSones.add(sone.getId());
1306 coreListenerManager.fireMarkSoneKnown(sone);
1307 touchConfiguration();
1312 * Loads and updates the given Sone from the configuration. If any error is
1313 * encountered, loading is aborted and the given Sone is not changed.
1316 * The Sone to load and update
1318 public void loadSone(Sone sone) {
1319 if (!isLocalSone(sone)) {
1320 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1324 /* initialize options. */
1325 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1326 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1327 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1328 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1329 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1330 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1333 String sonePrefix = "Sone/" + sone.getId();
1334 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1335 if (soneTime == null) {
1336 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1339 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1342 Profile profile = new Profile(sone);
1343 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1344 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1345 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1346 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1347 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1348 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1350 /* load profile fields. */
1352 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1353 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1354 if (fieldName == null) {
1357 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1358 profile.addField(fieldName).setValue(fieldValue);
1362 Set<Post> posts = new HashSet<Post>();
1364 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1365 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1366 if (postId == null) {
1369 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1370 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1371 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1372 if ((postTime == 0) || (postText == null)) {
1373 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1376 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1377 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1378 post.setRecipient(getSone(postRecipientId));
1384 Set<PostReply> replies = new HashSet<PostReply>();
1386 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1387 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1388 if (replyId == null) {
1391 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1392 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1393 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1394 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1395 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1398 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1401 /* load post likes. */
1402 Set<String> likedPostIds = new HashSet<String>();
1404 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1405 if (likedPostId == null) {
1408 likedPostIds.add(likedPostId);
1411 /* load reply likes. */
1412 Set<String> likedReplyIds = new HashSet<String>();
1414 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1415 if (likedReplyId == null) {
1418 likedReplyIds.add(likedReplyId);
1422 Set<String> friends = new HashSet<String>();
1424 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1425 if (friendId == null) {
1428 friends.add(friendId);
1432 List<Album> topLevelAlbums = new ArrayList<Album>();
1433 int albumCounter = 0;
1435 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1436 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1437 if (albumId == null) {
1440 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1441 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1442 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1443 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1444 if ((albumTitle == null) || (albumDescription == null)) {
1445 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1448 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1449 if (albumParentId != null) {
1450 Album parentAlbum = getAlbum(albumParentId, false);
1451 if (parentAlbum == null) {
1452 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1455 parentAlbum.addAlbum(album);
1457 if (!topLevelAlbums.contains(album)) {
1458 topLevelAlbums.add(album);
1464 int imageCounter = 0;
1466 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1467 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1468 if (imageId == null) {
1471 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1472 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1473 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1474 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1475 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1476 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1477 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1478 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1479 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1482 Album album = getAlbum(albumId, false);
1483 if (album == null) {
1484 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1487 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1488 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1489 album.addImage(image);
1493 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1494 if (avatarId != null) {
1495 profile.setAvatar(getImage(avatarId, false));
1499 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1500 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1501 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1502 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1503 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1504 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1506 /* if we’re still here, Sone was loaded successfully. */
1507 synchronized (sone) {
1508 sone.setTime(soneTime);
1509 sone.setProfile(profile);
1510 sone.setPosts(posts);
1511 sone.setReplies(replies);
1512 sone.setLikePostIds(likedPostIds);
1513 sone.setLikeReplyIds(likedReplyIds);
1514 for (String friendId : friends) {
1515 followSone(sone, friendId);
1517 sone.setAlbums(topLevelAlbums);
1518 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1520 synchronized (knownSones) {
1521 for (String friend : friends) {
1522 knownSones.add(friend);
1525 synchronized (knownPosts) {
1526 for (Post post : posts) {
1527 knownPosts.add(post.getId());
1530 synchronized (knownReplies) {
1531 for (PostReply reply : replies) {
1532 knownReplies.add(reply.getId());
1538 * Creates a new post.
1541 * The Sone that creates the post
1543 * The text of the post
1544 * @return The created post
1546 public Post createPost(Sone sone, String text) {
1547 return createPost(sone, System.currentTimeMillis(), text);
1551 * Creates a new post.
1554 * The Sone that creates the post
1556 * The time of the post
1558 * The text of the post
1559 * @return The created post
1561 public Post createPost(Sone sone, long time, String text) {
1562 return createPost(sone, null, time, text);
1566 * Creates a new post.
1569 * The Sone that creates the post
1571 * The recipient Sone, or {@code null} if this post does not have
1574 * The text of the post
1575 * @return The created post
1577 public Post createPost(Sone sone, Sone recipient, String text) {
1578 return createPost(sone, recipient, System.currentTimeMillis(), text);
1582 * Creates a new post.
1585 * The Sone that creates the post
1587 * The recipient Sone, or {@code null} if this post does not have
1590 * The time of the post
1592 * The text of the post
1593 * @return The created post
1595 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1596 if (!isLocalSone(sone)) {
1597 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1600 final Post post = new PostImpl(sone, time, text);
1601 if (recipient != null) {
1602 post.setRecipient(recipient);
1604 synchronized (posts) {
1605 posts.put(post.getId(), post);
1607 coreListenerManager.fireNewPostFound(post);
1609 touchConfiguration();
1610 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1617 markPostKnown(post);
1619 }, "Mark " + post + " read.");
1624 * Deletes the given post.
1627 * The post to delete
1629 public void deletePost(Post post) {
1630 if (!isLocalSone(post.getSone())) {
1631 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1634 post.getSone().removePost(post);
1635 synchronized (posts) {
1636 posts.remove(post.getId());
1638 coreListenerManager.firePostRemoved(post);
1639 markPostKnown(post);
1640 touchConfiguration();
1644 * Marks the given post as known, if it is currently not a known post
1645 * (according to {@link Post#isKnown()}).
1648 * The post to mark as known
1650 public void markPostKnown(Post post) {
1651 post.setKnown(true);
1652 synchronized (knownPosts) {
1653 coreListenerManager.fireMarkPostKnown(post);
1654 if (knownPosts.add(post.getId())) {
1655 touchConfiguration();
1658 for (PostReply reply : getReplies(post)) {
1659 markReplyKnown(reply);
1664 * Bookmarks the given post.
1667 * The post to bookmark
1669 public void bookmark(Post post) {
1670 bookmarkPost(post.getId());
1674 * Bookmarks the post with the given ID.
1677 * The ID of the post to bookmark
1679 public void bookmarkPost(String id) {
1680 synchronized (bookmarkedPosts) {
1681 bookmarkedPosts.add(id);
1686 * Removes the given post from the bookmarks.
1689 * The post to unbookmark
1691 public void unbookmark(Post post) {
1692 unbookmarkPost(post.getId());
1696 * Removes the post with the given ID from the bookmarks.
1699 * The ID of the post to unbookmark
1701 public void unbookmarkPost(String id) {
1702 synchronized (bookmarkedPosts) {
1703 bookmarkedPosts.remove(id);
1708 * Creates a new reply.
1711 * The Sone that creates the reply
1713 * The post that this reply refers to
1715 * The text of the reply
1716 * @return The created reply
1718 public PostReply createReply(Sone sone, Post post, String text) {
1719 return createReply(sone, post, System.currentTimeMillis(), text);
1723 * Creates a new reply.
1726 * The Sone that creates the reply
1728 * The post that this reply refers to
1730 * The time of the reply
1732 * The text of the reply
1733 * @return The created reply
1735 public PostReply createReply(Sone sone, Post post, long time, String text) {
1736 if (!isLocalSone(sone)) {
1737 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1740 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1741 synchronized (replies) {
1742 replies.put(reply.getId(), reply);
1744 synchronized (knownReplies) {
1745 coreListenerManager.fireNewReplyFound(reply);
1747 sone.addReply(reply);
1748 touchConfiguration();
1749 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1756 markReplyKnown(reply);
1758 }, "Mark " + reply + " read.");
1763 * Deletes the given reply.
1766 * The reply to delete
1768 public void deleteReply(PostReply reply) {
1769 Sone sone = reply.getSone();
1770 if (!isLocalSone(sone)) {
1771 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1774 synchronized (replies) {
1775 replies.remove(reply.getId());
1777 synchronized (knownReplies) {
1778 markReplyKnown(reply);
1779 knownReplies.remove(reply.getId());
1781 sone.removeReply(reply);
1782 touchConfiguration();
1786 * Marks the given reply as known, if it is currently not a known reply
1787 * (according to {@link Reply#isKnown()}).
1790 * The reply to mark as known
1792 public void markReplyKnown(PostReply reply) {
1793 reply.setKnown(true);
1794 synchronized (knownReplies) {
1795 coreListenerManager.fireMarkReplyKnown(reply);
1796 if (knownReplies.add(reply.getId())) {
1797 touchConfiguration();
1803 * Creates a new top-level album for the given Sone.
1806 * The Sone to create the album for
1807 * @return The new album
1809 public Album createAlbum(Sone sone) {
1810 return createAlbum(sone, null);
1814 * Creates a new album for the given Sone.
1817 * The Sone to create the album for
1819 * The parent of the album (may be {@code null} to create a
1821 * @return The new album
1823 public Album createAlbum(Sone sone, Album parent) {
1824 Album album = new Album();
1825 synchronized (albums) {
1826 albums.put(album.getId(), album);
1828 album.setSone(sone);
1829 if (parent != null) {
1830 parent.addAlbum(album);
1832 sone.addAlbum(album);
1838 * Deletes the given album. The owner of the album has to be a local Sone,
1839 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1842 * The album to remove
1844 public void deleteAlbum(Album album) {
1845 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1846 if (!album.isEmpty()) {
1849 if (album.getParent() == null) {
1850 album.getSone().removeAlbum(album);
1852 album.getParent().removeAlbum(album);
1854 synchronized (albums) {
1855 albums.remove(album.getId());
1857 saveSone(album.getSone());
1861 * Creates a new image.
1864 * The Sone creating the image
1866 * The album the image will be inserted into
1867 * @param temporaryImage
1868 * The temporary image to create the image from
1869 * @return The newly created image
1871 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1872 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();
1873 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1874 album.addImage(image);
1875 synchronized (images) {
1876 images.put(image.getId(), image);
1878 imageInserter.insertImage(temporaryImage, image);
1883 * Deletes the given image. This method will also delete a matching
1886 * @see #deleteTemporaryImage(TemporaryImage)
1888 * The image to delete
1890 public void deleteImage(Image image) {
1891 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1892 deleteTemporaryImage(image.getId());
1893 image.getAlbum().removeImage(image);
1894 synchronized (images) {
1895 images.remove(image.getId());
1897 saveSone(image.getSone());
1901 * Creates a new temporary image.
1904 * The MIME type of the temporary image
1906 * The encoded data of the image
1907 * @return The temporary image
1909 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1910 TemporaryImage temporaryImage = new TemporaryImage();
1911 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1912 synchronized (temporaryImages) {
1913 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1915 return temporaryImage;
1919 * Deletes the given temporary image.
1921 * @param temporaryImage
1922 * The temporary image to delete
1924 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1925 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1926 deleteTemporaryImage(temporaryImage.getId());
1930 * Deletes the temporary image with the given ID.
1933 * The ID of the temporary image to delete
1935 public void deleteTemporaryImage(String imageId) {
1936 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1937 synchronized (temporaryImages) {
1938 temporaryImages.remove(imageId);
1940 Image image = getImage(imageId, false);
1941 if (image != null) {
1942 imageInserter.cancelImageInsert(image);
1947 * Notifies the core that the configuration, either of the core or of a
1948 * single local Sone, has changed, and that the configuration should be
1951 public void touchConfiguration() {
1952 lastConfigurationUpdate = System.currentTimeMillis();
1963 public void serviceStart() {
1964 loadConfiguration();
1965 updateChecker.addUpdateListener(this);
1966 updateChecker.start();
1967 trustUpdater.start();
1974 public void serviceRun() {
1975 long lastSaved = System.currentTimeMillis();
1976 while (!shouldStop()) {
1978 long now = System.currentTimeMillis();
1979 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1980 for (Sone localSone : getLocalSones()) {
1981 saveSone(localSone);
1983 saveConfiguration();
1993 public void serviceStop() {
1994 synchronized (localSones) {
1995 for (SoneInserter soneInserter : soneInserters.values()) {
1996 soneInserter.removeSoneInsertListener(this);
1997 soneInserter.stop();
2000 trustUpdater.stop();
2001 updateChecker.stop();
2002 updateChecker.removeUpdateListener(this);
2003 soneDownloader.stop();
2011 * Saves the given Sone. This will persist all local settings for the given
2012 * Sone, such as the friends list and similar, private options.
2017 private synchronized void saveSone(Sone sone) {
2018 if (!isLocalSone(sone)) {
2019 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2022 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2023 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2027 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2029 /* save Sone into configuration. */
2030 String sonePrefix = "Sone/" + sone.getId();
2031 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2032 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2035 Profile profile = sone.getProfile();
2036 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2037 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2038 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2039 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2040 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2041 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2042 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2044 /* save profile fields. */
2045 int fieldCounter = 0;
2046 for (Field profileField : profile.getFields()) {
2047 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2048 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2049 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2051 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2054 int postCounter = 0;
2055 for (Post post : sone.getPosts()) {
2056 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2057 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2058 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2059 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2060 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2062 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2065 int replyCounter = 0;
2066 for (PostReply reply : sone.getReplies()) {
2067 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2068 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2069 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2070 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2071 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2073 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2075 /* save post likes. */
2076 int postLikeCounter = 0;
2077 for (String postId : sone.getLikedPostIds()) {
2078 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2080 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2082 /* save reply likes. */
2083 int replyLikeCounter = 0;
2084 for (String replyId : sone.getLikedReplyIds()) {
2085 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2087 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2090 int friendCounter = 0;
2091 for (String friendId : sone.getFriends()) {
2092 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2094 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2096 /* save albums. first, collect in a flat structure, top-level first. */
2097 List<Album> albums = sone.getAllAlbums();
2099 int albumCounter = 0;
2100 for (Album album : albums) {
2101 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2102 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2103 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2104 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2105 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2106 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2108 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2111 int imageCounter = 0;
2112 for (Album album : albums) {
2113 for (Image image : album.getImages()) {
2114 if (!image.isInserted()) {
2117 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2118 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2119 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2120 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2121 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2122 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2123 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2124 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2125 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2128 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2131 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2132 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2133 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2134 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2135 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2136 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2138 configuration.save();
2140 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2142 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2143 } catch (ConfigurationException ce1) {
2144 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2145 } catch (WebOfTrustException wote1) {
2146 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2151 * Saves the current options.
2153 private void saveConfiguration() {
2154 synchronized (configuration) {
2155 if (storingConfiguration) {
2156 logger.log(Level.FINE, "Already storing configuration…");
2159 storingConfiguration = true;
2162 /* store the options first. */
2164 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2165 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2166 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2167 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2168 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2169 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2170 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2171 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2172 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2173 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2174 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2175 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2176 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2177 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2178 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2180 /* save known Sones. */
2181 int soneCounter = 0;
2182 synchronized (knownSones) {
2183 for (String knownSoneId : knownSones) {
2184 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2186 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2189 /* save Sone following times. */
2191 synchronized (soneFollowingTimes) {
2192 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2193 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2194 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2197 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2200 /* save known posts. */
2201 int postCounter = 0;
2202 synchronized (knownPosts) {
2203 for (String knownPostId : knownPosts) {
2204 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2206 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2209 /* save known replies. */
2210 int replyCounter = 0;
2211 synchronized (knownReplies) {
2212 for (String knownReplyId : knownReplies) {
2213 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2215 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2218 /* save bookmarked posts. */
2219 int bookmarkedPostCounter = 0;
2220 synchronized (bookmarkedPosts) {
2221 for (String bookmarkedPostId : bookmarkedPosts) {
2222 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2225 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2228 configuration.save();
2230 } catch (ConfigurationException ce1) {
2231 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2233 synchronized (configuration) {
2234 storingConfiguration = false;
2240 * Loads the configuration.
2242 @SuppressWarnings("unchecked")
2243 private void loadConfiguration() {
2244 /* create options. */
2245 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2248 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2249 SoneInserter.setInsertionDelay(newValue);
2253 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2254 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2255 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2256 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2257 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2258 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2259 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2260 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2261 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2264 @SuppressWarnings("synthetic-access")
2265 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2266 fcpInterface.setActive(newValue);
2269 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2272 @SuppressWarnings("synthetic-access")
2273 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2274 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2278 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2279 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2280 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2282 /* read options from configuration. */
2283 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2284 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2285 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2286 options.getBooleanOption("ClearOnNextRestart").set(null);
2287 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2288 if (clearConfiguration) {
2289 /* stop loading the configuration. */
2293 loadConfigurationValue("InsertionDelay");
2294 loadConfigurationValue("PostsPerPage");
2295 loadConfigurationValue("ImagesPerPage");
2296 loadConfigurationValue("CharactersPerPost");
2297 loadConfigurationValue("PostCutOffLength");
2298 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2299 loadConfigurationValue("PositiveTrust");
2300 loadConfigurationValue("NegativeTrust");
2301 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2302 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2303 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2304 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2306 /* load known Sones. */
2307 int soneCounter = 0;
2309 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2310 if (knownSoneId == null) {
2313 synchronized (knownSones) {
2314 knownSones.add(knownSoneId);
2318 /* load Sone following times. */
2321 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2322 if (soneId == null) {
2325 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2326 Sone followedSone = getSone(soneId);
2327 if (followedSone == null) {
2328 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2330 synchronized (soneFollowingTimes) {
2331 soneFollowingTimes.put(getSone(soneId), time);
2337 /* load known posts. */
2338 int postCounter = 0;
2340 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2341 if (knownPostId == null) {
2344 synchronized (knownPosts) {
2345 knownPosts.add(knownPostId);
2349 /* load known replies. */
2350 int replyCounter = 0;
2352 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2353 if (knownReplyId == null) {
2356 synchronized (knownReplies) {
2357 knownReplies.add(knownReplyId);
2361 /* load bookmarked posts. */
2362 int bookmarkedPostCounter = 0;
2364 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2365 if (bookmarkedPostId == null) {
2368 synchronized (bookmarkedPosts) {
2369 bookmarkedPosts.add(bookmarkedPostId);
2376 * Loads an {@link Integer} configuration value for the option with the
2377 * given name, logging validation failures.
2380 * The name of the option to load
2382 private void loadConfigurationValue(String optionName) {
2384 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2385 } catch (IllegalArgumentException iae1) {
2386 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2391 * Generate a Sone URI from the given URI and latest edition.
2394 * The URI to derive the Sone URI from
2395 * @return The derived URI
2397 private FreenetURI getSoneUri(String uriString) {
2399 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2401 } catch (MalformedURLException mue1) {
2402 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2408 // INTERFACE IdentityListener
2415 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2416 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2417 if (ownIdentity.hasContext("Sone")) {
2418 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2419 addLocalSone(ownIdentity);
2427 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2428 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2429 trustedIdentities.remove(ownIdentity);
2436 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2437 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2438 trustedIdentities.get(ownIdentity).add(identity);
2439 addRemoteSone(identity);
2446 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2447 new Thread(new Runnable() {
2450 @SuppressWarnings("synthetic-access")
2452 Sone sone = getRemoteSone(identity.getId(), false);
2453 sone.setIdentity(identity);
2454 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2455 soneDownloader.addSone(sone);
2456 soneDownloader.fetchSone(sone);
2465 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2466 trustedIdentities.get(ownIdentity).remove(identity);
2467 boolean foundIdentity = false;
2468 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2469 if (trustedIdentity.getKey().equals(ownIdentity)) {
2472 if (trustedIdentity.getValue().contains(identity)) {
2473 foundIdentity = true;
2476 if (foundIdentity) {
2477 /* some local identity still trusts this identity, don’t remove. */
2480 Sone sone = getSone(identity.getId(), false);
2482 /* TODO - we don’t have the Sone anymore. should this happen? */
2485 synchronized (posts) {
2486 synchronized (knownPosts) {
2487 for (Post post : sone.getPosts()) {
2488 posts.remove(post.getId());
2489 coreListenerManager.firePostRemoved(post);
2493 synchronized (replies) {
2494 synchronized (knownReplies) {
2495 for (PostReply reply : sone.getReplies()) {
2496 replies.remove(reply.getId());
2497 coreListenerManager.fireReplyRemoved(reply);
2501 synchronized (remoteSones) {
2502 remoteSones.remove(identity.getId());
2504 coreListenerManager.fireSoneRemoved(sone);
2508 // INTERFACE UpdateListener
2515 public void updateFound(Version version, long releaseTime, long latestEdition) {
2516 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2520 // INTERFACE ImageInsertListener
2527 public void insertStarted(Sone sone) {
2528 coreListenerManager.fireSoneInserting(sone);
2535 public void insertFinished(Sone sone, long insertDuration) {
2536 coreListenerManager.fireSoneInserted(sone, insertDuration);
2543 public void insertAborted(Sone sone, Throwable cause) {
2544 coreListenerManager.fireSoneInsertAborted(sone, cause);
2548 // SONEINSERTLISTENER METHODS
2555 public void imageInsertStarted(Image image) {
2556 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2557 coreListenerManager.fireImageInsertStarted(image);
2564 public void imageInsertAborted(Image image) {
2565 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2566 coreListenerManager.fireImageInsertAborted(image);
2573 public void imageInsertFinished(Image image, FreenetURI key) {
2574 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2575 image.setKey(key.toString());
2576 deleteTemporaryImage(image.getId());
2577 saveSone(image.getSone());
2578 coreListenerManager.fireImageInsertFinished(image);
2585 public void imageInsertFailed(Image image, Throwable cause) {
2586 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2587 coreListenerManager.fireImageInsertFailed(image, cause);
2591 * Convenience interface for external classes that want to access the core’s
2594 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2596 public static class Preferences {
2598 /** The wrapped options. */
2599 private final Options options;
2602 * Creates a new preferences object wrapped around the given options.
2605 * The options to wrap
2607 public Preferences(Options options) {
2608 this.options = options;
2612 * Returns the insertion delay.
2614 * @return The insertion delay
2616 public int getInsertionDelay() {
2617 return options.getIntegerOption("InsertionDelay").get();
2621 * Validates the given insertion delay.
2623 * @param insertionDelay
2624 * The insertion delay to validate
2625 * @return {@code true} if the given insertion delay was valid,
2626 * {@code false} otherwise
2628 public boolean validateInsertionDelay(Integer insertionDelay) {
2629 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2633 * Sets the insertion delay
2635 * @param insertionDelay
2636 * The new insertion delay, or {@code null} to restore it to
2638 * @return This preferences
2640 public Preferences setInsertionDelay(Integer insertionDelay) {
2641 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2646 * Returns the number of posts to show per page.
2648 * @return The number of posts to show per page
2650 public int getPostsPerPage() {
2651 return options.getIntegerOption("PostsPerPage").get();
2655 * Validates the number of posts per page.
2657 * @param postsPerPage
2658 * The number of posts per page
2659 * @return {@code true} if the number of posts per page was valid,
2660 * {@code false} otherwise
2662 public boolean validatePostsPerPage(Integer postsPerPage) {
2663 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2667 * Sets the number of posts to show per page.
2669 * @param postsPerPage
2670 * The number of posts to show per page
2671 * @return This preferences object
2673 public Preferences setPostsPerPage(Integer postsPerPage) {
2674 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2679 * Returns the number of images to show per page.
2681 * @return The number of images to show per page
2683 public int getImagesPerPage() {
2684 return options.getIntegerOption("ImagesPerPage").get();
2688 * Validates the number of images per page.
2690 * @param imagesPerPage
2691 * The number of images per page
2692 * @return {@code true} if the number of images per page was valid,
2693 * {@code false} otherwise
2695 public boolean validateImagesPerPage(Integer imagesPerPage) {
2696 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2700 * Sets the number of images per page.
2702 * @param imagesPerPage
2703 * The number of images per page
2704 * @return This preferences object
2706 public Preferences setImagesPerPage(Integer imagesPerPage) {
2707 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2712 * Returns the number of characters per post, or <code>-1</code> if the
2713 * posts should not be cut off.
2715 * @return The numbers of characters per post
2717 public int getCharactersPerPost() {
2718 return options.getIntegerOption("CharactersPerPost").get();
2722 * Validates the number of characters per post.
2724 * @param charactersPerPost
2725 * The number of characters per post
2726 * @return {@code true} if the number of characters per post was valid,
2727 * {@code false} otherwise
2729 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2730 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2734 * Sets the number of characters per post.
2736 * @param charactersPerPost
2737 * The number of characters per post, or <code>-1</code> to
2738 * not cut off the posts
2739 * @return This preferences objects
2741 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2742 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2747 * Returns the number of characters the shortened post should have.
2749 * @return The number of characters of the snippet
2751 public int getPostCutOffLength() {
2752 return options.getIntegerOption("PostCutOffLength").get();
2756 * Validates the number of characters after which to cut off the post.
2758 * @param postCutOffLength
2759 * The number of characters of the snippet
2760 * @return {@code true} if the number of characters of the snippet is
2761 * valid, {@code false} otherwise
2763 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2764 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2768 * Sets the number of characters the shortened post should have.
2770 * @param postCutOffLength
2771 * The number of characters of the snippet
2772 * @return This preferences
2774 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2775 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2780 * Returns whether Sone requires full access to be even visible.
2782 * @return {@code true} if Sone requires full access, {@code false}
2785 public boolean isRequireFullAccess() {
2786 return options.getBooleanOption("RequireFullAccess").get();
2790 * Sets whether Sone requires full access to be even visible.
2792 * @param requireFullAccess
2793 * {@code true} if Sone requires full access, {@code false}
2796 public void setRequireFullAccess(Boolean requireFullAccess) {
2797 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2801 * Returns the positive trust.
2803 * @return The positive trust
2805 public int getPositiveTrust() {
2806 return options.getIntegerOption("PositiveTrust").get();
2810 * Validates the positive trust.
2812 * @param positiveTrust
2813 * The positive trust to validate
2814 * @return {@code true} if the positive trust was valid, {@code false}
2817 public boolean validatePositiveTrust(Integer positiveTrust) {
2818 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2822 * Sets the positive trust.
2824 * @param positiveTrust
2825 * The new positive trust, or {@code null} to restore it to
2827 * @return This preferences
2829 public Preferences setPositiveTrust(Integer positiveTrust) {
2830 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2835 * Returns the negative trust.
2837 * @return The negative trust
2839 public int getNegativeTrust() {
2840 return options.getIntegerOption("NegativeTrust").get();
2844 * Validates the negative trust.
2846 * @param negativeTrust
2847 * The negative trust to validate
2848 * @return {@code true} if the negative trust was valid, {@code false}
2851 public boolean validateNegativeTrust(Integer negativeTrust) {
2852 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2856 * Sets the negative trust.
2858 * @param negativeTrust
2859 * The negative trust, or {@code null} to restore it to the
2861 * @return The preferences
2863 public Preferences setNegativeTrust(Integer negativeTrust) {
2864 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2869 * Returns the trust comment. This is the comment that is set in the web
2870 * of trust when a trust value is assigned to an identity.
2872 * @return The trust comment
2874 public String getTrustComment() {
2875 return options.getStringOption("TrustComment").get();
2879 * Sets the trust comment.
2881 * @param trustComment
2882 * The trust comment, or {@code null} to restore it to the
2884 * @return This preferences
2886 public Preferences setTrustComment(String trustComment) {
2887 options.getStringOption("TrustComment").set(trustComment);
2892 * Returns whether the {@link FcpInterface FCP interface} is currently
2895 * @see FcpInterface#setActive(boolean)
2896 * @return {@code true} if the FCP interface is currently active,
2897 * {@code false} otherwise
2899 public boolean isFcpInterfaceActive() {
2900 return options.getBooleanOption("ActivateFcpInterface").get();
2904 * Sets whether the {@link FcpInterface FCP interface} is currently
2907 * @see FcpInterface#setActive(boolean)
2908 * @param fcpInterfaceActive
2909 * {@code true} to activate the FCP interface, {@code false}
2910 * to deactivate the FCP interface
2911 * @return This preferences object
2913 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2914 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2919 * Returns the action level for which full access to the FCP interface
2922 * @return The action level for which full access to the FCP interface
2925 public FullAccessRequired getFcpFullAccessRequired() {
2926 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2930 * Sets the action level for which full access to the FCP interface is
2933 * @param fcpFullAccessRequired
2935 * @return This preferences
2937 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2938 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2943 * Returns whether Sone should clear its settings on the next restart.
2944 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2945 * to return {@code true} as well!
2947 * @return {@code true} if Sone should clear its settings on the next
2948 * restart, {@code false} otherwise
2950 public boolean isClearOnNextRestart() {
2951 return options.getBooleanOption("ClearOnNextRestart").get();
2955 * Sets whether Sone will clear its settings on the next restart.
2957 * @param clearOnNextRestart
2958 * {@code true} if Sone should clear its settings on the next
2959 * restart, {@code false} otherwise
2960 * @return This preferences
2962 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2963 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2968 * Returns whether Sone should really clear its settings on next
2969 * restart. This is a confirmation option that needs to be set in
2970 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2971 * settings on the next restart.
2973 * @return {@code true} if Sone should really clear its settings on the
2974 * next restart, {@code false} otherwise
2976 public boolean isReallyClearOnNextRestart() {
2977 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2981 * Sets whether Sone should really clear its settings on the next
2984 * @param reallyClearOnNextRestart
2985 * {@code true} if Sone should really clear its settings on
2986 * the next restart, {@code false} otherwise
2987 * @return This preferences
2989 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2990 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);