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 new Sones. */
141 private Set<String> newSones = new HashSet<String>();
143 /** All known Sones. */
144 /* synchronize access on {@link #newSones}. */
145 private Set<String> knownSones = new HashSet<String>();
148 private Map<String, Post> posts = new HashMap<String, Post>();
150 /** All new posts. */
151 private Set<String> newPosts = new HashSet<String>();
153 /** All known posts. */
154 /* synchronize access on {@link #newPosts}. */
155 private Set<String> knownPosts = new HashSet<String>();
158 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
160 /** All new replies. */
161 private Set<String> newReplies = new HashSet<String>();
163 /** All known replies. */
164 private Set<String> knownReplies = new HashSet<String>();
166 /** All bookmarked posts. */
167 /* synchronize access on itself. */
168 private Set<String> bookmarkedPosts = new HashSet<String>();
170 /** Trusted identities, sorted by own identities. */
171 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
173 /** All known albums. */
174 private Map<String, Album> albums = new HashMap<String, Album>();
176 /** All known images. */
177 private Map<String, Image> images = new HashMap<String, Image>();
179 /** All temporary images. */
180 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
182 /** Ticker for threads that mark own elements as known. */
183 private Ticker localElementTicker = new Ticker();
185 /** The time the configuration was last touched. */
186 private volatile long lastConfigurationUpdate;
189 * Creates a new core.
191 * @param configuration
192 * The configuration of the core
193 * @param freenetInterface
194 * The freenet interface
195 * @param identityManager
196 * The identity manager
198 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
200 this.configuration = configuration;
201 this.freenetInterface = freenetInterface;
202 this.identityManager = identityManager;
203 this.soneDownloader = new SoneDownloader(this, freenetInterface);
204 this.imageInserter = new ImageInserter(this, freenetInterface);
205 this.updateChecker = new UpdateChecker(freenetInterface);
209 // LISTENER MANAGEMENT
213 * Adds a new core listener.
215 * @param coreListener
216 * The listener to add
218 public void addCoreListener(CoreListener coreListener) {
219 coreListenerManager.addListener(coreListener);
223 * Removes a core listener.
225 * @param coreListener
226 * The listener to remove
228 public void removeCoreListener(CoreListener coreListener) {
229 coreListenerManager.removeListener(coreListener);
237 * Sets the configuration to use. This will automatically save the current
238 * configuration to the given configuration.
240 * @param configuration
241 * The new configuration to use
243 public void setConfiguration(Configuration configuration) {
244 this.configuration = configuration;
245 touchConfiguration();
249 * Returns the options used by the core.
251 * @return The options of the core
253 public Preferences getPreferences() {
258 * Returns the identity manager used by the core.
260 * @return The identity manager
262 public IdentityManager getIdentityManager() {
263 return identityManager;
267 * Returns the update checker.
269 * @return The update checker
271 public UpdateChecker getUpdateChecker() {
272 return updateChecker;
276 * Sets the FCP interface to use.
278 * @param fcpInterface
279 * The FCP interface to use
281 public void setFcpInterface(FcpInterface fcpInterface) {
282 this.fcpInterface = fcpInterface;
286 * Returns the Sone rescuer for the given local Sone.
289 * The local Sone to get the rescuer for
290 * @return The Sone rescuer for the given Sone
292 public SoneRescuer getSoneRescuer(Sone sone) {
293 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
294 synchronized (localSones) {
295 SoneRescuer soneRescuer = soneRescuers.get(sone);
296 if (soneRescuer == null) {
297 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
298 soneRescuers.put(sone, soneRescuer);
306 * Returns whether the given Sone is currently locked.
310 * @return {@code true} if the Sone is locked, {@code false} if it is not
312 public boolean isLocked(Sone sone) {
313 synchronized (lockedSones) {
314 return lockedSones.contains(sone);
319 * Returns all Sones, remote and local.
323 public Set<Sone> getSones() {
324 Set<Sone> allSones = new HashSet<Sone>();
325 allSones.addAll(getLocalSones());
326 allSones.addAll(getRemoteSones());
331 * Returns the Sone with the given ID, regardless whether it’s local or
335 * The ID of the Sone to get
336 * @return The Sone with the given ID, or {@code null} if there is no such
339 public Sone getSone(String id) {
340 return getSone(id, true);
344 * Returns the Sone with the given ID, regardless whether it’s local or
348 * The ID of the Sone to get
350 * {@code true} to create a new Sone if none exists,
351 * {@code false} to return {@code null} if a Sone with the given
353 * @return The Sone with the given ID, or {@code null} if there is no such
357 public Sone getSone(String id, boolean create) {
358 if (isLocalSone(id)) {
359 return getLocalSone(id);
361 return getRemoteSone(id, create);
365 * Checks whether the core knows a Sone with the given ID.
369 * @return {@code true} if there is a Sone with the given ID, {@code false}
372 public boolean hasSone(String id) {
373 return isLocalSone(id) || isRemoteSone(id);
377 * Returns whether the given Sone is a local Sone.
380 * The Sone to check for its locality
381 * @return {@code true} if the given Sone is local, {@code false} otherwise
383 public boolean isLocalSone(Sone sone) {
384 synchronized (localSones) {
385 return localSones.containsKey(sone.getId());
390 * Returns whether the given ID is the ID of a local Sone.
393 * The Sone ID to check for its locality
394 * @return {@code true} if the given ID is a local Sone, {@code false}
397 public boolean isLocalSone(String id) {
398 synchronized (localSones) {
399 return localSones.containsKey(id);
404 * Returns all local Sones.
406 * @return All local Sones
408 public Set<Sone> getLocalSones() {
409 synchronized (localSones) {
410 return new HashSet<Sone>(localSones.values());
415 * Returns the local Sone with the given ID.
418 * The ID of the Sone to get
419 * @return The Sone with the given ID
421 public Sone getLocalSone(String id) {
422 return getLocalSone(id, true);
426 * Returns the local Sone with the given ID, optionally creating a new Sone.
431 * {@code true} to create a new Sone if none exists,
432 * {@code false} to return null if none exists
433 * @return The Sone with the given ID, or {@code null}
435 public Sone getLocalSone(String id, boolean create) {
436 synchronized (localSones) {
437 Sone sone = localSones.get(id);
438 if ((sone == null) && create) {
440 localSones.put(id, sone);
447 * Returns all remote Sones.
449 * @return All remote Sones
451 public Set<Sone> getRemoteSones() {
452 synchronized (remoteSones) {
453 return new HashSet<Sone>(remoteSones.values());
458 * Returns the remote Sone with the given ID.
461 * The ID of the remote Sone to get
463 * {@code true} to always create a Sone, {@code false} to return
464 * {@code null} if no Sone with the given ID exists
465 * @return The Sone with the given ID
467 public Sone getRemoteSone(String id, boolean create) {
468 synchronized (remoteSones) {
469 Sone sone = remoteSones.get(id);
470 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
472 remoteSones.put(id, sone);
479 * Returns whether the given Sone is a remote Sone.
483 * @return {@code true} if the given Sone is a remote Sone, {@code false}
486 public boolean isRemoteSone(Sone sone) {
487 synchronized (remoteSones) {
488 return remoteSones.containsKey(sone.getId());
493 * Returns whether the Sone with the given ID is a remote Sone.
496 * The ID of the Sone to check
497 * @return {@code true} if the Sone with the given ID is a remote Sone,
498 * {@code false} otherwise
500 public boolean isRemoteSone(String id) {
501 synchronized (remoteSones) {
502 return remoteSones.containsKey(id);
507 * Returns whether the Sone with the given ID is a new Sone.
510 * The ID of the sone to check for
511 * @return {@code true} if the given Sone is new, false otherwise
513 public boolean isNewSone(String soneId) {
514 synchronized (newSones) {
515 return !knownSones.contains(soneId) && newSones.contains(soneId);
520 * Returns whether the given Sone has been modified.
523 * The Sone to check for modifications
524 * @return {@code true} if a modification has been detected in the Sone,
525 * {@code false} otherwise
527 public boolean isModifiedSone(Sone sone) {
528 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
532 * Returns the time when the given was first followed by any local Sone.
535 * The Sone to get the time for
536 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
537 * been followed, or {@link Long#MAX_VALUE}
539 public long getSoneFollowingTime(Sone sone) {
540 synchronized (soneFollowingTimes) {
541 if (soneFollowingTimes.containsKey(sone)) {
542 return soneFollowingTimes.get(sone);
544 return Long.MAX_VALUE;
549 * Returns whether the target Sone is trusted by the origin Sone.
555 * @return {@code true} if the target Sone is trusted by the origin Sone
557 public boolean isSoneTrusted(Sone origin, Sone target) {
558 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
559 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
563 * Returns the post with the given ID.
566 * The ID of the post to get
567 * @return The post with the given ID, or a new post with the given ID
569 public Post getPost(String postId) {
570 return getPost(postId, true);
574 * Returns the post with the given ID, optionally creating a new post.
577 * The ID of the post to get
579 * {@code true} it create a new post if no post with the given ID
580 * exists, {@code false} to return {@code null}
581 * @return The post, or {@code null} if there is no such post
584 public Post getPost(String postId, boolean create) {
585 synchronized (posts) {
586 Post post = posts.get(postId);
587 if ((post == null) && create) {
588 post = new Post(postId);
589 posts.put(postId, post);
596 * Returns whether the given post ID is new.
600 * @return {@code true} if the post is considered to be new, {@code false}
603 public boolean isNewPost(String postId) {
604 synchronized (newPosts) {
605 return !knownPosts.contains(postId) && newPosts.contains(postId);
610 * Returns all posts that have the given Sone as recipient.
612 * @see Post#getRecipient()
614 * The recipient of the posts
615 * @return All posts that have the given Sone as recipient
617 public Set<Post> getDirectedPosts(Sone recipient) {
618 Validation.begin().isNotNull("Recipient", recipient).check();
619 Set<Post> directedPosts = new HashSet<Post>();
620 synchronized (posts) {
621 for (Post post : posts.values()) {
622 if (recipient.equals(post.getRecipient())) {
623 directedPosts.add(post);
627 return directedPosts;
631 * Returns the reply with the given ID. If there is no reply with the given
632 * ID yet, a new one is created.
635 * The ID of the reply to get
638 public PostReply getReply(String replyId) {
639 return getReply(replyId, true);
643 * Returns the reply with the given ID. If there is no reply with the given
644 * ID yet, a new one is created, unless {@code create} is false in which
645 * case {@code null} is returned.
648 * The ID of the reply to get
650 * {@code true} to always return a {@link Reply}, {@code false}
651 * to return {@code null} if no reply can be found
652 * @return The reply, or {@code null} if there is no such reply
654 public PostReply getReply(String replyId, boolean create) {
655 synchronized (replies) {
656 PostReply reply = replies.get(replyId);
657 if (create && (reply == null)) {
658 reply = new PostReply(replyId);
659 replies.put(replyId, reply);
666 * Returns all replies for the given post, order ascending by time.
669 * The post to get all replies for
670 * @return All replies for the given post
672 public List<PostReply> getReplies(Post post) {
673 Set<Sone> sones = getSones();
674 List<PostReply> replies = new ArrayList<PostReply>();
675 for (Sone sone : sones) {
676 for (PostReply reply : sone.getReplies()) {
677 if (reply.getPost().equals(post)) {
682 Collections.sort(replies, Reply.TIME_COMPARATOR);
687 * Returns whether the reply with the given ID is new.
690 * The ID of the reply to check
691 * @return {@code true} if the reply is considered to be new, {@code false}
694 public boolean isNewReply(String replyId) {
695 synchronized (newReplies) {
696 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
701 * Returns all Sones that have liked the given post.
704 * The post to get the liking Sones for
705 * @return The Sones that like the given post
707 public Set<Sone> getLikes(Post post) {
708 Set<Sone> sones = new HashSet<Sone>();
709 for (Sone sone : getSones()) {
710 if (sone.getLikedPostIds().contains(post.getId())) {
718 * Returns all Sones that have liked the given reply.
721 * The reply to get the liking Sones for
722 * @return The Sones that like the given reply
724 public Set<Sone> getLikes(PostReply reply) {
725 Set<Sone> sones = new HashSet<Sone>();
726 for (Sone sone : getSones()) {
727 if (sone.getLikedReplyIds().contains(reply.getId())) {
735 * Returns whether the given post is bookmarked.
739 * @return {@code true} if the given post is bookmarked, {@code false}
742 public boolean isBookmarked(Post post) {
743 return isPostBookmarked(post.getId());
747 * Returns whether the post with the given ID is bookmarked.
750 * The ID of the post to check
751 * @return {@code true} if the post with the given ID is bookmarked,
752 * {@code false} otherwise
754 public boolean isPostBookmarked(String id) {
755 synchronized (bookmarkedPosts) {
756 return bookmarkedPosts.contains(id);
761 * Returns all currently known bookmarked posts.
763 * @return All bookmarked posts
765 public Set<Post> getBookmarkedPosts() {
766 Set<Post> posts = new HashSet<Post>();
767 synchronized (bookmarkedPosts) {
768 for (String bookmarkedPostId : bookmarkedPosts) {
769 Post post = getPost(bookmarkedPostId, false);
779 * Returns the album with the given ID, creating a new album if no album
780 * with the given ID can be found.
783 * The ID of the album
784 * @return The album with the given ID
786 public Album getAlbum(String albumId) {
787 return getAlbum(albumId, true);
791 * Returns the album with the given ID, optionally creating a new album if
792 * an album with the given ID can not be found.
795 * The ID of the album
797 * {@code true} to create a new album if none exists for the
799 * @return The album with the given ID, or {@code null} if no album with the
800 * given ID exists and {@code create} is {@code false}
802 public Album getAlbum(String albumId, boolean create) {
803 synchronized (albums) {
804 Album album = albums.get(albumId);
805 if (create && (album == null)) {
806 album = new Album(albumId);
807 albums.put(albumId, album);
814 * Returns the image with the given ID, creating it if necessary.
817 * The ID of the image
818 * @return The image with the given ID
820 public Image getImage(String imageId) {
821 return getImage(imageId, true);
825 * Returns the image with the given ID, optionally creating it if it does
829 * The ID of the image
831 * {@code true} to create an image if none exists with the given
833 * @return The image with the given ID, or {@code null} if none exists and
836 public Image getImage(String imageId, boolean create) {
837 synchronized (images) {
838 Image image = images.get(imageId);
839 if (create && (image == null)) {
840 image = new Image(imageId);
841 images.put(imageId, image);
848 * Returns the temporary image with the given ID.
851 * The ID of the temporary image
852 * @return The temporary image, or {@code null} if there is no temporary
853 * image with the given ID
855 public TemporaryImage getTemporaryImage(String imageId) {
856 synchronized (temporaryImages) {
857 return temporaryImages.get(imageId);
866 * Locks the given Sone. A locked Sone will not be inserted by
867 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
873 public void lockSone(Sone sone) {
874 synchronized (lockedSones) {
875 if (lockedSones.add(sone)) {
876 coreListenerManager.fireSoneLocked(sone);
882 * Unlocks the given Sone.
884 * @see #lockSone(Sone)
888 public void unlockSone(Sone sone) {
889 synchronized (lockedSones) {
890 if (lockedSones.remove(sone)) {
891 coreListenerManager.fireSoneUnlocked(sone);
897 * Adds a local Sone from the given own identity.
900 * The own identity to create a Sone from
901 * @return The added (or already existing) Sone
903 public Sone addLocalSone(OwnIdentity ownIdentity) {
904 if (ownIdentity == null) {
905 logger.log(Level.WARNING, "Given OwnIdentity is null!");
908 synchronized (localSones) {
911 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
912 } catch (MalformedURLException mue1) {
913 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
916 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
917 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
918 /* TODO - load posts ’n stuff */
919 localSones.put(ownIdentity.getId(), sone);
920 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
921 soneInserter.addSoneInsertListener(this);
922 soneInserters.put(sone, soneInserter);
923 sone.setStatus(SoneStatus.idle);
925 soneInserter.start();
931 * Creates a new Sone for the given own identity.
934 * The own identity to create a Sone for
935 * @return The created Sone
937 public Sone createSone(OwnIdentity ownIdentity) {
939 ownIdentity.addContext("Sone");
940 } catch (WebOfTrustException wote1) {
941 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
944 Sone sone = addLocalSone(ownIdentity);
945 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
946 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
947 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
948 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
949 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
950 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
952 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
953 touchConfiguration();
958 * Adds the Sone of the given identity.
961 * The identity whose Sone to add
962 * @return The added or already existing Sone
964 public Sone addRemoteSone(Identity identity) {
965 if (identity == null) {
966 logger.log(Level.WARNING, "Given Identity is null!");
969 synchronized (remoteSones) {
970 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
971 boolean newSone = sone.getRequestUri() == null;
972 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
973 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
975 synchronized (newSones) {
976 newSone = !knownSones.contains(sone.getId());
978 newSones.add(sone.getId());
982 coreListenerManager.fireNewSoneFound(sone);
983 for (Sone localSone : getLocalSones()) {
984 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
985 followSone(localSone, sone);
990 soneDownloader.addSone(sone);
991 soneDownloaders.execute(new Runnable() {
994 @SuppressWarnings("synthetic-access")
996 soneDownloader.fetchSone(sone, sone.getRequestUri());
1005 * Lets the given local Sone follow the Sone with the given ID.
1008 * The local Sone that should follow another Sone
1010 * The ID of the Sone to follow
1012 public void followSone(Sone sone, String soneId) {
1013 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1014 Sone followedSone = getSone(soneId, true);
1015 if (followedSone == null) {
1016 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
1019 followSone(sone, getSone(soneId));
1023 * Lets the given local Sone follow the other given Sone. If the given Sone
1024 * was not followed by any local Sone before, this will mark all elements of
1025 * the followed Sone as read that have been created before the current
1029 * The local Sone that should follow the other Sone
1030 * @param followedSone
1031 * The Sone that should be followed
1033 public void followSone(Sone sone, Sone followedSone) {
1034 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
1035 sone.addFriend(followedSone.getId());
1036 synchronized (soneFollowingTimes) {
1037 if (!soneFollowingTimes.containsKey(followedSone)) {
1038 long now = System.currentTimeMillis();
1039 soneFollowingTimes.put(followedSone, now);
1040 for (Post post : followedSone.getPosts()) {
1041 if (post.getTime() < now) {
1042 markPostKnown(post);
1045 for (PostReply reply : followedSone.getReplies()) {
1046 if (reply.getTime() < now) {
1047 markReplyKnown(reply);
1052 touchConfiguration();
1056 * Lets the given local Sone unfollow the Sone with the given ID.
1059 * The local Sone that should unfollow another Sone
1061 * The ID of the Sone being unfollowed
1063 public void unfollowSone(Sone sone, String soneId) {
1064 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1065 unfollowSone(sone, getSone(soneId, false));
1069 * Lets the given local Sone unfollow the other given Sone. If the given
1070 * local Sone is the last local Sone that followed the given Sone, its
1071 * following time will be removed.
1074 * The local Sone that should unfollow another Sone
1075 * @param unfollowedSone
1076 * The Sone being unfollowed
1078 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1079 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1080 sone.removeFriend(unfollowedSone.getId());
1081 boolean unfollowedSoneStillFollowed = false;
1082 for (Sone localSone : getLocalSones()) {
1083 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1085 if (!unfollowedSoneStillFollowed) {
1086 synchronized (soneFollowingTimes) {
1087 soneFollowingTimes.remove(unfollowedSone);
1090 touchConfiguration();
1094 * Retrieves the trust relationship from the origin to the target. If the
1095 * trust relationship can not be retrieved, {@code null} is returned.
1097 * @see Identity#getTrust(OwnIdentity)
1099 * The origin of the trust tree
1101 * The target of the trust
1102 * @return The trust relationship
1104 public Trust getTrust(Sone origin, Sone target) {
1105 if (!isLocalSone(origin)) {
1106 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1109 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1113 * Sets the trust value of the given origin Sone for the target Sone.
1120 * The trust value (from {@code -100} to {@code 100})
1122 public void setTrust(Sone origin, Sone target, int trustValue) {
1123 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();
1125 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1126 } catch (WebOfTrustException wote1) {
1127 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1132 * Removes any trust assignment for the given target Sone.
1139 public void removeTrust(Sone origin, Sone target) {
1140 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1142 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1143 } catch (WebOfTrustException wote1) {
1144 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1149 * Assigns the configured positive trust value for the given target.
1156 public void trustSone(Sone origin, Sone target) {
1157 setTrust(origin, target, preferences.getPositiveTrust());
1161 * Assigns the configured negative trust value for the given target.
1168 public void distrustSone(Sone origin, Sone target) {
1169 setTrust(origin, target, preferences.getNegativeTrust());
1173 * Removes the trust assignment for the given target.
1180 public void untrustSone(Sone origin, Sone target) {
1181 removeTrust(origin, target);
1185 * Updates the stored Sone with the given Sone.
1190 public void updateSone(Sone sone) {
1191 updateSone(sone, false);
1195 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1196 * {@code true}, an older Sone than the current Sone can be given to restore
1200 * The Sone to update
1201 * @param soneRescueMode
1202 * {@code true} if the stored Sone should be updated regardless
1203 * of the age of the given Sone
1205 public void updateSone(Sone sone, boolean soneRescueMode) {
1206 if (hasSone(sone.getId())) {
1207 Sone storedSone = getSone(sone.getId());
1208 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1209 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1212 synchronized (posts) {
1213 if (!soneRescueMode) {
1214 for (Post post : storedSone.getPosts()) {
1215 posts.remove(post.getId());
1216 if (!sone.getPosts().contains(post)) {
1217 coreListenerManager.firePostRemoved(post);
1221 List<Post> storedPosts = storedSone.getPosts();
1222 synchronized (newPosts) {
1223 for (Post post : sone.getPosts()) {
1224 post.setSone(storedSone);
1225 if (!storedPosts.contains(post)) {
1226 if (post.getTime() < getSoneFollowingTime(sone)) {
1227 knownPosts.add(post.getId());
1228 } else if (!knownPosts.contains(post.getId())) {
1229 newPosts.add(post.getId());
1230 coreListenerManager.fireNewPostFound(post);
1233 posts.put(post.getId(), post);
1237 synchronized (replies) {
1238 if (!soneRescueMode) {
1239 for (PostReply reply : storedSone.getReplies()) {
1240 replies.remove(reply.getId());
1241 if (!sone.getReplies().contains(reply)) {
1242 coreListenerManager.fireReplyRemoved(reply);
1246 Set<PostReply> storedReplies = storedSone.getReplies();
1247 synchronized (newReplies) {
1248 for (PostReply reply : sone.getReplies()) {
1249 reply.setSone(storedSone);
1250 if (!storedReplies.contains(reply)) {
1251 if (reply.getTime() < getSoneFollowingTime(sone)) {
1252 knownReplies.add(reply.getId());
1253 } else if (!knownReplies.contains(reply.getId())) {
1254 newReplies.add(reply.getId());
1255 coreListenerManager.fireNewReplyFound(reply);
1258 replies.put(reply.getId(), reply);
1262 synchronized (albums) {
1263 synchronized (images) {
1264 for (Album album : storedSone.getAlbums()) {
1265 albums.remove(album.getId());
1266 for (Image image : album.getImages()) {
1267 images.remove(image.getId());
1270 for (Album album : sone.getAlbums()) {
1271 albums.put(album.getId(), album);
1272 for (Image image : album.getImages()) {
1273 images.put(image.getId(), image);
1278 synchronized (storedSone) {
1279 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1280 storedSone.setTime(sone.getTime());
1282 storedSone.setClient(sone.getClient());
1283 storedSone.setProfile(sone.getProfile());
1284 if (soneRescueMode) {
1285 for (Post post : sone.getPosts()) {
1286 storedSone.addPost(post);
1288 for (PostReply reply : sone.getReplies()) {
1289 storedSone.addReply(reply);
1291 for (String likedPostId : sone.getLikedPostIds()) {
1292 storedSone.addLikedPostId(likedPostId);
1294 for (String likedReplyId : sone.getLikedReplyIds()) {
1295 storedSone.addLikedReplyId(likedReplyId);
1297 for (Album album : sone.getAlbums()) {
1298 storedSone.addAlbum(album);
1301 storedSone.setPosts(sone.getPosts());
1302 storedSone.setReplies(sone.getReplies());
1303 storedSone.setLikePostIds(sone.getLikedPostIds());
1304 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1305 storedSone.setAlbums(sone.getAlbums());
1307 storedSone.setLatestEdition(sone.getLatestEdition());
1313 * Deletes the given Sone. This will remove the Sone from the
1314 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1315 * and remove the context from its identity.
1318 * The Sone to delete
1320 public void deleteSone(Sone sone) {
1321 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1322 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1325 synchronized (localSones) {
1326 if (!localSones.containsKey(sone.getId())) {
1327 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1330 localSones.remove(sone.getId());
1331 SoneInserter soneInserter = soneInserters.remove(sone);
1332 soneInserter.removeSoneInsertListener(this);
1333 soneInserter.stop();
1336 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1337 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1338 } catch (WebOfTrustException wote1) {
1339 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1342 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1343 } catch (ConfigurationException ce1) {
1344 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1349 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1350 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1353 * The Sone to mark as known
1355 public void markSoneKnown(Sone sone) {
1356 synchronized (newSones) {
1357 if (newSones.remove(sone.getId())) {
1358 knownSones.add(sone.getId());
1359 coreListenerManager.fireMarkSoneKnown(sone);
1360 touchConfiguration();
1366 * Loads and updates the given Sone from the configuration. If any error is
1367 * encountered, loading is aborted and the given Sone is not changed.
1370 * The Sone to load and update
1372 public void loadSone(Sone sone) {
1373 if (!isLocalSone(sone)) {
1374 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1378 /* initialize options. */
1379 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1380 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1381 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1382 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1383 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1384 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1387 String sonePrefix = "Sone/" + sone.getId();
1388 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1389 if (soneTime == null) {
1390 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1393 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1396 Profile profile = new Profile(sone);
1397 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1398 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1399 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1400 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1401 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1402 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1404 /* load profile fields. */
1406 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1407 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1408 if (fieldName == null) {
1411 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1412 profile.addField(fieldName).setValue(fieldValue);
1416 Set<Post> posts = new HashSet<Post>();
1418 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1419 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1420 if (postId == null) {
1423 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1424 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1425 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1426 if ((postTime == 0) || (postText == null)) {
1427 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1430 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1431 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1432 post.setRecipient(getSone(postRecipientId));
1438 Set<PostReply> replies = new HashSet<PostReply>();
1440 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1441 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1442 if (replyId == null) {
1445 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1446 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1447 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1448 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1449 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1452 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1455 /* load post likes. */
1456 Set<String> likedPostIds = new HashSet<String>();
1458 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1459 if (likedPostId == null) {
1462 likedPostIds.add(likedPostId);
1465 /* load reply likes. */
1466 Set<String> likedReplyIds = new HashSet<String>();
1468 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1469 if (likedReplyId == null) {
1472 likedReplyIds.add(likedReplyId);
1476 Set<String> friends = new HashSet<String>();
1478 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1479 if (friendId == null) {
1482 friends.add(friendId);
1486 List<Album> topLevelAlbums = new ArrayList<Album>();
1487 int albumCounter = 0;
1489 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1490 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1491 if (albumId == null) {
1494 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1495 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1496 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1497 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1498 if ((albumTitle == null) || (albumDescription == null)) {
1499 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1502 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1503 if (albumParentId != null) {
1504 Album parentAlbum = getAlbum(albumParentId, false);
1505 if (parentAlbum == null) {
1506 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1509 parentAlbum.addAlbum(album);
1511 topLevelAlbums.add(album);
1516 int imageCounter = 0;
1518 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1519 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1520 if (imageId == null) {
1523 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1524 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1525 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1526 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1527 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1528 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1529 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1530 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1531 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1534 Album album = getAlbum(albumId, false);
1535 if (album == null) {
1536 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1539 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1540 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1541 album.addImage(image);
1545 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1546 if (avatarId != null) {
1547 profile.setAvatar(getImage(avatarId, false));
1551 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1552 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1553 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1554 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1555 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1556 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1558 /* if we’re still here, Sone was loaded successfully. */
1559 synchronized (sone) {
1560 sone.setTime(soneTime);
1561 sone.setProfile(profile);
1562 sone.setPosts(posts);
1563 sone.setReplies(replies);
1564 sone.setLikePostIds(likedPostIds);
1565 sone.setLikeReplyIds(likedReplyIds);
1566 for (String friendId : friends) {
1567 followSone(sone, friendId);
1569 sone.setAlbums(topLevelAlbums);
1570 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1572 synchronized (newSones) {
1573 for (String friend : friends) {
1574 knownSones.add(friend);
1577 synchronized (newPosts) {
1578 for (Post post : posts) {
1579 knownPosts.add(post.getId());
1582 synchronized (newReplies) {
1583 for (PostReply reply : replies) {
1584 knownReplies.add(reply.getId());
1590 * Creates a new post.
1593 * The Sone that creates the post
1595 * The text of the post
1596 * @return The created post
1598 public Post createPost(Sone sone, String text) {
1599 return createPost(sone, System.currentTimeMillis(), text);
1603 * Creates a new post.
1606 * The Sone that creates the post
1608 * The time of the post
1610 * The text of the post
1611 * @return The created post
1613 public Post createPost(Sone sone, long time, String text) {
1614 return createPost(sone, null, time, text);
1618 * Creates a new post.
1621 * The Sone that creates the post
1623 * The recipient Sone, or {@code null} if this post does not have
1626 * The text of the post
1627 * @return The created post
1629 public Post createPost(Sone sone, Sone recipient, String text) {
1630 return createPost(sone, recipient, System.currentTimeMillis(), text);
1634 * Creates a new post.
1637 * The Sone that creates the post
1639 * The recipient Sone, or {@code null} if this post does not have
1642 * The time of the post
1644 * The text of the post
1645 * @return The created post
1647 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1648 if (!isLocalSone(sone)) {
1649 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1652 final Post post = new Post(sone, time, text);
1653 if (recipient != null) {
1654 post.setRecipient(recipient);
1656 synchronized (posts) {
1657 posts.put(post.getId(), post);
1659 synchronized (newPosts) {
1660 newPosts.add(post.getId());
1661 coreListenerManager.fireNewPostFound(post);
1664 touchConfiguration();
1665 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1672 markPostKnown(post);
1674 }, "Mark " + post + " read.");
1679 * Deletes the given post.
1682 * The post to delete
1684 public void deletePost(Post post) {
1685 if (!isLocalSone(post.getSone())) {
1686 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1689 post.getSone().removePost(post);
1690 synchronized (posts) {
1691 posts.remove(post.getId());
1693 coreListenerManager.firePostRemoved(post);
1694 synchronized (newPosts) {
1695 markPostKnown(post);
1696 knownPosts.remove(post.getId());
1698 touchConfiguration();
1702 * Marks the given post as known, if it is currently a new post (according
1703 * to {@link #isNewPost(String)}).
1706 * The post to mark as known
1708 public void markPostKnown(Post post) {
1709 synchronized (newPosts) {
1710 if (newPosts.remove(post.getId())) {
1711 knownPosts.add(post.getId());
1712 coreListenerManager.fireMarkPostKnown(post);
1713 touchConfiguration();
1719 * Bookmarks the given post.
1722 * The post to bookmark
1724 public void bookmark(Post post) {
1725 bookmarkPost(post.getId());
1729 * Bookmarks the post with the given ID.
1732 * The ID of the post to bookmark
1734 public void bookmarkPost(String id) {
1735 synchronized (bookmarkedPosts) {
1736 bookmarkedPosts.add(id);
1741 * Removes the given post from the bookmarks.
1744 * The post to unbookmark
1746 public void unbookmark(Post post) {
1747 unbookmarkPost(post.getId());
1751 * Removes the post with the given ID from the bookmarks.
1754 * The ID of the post to unbookmark
1756 public void unbookmarkPost(String id) {
1757 synchronized (bookmarkedPosts) {
1758 bookmarkedPosts.remove(id);
1763 * Creates a new reply.
1766 * The Sone that creates the reply
1768 * The post that this reply refers to
1770 * The text of the reply
1771 * @return The created reply
1773 public PostReply createReply(Sone sone, Post post, String text) {
1774 return createReply(sone, post, System.currentTimeMillis(), text);
1778 * Creates a new reply.
1781 * The Sone that creates the reply
1783 * The post that this reply refers to
1785 * The time of the reply
1787 * The text of the reply
1788 * @return The created reply
1790 public PostReply createReply(Sone sone, Post post, long time, String text) {
1791 if (!isLocalSone(sone)) {
1792 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1795 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1796 synchronized (replies) {
1797 replies.put(reply.getId(), reply);
1799 synchronized (newReplies) {
1800 newReplies.add(reply.getId());
1801 coreListenerManager.fireNewReplyFound(reply);
1803 sone.addReply(reply);
1804 touchConfiguration();
1805 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1812 markReplyKnown(reply);
1814 }, "Mark " + reply + " read.");
1819 * Deletes the given reply.
1822 * The reply to delete
1824 public void deleteReply(PostReply reply) {
1825 Sone sone = reply.getSone();
1826 if (!isLocalSone(sone)) {
1827 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1830 synchronized (replies) {
1831 replies.remove(reply.getId());
1833 synchronized (newReplies) {
1834 markReplyKnown(reply);
1835 knownReplies.remove(reply.getId());
1837 sone.removeReply(reply);
1838 touchConfiguration();
1842 * Marks the given reply as known, if it is currently a new reply (according
1843 * to {@link #isNewReply(String)}).
1846 * The reply to mark as known
1848 public void markReplyKnown(PostReply reply) {
1849 synchronized (newReplies) {
1850 if (newReplies.remove(reply.getId())) {
1851 knownReplies.add(reply.getId());
1852 coreListenerManager.fireMarkReplyKnown(reply);
1853 touchConfiguration();
1859 * Creates a new top-level album for the given Sone.
1862 * The Sone to create the album for
1863 * @return The new album
1865 public Album createAlbum(Sone sone) {
1866 return createAlbum(sone, null);
1870 * Creates a new album for the given Sone.
1873 * The Sone to create the album for
1875 * The parent of the album (may be {@code null} to create a
1877 * @return The new album
1879 public Album createAlbum(Sone sone, Album parent) {
1880 Album album = new Album();
1881 synchronized (albums) {
1882 albums.put(album.getId(), album);
1884 album.setSone(sone);
1885 if (parent != null) {
1886 parent.addAlbum(album);
1888 sone.addAlbum(album);
1894 * Deletes the given album. The owner of the album has to be a local Sone,
1895 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1898 * The album to remove
1900 public void deleteAlbum(Album album) {
1901 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1902 if (!album.isEmpty()) {
1905 if (album.getParent() == null) {
1906 album.getSone().removeAlbum(album);
1908 album.getParent().removeAlbum(album);
1910 synchronized (albums) {
1911 albums.remove(album.getId());
1913 saveSone(album.getSone());
1917 * Creates a new image.
1920 * The Sone creating the image
1922 * The album the image will be inserted into
1923 * @param temporaryImage
1924 * The temporary image to create the image from
1925 * @return The newly created image
1927 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1928 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();
1929 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1930 album.addImage(image);
1931 synchronized (images) {
1932 images.put(image.getId(), image);
1934 imageInserter.insertImage(temporaryImage, image);
1939 * Deletes the given image. This method will also delete a matching
1942 * @see #deleteTemporaryImage(TemporaryImage)
1944 * The image to delete
1946 public void deleteImage(Image image) {
1947 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1948 deleteTemporaryImage(image.getId());
1949 image.getAlbum().removeImage(image);
1950 synchronized (images) {
1951 images.remove(image.getId());
1953 saveSone(image.getSone());
1957 * Creates a new temporary image.
1960 * The MIME type of the temporary image
1962 * The encoded data of the image
1963 * @return The temporary image
1965 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1966 TemporaryImage temporaryImage = new TemporaryImage();
1967 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1968 synchronized (temporaryImages) {
1969 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1971 return temporaryImage;
1975 * Deletes the given temporary image.
1977 * @param temporaryImage
1978 * The temporary image to delete
1980 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1981 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1982 deleteTemporaryImage(temporaryImage.getId());
1986 * Deletes the temporary image with the given ID.
1989 * The ID of the temporary image to delete
1991 public void deleteTemporaryImage(String imageId) {
1992 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1993 synchronized (temporaryImages) {
1994 temporaryImages.remove(imageId);
1996 Image image = getImage(imageId, false);
1997 if (image != null) {
1998 imageInserter.cancelImageInsert(image);
2003 * Notifies the core that the configuration, either of the core or of a
2004 * single local Sone, has changed, and that the configuration should be
2007 public void touchConfiguration() {
2008 lastConfigurationUpdate = System.currentTimeMillis();
2019 public void serviceStart() {
2020 loadConfiguration();
2021 updateChecker.addUpdateListener(this);
2022 updateChecker.start();
2029 public void serviceRun() {
2030 long lastSaved = System.currentTimeMillis();
2031 while (!shouldStop()) {
2033 long now = System.currentTimeMillis();
2034 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
2035 for (Sone localSone : getLocalSones()) {
2036 saveSone(localSone);
2038 saveConfiguration();
2048 public void serviceStop() {
2049 synchronized (localSones) {
2050 for (SoneInserter soneInserter : soneInserters.values()) {
2051 soneInserter.removeSoneInsertListener(this);
2052 soneInserter.stop();
2055 updateChecker.stop();
2056 updateChecker.removeUpdateListener(this);
2057 soneDownloader.stop();
2065 * Saves the given Sone. This will persist all local settings for the given
2066 * Sone, such as the friends list and similar, private options.
2071 private synchronized void saveSone(Sone sone) {
2072 if (!isLocalSone(sone)) {
2073 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2076 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2077 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2081 logger.log(Level.INFO, "Saving Sone: %s", sone);
2083 /* save Sone into configuration. */
2084 String sonePrefix = "Sone/" + sone.getId();
2085 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2086 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2089 Profile profile = sone.getProfile();
2090 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2091 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2092 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2093 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2094 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2095 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2096 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2098 /* save profile fields. */
2099 int fieldCounter = 0;
2100 for (Field profileField : profile.getFields()) {
2101 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2102 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2103 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2105 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2108 int postCounter = 0;
2109 for (Post post : sone.getPosts()) {
2110 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2111 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2112 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2113 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2114 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2116 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2119 int replyCounter = 0;
2120 for (PostReply reply : sone.getReplies()) {
2121 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2122 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2123 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2124 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2125 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2127 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2129 /* save post likes. */
2130 int postLikeCounter = 0;
2131 for (String postId : sone.getLikedPostIds()) {
2132 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2134 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2136 /* save reply likes. */
2137 int replyLikeCounter = 0;
2138 for (String replyId : sone.getLikedReplyIds()) {
2139 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2141 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2144 int friendCounter = 0;
2145 for (String friendId : sone.getFriends()) {
2146 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2148 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2150 /* save albums. first, collect in a flat structure, top-level first. */
2151 List<Album> albums = sone.getAllAlbums();
2153 int albumCounter = 0;
2154 for (Album album : albums) {
2155 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2156 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2157 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2158 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2159 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2160 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2162 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2165 int imageCounter = 0;
2166 for (Album album : albums) {
2167 for (Image image : album.getImages()) {
2168 if (!image.isInserted()) {
2171 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2172 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2173 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2174 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2175 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2176 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2177 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2178 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2179 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2182 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2185 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2186 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2187 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2188 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2189 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2190 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2192 configuration.save();
2194 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2196 logger.log(Level.INFO, "Sone %s saved.", sone);
2197 } catch (ConfigurationException ce1) {
2198 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2199 } catch (WebOfTrustException wote1) {
2200 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2205 * Saves the current options.
2207 private void saveConfiguration() {
2208 synchronized (configuration) {
2209 if (storingConfiguration) {
2210 logger.log(Level.FINE, "Already storing configuration…");
2213 storingConfiguration = true;
2216 /* store the options first. */
2218 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2219 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2220 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2221 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2222 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2223 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2224 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2225 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2226 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2227 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2228 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2229 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2230 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2231 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2233 /* save known Sones. */
2234 int soneCounter = 0;
2235 synchronized (newSones) {
2236 for (String knownSoneId : knownSones) {
2237 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2239 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2242 /* save Sone following times. */
2244 synchronized (soneFollowingTimes) {
2245 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2246 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2247 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2250 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2253 /* save known posts. */
2254 int postCounter = 0;
2255 synchronized (newPosts) {
2256 for (String knownPostId : knownPosts) {
2257 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2259 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2262 /* save known replies. */
2263 int replyCounter = 0;
2264 synchronized (newReplies) {
2265 for (String knownReplyId : knownReplies) {
2266 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2268 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2271 /* save bookmarked posts. */
2272 int bookmarkedPostCounter = 0;
2273 synchronized (bookmarkedPosts) {
2274 for (String bookmarkedPostId : bookmarkedPosts) {
2275 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2278 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2281 configuration.save();
2283 } catch (ConfigurationException ce1) {
2284 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2286 synchronized (configuration) {
2287 storingConfiguration = false;
2293 * Loads the configuration.
2295 @SuppressWarnings("unchecked")
2296 private void loadConfiguration() {
2297 /* create options. */
2298 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2301 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2302 SoneInserter.setInsertionDelay(newValue);
2306 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2307 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2308 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2309 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2310 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2311 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2312 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2313 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2316 @SuppressWarnings("synthetic-access")
2317 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2318 fcpInterface.setActive(newValue);
2321 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2324 @SuppressWarnings("synthetic-access")
2325 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2326 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2330 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2331 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2332 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2334 /* read options from configuration. */
2335 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2336 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2337 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2338 options.getBooleanOption("ClearOnNextRestart").set(null);
2339 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2340 if (clearConfiguration) {
2341 /* stop loading the configuration. */
2345 loadConfigurationValue("InsertionDelay");
2346 loadConfigurationValue("PostsPerPage");
2347 loadConfigurationValue("CharactersPerPost");
2348 loadConfigurationValue("PostCutOffLength");
2349 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2350 loadConfigurationValue("PositiveTrust");
2351 loadConfigurationValue("NegativeTrust");
2352 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2353 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2354 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2355 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2357 /* load known Sones. */
2358 int soneCounter = 0;
2360 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2361 if (knownSoneId == null) {
2364 synchronized (newSones) {
2365 knownSones.add(knownSoneId);
2369 /* load Sone following times. */
2372 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2373 if (soneId == null) {
2376 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2377 Sone followedSone = getSone(soneId);
2378 if (followedSone == null) {
2379 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2381 synchronized (soneFollowingTimes) {
2382 soneFollowingTimes.put(getSone(soneId), time);
2388 /* load known posts. */
2389 int postCounter = 0;
2391 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2392 if (knownPostId == null) {
2395 synchronized (newPosts) {
2396 knownPosts.add(knownPostId);
2400 /* load known replies. */
2401 int replyCounter = 0;
2403 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2404 if (knownReplyId == null) {
2407 synchronized (newReplies) {
2408 knownReplies.add(knownReplyId);
2412 /* load bookmarked posts. */
2413 int bookmarkedPostCounter = 0;
2415 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2416 if (bookmarkedPostId == null) {
2419 synchronized (bookmarkedPosts) {
2420 bookmarkedPosts.add(bookmarkedPostId);
2427 * Loads an {@link Integer} configuration value for the option with the
2428 * given name, logging validation failures.
2431 * The name of the option to load
2433 private void loadConfigurationValue(String optionName) {
2435 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2436 } catch (IllegalArgumentException iae1) {
2437 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2442 * Generate a Sone URI from the given URI and latest edition.
2445 * The URI to derive the Sone URI from
2446 * @return The derived URI
2448 private FreenetURI getSoneUri(String uriString) {
2450 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2452 } catch (MalformedURLException mue1) {
2453 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2459 // INTERFACE IdentityListener
2466 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2467 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2468 if (ownIdentity.hasContext("Sone")) {
2469 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2470 addLocalSone(ownIdentity);
2478 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2479 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2480 trustedIdentities.remove(ownIdentity);
2487 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2488 logger.log(Level.FINEST, "Adding Identity: " + identity);
2489 trustedIdentities.get(ownIdentity).add(identity);
2490 addRemoteSone(identity);
2497 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2498 new Thread(new Runnable() {
2501 @SuppressWarnings("synthetic-access")
2503 Sone sone = getRemoteSone(identity.getId(), false);
2504 sone.setIdentity(identity);
2505 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2506 soneDownloader.addSone(sone);
2507 soneDownloader.fetchSone(sone);
2516 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2517 trustedIdentities.get(ownIdentity).remove(identity);
2518 boolean foundIdentity = false;
2519 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2520 if (trustedIdentity.getKey().equals(ownIdentity)) {
2523 if (trustedIdentity.getValue().contains(identity)) {
2524 foundIdentity = true;
2527 if (foundIdentity) {
2528 /* some local identity still trusts this identity, don’t remove. */
2531 Sone sone = getSone(identity.getId(), false);
2533 /* TODO - we don’t have the Sone anymore. should this happen? */
2536 synchronized (posts) {
2537 synchronized (newPosts) {
2538 for (Post post : sone.getPosts()) {
2539 posts.remove(post.getId());
2540 newPosts.remove(post.getId());
2541 coreListenerManager.firePostRemoved(post);
2545 synchronized (replies) {
2546 synchronized (newReplies) {
2547 for (PostReply reply : sone.getReplies()) {
2548 replies.remove(reply.getId());
2549 newReplies.remove(reply.getId());
2550 coreListenerManager.fireReplyRemoved(reply);
2554 synchronized (remoteSones) {
2555 remoteSones.remove(identity.getId());
2557 synchronized (newSones) {
2558 newSones.remove(identity.getId());
2559 coreListenerManager.fireSoneRemoved(sone);
2564 // INTERFACE UpdateListener
2571 public void updateFound(Version version, long releaseTime, long latestEdition) {
2572 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2576 // INTERFACE ImageInsertListener
2583 public void insertStarted(Sone sone) {
2584 coreListenerManager.fireSoneInserting(sone);
2591 public void insertFinished(Sone sone, long insertDuration) {
2592 coreListenerManager.fireSoneInserted(sone, insertDuration);
2599 public void insertAborted(Sone sone, Throwable cause) {
2600 coreListenerManager.fireSoneInsertAborted(sone, cause);
2604 // SONEINSERTLISTENER METHODS
2611 public void imageInsertStarted(Image image) {
2612 logger.log(Level.WARNING, "Image insert started for " + image);
2613 coreListenerManager.fireImageInsertStarted(image);
2620 public void imageInsertAborted(Image image) {
2621 logger.log(Level.WARNING, "Image insert aborted for " + image);
2622 coreListenerManager.fireImageInsertAborted(image);
2629 public void imageInsertFinished(Image image, FreenetURI key) {
2630 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2631 image.setKey(key.toString());
2632 deleteTemporaryImage(image.getId());
2633 saveSone(image.getSone());
2634 coreListenerManager.fireImageInsertFinished(image);
2641 public void imageInsertFailed(Image image, Throwable cause) {
2642 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2643 coreListenerManager.fireImageInsertFailed(image, cause);
2647 * Convenience interface for external classes that want to access the core’s
2650 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2652 public static class Preferences {
2654 /** The wrapped options. */
2655 private final Options options;
2658 * Creates a new preferences object wrapped around the given options.
2661 * The options to wrap
2663 public Preferences(Options options) {
2664 this.options = options;
2668 * Returns the insertion delay.
2670 * @return The insertion delay
2672 public int getInsertionDelay() {
2673 return options.getIntegerOption("InsertionDelay").get();
2677 * Validates the given insertion delay.
2679 * @param insertionDelay
2680 * The insertion delay to validate
2681 * @return {@code true} if the given insertion delay was valid, {@code
2684 public boolean validateInsertionDelay(Integer insertionDelay) {
2685 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2689 * Sets the insertion delay
2691 * @param insertionDelay
2692 * The new insertion delay, or {@code null} to restore it to
2694 * @return This preferences
2696 public Preferences setInsertionDelay(Integer insertionDelay) {
2697 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2702 * Returns the number of posts to show per page.
2704 * @return The number of posts to show per page
2706 public int getPostsPerPage() {
2707 return options.getIntegerOption("PostsPerPage").get();
2711 * Validates the number of posts per page.
2713 * @param postsPerPage
2714 * The number of posts per page
2715 * @return {@code true} if the number of posts per page was valid,
2716 * {@code false} otherwise
2718 public boolean validatePostsPerPage(Integer postsPerPage) {
2719 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2723 * Sets the number of posts to show per page.
2725 * @param postsPerPage
2726 * The number of posts to show per page
2727 * @return This preferences object
2729 public Preferences setPostsPerPage(Integer postsPerPage) {
2730 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2735 * Returns the number of characters per post, or <code>-1</code> if the
2736 * posts should not be cut off.
2738 * @return The numbers of characters per post
2740 public int getCharactersPerPost() {
2741 return options.getIntegerOption("CharactersPerPost").get();
2745 * Validates the number of characters per post.
2747 * @param charactersPerPost
2748 * The number of characters per post
2749 * @return {@code true} if the number of characters per post was valid,
2750 * {@code false} otherwise
2752 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2753 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2757 * Sets the number of characters per post.
2759 * @param charactersPerPost
2760 * The number of characters per post, or <code>-1</code> to
2761 * not cut off the posts
2762 * @return This preferences objects
2764 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2765 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2770 * Returns the number of characters the shortened post should have.
2772 * @return The number of characters of the snippet
2774 public int getPostCutOffLength() {
2775 return options.getIntegerOption("PostCutOffLength").get();
2779 * Validates the number of characters after which to cut off the post.
2781 * @param postCutOffLength
2782 * The number of characters of the snippet
2783 * @return {@code true} if the number of characters of the snippet is
2784 * valid, {@code false} otherwise
2786 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2787 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2791 * Sets the number of characters the shortened post should have.
2793 * @param postCutOffLength
2794 * The number of characters of the snippet
2795 * @return This preferences
2797 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2798 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2803 * Returns whether Sone requires full access to be even visible.
2805 * @return {@code true} if Sone requires full access, {@code false}
2808 public boolean isRequireFullAccess() {
2809 return options.getBooleanOption("RequireFullAccess").get();
2813 * Sets whether Sone requires full access to be even visible.