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 known posts. */
147 private Set<String> knownPosts = new HashSet<String>();
150 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
152 /** All new replies. */
153 private Set<String> newReplies = new HashSet<String>();
155 /** All known replies. */
156 private Set<String> knownReplies = new HashSet<String>();
158 /** All bookmarked posts. */
159 /* synchronize access on itself. */
160 private Set<String> bookmarkedPosts = new HashSet<String>();
162 /** Trusted identities, sorted by own identities. */
163 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
165 /** All known albums. */
166 private Map<String, Album> albums = new HashMap<String, Album>();
168 /** All known images. */
169 private Map<String, Image> images = new HashMap<String, Image>();
171 /** All temporary images. */
172 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
174 /** Ticker for threads that mark own elements as known. */
175 private Ticker localElementTicker = new Ticker();
177 /** The time the configuration was last touched. */
178 private volatile long lastConfigurationUpdate;
181 * Creates a new core.
183 * @param configuration
184 * The configuration of the core
185 * @param freenetInterface
186 * The freenet interface
187 * @param identityManager
188 * The identity manager
190 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
192 this.configuration = configuration;
193 this.freenetInterface = freenetInterface;
194 this.identityManager = identityManager;
195 this.soneDownloader = new SoneDownloader(this, freenetInterface);
196 this.imageInserter = new ImageInserter(this, freenetInterface);
197 this.updateChecker = new UpdateChecker(freenetInterface);
201 // LISTENER MANAGEMENT
205 * Adds a new core listener.
207 * @param coreListener
208 * The listener to add
210 public void addCoreListener(CoreListener coreListener) {
211 coreListenerManager.addListener(coreListener);
215 * Removes a core listener.
217 * @param coreListener
218 * The listener to remove
220 public void removeCoreListener(CoreListener coreListener) {
221 coreListenerManager.removeListener(coreListener);
229 * Sets the configuration to use. This will automatically save the current
230 * configuration to the given configuration.
232 * @param configuration
233 * The new configuration to use
235 public void setConfiguration(Configuration configuration) {
236 this.configuration = configuration;
237 touchConfiguration();
241 * Returns the options used by the core.
243 * @return The options of the core
245 public Preferences getPreferences() {
250 * Returns the identity manager used by the core.
252 * @return The identity manager
254 public IdentityManager getIdentityManager() {
255 return identityManager;
259 * Returns the update checker.
261 * @return The update checker
263 public UpdateChecker getUpdateChecker() {
264 return updateChecker;
268 * Sets the FCP interface to use.
270 * @param fcpInterface
271 * The FCP interface to use
273 public void setFcpInterface(FcpInterface fcpInterface) {
274 this.fcpInterface = fcpInterface;
278 * Returns the Sone rescuer for the given local Sone.
281 * The local Sone to get the rescuer for
282 * @return The Sone rescuer for the given Sone
284 public SoneRescuer getSoneRescuer(Sone sone) {
285 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
286 synchronized (localSones) {
287 SoneRescuer soneRescuer = soneRescuers.get(sone);
288 if (soneRescuer == null) {
289 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
290 soneRescuers.put(sone, soneRescuer);
298 * Returns whether the given Sone is currently locked.
302 * @return {@code true} if the Sone is locked, {@code false} if it is not
304 public boolean isLocked(Sone sone) {
305 synchronized (lockedSones) {
306 return lockedSones.contains(sone);
311 * Returns all Sones, remote and local.
315 public Set<Sone> getSones() {
316 Set<Sone> allSones = new HashSet<Sone>();
317 allSones.addAll(getLocalSones());
318 allSones.addAll(getRemoteSones());
323 * Returns the Sone with the given ID, regardless whether it’s local or
327 * The ID of the Sone to get
328 * @return The Sone with the given ID, or {@code null} if there is no such
331 public Sone getSone(String id) {
332 return getSone(id, true);
336 * Returns the Sone with the given ID, regardless whether it’s local or
340 * The ID of the Sone to get
342 * {@code true} to create a new Sone if none exists,
343 * {@code false} to return {@code null} if a Sone with the given
345 * @return The Sone with the given ID, or {@code null} if there is no such
349 public Sone getSone(String id, boolean create) {
350 if (isLocalSone(id)) {
351 return getLocalSone(id);
353 return getRemoteSone(id, create);
357 * Checks whether the core knows a Sone with the given ID.
361 * @return {@code true} if there is a Sone with the given ID, {@code false}
364 public boolean hasSone(String id) {
365 return isLocalSone(id) || isRemoteSone(id);
369 * Returns whether the given Sone is a local Sone.
372 * The Sone to check for its locality
373 * @return {@code true} if the given Sone is local, {@code false} otherwise
375 public boolean isLocalSone(Sone sone) {
376 synchronized (localSones) {
377 return localSones.containsKey(sone.getId());
382 * Returns whether the given ID is the ID of a local Sone.
385 * The Sone ID to check for its locality
386 * @return {@code true} if the given ID is a local Sone, {@code false}
389 public boolean isLocalSone(String id) {
390 synchronized (localSones) {
391 return localSones.containsKey(id);
396 * Returns all local Sones.
398 * @return All local Sones
400 public Set<Sone> getLocalSones() {
401 synchronized (localSones) {
402 return new HashSet<Sone>(localSones.values());
407 * Returns the local Sone with the given ID.
410 * The ID of the Sone to get
411 * @return The Sone with the given ID
413 public Sone getLocalSone(String id) {
414 return getLocalSone(id, true);
418 * Returns the local Sone with the given ID, optionally creating a new Sone.
423 * {@code true} to create a new Sone if none exists,
424 * {@code false} to return null if none exists
425 * @return The Sone with the given ID, or {@code null}
427 public Sone getLocalSone(String id, boolean create) {
428 synchronized (localSones) {
429 Sone sone = localSones.get(id);
430 if ((sone == null) && create) {
432 localSones.put(id, sone);
439 * Returns all remote Sones.
441 * @return All remote Sones
443 public Set<Sone> getRemoteSones() {
444 synchronized (remoteSones) {
445 return new HashSet<Sone>(remoteSones.values());
450 * Returns the remote Sone with the given ID.
453 * The ID of the remote Sone to get
455 * {@code true} to always create a Sone, {@code false} to return
456 * {@code null} if no Sone with the given ID exists
457 * @return The Sone with the given ID
459 public Sone getRemoteSone(String id, boolean create) {
460 synchronized (remoteSones) {
461 Sone sone = remoteSones.get(id);
462 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
464 remoteSones.put(id, sone);
471 * Returns whether the given Sone is a remote Sone.
475 * @return {@code true} if the given Sone is a remote Sone, {@code false}
478 public boolean isRemoteSone(Sone sone) {
479 synchronized (remoteSones) {
480 return remoteSones.containsKey(sone.getId());
485 * Returns whether the Sone with the given ID is a remote Sone.
488 * The ID of the Sone to check
489 * @return {@code true} if the Sone with the given ID is a remote Sone,
490 * {@code false} otherwise
492 public boolean isRemoteSone(String id) {
493 synchronized (remoteSones) {
494 return remoteSones.containsKey(id);
499 * Returns whether the given Sone has been modified.
502 * The Sone to check for modifications
503 * @return {@code true} if a modification has been detected in the Sone,
504 * {@code false} otherwise
506 public boolean isModifiedSone(Sone sone) {
507 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
511 * Returns the time when the given was first followed by any local Sone.
514 * The Sone to get the time for
515 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
516 * been followed, or {@link Long#MAX_VALUE}
518 public long getSoneFollowingTime(Sone sone) {
519 synchronized (soneFollowingTimes) {
520 if (soneFollowingTimes.containsKey(sone)) {
521 return soneFollowingTimes.get(sone);
523 return Long.MAX_VALUE;
528 * Returns whether the target Sone is trusted by the origin Sone.
534 * @return {@code true} if the target Sone is trusted by the origin Sone
536 public boolean isSoneTrusted(Sone origin, Sone target) {
537 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
538 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
542 * Returns the post with the given ID.
545 * The ID of the post to get
546 * @return The post with the given ID, or a new post with the given ID
548 public Post getPost(String postId) {
549 return getPost(postId, true);
553 * Returns the post with the given ID, optionally creating a new post.
556 * The ID of the post to get
558 * {@code true} it create a new post if no post with the given ID
559 * exists, {@code false} to return {@code null}
560 * @return The post, or {@code null} if there is no such post
563 public Post getPost(String postId, boolean create) {
564 synchronized (posts) {
565 Post post = posts.get(postId);
566 if ((post == null) && create) {
567 post = new Post(postId);
568 posts.put(postId, post);
575 * Returns all posts that have the given Sone as recipient.
577 * @see Post#getRecipient()
579 * The recipient of the posts
580 * @return All posts that have the given Sone as recipient
582 public Set<Post> getDirectedPosts(Sone recipient) {
583 Validation.begin().isNotNull("Recipient", recipient).check();
584 Set<Post> directedPosts = new HashSet<Post>();
585 synchronized (posts) {
586 for (Post post : posts.values()) {
587 if (recipient.equals(post.getRecipient())) {
588 directedPosts.add(post);
592 return directedPosts;
596 * Returns the reply with the given ID. If there is no reply with the given
597 * ID yet, a new one is created.
600 * The ID of the reply to get
603 public PostReply getReply(String replyId) {
604 return getReply(replyId, true);
608 * Returns the reply with the given ID. If there is no reply with the given
609 * ID yet, a new one is created, unless {@code create} is false in which
610 * case {@code null} is returned.
613 * The ID of the reply to get
615 * {@code true} to always return a {@link Reply}, {@code false}
616 * to return {@code null} if no reply can be found
617 * @return The reply, or {@code null} if there is no such reply
619 public PostReply getReply(String replyId, boolean create) {
620 synchronized (replies) {
621 PostReply reply = replies.get(replyId);
622 if (create && (reply == null)) {
623 reply = new PostReply(replyId);
624 replies.put(replyId, reply);
631 * Returns all replies for the given post, order ascending by time.
634 * The post to get all replies for
635 * @return All replies for the given post
637 public List<PostReply> getReplies(Post post) {
638 Set<Sone> sones = getSones();
639 List<PostReply> replies = new ArrayList<PostReply>();
640 for (Sone sone : sones) {
641 for (PostReply reply : sone.getReplies()) {
642 if (reply.getPost().equals(post)) {
647 Collections.sort(replies, Reply.TIME_COMPARATOR);
652 * Returns whether the reply with the given ID is new.
655 * The ID of the reply to check
656 * @return {@code true} if the reply is considered to be new, {@code false}
659 public boolean isNewReply(String replyId) {
660 synchronized (newReplies) {
661 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
666 * Returns all Sones that have liked the given post.
669 * The post to get the liking Sones for
670 * @return The Sones that like the given post
672 public Set<Sone> getLikes(Post post) {
673 Set<Sone> sones = new HashSet<Sone>();
674 for (Sone sone : getSones()) {
675 if (sone.getLikedPostIds().contains(post.getId())) {
683 * Returns all Sones that have liked the given reply.
686 * The reply to get the liking Sones for
687 * @return The Sones that like the given reply
689 public Set<Sone> getLikes(PostReply reply) {
690 Set<Sone> sones = new HashSet<Sone>();
691 for (Sone sone : getSones()) {
692 if (sone.getLikedReplyIds().contains(reply.getId())) {
700 * Returns whether the given post is bookmarked.
704 * @return {@code true} if the given post is bookmarked, {@code false}
707 public boolean isBookmarked(Post post) {
708 return isPostBookmarked(post.getId());
712 * Returns whether the post with the given ID is bookmarked.
715 * The ID of the post to check
716 * @return {@code true} if the post with the given ID is bookmarked,
717 * {@code false} otherwise
719 public boolean isPostBookmarked(String id) {
720 synchronized (bookmarkedPosts) {
721 return bookmarkedPosts.contains(id);
726 * Returns all currently known bookmarked posts.
728 * @return All bookmarked posts
730 public Set<Post> getBookmarkedPosts() {
731 Set<Post> posts = new HashSet<Post>();
732 synchronized (bookmarkedPosts) {
733 for (String bookmarkedPostId : bookmarkedPosts) {
734 Post post = getPost(bookmarkedPostId, false);
744 * Returns the album with the given ID, creating a new album if no album
745 * with the given ID can be found.
748 * The ID of the album
749 * @return The album with the given ID
751 public Album getAlbum(String albumId) {
752 return getAlbum(albumId, true);
756 * Returns the album with the given ID, optionally creating a new album if
757 * an album with the given ID can not be found.
760 * The ID of the album
762 * {@code true} to create a new album if none exists for the
764 * @return The album with the given ID, or {@code null} if no album with the
765 * given ID exists and {@code create} is {@code false}
767 public Album getAlbum(String albumId, boolean create) {
768 synchronized (albums) {
769 Album album = albums.get(albumId);
770 if (create && (album == null)) {
771 album = new Album(albumId);
772 albums.put(albumId, album);
779 * Returns the image with the given ID, creating it if necessary.
782 * The ID of the image
783 * @return The image with the given ID
785 public Image getImage(String imageId) {
786 return getImage(imageId, true);
790 * Returns the image with the given ID, optionally creating it if it does
794 * The ID of the image
796 * {@code true} to create an image if none exists with the given
798 * @return The image with the given ID, or {@code null} if none exists and
801 public Image getImage(String imageId, boolean create) {
802 synchronized (images) {
803 Image image = images.get(imageId);
804 if (create && (image == null)) {
805 image = new Image(imageId);
806 images.put(imageId, image);
813 * Returns the temporary image with the given ID.
816 * The ID of the temporary image
817 * @return The temporary image, or {@code null} if there is no temporary
818 * image with the given ID
820 public TemporaryImage getTemporaryImage(String imageId) {
821 synchronized (temporaryImages) {
822 return temporaryImages.get(imageId);
831 * Locks the given Sone. A locked Sone will not be inserted by
832 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
838 public void lockSone(Sone sone) {
839 synchronized (lockedSones) {
840 if (lockedSones.add(sone)) {
841 coreListenerManager.fireSoneLocked(sone);
847 * Unlocks the given Sone.
849 * @see #lockSone(Sone)
853 public void unlockSone(Sone sone) {
854 synchronized (lockedSones) {
855 if (lockedSones.remove(sone)) {
856 coreListenerManager.fireSoneUnlocked(sone);
862 * Adds a local Sone from the given own identity.
865 * The own identity to create a Sone from
866 * @return The added (or already existing) Sone
868 public Sone addLocalSone(OwnIdentity ownIdentity) {
869 if (ownIdentity == null) {
870 logger.log(Level.WARNING, "Given OwnIdentity is null!");
873 synchronized (localSones) {
876 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
877 } catch (MalformedURLException mue1) {
878 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
881 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
882 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
883 /* TODO - load posts ’n stuff */
884 localSones.put(ownIdentity.getId(), sone);
885 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
886 soneInserter.addSoneInsertListener(this);
887 soneInserters.put(sone, soneInserter);
888 sone.setStatus(SoneStatus.idle);
890 soneInserter.start();
896 * Creates a new Sone for the given own identity.
899 * The own identity to create a Sone for
900 * @return The created Sone
902 public Sone createSone(OwnIdentity ownIdentity) {
904 ownIdentity.addContext("Sone");
905 } catch (WebOfTrustException wote1) {
906 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
909 Sone sone = addLocalSone(ownIdentity);
910 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
911 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
912 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
913 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
914 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
915 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
917 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
918 touchConfiguration();
923 * Adds the Sone of the given identity.
926 * The identity whose Sone to add
927 * @return The added or already existing Sone
929 public Sone addRemoteSone(Identity identity) {
930 if (identity == null) {
931 logger.log(Level.WARNING, "Given Identity is null!");
934 synchronized (remoteSones) {
935 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
936 boolean newSone = sone.getRequestUri() == null;
937 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
938 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
940 synchronized (knownSones) {
941 newSone = !knownSones.contains(sone.getId());
943 sone.setKnown(!newSone);
945 coreListenerManager.fireNewSoneFound(sone);
946 for (Sone localSone : getLocalSones()) {
947 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
948 followSone(localSone, sone);
953 soneDownloader.addSone(sone);
954 soneDownloaders.execute(new Runnable() {
957 @SuppressWarnings("synthetic-access")
959 soneDownloader.fetchSone(sone, sone.getRequestUri());
968 * Lets the given local Sone follow the Sone with the given ID.
971 * The local Sone that should follow another Sone
973 * The ID of the Sone to follow
975 public void followSone(Sone sone, String soneId) {
976 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
977 Sone followedSone = getSone(soneId, true);
978 if (followedSone == null) {
979 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
982 followSone(sone, getSone(soneId));
986 * Lets the given local Sone follow the other given Sone. If the given Sone
987 * was not followed by any local Sone before, this will mark all elements of
988 * the followed Sone as read that have been created before the current
992 * The local Sone that should follow the other Sone
993 * @param followedSone
994 * The Sone that should be followed
996 public void followSone(Sone sone, Sone followedSone) {
997 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
998 sone.addFriend(followedSone.getId());
999 synchronized (soneFollowingTimes) {
1000 if (!soneFollowingTimes.containsKey(followedSone)) {
1001 long now = System.currentTimeMillis();
1002 soneFollowingTimes.put(followedSone, now);
1003 for (Post post : followedSone.getPosts()) {
1004 if (post.getTime() < now) {
1005 markPostKnown(post);
1008 for (PostReply reply : followedSone.getReplies()) {
1009 if (reply.getTime() < now) {
1010 markReplyKnown(reply);
1015 touchConfiguration();
1019 * Lets the given local Sone unfollow the Sone with the given ID.
1022 * The local Sone that should unfollow another Sone
1024 * The ID of the Sone being unfollowed
1026 public void unfollowSone(Sone sone, String soneId) {
1027 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1028 unfollowSone(sone, getSone(soneId, false));
1032 * Lets the given local Sone unfollow the other given Sone. If the given
1033 * local Sone is the last local Sone that followed the given Sone, its
1034 * following time will be removed.
1037 * The local Sone that should unfollow another Sone
1038 * @param unfollowedSone
1039 * The Sone being unfollowed
1041 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1042 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1043 sone.removeFriend(unfollowedSone.getId());
1044 boolean unfollowedSoneStillFollowed = false;
1045 for (Sone localSone : getLocalSones()) {
1046 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1048 if (!unfollowedSoneStillFollowed) {
1049 synchronized (soneFollowingTimes) {
1050 soneFollowingTimes.remove(unfollowedSone);
1053 touchConfiguration();
1057 * Retrieves the trust relationship from the origin to the target. If the
1058 * trust relationship can not be retrieved, {@code null} is returned.
1060 * @see Identity#getTrust(OwnIdentity)
1062 * The origin of the trust tree
1064 * The target of the trust
1065 * @return The trust relationship
1067 public Trust getTrust(Sone origin, Sone target) {
1068 if (!isLocalSone(origin)) {
1069 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1072 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1076 * Sets the trust value of the given origin Sone for the target Sone.
1083 * The trust value (from {@code -100} to {@code 100})
1085 public void setTrust(Sone origin, Sone target, int trustValue) {
1086 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();
1088 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1089 } catch (WebOfTrustException wote1) {
1090 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1095 * Removes any trust assignment for the given target Sone.
1102 public void removeTrust(Sone origin, Sone target) {
1103 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1105 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1106 } catch (WebOfTrustException wote1) {
1107 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1112 * Assigns the configured positive trust value for the given target.
1119 public void trustSone(Sone origin, Sone target) {
1120 setTrust(origin, target, preferences.getPositiveTrust());
1124 * Assigns the configured negative trust value for the given target.
1131 public void distrustSone(Sone origin, Sone target) {
1132 setTrust(origin, target, preferences.getNegativeTrust());
1136 * Removes the trust assignment for the given target.
1143 public void untrustSone(Sone origin, Sone target) {
1144 removeTrust(origin, target);
1148 * Updates the stored Sone with the given Sone.
1153 public void updateSone(Sone sone) {
1154 updateSone(sone, false);
1158 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1159 * {@code true}, an older Sone than the current Sone can be given to restore
1163 * The Sone to update
1164 * @param soneRescueMode
1165 * {@code true} if the stored Sone should be updated regardless
1166 * of the age of the given Sone
1168 public void updateSone(Sone sone, boolean soneRescueMode) {
1169 if (hasSone(sone.getId())) {
1170 Sone storedSone = getSone(sone.getId());
1171 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1172 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1175 synchronized (posts) {
1176 if (!soneRescueMode) {
1177 for (Post post : storedSone.getPosts()) {
1178 posts.remove(post.getId());
1179 if (!sone.getPosts().contains(post)) {
1180 coreListenerManager.firePostRemoved(post);
1184 List<Post> storedPosts = storedSone.getPosts();
1185 synchronized (knownPosts) {
1186 for (Post post : sone.getPosts()) {
1187 post.setSone(storedSone);
1188 if (!storedPosts.contains(post)) {
1189 if (post.getTime() < getSoneFollowingTime(sone)) {
1190 sone.setKnown(true);
1191 knownPosts.add(post.getId());
1192 } else if (!knownPosts.contains(post.getId())) {
1193 coreListenerManager.fireNewPostFound(post);
1195 sone.setKnown(true);
1198 posts.put(post.getId(), post);
1202 synchronized (replies) {
1203 if (!soneRescueMode) {
1204 for (PostReply reply : storedSone.getReplies()) {
1205 replies.remove(reply.getId());
1206 if (!sone.getReplies().contains(reply)) {
1207 coreListenerManager.fireReplyRemoved(reply);
1211 Set<PostReply> storedReplies = storedSone.getReplies();
1212 synchronized (newReplies) {
1213 for (PostReply reply : sone.getReplies()) {
1214 reply.setSone(storedSone);
1215 if (!storedReplies.contains(reply)) {
1216 if (reply.getTime() < getSoneFollowingTime(sone)) {
1217 knownReplies.add(reply.getId());
1218 } else if (!knownReplies.contains(reply.getId())) {
1219 newReplies.add(reply.getId());
1220 coreListenerManager.fireNewReplyFound(reply);
1223 replies.put(reply.getId(), reply);
1227 synchronized (albums) {
1228 synchronized (images) {
1229 for (Album album : storedSone.getAlbums()) {
1230 albums.remove(album.getId());
1231 for (Image image : album.getImages()) {
1232 images.remove(image.getId());
1235 for (Album album : sone.getAlbums()) {
1236 albums.put(album.getId(), album);
1237 for (Image image : album.getImages()) {
1238 images.put(image.getId(), image);
1243 synchronized (storedSone) {
1244 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1245 storedSone.setTime(sone.getTime());
1247 storedSone.setClient(sone.getClient());
1248 storedSone.setProfile(sone.getProfile());
1249 if (soneRescueMode) {
1250 for (Post post : sone.getPosts()) {
1251 storedSone.addPost(post);
1253 for (PostReply reply : sone.getReplies()) {
1254 storedSone.addReply(reply);
1256 for (String likedPostId : sone.getLikedPostIds()) {
1257 storedSone.addLikedPostId(likedPostId);
1259 for (String likedReplyId : sone.getLikedReplyIds()) {
1260 storedSone.addLikedReplyId(likedReplyId);
1262 for (Album album : sone.getAlbums()) {
1263 storedSone.addAlbum(album);
1266 storedSone.setPosts(sone.getPosts());
1267 storedSone.setReplies(sone.getReplies());
1268 storedSone.setLikePostIds(sone.getLikedPostIds());
1269 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1270 storedSone.setAlbums(sone.getAlbums());
1272 storedSone.setLatestEdition(sone.getLatestEdition());
1278 * Deletes the given Sone. This will remove the Sone from the
1279 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1280 * and remove the context from its identity.
1283 * The Sone to delete
1285 public void deleteSone(Sone sone) {
1286 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1287 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1290 synchronized (localSones) {
1291 if (!localSones.containsKey(sone.getId())) {
1292 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1295 localSones.remove(sone.getId());
1296 SoneInserter soneInserter = soneInserters.remove(sone);
1297 soneInserter.removeSoneInsertListener(this);
1298 soneInserter.stop();
1301 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1302 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1303 } catch (WebOfTrustException wote1) {
1304 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1307 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1308 } catch (ConfigurationException ce1) {
1309 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1314 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1315 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1318 * The Sone to mark as known
1320 public void markSoneKnown(Sone sone) {
1321 if (!sone.isKnown()) {
1322 sone.setKnown(true);
1323 synchronized (knownSones) {
1324 knownSones.add(sone.getId());
1326 coreListenerManager.fireMarkSoneKnown(sone);
1327 touchConfiguration();
1332 * Loads and updates the given Sone from the configuration. If any error is
1333 * encountered, loading is aborted and the given Sone is not changed.
1336 * The Sone to load and update
1338 public void loadSone(Sone sone) {
1339 if (!isLocalSone(sone)) {
1340 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1344 /* initialize options. */
1345 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1346 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1347 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1348 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1349 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1350 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1353 String sonePrefix = "Sone/" + sone.getId();
1354 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1355 if (soneTime == null) {
1356 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1359 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1362 Profile profile = new Profile(sone);
1363 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1364 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1365 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1366 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1367 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1368 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1370 /* load profile fields. */
1372 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1373 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1374 if (fieldName == null) {
1377 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1378 profile.addField(fieldName).setValue(fieldValue);
1382 Set<Post> posts = new HashSet<Post>();
1384 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1385 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1386 if (postId == null) {
1389 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1390 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1391 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1392 if ((postTime == 0) || (postText == null)) {
1393 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1396 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1397 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1398 post.setRecipient(getSone(postRecipientId));
1404 Set<PostReply> replies = new HashSet<PostReply>();
1406 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1407 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1408 if (replyId == null) {
1411 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1412 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1413 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1414 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1415 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1418 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1421 /* load post likes. */
1422 Set<String> likedPostIds = new HashSet<String>();
1424 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1425 if (likedPostId == null) {
1428 likedPostIds.add(likedPostId);
1431 /* load reply likes. */
1432 Set<String> likedReplyIds = new HashSet<String>();
1434 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1435 if (likedReplyId == null) {
1438 likedReplyIds.add(likedReplyId);
1442 Set<String> friends = new HashSet<String>();
1444 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1445 if (friendId == null) {
1448 friends.add(friendId);
1452 List<Album> topLevelAlbums = new ArrayList<Album>();
1453 int albumCounter = 0;
1455 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1456 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1457 if (albumId == null) {
1460 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1461 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1462 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1463 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1464 if ((albumTitle == null) || (albumDescription == null)) {
1465 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1468 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1469 if (albumParentId != null) {
1470 Album parentAlbum = getAlbum(albumParentId, false);
1471 if (parentAlbum == null) {
1472 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1475 parentAlbum.addAlbum(album);
1477 topLevelAlbums.add(album);
1482 int imageCounter = 0;
1484 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1485 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1486 if (imageId == null) {
1489 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1490 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1491 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1492 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1493 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1494 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1495 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1496 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1497 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1500 Album album = getAlbum(albumId, false);
1501 if (album == null) {
1502 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1505 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1506 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1507 album.addImage(image);
1511 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1512 if (avatarId != null) {
1513 profile.setAvatar(getImage(avatarId, false));
1517 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1518 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1519 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1520 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1521 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1522 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1524 /* if we’re still here, Sone was loaded successfully. */
1525 synchronized (sone) {
1526 sone.setTime(soneTime);
1527 sone.setProfile(profile);
1528 sone.setPosts(posts);
1529 sone.setReplies(replies);
1530 sone.setLikePostIds(likedPostIds);
1531 sone.setLikeReplyIds(likedReplyIds);
1532 for (String friendId : friends) {
1533 followSone(sone, friendId);
1535 sone.setAlbums(topLevelAlbums);
1536 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1538 synchronized (knownSones) {
1539 for (String friend : friends) {
1540 knownSones.add(friend);
1543 synchronized (knownPosts) {
1544 for (Post post : posts) {
1545 knownPosts.add(post.getId());
1548 synchronized (newReplies) {
1549 for (PostReply reply : replies) {
1550 knownReplies.add(reply.getId());
1556 * Creates a new post.
1559 * The Sone that creates the post
1561 * The text of the post
1562 * @return The created post
1564 public Post createPost(Sone sone, String text) {
1565 return createPost(sone, System.currentTimeMillis(), text);
1569 * Creates a new post.
1572 * The Sone that creates the post
1574 * The time of the post
1576 * The text of the post
1577 * @return The created post
1579 public Post createPost(Sone sone, long time, String text) {
1580 return createPost(sone, null, time, text);
1584 * Creates a new post.
1587 * The Sone that creates the post
1589 * The recipient Sone, or {@code null} if this post does not have
1592 * The text of the post
1593 * @return The created post
1595 public Post createPost(Sone sone, Sone recipient, String text) {
1596 return createPost(sone, recipient, System.currentTimeMillis(), 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 time of the post
1610 * The text of the post
1611 * @return The created post
1613 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1614 if (!isLocalSone(sone)) {
1615 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1618 final Post post = new Post(sone, time, text);
1619 if (recipient != null) {
1620 post.setRecipient(recipient);
1622 synchronized (posts) {
1623 posts.put(post.getId(), post);
1625 coreListenerManager.fireNewPostFound(post);
1627 touchConfiguration();
1628 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1635 markPostKnown(post);
1637 }, "Mark " + post + " read.");
1642 * Deletes the given post.
1645 * The post to delete
1647 public void deletePost(Post post) {
1648 if (!isLocalSone(post.getSone())) {
1649 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1652 post.getSone().removePost(post);
1653 synchronized (posts) {
1654 posts.remove(post.getId());
1656 coreListenerManager.firePostRemoved(post);
1657 markPostKnown(post);
1658 touchConfiguration();
1662 * Marks the given post as known, if it is currently a new post (according
1663 * to {@link #isNewPost(String)}).
1666 * The post to mark as known
1668 public void markPostKnown(Post post) {
1669 post.setKnown(true);
1670 synchronized (knownPosts) {
1671 if (knownPosts.add(post.getId())) {
1672 coreListenerManager.fireMarkPostKnown(post);
1673 touchConfiguration();
1679 * Bookmarks the given post.
1682 * The post to bookmark
1684 public void bookmark(Post post) {
1685 bookmarkPost(post.getId());
1689 * Bookmarks the post with the given ID.
1692 * The ID of the post to bookmark
1694 public void bookmarkPost(String id) {
1695 synchronized (bookmarkedPosts) {
1696 bookmarkedPosts.add(id);
1701 * Removes the given post from the bookmarks.
1704 * The post to unbookmark
1706 public void unbookmark(Post post) {
1707 unbookmarkPost(post.getId());
1711 * Removes the post with the given ID from the bookmarks.
1714 * The ID of the post to unbookmark
1716 public void unbookmarkPost(String id) {
1717 synchronized (bookmarkedPosts) {
1718 bookmarkedPosts.remove(id);
1723 * Creates a new reply.
1726 * The Sone that creates the reply
1728 * The post that this reply refers to
1730 * The text of the reply
1731 * @return The created reply
1733 public PostReply createReply(Sone sone, Post post, String text) {
1734 return createReply(sone, post, System.currentTimeMillis(), text);
1738 * Creates a new reply.
1741 * The Sone that creates the reply
1743 * The post that this reply refers to
1745 * The time of the reply
1747 * The text of the reply
1748 * @return The created reply
1750 public PostReply createReply(Sone sone, Post post, long time, String text) {
1751 if (!isLocalSone(sone)) {
1752 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1755 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1756 synchronized (replies) {
1757 replies.put(reply.getId(), reply);
1759 synchronized (newReplies) {
1760 newReplies.add(reply.getId());
1761 coreListenerManager.fireNewReplyFound(reply);
1763 sone.addReply(reply);
1764 touchConfiguration();
1765 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1772 markReplyKnown(reply);
1774 }, "Mark " + reply + " read.");
1779 * Deletes the given reply.
1782 * The reply to delete
1784 public void deleteReply(PostReply reply) {
1785 Sone sone = reply.getSone();
1786 if (!isLocalSone(sone)) {
1787 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1790 synchronized (replies) {
1791 replies.remove(reply.getId());
1793 synchronized (newReplies) {
1794 markReplyKnown(reply);
1795 knownReplies.remove(reply.getId());
1797 sone.removeReply(reply);
1798 touchConfiguration();
1802 * Marks the given reply as known, if it is currently a new reply (according
1803 * to {@link #isNewReply(String)}).
1806 * The reply to mark as known
1808 public void markReplyKnown(PostReply reply) {
1809 synchronized (newReplies) {
1810 newReplies.remove(reply.getId());
1811 if (knownReplies.add(reply.getId())) {
1812 coreListenerManager.fireMarkReplyKnown(reply);
1813 touchConfiguration();
1819 * Creates a new top-level album for the given Sone.
1822 * The Sone to create the album for
1823 * @return The new album
1825 public Album createAlbum(Sone sone) {
1826 return createAlbum(sone, null);
1830 * Creates a new album for the given Sone.
1833 * The Sone to create the album for
1835 * The parent of the album (may be {@code null} to create a
1837 * @return The new album
1839 public Album createAlbum(Sone sone, Album parent) {
1840 Album album = new Album();
1841 synchronized (albums) {
1842 albums.put(album.getId(), album);
1844 album.setSone(sone);
1845 if (parent != null) {
1846 parent.addAlbum(album);
1848 sone.addAlbum(album);
1854 * Deletes the given album. The owner of the album has to be a local Sone,
1855 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1858 * The album to remove
1860 public void deleteAlbum(Album album) {
1861 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1862 if (!album.isEmpty()) {
1865 if (album.getParent() == null) {
1866 album.getSone().removeAlbum(album);
1868 album.getParent().removeAlbum(album);
1870 synchronized (albums) {
1871 albums.remove(album.getId());
1873 saveSone(album.getSone());
1877 * Creates a new image.
1880 * The Sone creating the image
1882 * The album the image will be inserted into
1883 * @param temporaryImage
1884 * The temporary image to create the image from
1885 * @return The newly created image
1887 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1888 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();
1889 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1890 album.addImage(image);
1891 synchronized (images) {
1892 images.put(image.getId(), image);
1894 imageInserter.insertImage(temporaryImage, image);
1899 * Deletes the given image. This method will also delete a matching
1902 * @see #deleteTemporaryImage(TemporaryImage)
1904 * The image to delete
1906 public void deleteImage(Image image) {
1907 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1908 deleteTemporaryImage(image.getId());
1909 image.getAlbum().removeImage(image);
1910 synchronized (images) {
1911 images.remove(image.getId());
1913 saveSone(image.getSone());
1917 * Creates a new temporary image.
1920 * The MIME type of the temporary image
1922 * The encoded data of the image
1923 * @return The temporary image
1925 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1926 TemporaryImage temporaryImage = new TemporaryImage();
1927 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1928 synchronized (temporaryImages) {
1929 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1931 return temporaryImage;
1935 * Deletes the given temporary image.
1937 * @param temporaryImage
1938 * The temporary image to delete
1940 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1941 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1942 deleteTemporaryImage(temporaryImage.getId());
1946 * Deletes the temporary image with the given ID.
1949 * The ID of the temporary image to delete
1951 public void deleteTemporaryImage(String imageId) {
1952 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1953 synchronized (temporaryImages) {
1954 temporaryImages.remove(imageId);
1956 Image image = getImage(imageId, false);
1957 if (image != null) {
1958 imageInserter.cancelImageInsert(image);
1963 * Notifies the core that the configuration, either of the core or of a
1964 * single local Sone, has changed, and that the configuration should be
1967 public void touchConfiguration() {
1968 lastConfigurationUpdate = System.currentTimeMillis();
1979 public void serviceStart() {
1980 loadConfiguration();
1981 updateChecker.addUpdateListener(this);
1982 updateChecker.start();
1989 public void serviceRun() {
1990 long lastSaved = System.currentTimeMillis();
1991 while (!shouldStop()) {
1993 long now = System.currentTimeMillis();
1994 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1995 for (Sone localSone : getLocalSones()) {
1996 saveSone(localSone);
1998 saveConfiguration();
2008 public void serviceStop() {
2009 synchronized (localSones) {
2010 for (SoneInserter soneInserter : soneInserters.values()) {
2011 soneInserter.removeSoneInsertListener(this);
2012 soneInserter.stop();
2015 updateChecker.stop();
2016 updateChecker.removeUpdateListener(this);
2017 soneDownloader.stop();
2025 * Saves the given Sone. This will persist all local settings for the given
2026 * Sone, such as the friends list and similar, private options.
2031 private synchronized void saveSone(Sone sone) {
2032 if (!isLocalSone(sone)) {
2033 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2036 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2037 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2041 logger.log(Level.INFO, "Saving Sone: %s", sone);
2043 /* save Sone into configuration. */
2044 String sonePrefix = "Sone/" + sone.getId();
2045 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2046 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2049 Profile profile = sone.getProfile();
2050 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2051 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2052 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2053 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2054 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2055 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2056 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2058 /* save profile fields. */
2059 int fieldCounter = 0;
2060 for (Field profileField : profile.getFields()) {
2061 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2062 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2063 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2065 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2068 int postCounter = 0;
2069 for (Post post : sone.getPosts()) {
2070 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2071 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2072 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2073 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2074 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2076 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2079 int replyCounter = 0;
2080 for (PostReply reply : sone.getReplies()) {
2081 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2082 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2083 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2084 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2085 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2087 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2089 /* save post likes. */
2090 int postLikeCounter = 0;
2091 for (String postId : sone.getLikedPostIds()) {
2092 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2094 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2096 /* save reply likes. */
2097 int replyLikeCounter = 0;
2098 for (String replyId : sone.getLikedReplyIds()) {
2099 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2101 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2104 int friendCounter = 0;
2105 for (String friendId : sone.getFriends()) {
2106 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2108 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2110 /* save albums. first, collect in a flat structure, top-level first. */
2111 List<Album> albums = sone.getAllAlbums();
2113 int albumCounter = 0;
2114 for (Album album : albums) {
2115 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2116 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2117 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2118 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2119 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2120 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2122 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2125 int imageCounter = 0;
2126 for (Album album : albums) {
2127 for (Image image : album.getImages()) {
2128 if (!image.isInserted()) {
2131 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2132 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2133 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2134 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2135 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2136 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2137 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2138 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2139 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2142 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2145 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2146 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2147 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2148 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2149 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2150 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2152 configuration.save();
2154 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2156 logger.log(Level.INFO, "Sone %s saved.", sone);
2157 } catch (ConfigurationException ce1) {
2158 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2159 } catch (WebOfTrustException wote1) {
2160 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2165 * Saves the current options.
2167 private void saveConfiguration() {
2168 synchronized (configuration) {
2169 if (storingConfiguration) {
2170 logger.log(Level.FINE, "Already storing configuration…");
2173 storingConfiguration = true;
2176 /* store the options first. */
2178 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2179 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2180 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2181 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2182 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2183 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2184 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2185 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2186 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2187 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2188 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2189 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2190 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2191 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2193 /* save known Sones. */
2194 int soneCounter = 0;
2195 synchronized (knownSones) {
2196 for (String knownSoneId : knownSones) {
2197 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2199 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2202 /* save Sone following times. */
2204 synchronized (soneFollowingTimes) {
2205 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2206 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2207 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2210 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2213 /* save known posts. */
2214 int postCounter = 0;
2215 synchronized (knownPosts) {
2216 for (String knownPostId : knownPosts) {
2217 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2219 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2222 /* save known replies. */
2223 int replyCounter = 0;
2224 synchronized (newReplies) {
2225 for (String knownReplyId : knownReplies) {
2226 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2228 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2231 /* save bookmarked posts. */
2232 int bookmarkedPostCounter = 0;
2233 synchronized (bookmarkedPosts) {
2234 for (String bookmarkedPostId : bookmarkedPosts) {
2235 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2238 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2241 configuration.save();
2243 } catch (ConfigurationException ce1) {
2244 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2246 synchronized (configuration) {
2247 storingConfiguration = false;
2253 * Loads the configuration.
2255 @SuppressWarnings("unchecked")
2256 private void loadConfiguration() {
2257 /* create options. */
2258 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2261 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2262 SoneInserter.setInsertionDelay(newValue);
2266 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2267 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2268 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2269 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2270 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2271 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2272 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2273 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2276 @SuppressWarnings("synthetic-access")
2277 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2278 fcpInterface.setActive(newValue);
2281 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2284 @SuppressWarnings("synthetic-access")
2285 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2286 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2290 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2291 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2292 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2294 /* read options from configuration. */
2295 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2296 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2297 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2298 options.getBooleanOption("ClearOnNextRestart").set(null);
2299 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2300 if (clearConfiguration) {
2301 /* stop loading the configuration. */
2305 loadConfigurationValue("InsertionDelay");
2306 loadConfigurationValue("PostsPerPage");
2307 loadConfigurationValue("CharactersPerPost");
2308 loadConfigurationValue("PostCutOffLength");
2309 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2310 loadConfigurationValue("PositiveTrust");
2311 loadConfigurationValue("NegativeTrust");
2312 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2313 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2314 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2315 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2317 /* load known Sones. */
2318 int soneCounter = 0;
2320 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2321 if (knownSoneId == null) {
2324 synchronized (knownSones) {
2325 knownSones.add(knownSoneId);
2329 /* load Sone following times. */
2332 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2333 if (soneId == null) {
2336 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2337 Sone followedSone = getSone(soneId);
2338 if (followedSone == null) {
2339 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2341 synchronized (soneFollowingTimes) {
2342 soneFollowingTimes.put(getSone(soneId), time);
2348 /* load known posts. */
2349 int postCounter = 0;
2351 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2352 if (knownPostId == null) {
2355 synchronized (knownPosts) {
2356 knownPosts.add(knownPostId);
2360 /* load known replies. */
2361 int replyCounter = 0;
2363 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2364 if (knownReplyId == null) {
2367 synchronized (newReplies) {
2368 knownReplies.add(knownReplyId);
2372 /* load bookmarked posts. */
2373 int bookmarkedPostCounter = 0;
2375 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2376 if (bookmarkedPostId == null) {
2379 synchronized (bookmarkedPosts) {
2380 bookmarkedPosts.add(bookmarkedPostId);
2387 * Loads an {@link Integer} configuration value for the option with the
2388 * given name, logging validation failures.
2391 * The name of the option to load
2393 private void loadConfigurationValue(String optionName) {
2395 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2396 } catch (IllegalArgumentException iae1) {
2397 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2402 * Generate a Sone URI from the given URI and latest edition.
2405 * The URI to derive the Sone URI from
2406 * @return The derived URI
2408 private FreenetURI getSoneUri(String uriString) {
2410 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2412 } catch (MalformedURLException mue1) {
2413 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2419 // INTERFACE IdentityListener
2426 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2427 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2428 if (ownIdentity.hasContext("Sone")) {
2429 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2430 addLocalSone(ownIdentity);
2438 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2439 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2440 trustedIdentities.remove(ownIdentity);
2447 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2448 logger.log(Level.FINEST, "Adding Identity: " + identity);
2449 trustedIdentities.get(ownIdentity).add(identity);
2450 addRemoteSone(identity);
2457 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2458 new Thread(new Runnable() {
2461 @SuppressWarnings("synthetic-access")
2463 Sone sone = getRemoteSone(identity.getId(), false);
2464 sone.setIdentity(identity);
2465 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2466 soneDownloader.addSone(sone);
2467 soneDownloader.fetchSone(sone);
2476 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2477 trustedIdentities.get(ownIdentity).remove(identity);
2478 boolean foundIdentity = false;
2479 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2480 if (trustedIdentity.getKey().equals(ownIdentity)) {
2483 if (trustedIdentity.getValue().contains(identity)) {
2484 foundIdentity = true;
2487 if (foundIdentity) {
2488 /* some local identity still trusts this identity, don’t remove. */
2491 Sone sone = getSone(identity.getId(), false);
2493 /* TODO - we don’t have the Sone anymore. should this happen? */
2496 synchronized (posts) {
2497 synchronized (knownPosts) {
2498 for (Post post : sone.getPosts()) {
2499 posts.remove(post.getId());
2500 coreListenerManager.firePostRemoved(post);
2504 synchronized (replies) {
2505 synchronized (newReplies) {
2506 for (PostReply reply : sone.getReplies()) {
2507 replies.remove(reply.getId());
2508 newReplies.remove(reply.getId());
2509 coreListenerManager.fireReplyRemoved(reply);
2513 synchronized (remoteSones) {
2514 remoteSones.remove(identity.getId());
2516 coreListenerManager.fireSoneRemoved(sone);
2520 // INTERFACE UpdateListener
2527 public void updateFound(Version version, long releaseTime, long latestEdition) {
2528 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2532 // INTERFACE ImageInsertListener
2539 public void insertStarted(Sone sone) {
2540 coreListenerManager.fireSoneInserting(sone);
2547 public void insertFinished(Sone sone, long insertDuration) {
2548 coreListenerManager.fireSoneInserted(sone, insertDuration);
2555 public void insertAborted(Sone sone, Throwable cause) {
2556 coreListenerManager.fireSoneInsertAborted(sone, cause);
2560 // SONEINSERTLISTENER METHODS
2567 public void imageInsertStarted(Image image) {
2568 logger.log(Level.WARNING, "Image insert started for " + image);
2569 coreListenerManager.fireImageInsertStarted(image);
2576 public void imageInsertAborted(Image image) {
2577 logger.log(Level.WARNING, "Image insert aborted for " + image);
2578 coreListenerManager.fireImageInsertAborted(image);
2585 public void imageInsertFinished(Image image, FreenetURI key) {
2586 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2587 image.setKey(key.toString());
2588 deleteTemporaryImage(image.getId());
2589 saveSone(image.getSone());
2590 coreListenerManager.fireImageInsertFinished(image);
2597 public void imageInsertFailed(Image image, Throwable cause) {
2598 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2599 coreListenerManager.fireImageInsertFailed(image, cause);
2603 * Convenience interface for external classes that want to access the core’s
2606 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2608 public static class Preferences {
2610 /** The wrapped options. */
2611 private final Options options;
2614 * Creates a new preferences object wrapped around the given options.
2617 * The options to wrap
2619 public Preferences(Options options) {
2620 this.options = options;
2624 * Returns the insertion delay.
2626 * @return The insertion delay
2628 public int getInsertionDelay() {
2629 return options.getIntegerOption("InsertionDelay").get();
2633 * Validates the given insertion delay.
2635 * @param insertionDelay
2636 * The insertion delay to validate
2637 * @return {@code true} if the given insertion delay was valid,
2638 * {@code false} otherwise
2640 public boolean validateInsertionDelay(Integer insertionDelay) {
2641 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2645 * Sets the insertion delay
2647 * @param insertionDelay
2648 * The new insertion delay, or {@code null} to restore it to
2650 * @return This preferences
2652 public Preferences setInsertionDelay(Integer insertionDelay) {
2653 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2658 * Returns the number of posts to show per page.
2660 * @return The number of posts to show per page
2662 public int getPostsPerPage() {
2663 return options.getIntegerOption("PostsPerPage").get();
2667 * Validates the number of posts per page.
2669 * @param postsPerPage
2670 * The number of posts per page
2671 * @return {@code true} if the number of posts per page was valid,
2672 * {@code false} otherwise
2674 public boolean validatePostsPerPage(Integer postsPerPage) {
2675 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2679 * Sets the number of posts to show per page.
2681 * @param postsPerPage
2682 * The number of posts to show per page
2683 * @return This preferences object
2685 public Preferences setPostsPerPage(Integer postsPerPage) {
2686 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2691 * Returns the number of characters per post, or <code>-1</code> if the
2692 * posts should not be cut off.
2694 * @return The numbers of characters per post
2696 public int getCharactersPerPost() {
2697 return options.getIntegerOption("CharactersPerPost").get();
2701 * Validates the number of characters per post.
2703 * @param charactersPerPost
2704 * The number of characters per post
2705 * @return {@code true} if the number of characters per post was valid,
2706 * {@code false} otherwise
2708 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2709 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2713 * Sets the number of characters per post.
2715 * @param charactersPerPost
2716 * The number of characters per post, or <code>-1</code> to
2717 * not cut off the posts
2718 * @return This preferences objects
2720 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2721 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2726 * Returns the number of characters the shortened post should have.
2728 * @return The number of characters of the snippet
2730 public int getPostCutOffLength() {
2731 return options.getIntegerOption("PostCutOffLength").get();
2735 * Validates the number of characters after which to cut off the post.
2737 * @param postCutOffLength
2738 * The number of characters of the snippet
2739 * @return {@code true} if the number of characters of the snippet is
2740 * valid, {@code false} otherwise
2742 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2743 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2747 * Sets the number of characters the shortened post should have.
2749 * @param postCutOffLength
2750 * The number of characters of the snippet
2751 * @return This preferences
2753 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2754 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2759 * Returns whether Sone requires full access to be even visible.
2761 * @return {@code true} if Sone requires full access, {@code false}
2764 public boolean isRequireFullAccess() {
2765 return options.getBooleanOption("RequireFullAccess").get();
2769 * Sets whether Sone requires full access to be even visible.
2771 * @param requireFullAccess
2772 * {@code true} if Sone requires full access, {@code false}
2775 public void setRequireFullAccess(Boolean requireFullAccess) {
2776 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2780 * Returns the positive trust.
2782 * @return The positive trust
2784 public int getPositiveTrust() {
2785 return options.getIntegerOption("PositiveTrust").get();
2789 * Validates the positive trust.
2791 * @param positiveTrust
2792 * The positive trust to validate
2793 * @return {@code true} if the positive trust was valid, {@code false}
2796 public boolean validatePositiveTrust(Integer positiveTrust) {
2797 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2801 * Sets the positive trust.
2803 * @param positiveTrust
2804 * The new positive trust, or {@code null} to restore it to
2806 * @return This preferences
2808 public Preferences setPositiveTrust(Integer positiveTrust) {
2809 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2814 * Returns the negative trust.
2816 * @return The negative trust
2818 public int getNegativeTrust() {
2819 return options.getIntegerOption("NegativeTrust").get();
2823 * Validates the negative trust.
2825 * @param negativeTrust
2826 * The negative trust to validate
2827 * @return {@code true} if the negative trust was valid, {@code false}
2830 public boolean validateNegativeTrust(Integer negativeTrust) {
2831 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2835 * Sets the negative trust.
2837 * @param negativeTrust
2838 * The negative trust, or {@code null} to restore it to the
2840 * @return The preferences
2842 public Preferences setNegativeTrust(Integer negativeTrust) {
2843 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2848 * Returns the trust comment. This is the comment that is set in the web
2849 * of trust when a trust value is assigned to an identity.
2851 * @return The trust comment
2853 public String getTrustComment() {
2854 return options.getStringOption("TrustComment").get();
2858 * Sets the trust comment.
2860 * @param trustComment
2861 * The trust comment, or {@code null} to restore it to the
2863 * @return This preferences
2865 public Preferences setTrustComment(String trustComment) {
2866 options.getStringOption("TrustComment").set(trustComment);
2871 * Returns whether the {@link FcpInterface FCP interface} is currently
2874 * @see FcpInterface#setActive(boolean)
2875 * @return {@code true} if the FCP interface is currently active,
2876 * {@code false} otherwise
2878 public boolean isFcpInterfaceActive() {
2879 return options.getBooleanOption("ActivateFcpInterface").get();
2883 * Sets whether the {@link FcpInterface FCP interface} is currently
2886 * @see FcpInterface#setActive(boolean)
2887 * @param fcpInterfaceActive
2888 * {@code true} to activate the FCP interface, {@code false}
2889 * to deactivate the FCP interface
2890 * @return This preferences object
2892 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2893 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2898 * Returns the action level for which full access to the FCP interface
2901 * @return The action level for which full access to the FCP interface
2904 public FullAccessRequired getFcpFullAccessRequired() {
2905 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2909 * Sets the action level for which full access to the FCP interface is
2912 * @param fcpFullAccessRequired
2914 * @return This preferences
2916 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2917 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2922 * Returns whether Sone should clear its settings on the next restart.
2923 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2924 * to return {@code true} as well!
2926 * @return {@code true} if Sone should clear its settings on the next
2927 * restart, {@code false} otherwise
2929 public boolean isClearOnNextRestart() {
2930 return options.getBooleanOption("ClearOnNextRestart").get();
2934 * Sets whether Sone will clear its settings on the next restart.
2936 * @param clearOnNextRestart
2937 * {@code true} if Sone should clear its settings on the next
2938 * restart, {@code false} otherwise
2939 * @return This preferences
2941 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2942 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2947 * Returns whether Sone should really clear its settings on next
2948 * restart. This is a confirmation option that needs to be set in
2949 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2950 * settings on the next restart.
2952 * @return {@code true} if Sone should really clear its settings on the
2953 * next restart, {@code false} otherwise
2955 public boolean isReallyClearOnNextRestart() {
2956 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2960 * Sets whether Sone should really clear its settings on the next
2963 * @param reallyClearOnNextRestart
2964 * {@code true} if Sone should really clear its settings on
2965 * the next restart, {@code false} otherwise
2966 * @return This preferences
2968 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2969 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);