2 * Sone - Core.java - Copyright © 2010 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;
28 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.Reply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.TemporaryImage;
46 import net.pterodactylus.sone.data.Profile.Field;
47 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.fcp.FcpInterface;
50 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
51 import net.pterodactylus.sone.freenet.wot.Identity;
52 import net.pterodactylus.sone.freenet.wot.IdentityListener;
53 import net.pterodactylus.sone.freenet.wot.IdentityManager;
54 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
55 import net.pterodactylus.sone.freenet.wot.Trust;
56 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
57 import net.pterodactylus.sone.main.SonePlugin;
58 import net.pterodactylus.util.config.Configuration;
59 import net.pterodactylus.util.config.ConfigurationException;
60 import net.pterodactylus.util.logging.Logging;
61 import net.pterodactylus.util.number.Numbers;
62 import net.pterodactylus.util.service.AbstractService;
63 import net.pterodactylus.util.thread.Ticker;
64 import net.pterodactylus.util.validation.EqualityValidator;
65 import net.pterodactylus.util.validation.IntegerRangeValidator;
66 import net.pterodactylus.util.validation.OrValidator;
67 import net.pterodactylus.util.validation.Validation;
68 import net.pterodactylus.util.version.Version;
69 import freenet.keys.FreenetURI;
74 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
79 private static final Logger logger = Logging.getLogger(Core.class);
82 private final Options options = new Options();
84 /** The preferences. */
85 private final Preferences preferences = new Preferences(options);
87 /** The core listener manager. */
88 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
90 /** The configuration. */
91 private Configuration configuration;
93 /** Whether we’re currently saving the configuration. */
94 private boolean storingConfiguration = false;
96 /** The identity manager. */
97 private final IdentityManager identityManager;
99 /** Interface to freenet. */
100 private final FreenetInterface freenetInterface;
102 /** The Sone downloader. */
103 private final SoneDownloader soneDownloader;
105 /** The image inserter. */
106 private final ImageInserter imageInserter;
108 /** Sone downloader thread-pool. */
109 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
111 /** The update checker. */
112 private final UpdateChecker updateChecker;
114 /** The FCP interface. */
115 private volatile FcpInterface fcpInterface;
117 /** The times Sones were followed. */
118 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
120 /** Locked local Sones. */
121 /* synchronize on itself. */
122 private final Set<Sone> lockedSones = new HashSet<Sone>();
124 /** Sone inserters. */
125 /* synchronize access on this on localSones. */
126 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
128 /** Sone rescuers. */
129 /* synchronize access on this on localSones. */
130 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
132 /** All local Sones. */
133 /* synchronize access on this on itself. */
134 private Map<String, Sone> localSones = new HashMap<String, Sone>();
136 /** All remote Sones. */
137 /* synchronize access on this on itself. */
138 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
140 /** All known Sones. */
141 private Set<String> knownSones = new HashSet<String>();
144 private Map<String, Post> posts = new HashMap<String, Post>();
146 /** All new posts. */
147 private Set<String> newPosts = new HashSet<String>();
149 /** All known posts. */
150 /* synchronize access on {@link #newPosts}. */
151 private Set<String> knownPosts = new HashSet<String>();
154 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
156 /** All new replies. */
157 private Set<String> newReplies = new HashSet<String>();
159 /** All known replies. */
160 private Set<String> knownReplies = new HashSet<String>();
162 /** All bookmarked posts. */
163 /* synchronize access on itself. */
164 private Set<String> bookmarkedPosts = new HashSet<String>();
166 /** Trusted identities, sorted by own identities. */
167 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
169 /** All known albums. */
170 private Map<String, Album> albums = new HashMap<String, Album>();
172 /** All known images. */
173 private Map<String, Image> images = new HashMap<String, Image>();
175 /** All temporary images. */
176 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
178 /** Ticker for threads that mark own elements as known. */
179 private Ticker localElementTicker = new Ticker();
181 /** The time the configuration was last touched. */
182 private volatile long lastConfigurationUpdate;
185 * Creates a new core.
187 * @param configuration
188 * The configuration of the core
189 * @param freenetInterface
190 * The freenet interface
191 * @param identityManager
192 * The identity manager
194 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
196 this.configuration = configuration;
197 this.freenetInterface = freenetInterface;
198 this.identityManager = identityManager;
199 this.soneDownloader = new SoneDownloader(this, freenetInterface);
200 this.imageInserter = new ImageInserter(this, freenetInterface);
201 this.updateChecker = new UpdateChecker(freenetInterface);
205 // LISTENER MANAGEMENT
209 * Adds a new core listener.
211 * @param coreListener
212 * The listener to add
214 public void addCoreListener(CoreListener coreListener) {
215 coreListenerManager.addListener(coreListener);
219 * Removes a core listener.
221 * @param coreListener
222 * The listener to remove
224 public void removeCoreListener(CoreListener coreListener) {
225 coreListenerManager.removeListener(coreListener);
233 * Sets the configuration to use. This will automatically save the current
234 * configuration to the given configuration.
236 * @param configuration
237 * The new configuration to use
239 public void setConfiguration(Configuration configuration) {
240 this.configuration = configuration;
241 touchConfiguration();
245 * Returns the options used by the core.
247 * @return The options of the core
249 public Preferences getPreferences() {
254 * Returns the identity manager used by the core.
256 * @return The identity manager
258 public IdentityManager getIdentityManager() {
259 return identityManager;
263 * Returns the update checker.
265 * @return The update checker
267 public UpdateChecker getUpdateChecker() {
268 return updateChecker;
272 * Sets the FCP interface to use.
274 * @param fcpInterface
275 * The FCP interface to use
277 public void setFcpInterface(FcpInterface fcpInterface) {
278 this.fcpInterface = fcpInterface;
282 * Returns the Sone rescuer for the given local Sone.
285 * The local Sone to get the rescuer for
286 * @return The Sone rescuer for the given Sone
288 public SoneRescuer getSoneRescuer(Sone sone) {
289 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
290 synchronized (localSones) {
291 SoneRescuer soneRescuer = soneRescuers.get(sone);
292 if (soneRescuer == null) {
293 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
294 soneRescuers.put(sone, soneRescuer);
302 * Returns whether the given Sone is currently locked.
306 * @return {@code true} if the Sone is locked, {@code false} if it is not
308 public boolean isLocked(Sone sone) {
309 synchronized (lockedSones) {
310 return lockedSones.contains(sone);
315 * Returns all Sones, remote and local.
319 public Set<Sone> getSones() {
320 Set<Sone> allSones = new HashSet<Sone>();
321 allSones.addAll(getLocalSones());
322 allSones.addAll(getRemoteSones());
327 * Returns the Sone with the given ID, regardless whether it’s local or
331 * The ID of the Sone to get
332 * @return The Sone with the given ID, or {@code null} if there is no such
335 public Sone getSone(String id) {
336 return getSone(id, true);
340 * Returns the Sone with the given ID, regardless whether it’s local or
344 * The ID of the Sone to get
346 * {@code true} to create a new Sone if none exists,
347 * {@code false} to return {@code null} if a Sone with the given
349 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Sone getSone(String id, boolean create) {
354 if (isLocalSone(id)) {
355 return getLocalSone(id);
357 return getRemoteSone(id, create);
361 * Checks whether the core knows a Sone with the given ID.
365 * @return {@code true} if there is a Sone with the given ID, {@code false}
368 public boolean hasSone(String id) {
369 return isLocalSone(id) || isRemoteSone(id);
373 * Returns whether the given Sone is a local Sone.
376 * The Sone to check for its locality
377 * @return {@code true} if the given Sone is local, {@code false} otherwise
379 public boolean isLocalSone(Sone sone) {
380 synchronized (localSones) {
381 return localSones.containsKey(sone.getId());
386 * Returns whether the given ID is the ID of a local Sone.
389 * The Sone ID to check for its locality
390 * @return {@code true} if the given ID is a local Sone, {@code false}
393 public boolean isLocalSone(String id) {
394 synchronized (localSones) {
395 return localSones.containsKey(id);
400 * Returns all local Sones.
402 * @return All local Sones
404 public Set<Sone> getLocalSones() {
405 synchronized (localSones) {
406 return new HashSet<Sone>(localSones.values());
411 * Returns the local Sone with the given ID.
414 * The ID of the Sone to get
415 * @return The Sone with the given ID
417 public Sone getLocalSone(String id) {
418 return getLocalSone(id, true);
422 * Returns the local Sone with the given ID, optionally creating a new Sone.
427 * {@code true} to create a new Sone if none exists,
428 * {@code false} to return null if none exists
429 * @return The Sone with the given ID, or {@code null}
431 public Sone getLocalSone(String id, boolean create) {
432 synchronized (localSones) {
433 Sone sone = localSones.get(id);
434 if ((sone == null) && create) {
436 localSones.put(id, sone);
443 * Returns all remote Sones.
445 * @return All remote Sones
447 public Set<Sone> getRemoteSones() {
448 synchronized (remoteSones) {
449 return new HashSet<Sone>(remoteSones.values());
454 * Returns the remote Sone with the given ID.
457 * The ID of the remote Sone to get
459 * {@code true} to always create a Sone, {@code false} to return
460 * {@code null} if no Sone with the given ID exists
461 * @return The Sone with the given ID
463 public Sone getRemoteSone(String id, boolean create) {
464 synchronized (remoteSones) {
465 Sone sone = remoteSones.get(id);
466 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
468 remoteSones.put(id, sone);
475 * Returns whether the given Sone is a remote Sone.
479 * @return {@code true} if the given Sone is a remote Sone, {@code false}
482 public boolean isRemoteSone(Sone sone) {
483 synchronized (remoteSones) {
484 return remoteSones.containsKey(sone.getId());
489 * Returns whether the Sone with the given ID is a remote Sone.
492 * The ID of the Sone to check
493 * @return {@code true} if the Sone with the given ID is a remote Sone,
494 * {@code false} otherwise
496 public boolean isRemoteSone(String id) {
497 synchronized (remoteSones) {
498 return remoteSones.containsKey(id);
503 * Returns whether the given Sone has been modified.
506 * The Sone to check for modifications
507 * @return {@code true} if a modification has been detected in the Sone,
508 * {@code false} otherwise
510 public boolean isModifiedSone(Sone sone) {
511 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
515 * Returns the time when the given was first followed by any local Sone.
518 * The Sone to get the time for
519 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
520 * been followed, or {@link Long#MAX_VALUE}
522 public long getSoneFollowingTime(Sone sone) {
523 synchronized (soneFollowingTimes) {
524 if (soneFollowingTimes.containsKey(sone)) {
525 return soneFollowingTimes.get(sone);
527 return Long.MAX_VALUE;
532 * Returns whether the target Sone is trusted by the origin Sone.
538 * @return {@code true} if the target Sone is trusted by the origin Sone
540 public boolean isSoneTrusted(Sone origin, Sone target) {
541 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
542 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
546 * Returns the post with the given ID.
549 * The ID of the post to get
550 * @return The post with the given ID, or a new post with the given ID
552 public Post getPost(String postId) {
553 return getPost(postId, true);
557 * Returns the post with the given ID, optionally creating a new post.
560 * The ID of the post to get
562 * {@code true} it create a new post if no post with the given ID
563 * exists, {@code false} to return {@code null}
564 * @return The post, or {@code null} if there is no such post
567 public Post getPost(String postId, boolean create) {
568 synchronized (posts) {
569 Post post = posts.get(postId);
570 if ((post == null) && create) {
571 post = new Post(postId);
572 posts.put(postId, post);
579 * Returns whether the given post ID is new.
583 * @return {@code true} if the post is considered to be new, {@code false}
586 public boolean isNewPost(String postId) {
587 synchronized (newPosts) {
588 return !knownPosts.contains(postId) && newPosts.contains(postId);
593 * Returns all posts that have the given Sone as recipient.
595 * @see Post#getRecipient()
597 * The recipient of the posts
598 * @return All posts that have the given Sone as recipient
600 public Set<Post> getDirectedPosts(Sone recipient) {
601 Validation.begin().isNotNull("Recipient", recipient).check();
602 Set<Post> directedPosts = new HashSet<Post>();
603 synchronized (posts) {
604 for (Post post : posts.values()) {
605 if (recipient.equals(post.getRecipient())) {
606 directedPosts.add(post);
610 return directedPosts;
614 * Returns the reply with the given ID. If there is no reply with the given
615 * ID yet, a new one is created.
618 * The ID of the reply to get
621 public PostReply getReply(String replyId) {
622 return getReply(replyId, true);
626 * Returns the reply with the given ID. If there is no reply with the given
627 * ID yet, a new one is created, unless {@code create} is false in which
628 * case {@code null} is returned.
631 * The ID of the reply to get
633 * {@code true} to always return a {@link Reply}, {@code false}
634 * to return {@code null} if no reply can be found
635 * @return The reply, or {@code null} if there is no such reply
637 public PostReply getReply(String replyId, boolean create) {
638 synchronized (replies) {
639 PostReply reply = replies.get(replyId);
640 if (create && (reply == null)) {
641 reply = new PostReply(replyId);
642 replies.put(replyId, reply);
649 * Returns all replies for the given post, order ascending by time.
652 * The post to get all replies for
653 * @return All replies for the given post
655 public List<PostReply> getReplies(Post post) {
656 Set<Sone> sones = getSones();
657 List<PostReply> replies = new ArrayList<PostReply>();
658 for (Sone sone : sones) {
659 for (PostReply reply : sone.getReplies()) {
660 if (reply.getPost().equals(post)) {
665 Collections.sort(replies, Reply.TIME_COMPARATOR);
670 * Returns whether the reply with the given ID is new.
673 * The ID of the reply to check
674 * @return {@code true} if the reply is considered to be new, {@code false}
677 public boolean isNewReply(String replyId) {
678 synchronized (newReplies) {
679 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
684 * Returns all Sones that have liked the given post.
687 * The post to get the liking Sones for
688 * @return The Sones that like the given post
690 public Set<Sone> getLikes(Post post) {
691 Set<Sone> sones = new HashSet<Sone>();
692 for (Sone sone : getSones()) {
693 if (sone.getLikedPostIds().contains(post.getId())) {
701 * Returns all Sones that have liked the given reply.
704 * The reply to get the liking Sones for
705 * @return The Sones that like the given reply
707 public Set<Sone> getLikes(PostReply reply) {
708 Set<Sone> sones = new HashSet<Sone>();
709 for (Sone sone : getSones()) {
710 if (sone.getLikedReplyIds().contains(reply.getId())) {
718 * Returns whether the given post is bookmarked.
722 * @return {@code true} if the given post is bookmarked, {@code false}
725 public boolean isBookmarked(Post post) {
726 return isPostBookmarked(post.getId());
730 * Returns whether the post with the given ID is bookmarked.
733 * The ID of the post to check
734 * @return {@code true} if the post with the given ID is bookmarked,
735 * {@code false} otherwise
737 public boolean isPostBookmarked(String id) {
738 synchronized (bookmarkedPosts) {
739 return bookmarkedPosts.contains(id);
744 * Returns all currently known bookmarked posts.
746 * @return All bookmarked posts
748 public Set<Post> getBookmarkedPosts() {
749 Set<Post> posts = new HashSet<Post>();
750 synchronized (bookmarkedPosts) {
751 for (String bookmarkedPostId : bookmarkedPosts) {
752 Post post = getPost(bookmarkedPostId, false);
762 * Returns the album with the given ID, creating a new album if no album
763 * with the given ID can be found.
766 * The ID of the album
767 * @return The album with the given ID
769 public Album getAlbum(String albumId) {
770 return getAlbum(albumId, true);
774 * Returns the album with the given ID, optionally creating a new album if
775 * an album with the given ID can not be found.
778 * The ID of the album
780 * {@code true} to create a new album if none exists for the
782 * @return The album with the given ID, or {@code null} if no album with the
783 * given ID exists and {@code create} is {@code false}
785 public Album getAlbum(String albumId, boolean create) {
786 synchronized (albums) {
787 Album album = albums.get(albumId);
788 if (create && (album == null)) {
789 album = new Album(albumId);
790 albums.put(albumId, album);
797 * Returns the image with the given ID, creating it if necessary.
800 * The ID of the image
801 * @return The image with the given ID
803 public Image getImage(String imageId) {
804 return getImage(imageId, true);
808 * Returns the image with the given ID, optionally creating it if it does
812 * The ID of the image
814 * {@code true} to create an image if none exists with the given
816 * @return The image with the given ID, or {@code null} if none exists and
819 public Image getImage(String imageId, boolean create) {
820 synchronized (images) {
821 Image image = images.get(imageId);
822 if (create && (image == null)) {
823 image = new Image(imageId);
824 images.put(imageId, image);
831 * Returns the temporary image with the given ID.
834 * The ID of the temporary image
835 * @return The temporary image, or {@code null} if there is no temporary
836 * image with the given ID
838 public TemporaryImage getTemporaryImage(String imageId) {
839 synchronized (temporaryImages) {
840 return temporaryImages.get(imageId);
849 * Locks the given Sone. A locked Sone will not be inserted by
850 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
856 public void lockSone(Sone sone) {
857 synchronized (lockedSones) {
858 if (lockedSones.add(sone)) {
859 coreListenerManager.fireSoneLocked(sone);
865 * Unlocks the given Sone.
867 * @see #lockSone(Sone)
871 public void unlockSone(Sone sone) {
872 synchronized (lockedSones) {
873 if (lockedSones.remove(sone)) {
874 coreListenerManager.fireSoneUnlocked(sone);
880 * Adds a local Sone from the given own identity.
883 * The own identity to create a Sone from
884 * @return The added (or already existing) Sone
886 public Sone addLocalSone(OwnIdentity ownIdentity) {
887 if (ownIdentity == null) {
888 logger.log(Level.WARNING, "Given OwnIdentity is null!");
891 synchronized (localSones) {
894 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
895 } catch (MalformedURLException mue1) {
896 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
899 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
900 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
901 /* TODO - load posts ’n stuff */
902 localSones.put(ownIdentity.getId(), sone);
903 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
904 soneInserter.addSoneInsertListener(this);
905 soneInserters.put(sone, soneInserter);
906 sone.setStatus(SoneStatus.idle);
908 soneInserter.start();
914 * Creates a new Sone for the given own identity.
917 * The own identity to create a Sone for
918 * @return The created Sone
920 public Sone createSone(OwnIdentity ownIdentity) {
922 ownIdentity.addContext("Sone");
923 } catch (WebOfTrustException wote1) {
924 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
927 Sone sone = addLocalSone(ownIdentity);
928 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
929 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
930 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
931 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
932 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
933 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
935 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
936 touchConfiguration();
941 * Adds the Sone of the given identity.
944 * The identity whose Sone to add
945 * @return The added or already existing Sone
947 public Sone addRemoteSone(Identity identity) {
948 if (identity == null) {
949 logger.log(Level.WARNING, "Given Identity is null!");
952 synchronized (remoteSones) {
953 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
954 boolean newSone = sone.getRequestUri() == null;
955 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
956 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
958 synchronized (knownSones) {
959 newSone = !knownSones.contains(sone.getId());
961 sone.setKnown(!newSone);
963 coreListenerManager.fireNewSoneFound(sone);
964 for (Sone localSone : getLocalSones()) {
965 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
966 followSone(localSone, sone);
971 soneDownloader.addSone(sone);
972 soneDownloaders.execute(new Runnable() {
975 @SuppressWarnings("synthetic-access")
977 soneDownloader.fetchSone(sone, sone.getRequestUri());
986 * Lets the given local Sone follow the Sone with the given ID.
989 * The local Sone that should follow another Sone
991 * The ID of the Sone to follow
993 public void followSone(Sone sone, String soneId) {
994 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
995 Sone followedSone = getSone(soneId, true);
996 if (followedSone == null) {
997 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
1000 followSone(sone, getSone(soneId));
1004 * Lets the given local Sone follow the other given Sone. If the given Sone
1005 * was not followed by any local Sone before, this will mark all elements of
1006 * the followed Sone as read that have been created before the current
1010 * The local Sone that should follow the other Sone
1011 * @param followedSone
1012 * The Sone that should be followed
1014 public void followSone(Sone sone, Sone followedSone) {
1015 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
1016 sone.addFriend(followedSone.getId());
1017 synchronized (soneFollowingTimes) {
1018 if (!soneFollowingTimes.containsKey(followedSone)) {
1019 long now = System.currentTimeMillis();
1020 soneFollowingTimes.put(followedSone, now);
1021 for (Post post : followedSone.getPosts()) {
1022 if (post.getTime() < now) {
1023 markPostKnown(post);
1026 for (PostReply reply : followedSone.getReplies()) {
1027 if (reply.getTime() < now) {
1028 markReplyKnown(reply);
1033 touchConfiguration();
1037 * Lets the given local Sone unfollow the Sone with the given ID.
1040 * The local Sone that should unfollow another Sone
1042 * The ID of the Sone being unfollowed
1044 public void unfollowSone(Sone sone, String soneId) {
1045 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1046 unfollowSone(sone, getSone(soneId, false));
1050 * Lets the given local Sone unfollow the other given Sone. If the given
1051 * local Sone is the last local Sone that followed the given Sone, its
1052 * following time will be removed.
1055 * The local Sone that should unfollow another Sone
1056 * @param unfollowedSone
1057 * The Sone being unfollowed
1059 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1060 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1061 sone.removeFriend(unfollowedSone.getId());
1062 boolean unfollowedSoneStillFollowed = false;
1063 for (Sone localSone : getLocalSones()) {
1064 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1066 if (!unfollowedSoneStillFollowed) {
1067 synchronized (soneFollowingTimes) {
1068 soneFollowingTimes.remove(unfollowedSone);
1071 touchConfiguration();
1075 * Retrieves the trust relationship from the origin to the target. If the
1076 * trust relationship can not be retrieved, {@code null} is returned.
1078 * @see Identity#getTrust(OwnIdentity)
1080 * The origin of the trust tree
1082 * The target of the trust
1083 * @return The trust relationship
1085 public Trust getTrust(Sone origin, Sone target) {
1086 if (!isLocalSone(origin)) {
1087 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1090 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1094 * Sets the trust value of the given origin Sone for the target Sone.
1101 * The trust value (from {@code -100} to {@code 100})
1103 public void setTrust(Sone origin, Sone target, int trustValue) {
1104 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();
1106 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1107 } catch (WebOfTrustException wote1) {
1108 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1113 * Removes any trust assignment for the given target Sone.
1120 public void removeTrust(Sone origin, Sone target) {
1121 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1123 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1124 } catch (WebOfTrustException wote1) {
1125 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1130 * Assigns the configured positive trust value for the given target.
1137 public void trustSone(Sone origin, Sone target) {
1138 setTrust(origin, target, preferences.getPositiveTrust());
1142 * Assigns the configured negative trust value for the given target.
1149 public void distrustSone(Sone origin, Sone target) {
1150 setTrust(origin, target, preferences.getNegativeTrust());
1154 * Removes the trust assignment for the given target.
1161 public void untrustSone(Sone origin, Sone target) {
1162 removeTrust(origin, target);
1166 * Updates the stored Sone with the given Sone.
1171 public void updateSone(Sone sone) {
1172 updateSone(sone, false);
1176 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1177 * {@code true}, an older Sone than the current Sone can be given to restore
1181 * The Sone to update
1182 * @param soneRescueMode
1183 * {@code true} if the stored Sone should be updated regardless
1184 * of the age of the given Sone
1186 public void updateSone(Sone sone, boolean soneRescueMode) {
1187 if (hasSone(sone.getId())) {
1188 Sone storedSone = getSone(sone.getId());
1189 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1190 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1193 synchronized (posts) {
1194 if (!soneRescueMode) {
1195 for (Post post : storedSone.getPosts()) {
1196 posts.remove(post.getId());
1197 if (!sone.getPosts().contains(post)) {
1198 coreListenerManager.firePostRemoved(post);
1202 List<Post> storedPosts = storedSone.getPosts();
1203 synchronized (newPosts) {
1204 for (Post post : sone.getPosts()) {
1205 post.setSone(storedSone);
1206 if (!storedPosts.contains(post)) {
1207 if (post.getTime() < getSoneFollowingTime(sone)) {
1208 knownPosts.add(post.getId());
1209 } else if (!knownPosts.contains(post.getId())) {
1210 newPosts.add(post.getId());
1211 coreListenerManager.fireNewPostFound(post);
1214 posts.put(post.getId(), post);
1218 synchronized (replies) {
1219 if (!soneRescueMode) {
1220 for (PostReply reply : storedSone.getReplies()) {
1221 replies.remove(reply.getId());
1222 if (!sone.getReplies().contains(reply)) {
1223 coreListenerManager.fireReplyRemoved(reply);
1227 Set<PostReply> storedReplies = storedSone.getReplies();
1228 synchronized (newReplies) {
1229 for (PostReply reply : sone.getReplies()) {
1230 reply.setSone(storedSone);
1231 if (!storedReplies.contains(reply)) {
1232 if (reply.getTime() < getSoneFollowingTime(sone)) {
1233 knownReplies.add(reply.getId());
1234 } else if (!knownReplies.contains(reply.getId())) {
1235 newReplies.add(reply.getId());
1236 coreListenerManager.fireNewReplyFound(reply);
1239 replies.put(reply.getId(), reply);
1243 synchronized (albums) {
1244 synchronized (images) {
1245 for (Album album : storedSone.getAlbums()) {
1246 albums.remove(album.getId());
1247 for (Image image : album.getImages()) {
1248 images.remove(image.getId());
1251 for (Album album : sone.getAlbums()) {
1252 albums.put(album.getId(), album);
1253 for (Image image : album.getImages()) {
1254 images.put(image.getId(), image);
1259 synchronized (storedSone) {
1260 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1261 storedSone.setTime(sone.getTime());
1263 storedSone.setClient(sone.getClient());
1264 storedSone.setProfile(sone.getProfile());
1265 if (soneRescueMode) {
1266 for (Post post : sone.getPosts()) {
1267 storedSone.addPost(post);
1269 for (PostReply reply : sone.getReplies()) {
1270 storedSone.addReply(reply);
1272 for (String likedPostId : sone.getLikedPostIds()) {
1273 storedSone.addLikedPostId(likedPostId);
1275 for (String likedReplyId : sone.getLikedReplyIds()) {
1276 storedSone.addLikedReplyId(likedReplyId);
1278 for (Album album : sone.getAlbums()) {
1279 storedSone.addAlbum(album);
1282 storedSone.setPosts(sone.getPosts());
1283 storedSone.setReplies(sone.getReplies());
1284 storedSone.setLikePostIds(sone.getLikedPostIds());
1285 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1286 storedSone.setAlbums(sone.getAlbums());
1288 storedSone.setLatestEdition(sone.getLatestEdition());
1294 * Deletes the given Sone. This will remove the Sone from the
1295 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1296 * and remove the context from its identity.
1299 * The Sone to delete
1301 public void deleteSone(Sone sone) {
1302 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1303 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1306 synchronized (localSones) {
1307 if (!localSones.containsKey(sone.getId())) {
1308 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1311 localSones.remove(sone.getId());
1312 SoneInserter soneInserter = soneInserters.remove(sone);
1313 soneInserter.removeSoneInsertListener(this);
1314 soneInserter.stop();
1317 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1318 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1319 } catch (WebOfTrustException wote1) {
1320 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1323 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1324 } catch (ConfigurationException ce1) {
1325 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1330 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1331 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1334 * The Sone to mark as known
1336 public void markSoneKnown(Sone sone) {
1337 if (!sone.isKnown()) {
1338 sone.setKnown(true);
1339 synchronized (knownSones) {
1340 knownSones.add(sone.getId());
1342 coreListenerManager.fireMarkSoneKnown(sone);
1343 touchConfiguration();
1348 * Loads and updates the given Sone from the configuration. If any error is
1349 * encountered, loading is aborted and the given Sone is not changed.
1352 * The Sone to load and update
1354 public void loadSone(Sone sone) {
1355 if (!isLocalSone(sone)) {
1356 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1360 /* initialize options. */
1361 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1362 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1363 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1364 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1365 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1366 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1369 String sonePrefix = "Sone/" + sone.getId();
1370 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1371 if (soneTime == null) {
1372 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1375 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1378 Profile profile = new Profile(sone);
1379 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1380 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1381 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1382 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1383 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1384 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1386 /* load profile fields. */
1388 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1389 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1390 if (fieldName == null) {
1393 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1394 profile.addField(fieldName).setValue(fieldValue);
1398 Set<Post> posts = new HashSet<Post>();
1400 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1401 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1402 if (postId == null) {
1405 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1406 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1407 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1408 if ((postTime == 0) || (postText == null)) {
1409 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1412 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1413 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1414 post.setRecipient(getSone(postRecipientId));
1420 Set<PostReply> replies = new HashSet<PostReply>();
1422 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1423 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1424 if (replyId == null) {
1427 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1428 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1429 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1430 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1431 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1434 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1437 /* load post likes. */
1438 Set<String> likedPostIds = new HashSet<String>();
1440 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1441 if (likedPostId == null) {
1444 likedPostIds.add(likedPostId);
1447 /* load reply likes. */
1448 Set<String> likedReplyIds = new HashSet<String>();
1450 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1451 if (likedReplyId == null) {
1454 likedReplyIds.add(likedReplyId);
1458 Set<String> friends = new HashSet<String>();
1460 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1461 if (friendId == null) {
1464 friends.add(friendId);
1468 List<Album> topLevelAlbums = new ArrayList<Album>();
1469 int albumCounter = 0;
1471 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1472 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1473 if (albumId == null) {
1476 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1477 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1478 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1479 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1480 if ((albumTitle == null) || (albumDescription == null)) {
1481 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1484 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1485 if (albumParentId != null) {
1486 Album parentAlbum = getAlbum(albumParentId, false);
1487 if (parentAlbum == null) {
1488 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1491 parentAlbum.addAlbum(album);
1493 topLevelAlbums.add(album);
1498 int imageCounter = 0;
1500 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1501 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1502 if (imageId == null) {
1505 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1506 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1507 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1508 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1509 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1510 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1511 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1512 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1513 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1516 Album album = getAlbum(albumId, false);
1517 if (album == null) {
1518 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1521 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1522 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1523 album.addImage(image);
1527 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1528 if (avatarId != null) {
1529 profile.setAvatar(getImage(avatarId, false));
1533 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1534 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1535 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1536 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1537 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1538 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1540 /* if we’re still here, Sone was loaded successfully. */
1541 synchronized (sone) {
1542 sone.setTime(soneTime);
1543 sone.setProfile(profile);
1544 sone.setPosts(posts);
1545 sone.setReplies(replies);
1546 sone.setLikePostIds(likedPostIds);
1547 sone.setLikeReplyIds(likedReplyIds);
1548 for (String friendId : friends) {
1549 followSone(sone, friendId);
1551 sone.setAlbums(topLevelAlbums);
1552 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1554 synchronized (knownSones) {
1555 for (String friend : friends) {
1556 knownSones.add(friend);
1559 synchronized (newPosts) {
1560 for (Post post : posts) {
1561 knownPosts.add(post.getId());
1564 synchronized (newReplies) {
1565 for (PostReply reply : replies) {
1566 knownReplies.add(reply.getId());
1572 * Creates a new post.
1575 * The Sone that creates the post
1577 * The text of the post
1578 * @return The created post
1580 public Post createPost(Sone sone, String text) {
1581 return createPost(sone, System.currentTimeMillis(), text);
1585 * Creates a new post.
1588 * The Sone that creates the post
1590 * The time of the post
1592 * The text of the post
1593 * @return The created post
1595 public Post createPost(Sone sone, long time, String text) {
1596 return createPost(sone, null, time, text);
1600 * Creates a new post.
1603 * The Sone that creates the post
1605 * The recipient Sone, or {@code null} if this post does not have
1608 * The text of the post
1609 * @return The created post
1611 public Post createPost(Sone sone, Sone recipient, String text) {
1612 return createPost(sone, recipient, System.currentTimeMillis(), text);
1616 * Creates a new post.
1619 * The Sone that creates the post
1621 * The recipient Sone, or {@code null} if this post does not have
1624 * The time of the post
1626 * The text of the post
1627 * @return The created post
1629 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1630 if (!isLocalSone(sone)) {
1631 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1634 final Post post = new Post(sone, time, text);
1635 if (recipient != null) {
1636 post.setRecipient(recipient);
1638 synchronized (posts) {
1639 posts.put(post.getId(), post);
1641 synchronized (newPosts) {
1642 newPosts.add(post.getId());
1643 coreListenerManager.fireNewPostFound(post);
1646 touchConfiguration();
1647 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1654 markPostKnown(post);
1656 }, "Mark " + post + " read.");
1661 * Deletes the given post.
1664 * The post to delete
1666 public void deletePost(Post post) {
1667 if (!isLocalSone(post.getSone())) {
1668 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1671 post.getSone().removePost(post);
1672 synchronized (posts) {
1673 posts.remove(post.getId());
1675 coreListenerManager.firePostRemoved(post);
1676 synchronized (newPosts) {
1677 markPostKnown(post);
1678 knownPosts.remove(post.getId());
1680 touchConfiguration();
1684 * Marks the given post as known, if it is currently a new post (according
1685 * to {@link #isNewPost(String)}).
1688 * The post to mark as known
1690 public void markPostKnown(Post post) {
1691 synchronized (newPosts) {
1692 newPosts.remove(post.getId());
1693 if (knownPosts.add(post.getId())) {
1694 coreListenerManager.fireMarkPostKnown(post);
1695 touchConfiguration();
1701 * Bookmarks the given post.
1704 * The post to bookmark
1706 public void bookmark(Post post) {
1707 bookmarkPost(post.getId());
1711 * Bookmarks the post with the given ID.
1714 * The ID of the post to bookmark
1716 public void bookmarkPost(String id) {
1717 synchronized (bookmarkedPosts) {
1718 bookmarkedPosts.add(id);
1723 * Removes the given post from the bookmarks.
1726 * The post to unbookmark
1728 public void unbookmark(Post post) {
1729 unbookmarkPost(post.getId());
1733 * Removes the post with the given ID from the bookmarks.
1736 * The ID of the post to unbookmark
1738 public void unbookmarkPost(String id) {
1739 synchronized (bookmarkedPosts) {
1740 bookmarkedPosts.remove(id);
1745 * Creates a new reply.
1748 * The Sone that creates the reply
1750 * The post that this reply refers to
1752 * The text of the reply
1753 * @return The created reply
1755 public PostReply createReply(Sone sone, Post post, String text) {
1756 return createReply(sone, post, System.currentTimeMillis(), text);
1760 * Creates a new reply.
1763 * The Sone that creates the reply
1765 * The post that this reply refers to
1767 * The time of the reply
1769 * The text of the reply
1770 * @return The created reply
1772 public PostReply createReply(Sone sone, Post post, long time, String text) {
1773 if (!isLocalSone(sone)) {
1774 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1777 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1778 synchronized (replies) {
1779 replies.put(reply.getId(), reply);
1781 synchronized (newReplies) {
1782 newReplies.add(reply.getId());
1783 coreListenerManager.fireNewReplyFound(reply);
1785 sone.addReply(reply);
1786 touchConfiguration();
1787 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1794 markReplyKnown(reply);
1796 }, "Mark " + reply + " read.");
1801 * Deletes the given reply.
1804 * The reply to delete
1806 public void deleteReply(PostReply reply) {
1807 Sone sone = reply.getSone();
1808 if (!isLocalSone(sone)) {
1809 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1812 synchronized (replies) {
1813 replies.remove(reply.getId());
1815 synchronized (newReplies) {
1816 markReplyKnown(reply);
1817 knownReplies.remove(reply.getId());
1819 sone.removeReply(reply);
1820 touchConfiguration();
1824 * Marks the given reply as known, if it is currently a new reply (according
1825 * to {@link #isNewReply(String)}).
1828 * The reply to mark as known
1830 public void markReplyKnown(PostReply reply) {
1831 synchronized (newReplies) {
1832 newReplies.remove(reply.getId());
1833 if (knownReplies.add(reply.getId())) {
1834 coreListenerManager.fireMarkReplyKnown(reply);
1835 touchConfiguration();
1841 * Creates a new top-level album for the given Sone.
1844 * The Sone to create the album for
1845 * @return The new album
1847 public Album createAlbum(Sone sone) {
1848 return createAlbum(sone, null);
1852 * Creates a new album for the given Sone.
1855 * The Sone to create the album for
1857 * The parent of the album (may be {@code null} to create a
1859 * @return The new album
1861 public Album createAlbum(Sone sone, Album parent) {
1862 Album album = new Album();
1863 synchronized (albums) {
1864 albums.put(album.getId(), album);
1866 album.setSone(sone);
1867 if (parent != null) {
1868 parent.addAlbum(album);
1870 sone.addAlbum(album);
1876 * Deletes the given album. The owner of the album has to be a local Sone,
1877 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1880 * The album to remove
1882 public void deleteAlbum(Album album) {
1883 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1884 if (!album.isEmpty()) {
1887 if (album.getParent() == null) {
1888 album.getSone().removeAlbum(album);
1890 album.getParent().removeAlbum(album);
1892 synchronized (albums) {
1893 albums.remove(album.getId());
1895 saveSone(album.getSone());
1899 * Creates a new image.
1902 * The Sone creating the image
1904 * The album the image will be inserted into
1905 * @param temporaryImage
1906 * The temporary image to create the image from
1907 * @return The newly created image
1909 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1910 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();
1911 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1912 album.addImage(image);
1913 synchronized (images) {
1914 images.put(image.getId(), image);
1916 imageInserter.insertImage(temporaryImage, image);
1921 * Deletes the given image. This method will also delete a matching
1924 * @see #deleteTemporaryImage(TemporaryImage)
1926 * The image to delete
1928 public void deleteImage(Image image) {
1929 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1930 deleteTemporaryImage(image.getId());
1931 image.getAlbum().removeImage(image);
1932 synchronized (images) {
1933 images.remove(image.getId());
1935 saveSone(image.getSone());
1939 * Creates a new temporary image.
1942 * The MIME type of the temporary image
1944 * The encoded data of the image
1945 * @return The temporary image
1947 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1948 TemporaryImage temporaryImage = new TemporaryImage();
1949 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1950 synchronized (temporaryImages) {
1951 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1953 return temporaryImage;
1957 * Deletes the given temporary image.
1959 * @param temporaryImage
1960 * The temporary image to delete
1962 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1963 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1964 deleteTemporaryImage(temporaryImage.getId());
1968 * Deletes the temporary image with the given ID.
1971 * The ID of the temporary image to delete
1973 public void deleteTemporaryImage(String imageId) {
1974 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1975 synchronized (temporaryImages) {
1976 temporaryImages.remove(imageId);
1978 Image image = getImage(imageId, false);
1979 if (image != null) {
1980 imageInserter.cancelImageInsert(image);
1985 * Notifies the core that the configuration, either of the core or of a
1986 * single local Sone, has changed, and that the configuration should be
1989 public void touchConfiguration() {
1990 lastConfigurationUpdate = System.currentTimeMillis();
2001 public void serviceStart() {
2002 loadConfiguration();
2003 updateChecker.addUpdateListener(this);
2004 updateChecker.start();
2011 public void serviceRun() {
2012 long lastSaved = System.currentTimeMillis();
2013 while (!shouldStop()) {
2015 long now = System.currentTimeMillis();
2016 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
2017 for (Sone localSone : getLocalSones()) {
2018 saveSone(localSone);
2020 saveConfiguration();
2030 public void serviceStop() {
2031 synchronized (localSones) {
2032 for (SoneInserter soneInserter : soneInserters.values()) {
2033 soneInserter.removeSoneInsertListener(this);
2034 soneInserter.stop();
2037 updateChecker.stop();
2038 updateChecker.removeUpdateListener(this);
2039 soneDownloader.stop();
2047 * Saves the given Sone. This will persist all local settings for the given
2048 * Sone, such as the friends list and similar, private options.
2053 private synchronized void saveSone(Sone sone) {
2054 if (!isLocalSone(sone)) {
2055 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2058 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2059 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2063 logger.log(Level.INFO, "Saving Sone: %s", sone);
2065 /* save Sone into configuration. */
2066 String sonePrefix = "Sone/" + sone.getId();
2067 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2068 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2071 Profile profile = sone.getProfile();
2072 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2073 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2074 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2075 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2076 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2077 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2078 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2080 /* save profile fields. */
2081 int fieldCounter = 0;
2082 for (Field profileField : profile.getFields()) {
2083 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2084 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2085 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2087 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2090 int postCounter = 0;
2091 for (Post post : sone.getPosts()) {
2092 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2093 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2094 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2095 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2096 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2098 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2101 int replyCounter = 0;
2102 for (PostReply reply : sone.getReplies()) {
2103 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2104 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2105 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2106 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2107 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2109 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2111 /* save post likes. */
2112 int postLikeCounter = 0;
2113 for (String postId : sone.getLikedPostIds()) {
2114 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2116 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2118 /* save reply likes. */
2119 int replyLikeCounter = 0;
2120 for (String replyId : sone.getLikedReplyIds()) {
2121 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2123 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2126 int friendCounter = 0;
2127 for (String friendId : sone.getFriends()) {
2128 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2130 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2132 /* save albums. first, collect in a flat structure, top-level first. */
2133 List<Album> albums = sone.getAllAlbums();
2135 int albumCounter = 0;
2136 for (Album album : albums) {
2137 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2138 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2139 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2140 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2141 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2142 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2144 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2147 int imageCounter = 0;
2148 for (Album album : albums) {
2149 for (Image image : album.getImages()) {
2150 if (!image.isInserted()) {
2153 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2154 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2155 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2156 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2157 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2158 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2159 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2160 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2161 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2164 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2167 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2168 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2169 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2170 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2171 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2172 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2174 configuration.save();
2176 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2178 logger.log(Level.INFO, "Sone %s saved.", sone);
2179 } catch (ConfigurationException ce1) {
2180 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2181 } catch (WebOfTrustException wote1) {
2182 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2187 * Saves the current options.
2189 private void saveConfiguration() {
2190 synchronized (configuration) {
2191 if (storingConfiguration) {
2192 logger.log(Level.FINE, "Already storing configuration…");
2195 storingConfiguration = true;
2198 /* store the options first. */
2200 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2201 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2202 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2203 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2204 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2205 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2206 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2207 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2208 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2209 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2210 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2211 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2212 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2213 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2215 /* save known Sones. */
2216 int soneCounter = 0;
2217 synchronized (knownSones) {
2218 for (String knownSoneId : knownSones) {
2219 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2221 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2224 /* save Sone following times. */
2226 synchronized (soneFollowingTimes) {
2227 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2228 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2229 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2232 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2235 /* save known posts. */
2236 int postCounter = 0;
2237 synchronized (newPosts) {
2238 for (String knownPostId : knownPosts) {
2239 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2241 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2244 /* save known replies. */
2245 int replyCounter = 0;
2246 synchronized (newReplies) {
2247 for (String knownReplyId : knownReplies) {
2248 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2250 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2253 /* save bookmarked posts. */
2254 int bookmarkedPostCounter = 0;
2255 synchronized (bookmarkedPosts) {
2256 for (String bookmarkedPostId : bookmarkedPosts) {
2257 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2260 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2263 configuration.save();
2265 } catch (ConfigurationException ce1) {
2266 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2268 synchronized (configuration) {
2269 storingConfiguration = false;
2275 * Loads the configuration.
2277 @SuppressWarnings("unchecked")
2278 private void loadConfiguration() {
2279 /* create options. */
2280 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2283 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2284 SoneInserter.setInsertionDelay(newValue);
2288 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2289 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2290 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2291 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2292 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2293 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2294 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2295 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2298 @SuppressWarnings("synthetic-access")
2299 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2300 fcpInterface.setActive(newValue);
2303 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2306 @SuppressWarnings("synthetic-access")
2307 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2308 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2312 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2313 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2314 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2316 /* read options from configuration. */
2317 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2318 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2319 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2320 options.getBooleanOption("ClearOnNextRestart").set(null);
2321 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2322 if (clearConfiguration) {
2323 /* stop loading the configuration. */
2327 loadConfigurationValue("InsertionDelay");
2328 loadConfigurationValue("PostsPerPage");
2329 loadConfigurationValue("CharactersPerPost");
2330 loadConfigurationValue("PostCutOffLength");
2331 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2332 loadConfigurationValue("PositiveTrust");
2333 loadConfigurationValue("NegativeTrust");
2334 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2335 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2336 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2337 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2339 /* load known Sones. */
2340 int soneCounter = 0;
2342 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2343 if (knownSoneId == null) {
2346 synchronized (knownSones) {
2347 knownSones.add(knownSoneId);
2351 /* load Sone following times. */
2354 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2355 if (soneId == null) {
2358 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2359 Sone followedSone = getSone(soneId);
2360 if (followedSone == null) {
2361 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2363 synchronized (soneFollowingTimes) {
2364 soneFollowingTimes.put(getSone(soneId), time);
2370 /* load known posts. */
2371 int postCounter = 0;
2373 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2374 if (knownPostId == null) {
2377 synchronized (newPosts) {
2378 knownPosts.add(knownPostId);
2382 /* load known replies. */
2383 int replyCounter = 0;
2385 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2386 if (knownReplyId == null) {
2389 synchronized (newReplies) {
2390 knownReplies.add(knownReplyId);
2394 /* load bookmarked posts. */
2395 int bookmarkedPostCounter = 0;
2397 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2398 if (bookmarkedPostId == null) {
2401 synchronized (bookmarkedPosts) {
2402 bookmarkedPosts.add(bookmarkedPostId);
2409 * Loads an {@link Integer} configuration value for the option with the
2410 * given name, logging validation failures.
2413 * The name of the option to load
2415 private void loadConfigurationValue(String optionName) {
2417 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2418 } catch (IllegalArgumentException iae1) {
2419 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2424 * Generate a Sone URI from the given URI and latest edition.
2427 * The URI to derive the Sone URI from
2428 * @return The derived URI
2430 private FreenetURI getSoneUri(String uriString) {
2432 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2434 } catch (MalformedURLException mue1) {
2435 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2441 // INTERFACE IdentityListener
2448 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2449 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2450 if (ownIdentity.hasContext("Sone")) {
2451 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2452 addLocalSone(ownIdentity);
2460 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2461 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2462 trustedIdentities.remove(ownIdentity);
2469 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2470 logger.log(Level.FINEST, "Adding Identity: " + identity);
2471 trustedIdentities.get(ownIdentity).add(identity);
2472 addRemoteSone(identity);
2479 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2480 new Thread(new Runnable() {
2483 @SuppressWarnings("synthetic-access")
2485 Sone sone = getRemoteSone(identity.getId(), false);
2486 sone.setIdentity(identity);
2487 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2488 soneDownloader.addSone(sone);
2489 soneDownloader.fetchSone(sone);
2498 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2499 trustedIdentities.get(ownIdentity).remove(identity);
2500 boolean foundIdentity = false;
2501 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2502 if (trustedIdentity.getKey().equals(ownIdentity)) {
2505 if (trustedIdentity.getValue().contains(identity)) {
2506 foundIdentity = true;
2509 if (foundIdentity) {
2510 /* some local identity still trusts this identity, don’t remove. */
2513 Sone sone = getSone(identity.getId(), false);
2515 /* TODO - we don’t have the Sone anymore. should this happen? */
2518 synchronized (posts) {
2519 synchronized (newPosts) {
2520 for (Post post : sone.getPosts()) {
2521 posts.remove(post.getId());
2522 newPosts.remove(post.getId());
2523 coreListenerManager.firePostRemoved(post);
2527 synchronized (replies) {
2528 synchronized (newReplies) {
2529 for (PostReply reply : sone.getReplies()) {
2530 replies.remove(reply.getId());
2531 newReplies.remove(reply.getId());
2532 coreListenerManager.fireReplyRemoved(reply);
2536 synchronized (remoteSones) {
2537 remoteSones.remove(identity.getId());
2539 coreListenerManager.fireSoneRemoved(sone);
2543 // INTERFACE UpdateListener
2550 public void updateFound(Version version, long releaseTime, long latestEdition) {
2551 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2555 // INTERFACE ImageInsertListener
2562 public void insertStarted(Sone sone) {
2563 coreListenerManager.fireSoneInserting(sone);
2570 public void insertFinished(Sone sone, long insertDuration) {
2571 coreListenerManager.fireSoneInserted(sone, insertDuration);
2578 public void insertAborted(Sone sone, Throwable cause) {
2579 coreListenerManager.fireSoneInsertAborted(sone, cause);
2583 // SONEINSERTLISTENER METHODS
2590 public void imageInsertStarted(Image image) {
2591 logger.log(Level.WARNING, "Image insert started for " + image);
2592 coreListenerManager.fireImageInsertStarted(image);
2599 public void imageInsertAborted(Image image) {
2600 logger.log(Level.WARNING, "Image insert aborted for " + image);
2601 coreListenerManager.fireImageInsertAborted(image);
2608 public void imageInsertFinished(Image image, FreenetURI key) {
2609 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2610 image.setKey(key.toString());
2611 deleteTemporaryImage(image.getId());
2612 saveSone(image.getSone());
2613 coreListenerManager.fireImageInsertFinished(image);
2620 public void imageInsertFailed(Image image, Throwable cause) {
2621 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2622 coreListenerManager.fireImageInsertFailed(image, cause);
2626 * Convenience interface for external classes that want to access the core’s
2629 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2631 public static class Preferences {
2633 /** The wrapped options. */
2634 private final Options options;
2637 * Creates a new preferences object wrapped around the given options.
2640 * The options to wrap
2642 public Preferences(Options options) {
2643 this.options = options;
2647 * Returns the insertion delay.
2649 * @return The insertion delay
2651 public int getInsertionDelay() {
2652 return options.getIntegerOption("InsertionDelay").get();
2656 * Validates the given insertion delay.
2658 * @param insertionDelay
2659 * The insertion delay to validate
2660 * @return {@code true} if the given insertion delay was valid, {@code
2663 public boolean validateInsertionDelay(Integer insertionDelay) {
2664 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2668 * Sets the insertion delay
2670 * @param insertionDelay
2671 * The new insertion delay, or {@code null} to restore it to
2673 * @return This preferences
2675 public Preferences setInsertionDelay(Integer insertionDelay) {
2676 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2681 * Returns the number of posts to show per page.
2683 * @return The number of posts to show per page
2685 public int getPostsPerPage() {
2686 return options.getIntegerOption("PostsPerPage").get();
2690 * Validates the number of posts per page.
2692 * @param postsPerPage
2693 * The number of posts per page
2694 * @return {@code true} if the number of posts per page was valid,
2695 * {@code false} otherwise
2697 public boolean validatePostsPerPage(Integer postsPerPage) {
2698 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2702 * Sets the number of posts to show per page.
2704 * @param postsPerPage
2705 * The number of posts to show per page
2706 * @return This preferences object
2708 public Preferences setPostsPerPage(Integer postsPerPage) {
2709 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2714 * Returns the number of characters per post, or <code>-1</code> if the
2715 * posts should not be cut off.
2717 * @return The numbers of characters per post
2719 public int getCharactersPerPost() {
2720 return options.getIntegerOption("CharactersPerPost").get();
2724 * Validates the number of characters per post.
2726 * @param charactersPerPost
2727 * The number of characters per post
2728 * @return {@code true} if the number of characters per post was valid,
2729 * {@code false} otherwise
2731 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2732 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2736 * Sets the number of characters per post.
2738 * @param charactersPerPost
2739 * The number of characters per post, or <code>-1</code> to
2740 * not cut off the posts
2741 * @return This preferences objects
2743 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2744 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2749 * Returns the number of characters the shortened post should have.
2751 * @return The number of characters of the snippet
2753 public int getPostCutOffLength() {
2754 return options.getIntegerOption("PostCutOffLength").get();
2758 * Validates the number of characters after which to cut off the post.
2760 * @param postCutOffLength
2761 * The number of characters of the snippet
2762 * @return {@code true} if the number of characters of the snippet is
2763 * valid, {@code false} otherwise
2765 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2766 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2770 * Sets the number of characters the shortened post should have.
2772 * @param postCutOffLength
2773 * The number of characters of the snippet
2774 * @return This preferences
2776 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2777 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2782 * Returns whether Sone requires full access to be even visible.
2784 * @return {@code true} if Sone requires full access, {@code false}
2787 public boolean isRequireFullAccess() {
2788 return options.getBooleanOption("RequireFullAccess").get();
2792 * Sets whether Sone requires full access to be even visible.
2794 * @param requireFullAccess
2795 * {@code true} if Sone requires full access, {@code false}
2798 public void setRequireFullAccess(Boolean requireFullAccess) {
2799 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2803 * Returns the positive trust.
2805 * @return The positive trust
2807 public int getPositiveTrust() {
2808 return options.getIntegerOption("PositiveTrust").get();
2812 * Validates the positive trust.
2814 * @param positiveTrust
2815 * The positive trust to validate
2816 * @return {@code true} if the positive trust was valid, {@code false}
2819 public boolean validatePositiveTrust(Integer positiveTrust) {
2820 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2824 * Sets the positive trust.
2826 * @param positiveTrust
2827 * The new positive trust, or {@code null} to restore it to
2829 * @return This preferences
2831 public Preferences setPositiveTrust(Integer positiveTrust) {
2832 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2837 * Returns the negative trust.
2839 * @return The negative trust
2841 public int getNegativeTrust() {
2842 return options.getIntegerOption("NegativeTrust").get();
2846 * Validates the negative trust.
2848 * @param negativeTrust
2849 * The negative trust to validate
2850 * @return {@code true} if the negative trust was valid, {@code false}
2853 public boolean validateNegativeTrust(Integer negativeTrust) {
2854 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2858 * Sets the negative trust.
2860 * @param negativeTrust
2861 * The negative trust, or {@code null} to restore it to the
2863 * @return The preferences
2865 public Preferences setNegativeTrust(Integer negativeTrust) {
2866 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2871 * Returns the trust comment. This is the comment that is set in the web
2872 * of trust when a trust value is assigned to an identity.
2874 * @return The trust comment
2876 public String getTrustComment() {
2877 return options.getStringOption("TrustComment").get();
2881 * Sets the trust comment.
2883 * @param trustComment
2884 * The trust comment, or {@code null} to restore it to the
2886 * @return This preferences
2888 public Preferences setTrustComment(String trustComment) {
2889 options.getStringOption("TrustComment").set(trustComment);
2894 * Returns whether the {@link FcpInterface FCP interface} is currently
2897 * @see FcpInterface#setActive(boolean)
2898 * @return {@code true} if the FCP interface is currently active,
2899 * {@code false} otherwise
2901 public boolean isFcpInterfaceActive() {
2902 return options.getBooleanOption("ActivateFcpInterface").get();
2906 * Sets whether the {@link FcpInterface FCP interface} is currently
2909 * @see FcpInterface#setActive(boolean)
2910 * @param fcpInterfaceActive
2911 * {@code true} to activate the FCP interface, {@code false}
2912 * to deactivate the FCP interface
2913 * @return This preferences object
2915 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2916 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2921 * Returns the action level for which full access to the FCP interface
2924 * @return The action level for which full access to the FCP interface
2927 public FullAccessRequired getFcpFullAccessRequired() {
2928 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2932 * Sets the action level for which full access to the FCP interface is
2935 * @param fcpFullAccessRequired
2937 * @return This preferences
2939 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2940 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2945 * Returns whether Sone should clear its settings on the next restart.
2946 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2947 * to return {@code true} as well!
2949 * @return {@code true} if Sone should clear its settings on the next
2950 * restart, {@code false} otherwise
2952 public boolean isClearOnNextRestart() {
2953 return options.getBooleanOption("ClearOnNextRestart").get();
2957 * Sets whether Sone will clear its settings on the next restart.
2959 * @param clearOnNextRestart
2960 * {@code true} if Sone should clear its settings on the next
2961 * restart, {@code false} otherwise
2962 * @return This preferences
2964 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2965 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2970 * Returns whether Sone should really clear its settings on next
2971 * restart. This is a confirmation option that needs to be set in
2972 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2973 * settings on the next restart.
2975 * @return {@code true} if Sone should really clear its settings on the
2976 * next restart, {@code false} otherwise
2978 public boolean isReallyClearOnNextRestart() {
2979 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2983 * Sets whether Sone should really clear its settings on the next
2986 * @param reallyClearOnNextRestart
2987 * {@code true} if Sone should really clear its settings on
2988 * the next restart, {@code false} otherwise
2989 * @return This preferences
2991 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2992 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);