2 * Sone - Core.java - Copyright © 2010–2012 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Profile.Field;
44 import net.pterodactylus.sone.data.Reply;
45 import net.pterodactylus.sone.data.Sone;
46 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
47 import net.pterodactylus.sone.data.Sone.SoneStatus;
48 import net.pterodactylus.sone.data.TemporaryImage;
49 import net.pterodactylus.sone.data.impl.PostImpl;
50 import net.pterodactylus.sone.fcp.FcpInterface;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.freenet.wot.Identity;
53 import net.pterodactylus.sone.freenet.wot.IdentityListener;
54 import net.pterodactylus.sone.freenet.wot.IdentityManager;
55 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
56 import net.pterodactylus.sone.freenet.wot.Trust;
57 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
58 import net.pterodactylus.sone.main.SonePlugin;
59 import net.pterodactylus.util.config.Configuration;
60 import net.pterodactylus.util.config.ConfigurationException;
61 import net.pterodactylus.util.logging.Logging;
62 import net.pterodactylus.util.number.Numbers;
63 import net.pterodactylus.util.service.AbstractService;
64 import net.pterodactylus.util.thread.Ticker;
65 import net.pterodactylus.util.validation.EqualityValidator;
66 import net.pterodactylus.util.validation.IntegerRangeValidator;
67 import net.pterodactylus.util.validation.OrValidator;
68 import net.pterodactylus.util.validation.Validation;
69 import net.pterodactylus.util.version.Version;
70 import freenet.keys.FreenetURI;
75 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
77 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
80 private static final Logger logger = Logging.getLogger(Core.class);
83 private final Options options = new Options();
85 /** The preferences. */
86 private final Preferences preferences = new Preferences(options);
88 /** The core listener manager. */
89 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
91 /** The configuration. */
92 private Configuration configuration;
94 /** Whether we’re currently saving the configuration. */
95 private boolean storingConfiguration = false;
97 /** The identity manager. */
98 private final IdentityManager identityManager;
100 /** Interface to freenet. */
101 private final FreenetInterface freenetInterface;
103 /** The Sone downloader. */
104 private final SoneDownloader soneDownloader;
106 /** The image inserter. */
107 private final ImageInserter imageInserter;
109 /** Sone downloader thread-pool. */
110 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
112 /** The update checker. */
113 private final UpdateChecker updateChecker;
115 /** The FCP interface. */
116 private volatile FcpInterface fcpInterface;
118 /** The times Sones were followed. */
119 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
121 /** Locked local Sones. */
122 /* synchronize on itself. */
123 private final Set<Sone> lockedSones = new HashSet<Sone>();
125 /** Sone inserters. */
126 /* synchronize access on this on localSones. */
127 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
129 /** Sone rescuers. */
130 /* synchronize access on this on localSones. */
131 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
133 /** All local Sones. */
134 /* synchronize access on this on itself. */
135 private final Map<String, Sone> localSones = new HashMap<String, Sone>();
137 /** All remote Sones. */
138 /* synchronize access on this on itself. */
139 private final Map<String, Sone> remoteSones = new HashMap<String, Sone>();
141 /** All known Sones. */
142 private final Set<String> knownSones = new HashSet<String>();
145 private final Map<String, Post> posts = new HashMap<String, Post>();
147 /** All known posts. */
148 private final Set<String> knownPosts = new HashSet<String>();
151 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
153 /** All known replies. */
154 private final Set<String> knownReplies = new HashSet<String>();
156 /** All bookmarked posts. */
157 /* synchronize access on itself. */
158 private final Set<String> bookmarkedPosts = new HashSet<String>();
160 /** Trusted identities, sorted by own identities. */
161 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
163 /** All known albums. */
164 private final Map<String, Album> albums = new HashMap<String, Album>();
166 /** All known images. */
167 private final Map<String, Image> images = new HashMap<String, Image>();
169 /** All temporary images. */
170 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
172 /** Ticker for threads that mark own elements as known. */
173 private final Ticker localElementTicker = new Ticker();
175 /** The time the configuration was last touched. */
176 private volatile long lastConfigurationUpdate;
179 * Creates a new core.
181 * @param configuration
182 * The configuration of the core
183 * @param freenetInterface
184 * The freenet interface
185 * @param identityManager
186 * The identity manager
188 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
190 this.configuration = configuration;
191 this.freenetInterface = freenetInterface;
192 this.identityManager = identityManager;
193 this.soneDownloader = new SoneDownloader(this, freenetInterface);
194 this.imageInserter = new ImageInserter(this, freenetInterface);
195 this.updateChecker = new UpdateChecker(freenetInterface);
199 // LISTENER MANAGEMENT
203 * Adds a new core listener.
205 * @param coreListener
206 * The listener to add
208 public void addCoreListener(CoreListener coreListener) {
209 coreListenerManager.addListener(coreListener);
213 * Removes a core listener.
215 * @param coreListener
216 * The listener to remove
218 public void removeCoreListener(CoreListener coreListener) {
219 coreListenerManager.removeListener(coreListener);
227 * Sets the configuration to use. This will automatically save the current
228 * configuration to the given configuration.
230 * @param configuration
231 * The new configuration to use
233 public void setConfiguration(Configuration configuration) {
234 this.configuration = configuration;
235 touchConfiguration();
239 * Returns the options used by the core.
241 * @return The options of the core
243 public Preferences getPreferences() {
248 * Returns the identity manager used by the core.
250 * @return The identity manager
252 public IdentityManager getIdentityManager() {
253 return identityManager;
257 * Returns the update checker.
259 * @return The update checker
261 public UpdateChecker getUpdateChecker() {
262 return updateChecker;
266 * Sets the FCP interface to use.
268 * @param fcpInterface
269 * The FCP interface to use
271 public void setFcpInterface(FcpInterface fcpInterface) {
272 this.fcpInterface = fcpInterface;
276 * Returns the Sone rescuer for the given local Sone.
279 * The local Sone to get the rescuer for
280 * @return The Sone rescuer for the given Sone
282 public SoneRescuer getSoneRescuer(Sone sone) {
283 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
284 synchronized (localSones) {
285 SoneRescuer soneRescuer = soneRescuers.get(sone);
286 if (soneRescuer == null) {
287 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
288 soneRescuers.put(sone, soneRescuer);
296 * Returns whether the given Sone is currently locked.
300 * @return {@code true} if the Sone is locked, {@code false} if it is not
302 public boolean isLocked(Sone sone) {
303 synchronized (lockedSones) {
304 return lockedSones.contains(sone);
309 * Returns all Sones, remote and local.
313 public Set<Sone> getSones() {
314 Set<Sone> allSones = new HashSet<Sone>();
315 allSones.addAll(getLocalSones());
316 allSones.addAll(getRemoteSones());
321 * Returns the Sone with the given ID, regardless whether it’s local or
325 * The ID of the Sone to get
326 * @return The Sone with the given ID, or {@code null} if there is no such
329 public Sone getSone(String id) {
330 return getSone(id, true);
334 * Returns the Sone with the given ID, regardless whether it’s local or
338 * The ID of the Sone to get
340 * {@code true} to create a new Sone if none exists,
341 * {@code false} to return {@code null} if a Sone with the given
343 * @return The Sone with the given ID, or {@code null} if there is no such
347 public Sone getSone(String id, boolean create) {
348 if (isLocalSone(id)) {
349 return getLocalSone(id);
351 return getRemoteSone(id, create);
355 * Checks whether the core knows a Sone with the given ID.
359 * @return {@code true} if there is a Sone with the given ID, {@code false}
362 public boolean hasSone(String id) {
363 return isLocalSone(id) || isRemoteSone(id);
367 * Returns whether the given Sone is a local Sone.
370 * The Sone to check for its locality
371 * @return {@code true} if the given Sone is local, {@code false} otherwise
373 public boolean isLocalSone(Sone sone) {
374 synchronized (localSones) {
375 return localSones.containsKey(sone.getId());
380 * Returns whether the given ID is the ID of a local Sone.
383 * The Sone ID to check for its locality
384 * @return {@code true} if the given ID is a local Sone, {@code false}
387 public boolean isLocalSone(String id) {
388 synchronized (localSones) {
389 return localSones.containsKey(id);
394 * Returns all local Sones.
396 * @return All local Sones
398 public Set<Sone> getLocalSones() {
399 synchronized (localSones) {
400 return new HashSet<Sone>(localSones.values());
405 * Returns the local Sone with the given ID.
408 * The ID of the Sone to get
409 * @return The Sone with the given ID
411 public Sone getLocalSone(String id) {
412 return getLocalSone(id, true);
416 * Returns the local Sone with the given ID, optionally creating a new Sone.
421 * {@code true} to create a new Sone if none exists,
422 * {@code false} to return null if none exists
423 * @return The Sone with the given ID, or {@code null}
425 public Sone getLocalSone(String id, boolean create) {
426 synchronized (localSones) {
427 Sone sone = localSones.get(id);
428 if ((sone == null) && create) {
430 localSones.put(id, sone);
437 * Returns all remote Sones.
439 * @return All remote Sones
441 public Set<Sone> getRemoteSones() {
442 synchronized (remoteSones) {
443 return new HashSet<Sone>(remoteSones.values());
448 * Returns the remote Sone with the given ID.
451 * The ID of the remote Sone to get
453 * {@code true} to always create a Sone, {@code false} to return
454 * {@code null} if no Sone with the given ID exists
455 * @return The Sone with the given ID
457 public Sone getRemoteSone(String id, boolean create) {
458 synchronized (remoteSones) {
459 Sone sone = remoteSones.get(id);
460 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
462 remoteSones.put(id, sone);
469 * Returns whether the given Sone is a remote Sone.
473 * @return {@code true} if the given Sone is a remote Sone, {@code false}
476 public boolean isRemoteSone(Sone sone) {
477 synchronized (remoteSones) {
478 return remoteSones.containsKey(sone.getId());
483 * Returns whether the Sone with the given ID is a remote Sone.
486 * The ID of the Sone to check
487 * @return {@code true} if the Sone with the given ID is a remote Sone,
488 * {@code false} otherwise
490 public boolean isRemoteSone(String id) {
491 synchronized (remoteSones) {
492 return remoteSones.containsKey(id);
497 * Returns whether the given Sone has been modified.
500 * The Sone to check for modifications
501 * @return {@code true} if a modification has been detected in the Sone,
502 * {@code false} otherwise
504 public boolean isModifiedSone(Sone sone) {
505 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
509 * Returns the time when the given was first followed by any local Sone.
512 * The Sone to get the time for
513 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
514 * been followed, or {@link Long#MAX_VALUE}
516 public long getSoneFollowingTime(Sone sone) {
517 synchronized (soneFollowingTimes) {
518 if (soneFollowingTimes.containsKey(sone)) {
519 return soneFollowingTimes.get(sone);
521 return Long.MAX_VALUE;
526 * Returns whether the target Sone is trusted by the origin Sone.
532 * @return {@code true} if the target Sone is trusted by the origin Sone
534 public boolean isSoneTrusted(Sone origin, Sone target) {
535 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
536 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
540 * Returns the post with the given ID.
543 * The ID of the post to get
544 * @return The post with the given ID, or a new post with the given ID
546 public Post getPost(String postId) {
547 return getPost(postId, true);
551 * Returns the post with the given ID, optionally creating a new post.
554 * The ID of the post to get
556 * {@code true} it create a new post if no post with the given ID
557 * exists, {@code false} to return {@code null}
558 * @return The post, or {@code null} if there is no such post
561 public Post getPost(String postId, boolean create) {
562 synchronized (posts) {
563 Post post = posts.get(postId);
564 if ((post == null) && create) {
565 post = new PostImpl(postId);
566 posts.put(postId, post);
573 * Returns all posts that have the given Sone as recipient.
575 * @see Post#getRecipient()
577 * The recipient of the posts
578 * @return All posts that have the given Sone as recipient
580 public Set<Post> getDirectedPosts(Sone recipient) {
581 Validation.begin().isNotNull("Recipient", recipient).check();
582 Set<Post> directedPosts = new HashSet<Post>();
583 synchronized (posts) {
584 for (Post post : posts.values()) {
585 if (recipient.equals(post.getRecipient())) {
586 directedPosts.add(post);
590 return directedPosts;
594 * Returns the reply with the given ID. If there is no reply with the given
595 * ID yet, a new one is created.
598 * The ID of the reply to get
601 public PostReply getReply(String replyId) {
602 return getReply(replyId, true);
606 * Returns the reply with the given ID. If there is no reply with the given
607 * ID yet, a new one is created, unless {@code create} is false in which
608 * case {@code null} is returned.
611 * The ID of the reply to get
613 * {@code true} to always return a {@link Reply}, {@code false}
614 * to return {@code null} if no reply can be found
615 * @return The reply, or {@code null} if there is no such reply
617 public PostReply getReply(String replyId, boolean create) {
618 synchronized (replies) {
619 PostReply reply = replies.get(replyId);
620 if (create && (reply == null)) {
621 reply = new PostReply(replyId);
622 replies.put(replyId, reply);
629 * Returns all replies for the given post, order ascending by time.
632 * The post to get all replies for
633 * @return All replies for the given post
635 public List<PostReply> getReplies(Post post) {
636 Set<Sone> sones = getSones();
637 List<PostReply> replies = new ArrayList<PostReply>();
638 for (Sone sone : sones) {
639 for (PostReply reply : sone.getReplies()) {
640 if (reply.getPost().equals(post)) {
645 Collections.sort(replies, Reply.TIME_COMPARATOR);
650 * Returns all Sones that have liked the given post.
653 * The post to get the liking Sones for
654 * @return The Sones that like the given post
656 public Set<Sone> getLikes(Post post) {
657 Set<Sone> sones = new HashSet<Sone>();
658 for (Sone sone : getSones()) {
659 if (sone.getLikedPostIds().contains(post.getId())) {
667 * Returns all Sones that have liked the given reply.
670 * The reply to get the liking Sones for
671 * @return The Sones that like the given reply
673 public Set<Sone> getLikes(PostReply reply) {
674 Set<Sone> sones = new HashSet<Sone>();
675 for (Sone sone : getSones()) {
676 if (sone.getLikedReplyIds().contains(reply.getId())) {
684 * Returns whether the given post is bookmarked.
688 * @return {@code true} if the given post is bookmarked, {@code false}
691 public boolean isBookmarked(Post post) {
692 return isPostBookmarked(post.getId());
696 * Returns whether the post with the given ID is bookmarked.
699 * The ID of the post to check
700 * @return {@code true} if the post with the given ID is bookmarked,
701 * {@code false} otherwise
703 public boolean isPostBookmarked(String id) {
704 synchronized (bookmarkedPosts) {
705 return bookmarkedPosts.contains(id);
710 * Returns all currently known bookmarked posts.
712 * @return All bookmarked posts
714 public Set<Post> getBookmarkedPosts() {
715 Set<Post> posts = new HashSet<Post>();
716 synchronized (bookmarkedPosts) {
717 for (String bookmarkedPostId : bookmarkedPosts) {
718 Post post = getPost(bookmarkedPostId, false);
728 * Returns the album with the given ID, creating a new album if no album
729 * with the given ID can be found.
732 * The ID of the album
733 * @return The album with the given ID
735 public Album getAlbum(String albumId) {
736 return getAlbum(albumId, true);
740 * Returns the album with the given ID, optionally creating a new album if
741 * an album with the given ID can not be found.
744 * The ID of the album
746 * {@code true} to create a new album if none exists for the
748 * @return The album with the given ID, or {@code null} if no album with the
749 * given ID exists and {@code create} is {@code false}
751 public Album getAlbum(String albumId, boolean create) {
752 synchronized (albums) {
753 Album album = albums.get(albumId);
754 if (create && (album == null)) {
755 album = new Album(albumId);
756 albums.put(albumId, album);
763 * Returns the image with the given ID, creating it if necessary.
766 * The ID of the image
767 * @return The image with the given ID
769 public Image getImage(String imageId) {
770 return getImage(imageId, true);
774 * Returns the image with the given ID, optionally creating it if it does
778 * The ID of the image
780 * {@code true} to create an image if none exists with the given
782 * @return The image with the given ID, or {@code null} if none exists and
785 public Image getImage(String imageId, boolean create) {
786 synchronized (images) {
787 Image image = images.get(imageId);
788 if (create && (image == null)) {
789 image = new Image(imageId);
790 images.put(imageId, image);
797 * Returns the temporary image with the given ID.
800 * The ID of the temporary image
801 * @return The temporary image, or {@code null} if there is no temporary
802 * image with the given ID
804 public TemporaryImage getTemporaryImage(String imageId) {
805 synchronized (temporaryImages) {
806 return temporaryImages.get(imageId);
815 * Locks the given Sone. A locked Sone will not be inserted by
816 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
822 public void lockSone(Sone sone) {
823 synchronized (lockedSones) {
824 if (lockedSones.add(sone)) {
825 coreListenerManager.fireSoneLocked(sone);
831 * Unlocks the given Sone.
833 * @see #lockSone(Sone)
837 public void unlockSone(Sone sone) {
838 synchronized (lockedSones) {
839 if (lockedSones.remove(sone)) {
840 coreListenerManager.fireSoneUnlocked(sone);
846 * Adds a local Sone from the given own identity.
849 * The own identity to create a Sone from
850 * @return The added (or already existing) Sone
852 public Sone addLocalSone(OwnIdentity ownIdentity) {
853 if (ownIdentity == null) {
854 logger.log(Level.WARNING, "Given OwnIdentity is null!");
857 synchronized (localSones) {
860 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
861 } catch (MalformedURLException mue1) {
862 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
865 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
866 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
868 /* TODO - load posts ’n stuff */
869 localSones.put(ownIdentity.getId(), sone);
870 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
871 soneInserter.addSoneInsertListener(this);
872 soneInserters.put(sone, soneInserter);
873 sone.setStatus(SoneStatus.idle);
875 soneInserter.start();
881 * Creates a new Sone for the given own identity.
884 * The own identity to create a Sone for
885 * @return The created Sone
887 public Sone createSone(OwnIdentity ownIdentity) {
889 ownIdentity.addContext("Sone");
890 } catch (WebOfTrustException wote1) {
891 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity), wote1);
894 Sone sone = addLocalSone(ownIdentity);
895 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
896 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
897 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
898 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
899 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
900 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
902 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
903 touchConfiguration();
908 * Adds the Sone of the given identity.
911 * The identity whose Sone to add
912 * @return The added or already existing Sone
914 public Sone addRemoteSone(Identity identity) {
915 if (identity == null) {
916 logger.log(Level.WARNING, "Given Identity is null!");
919 synchronized (remoteSones) {
920 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
921 boolean newSone = sone.getRequestUri() == null;
922 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
923 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
925 synchronized (knownSones) {
926 newSone = !knownSones.contains(sone.getId());
928 sone.setKnown(!newSone);
930 coreListenerManager.fireNewSoneFound(sone);
931 for (Sone localSone : getLocalSones()) {
932 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
933 followSone(localSone, sone);
938 soneDownloader.addSone(sone);
939 soneDownloaders.execute(new Runnable() {
942 @SuppressWarnings("synthetic-access")
944 soneDownloader.fetchSone(sone, sone.getRequestUri());
953 * Lets the given local Sone follow the Sone with the given ID.
956 * The local Sone that should follow another Sone
958 * The ID of the Sone to follow
960 public void followSone(Sone sone, String soneId) {
961 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
962 Sone followedSone = getSone(soneId, true);
963 if (followedSone == null) {
964 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
967 followSone(sone, getSone(soneId));
971 * Lets the given local Sone follow the other given Sone. If the given Sone
972 * was not followed by any local Sone before, this will mark all elements of
973 * the followed Sone as read that have been created before the current
977 * The local Sone that should follow the other Sone
978 * @param followedSone
979 * The Sone that should be followed
981 public void followSone(Sone sone, Sone followedSone) {
982 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
983 sone.addFriend(followedSone.getId());
984 synchronized (soneFollowingTimes) {
985 if (!soneFollowingTimes.containsKey(followedSone)) {
986 long now = System.currentTimeMillis();
987 soneFollowingTimes.put(followedSone, now);
988 for (Post post : followedSone.getPosts()) {
989 if (post.getTime() < now) {
993 for (PostReply reply : followedSone.getReplies()) {
994 if (reply.getTime() < now) {
995 markReplyKnown(reply);
1000 touchConfiguration();
1004 * Lets the given local Sone unfollow the Sone with the given ID.
1007 * The local Sone that should unfollow another Sone
1009 * The ID of the Sone being unfollowed
1011 public void unfollowSone(Sone sone, String soneId) {
1012 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1013 unfollowSone(sone, getSone(soneId, false));
1017 * Lets the given local Sone unfollow the other given Sone. If the given
1018 * local Sone is the last local Sone that followed the given Sone, its
1019 * following time will be removed.
1022 * The local Sone that should unfollow another Sone
1023 * @param unfollowedSone
1024 * The Sone being unfollowed
1026 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1027 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1028 sone.removeFriend(unfollowedSone.getId());
1029 boolean unfollowedSoneStillFollowed = false;
1030 for (Sone localSone : getLocalSones()) {
1031 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1033 if (!unfollowedSoneStillFollowed) {
1034 synchronized (soneFollowingTimes) {
1035 soneFollowingTimes.remove(unfollowedSone);
1038 touchConfiguration();
1042 * Retrieves the trust relationship from the origin to the target. If the
1043 * trust relationship can not be retrieved, {@code null} is returned.
1045 * @see Identity#getTrust(OwnIdentity)
1047 * The origin of the trust tree
1049 * The target of the trust
1050 * @return The trust relationship
1052 public Trust getTrust(Sone origin, Sone target) {
1053 if (!isLocalSone(origin)) {
1054 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
1057 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1061 * Sets the trust value of the given origin Sone for the target Sone.
1068 * The trust value (from {@code -100} to {@code 100})
1070 public void setTrust(Sone origin, Sone target, int trustValue) {
1071 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();
1073 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1074 } catch (WebOfTrustException wote1) {
1075 logger.log(Level.WARNING, String.format("Could not set trust for Sone: %s", target), wote1);
1080 * Removes any trust assignment for the given target Sone.
1087 public void removeTrust(Sone origin, Sone target) {
1088 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1090 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1091 } catch (WebOfTrustException wote1) {
1092 logger.log(Level.WARNING, String.format("Could not remove trust for Sone: %s", target), wote1);
1097 * Assigns the configured positive trust value for the given target.
1104 public void trustSone(Sone origin, Sone target) {
1105 setTrust(origin, target, preferences.getPositiveTrust());
1109 * Assigns the configured negative trust value for the given target.
1116 public void distrustSone(Sone origin, Sone target) {
1117 setTrust(origin, target, preferences.getNegativeTrust());
1121 * Removes the trust assignment for the given target.
1128 public void untrustSone(Sone origin, Sone target) {
1129 removeTrust(origin, target);
1133 * Updates the stored Sone with the given Sone.
1138 public void updateSone(Sone sone) {
1139 updateSone(sone, false);
1143 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1144 * {@code true}, an older Sone than the current Sone can be given to restore
1148 * The Sone to update
1149 * @param soneRescueMode
1150 * {@code true} if the stored Sone should be updated regardless
1151 * of the age of the given Sone
1153 public void updateSone(Sone sone, boolean soneRescueMode) {
1154 if (hasSone(sone.getId())) {
1155 Sone storedSone = getSone(sone.getId());
1156 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1157 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1160 synchronized (posts) {
1161 if (!soneRescueMode) {
1162 for (Post post : storedSone.getPosts()) {
1163 posts.remove(post.getId());
1164 if (!sone.getPosts().contains(post)) {
1165 coreListenerManager.firePostRemoved(post);
1169 List<Post> storedPosts = storedSone.getPosts();
1170 synchronized (knownPosts) {
1171 for (Post post : sone.getPosts()) {
1172 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1173 if (!storedPosts.contains(post)) {
1174 if (post.getTime() < getSoneFollowingTime(sone)) {
1175 knownPosts.add(post.getId());
1176 } else if (!knownPosts.contains(post.getId())) {
1177 sone.setKnown(false);
1178 coreListenerManager.fireNewPostFound(post);
1181 posts.put(post.getId(), post);
1185 synchronized (replies) {
1186 if (!soneRescueMode) {
1187 for (PostReply reply : storedSone.getReplies()) {
1188 replies.remove(reply.getId());
1189 if (!sone.getReplies().contains(reply)) {
1190 coreListenerManager.fireReplyRemoved(reply);
1194 Set<PostReply> storedReplies = storedSone.getReplies();
1195 synchronized (knownReplies) {
1196 for (PostReply reply : sone.getReplies()) {
1197 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1198 if (!storedReplies.contains(reply)) {
1199 if (reply.getTime() < getSoneFollowingTime(sone)) {
1200 knownReplies.add(reply.getId());
1201 } else if (!knownReplies.contains(reply.getId())) {
1202 reply.setKnown(false);
1203 coreListenerManager.fireNewReplyFound(reply);
1206 replies.put(reply.getId(), reply);
1210 synchronized (albums) {
1211 synchronized (images) {
1212 for (Album album : storedSone.getAlbums()) {
1213 albums.remove(album.getId());
1214 for (Image image : album.getImages()) {
1215 images.remove(image.getId());
1218 for (Album album : sone.getAlbums()) {
1219 albums.put(album.getId(), album);
1220 for (Image image : album.getImages()) {
1221 images.put(image.getId(), image);
1226 synchronized (storedSone) {
1227 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1228 storedSone.setTime(sone.getTime());
1230 storedSone.setClient(sone.getClient());
1231 storedSone.setProfile(sone.getProfile());
1232 if (soneRescueMode) {
1233 for (Post post : sone.getPosts()) {
1234 storedSone.addPost(post);
1236 for (PostReply reply : sone.getReplies()) {
1237 storedSone.addReply(reply);
1239 for (String likedPostId : sone.getLikedPostIds()) {
1240 storedSone.addLikedPostId(likedPostId);
1242 for (String likedReplyId : sone.getLikedReplyIds()) {
1243 storedSone.addLikedReplyId(likedReplyId);
1245 for (Album album : sone.getAlbums()) {
1246 storedSone.addAlbum(album);
1249 storedSone.setPosts(sone.getPosts());
1250 storedSone.setReplies(sone.getReplies());
1251 storedSone.setLikePostIds(sone.getLikedPostIds());
1252 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1253 storedSone.setAlbums(sone.getAlbums());
1255 storedSone.setLatestEdition(sone.getLatestEdition());
1261 * Deletes the given Sone. This will remove the Sone from the
1262 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1263 * and remove the context from its identity.
1266 * The Sone to delete
1268 public void deleteSone(Sone sone) {
1269 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1270 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1273 synchronized (localSones) {
1274 if (!localSones.containsKey(sone.getId())) {
1275 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1278 localSones.remove(sone.getId());
1279 SoneInserter soneInserter = soneInserters.remove(sone);
1280 soneInserter.removeSoneInsertListener(this);
1281 soneInserter.stop();
1284 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1285 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1286 } catch (WebOfTrustException wote1) {
1287 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1290 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1291 } catch (ConfigurationException ce1) {
1292 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1297 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1298 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1301 * The Sone to mark as known
1303 public void markSoneKnown(Sone sone) {
1304 if (!sone.isKnown()) {
1305 sone.setKnown(true);
1306 synchronized (knownSones) {
1307 knownSones.add(sone.getId());
1309 coreListenerManager.fireMarkSoneKnown(sone);
1310 touchConfiguration();
1315 * Loads and updates the given Sone from the configuration. If any error is
1316 * encountered, loading is aborted and the given Sone is not changed.
1319 * The Sone to load and update
1321 public void loadSone(Sone sone) {
1322 if (!isLocalSone(sone)) {
1323 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1327 /* initialize options. */
1328 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1329 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1330 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1331 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1332 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1333 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1336 String sonePrefix = "Sone/" + sone.getId();
1337 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1338 if (soneTime == null) {
1339 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1342 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1345 Profile profile = new Profile(sone);
1346 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1347 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1348 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1349 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1350 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1351 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1353 /* load profile fields. */
1355 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1356 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1357 if (fieldName == null) {
1360 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1361 profile.addField(fieldName).setValue(fieldValue);
1365 Set<Post> posts = new HashSet<Post>();
1367 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1368 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1369 if (postId == null) {
1372 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1373 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1374 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1375 if ((postTime == 0) || (postText == null)) {
1376 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1379 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1380 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1381 post.setRecipient(getSone(postRecipientId));
1387 Set<PostReply> replies = new HashSet<PostReply>();
1389 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1390 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1391 if (replyId == null) {
1394 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1395 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1396 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1397 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1398 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1401 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1404 /* load post likes. */
1405 Set<String> likedPostIds = new HashSet<String>();
1407 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1408 if (likedPostId == null) {
1411 likedPostIds.add(likedPostId);
1414 /* load reply likes. */
1415 Set<String> likedReplyIds = new HashSet<String>();
1417 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1418 if (likedReplyId == null) {
1421 likedReplyIds.add(likedReplyId);
1425 Set<String> friends = new HashSet<String>();
1427 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1428 if (friendId == null) {
1431 friends.add(friendId);
1435 List<Album> topLevelAlbums = new ArrayList<Album>();
1436 int albumCounter = 0;
1438 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1439 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1440 if (albumId == null) {
1443 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1444 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1445 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1446 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1447 if ((albumTitle == null) || (albumDescription == null)) {
1448 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1451 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1452 if (albumParentId != null) {
1453 Album parentAlbum = getAlbum(albumParentId, false);
1454 if (parentAlbum == null) {
1455 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1458 parentAlbum.addAlbum(album);
1460 if (!topLevelAlbums.contains(album)) {
1461 topLevelAlbums.add(album);
1467 int imageCounter = 0;
1469 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1470 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1471 if (imageId == null) {
1474 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1475 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1476 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1477 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1478 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1479 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1480 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1481 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1482 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1485 Album album = getAlbum(albumId, false);
1486 if (album == null) {
1487 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1490 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1491 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1492 album.addImage(image);
1496 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1497 if (avatarId != null) {
1498 profile.setAvatar(getImage(avatarId, false));
1502 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1503 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1504 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1505 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1506 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1507 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1509 /* if we’re still here, Sone was loaded successfully. */
1510 synchronized (sone) {
1511 sone.setTime(soneTime);
1512 sone.setProfile(profile);
1513 sone.setPosts(posts);
1514 sone.setReplies(replies);
1515 sone.setLikePostIds(likedPostIds);
1516 sone.setLikeReplyIds(likedReplyIds);
1517 for (String friendId : friends) {
1518 followSone(sone, friendId);
1520 sone.setAlbums(topLevelAlbums);
1521 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1523 synchronized (knownSones) {
1524 for (String friend : friends) {
1525 knownSones.add(friend);
1528 synchronized (knownPosts) {
1529 for (Post post : posts) {
1530 knownPosts.add(post.getId());
1533 synchronized (knownReplies) {
1534 for (PostReply reply : replies) {
1535 knownReplies.add(reply.getId());
1541 * Creates a new post.
1544 * The Sone that creates the post
1546 * The text of the post
1547 * @return The created post
1549 public Post createPost(Sone sone, String text) {
1550 return createPost(sone, System.currentTimeMillis(), text);
1554 * Creates a new post.
1557 * The Sone that creates the post
1559 * The time of the post
1561 * The text of the post
1562 * @return The created post
1564 public Post createPost(Sone sone, long time, String text) {
1565 return createPost(sone, null, time, text);
1569 * Creates a new post.
1572 * The Sone that creates the post
1574 * The recipient Sone, or {@code null} if this post does not have
1577 * The text of the post
1578 * @return The created post
1580 public Post createPost(Sone sone, Sone recipient, String text) {
1581 return createPost(sone, recipient, System.currentTimeMillis(), text);
1585 * Creates a new post.
1588 * The Sone that creates the post
1590 * The recipient Sone, or {@code null} if this post does not have
1593 * The time of the post
1595 * The text of the post
1596 * @return The created post
1598 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1599 if (!isLocalSone(sone)) {
1600 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1603 final Post post = new PostImpl(sone, time, text);
1604 if (recipient != null) {
1605 post.setRecipient(recipient);
1607 synchronized (posts) {
1608 posts.put(post.getId(), post);
1610 coreListenerManager.fireNewPostFound(post);
1612 touchConfiguration();
1613 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1620 markPostKnown(post);
1622 }, "Mark " + post + " read.");
1627 * Deletes the given post.
1630 * The post to delete
1632 public void deletePost(Post post) {
1633 if (!isLocalSone(post.getSone())) {
1634 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1637 post.getSone().removePost(post);
1638 synchronized (posts) {
1639 posts.remove(post.getId());
1641 coreListenerManager.firePostRemoved(post);
1642 markPostKnown(post);
1643 touchConfiguration();
1647 * Marks the given post as known, if it is currently not a known post
1648 * (according to {@link Post#isKnown()}).
1651 * The post to mark as known
1653 public void markPostKnown(Post post) {
1654 post.setKnown(true);
1655 synchronized (knownPosts) {
1656 coreListenerManager.fireMarkPostKnown(post);
1657 if (knownPosts.add(post.getId())) {
1658 touchConfiguration();
1661 for (PostReply reply : getReplies(post)) {
1662 markReplyKnown(reply);
1667 * Bookmarks the given post.
1670 * The post to bookmark
1672 public void bookmark(Post post) {
1673 bookmarkPost(post.getId());
1677 * Bookmarks the post with the given ID.
1680 * The ID of the post to bookmark
1682 public void bookmarkPost(String id) {
1683 synchronized (bookmarkedPosts) {
1684 bookmarkedPosts.add(id);
1689 * Removes the given post from the bookmarks.
1692 * The post to unbookmark
1694 public void unbookmark(Post post) {
1695 unbookmarkPost(post.getId());
1699 * Removes the post with the given ID from the bookmarks.
1702 * The ID of the post to unbookmark
1704 public void unbookmarkPost(String id) {
1705 synchronized (bookmarkedPosts) {
1706 bookmarkedPosts.remove(id);
1711 * Creates a new reply.
1714 * The Sone that creates the reply
1716 * The post that this reply refers to
1718 * The text of the reply
1719 * @return The created reply
1721 public PostReply createReply(Sone sone, Post post, String text) {
1722 return createReply(sone, post, System.currentTimeMillis(), text);
1726 * Creates a new reply.
1729 * The Sone that creates the reply
1731 * The post that this reply refers to
1733 * The time of the reply
1735 * The text of the reply
1736 * @return The created reply
1738 public PostReply createReply(Sone sone, Post post, long time, String text) {
1739 if (!isLocalSone(sone)) {
1740 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1743 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1744 synchronized (replies) {
1745 replies.put(reply.getId(), reply);
1747 synchronized (knownReplies) {
1748 coreListenerManager.fireNewReplyFound(reply);
1750 sone.addReply(reply);
1751 touchConfiguration();
1752 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1759 markReplyKnown(reply);
1761 }, "Mark " + reply + " read.");
1766 * Deletes the given reply.
1769 * The reply to delete
1771 public void deleteReply(PostReply reply) {
1772 Sone sone = reply.getSone();
1773 if (!isLocalSone(sone)) {
1774 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1777 synchronized (replies) {
1778 replies.remove(reply.getId());
1780 synchronized (knownReplies) {
1781 markReplyKnown(reply);
1782 knownReplies.remove(reply.getId());
1784 sone.removeReply(reply);
1785 touchConfiguration();
1789 * Marks the given reply as known, if it is currently not a known reply
1790 * (according to {@link Reply#isKnown()}).
1793 * The reply to mark as known
1795 public void markReplyKnown(PostReply reply) {
1796 reply.setKnown(true);
1797 synchronized (knownReplies) {
1798 coreListenerManager.fireMarkReplyKnown(reply);
1799 if (knownReplies.add(reply.getId())) {
1800 touchConfiguration();
1806 * Creates a new top-level album for the given Sone.
1809 * The Sone to create the album for
1810 * @return The new album
1812 public Album createAlbum(Sone sone) {
1813 return createAlbum(sone, null);
1817 * Creates a new album for the given Sone.
1820 * The Sone to create the album for
1822 * The parent of the album (may be {@code null} to create a
1824 * @return The new album
1826 public Album createAlbum(Sone sone, Album parent) {
1827 Album album = new Album();
1828 synchronized (albums) {
1829 albums.put(album.getId(), album);
1831 album.setSone(sone);
1832 if (parent != null) {
1833 parent.addAlbum(album);
1835 sone.addAlbum(album);
1841 * Deletes the given album. The owner of the album has to be a local Sone,
1842 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1845 * The album to remove
1847 public void deleteAlbum(Album album) {
1848 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1849 if (!album.isEmpty()) {
1852 if (album.getParent() == null) {
1853 album.getSone().removeAlbum(album);
1855 album.getParent().removeAlbum(album);
1857 synchronized (albums) {
1858 albums.remove(album.getId());
1860 saveSone(album.getSone());
1864 * Creates a new image.
1867 * The Sone creating the image
1869 * The album the image will be inserted into
1870 * @param temporaryImage
1871 * The temporary image to create the image from
1872 * @return The newly created image
1874 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1875 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();
1876 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1877 album.addImage(image);
1878 synchronized (images) {
1879 images.put(image.getId(), image);
1881 imageInserter.insertImage(temporaryImage, image);
1886 * Deletes the given image. This method will also delete a matching
1889 * @see #deleteTemporaryImage(TemporaryImage)
1891 * The image to delete
1893 public void deleteImage(Image image) {
1894 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
1895 deleteTemporaryImage(image.getId());
1896 image.getAlbum().removeImage(image);
1897 synchronized (images) {
1898 images.remove(image.getId());
1900 saveSone(image.getSone());
1904 * Creates a new temporary image.
1907 * The MIME type of the temporary image
1909 * The encoded data of the image
1910 * @return The temporary image
1912 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1913 TemporaryImage temporaryImage = new TemporaryImage();
1914 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1915 synchronized (temporaryImages) {
1916 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1918 return temporaryImage;
1922 * Deletes the given temporary image.
1924 * @param temporaryImage
1925 * The temporary image to delete
1927 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1928 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1929 deleteTemporaryImage(temporaryImage.getId());
1933 * Deletes the temporary image with the given ID.
1936 * The ID of the temporary image to delete
1938 public void deleteTemporaryImage(String imageId) {
1939 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1940 synchronized (temporaryImages) {
1941 temporaryImages.remove(imageId);
1943 Image image = getImage(imageId, false);
1944 if (image != null) {
1945 imageInserter.cancelImageInsert(image);
1950 * Notifies the core that the configuration, either of the core or of a
1951 * single local Sone, has changed, and that the configuration should be
1954 public void touchConfiguration() {
1955 lastConfigurationUpdate = System.currentTimeMillis();
1966 public void serviceStart() {
1967 loadConfiguration();
1968 updateChecker.addUpdateListener(this);
1969 updateChecker.start();
1976 public void serviceRun() {
1977 long lastSaved = System.currentTimeMillis();
1978 while (!shouldStop()) {
1980 long now = System.currentTimeMillis();
1981 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1982 for (Sone localSone : getLocalSones()) {
1983 saveSone(localSone);
1985 saveConfiguration();
1995 public void serviceStop() {
1996 synchronized (localSones) {
1997 for (SoneInserter soneInserter : soneInserters.values()) {
1998 soneInserter.removeSoneInsertListener(this);
1999 soneInserter.stop();
2002 updateChecker.stop();
2003 updateChecker.removeUpdateListener(this);
2004 soneDownloader.stop();
2012 * Saves the given Sone. This will persist all local settings for the given
2013 * Sone, such as the friends list and similar, private options.
2018 private synchronized void saveSone(Sone sone) {
2019 if (!isLocalSone(sone)) {
2020 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
2023 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2024 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
2028 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
2030 /* save Sone into configuration. */
2031 String sonePrefix = "Sone/" + sone.getId();
2032 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2033 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2036 Profile profile = sone.getProfile();
2037 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2038 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2039 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2040 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2041 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2042 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2043 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2045 /* save profile fields. */
2046 int fieldCounter = 0;
2047 for (Field profileField : profile.getFields()) {
2048 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2049 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2050 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2052 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2055 int postCounter = 0;
2056 for (Post post : sone.getPosts()) {
2057 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2058 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2059 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2060 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2061 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2063 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2066 int replyCounter = 0;
2067 for (PostReply reply : sone.getReplies()) {
2068 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2069 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2070 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2071 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2072 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2074 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2076 /* save post likes. */
2077 int postLikeCounter = 0;
2078 for (String postId : sone.getLikedPostIds()) {
2079 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2081 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2083 /* save reply likes. */
2084 int replyLikeCounter = 0;
2085 for (String replyId : sone.getLikedReplyIds()) {
2086 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2088 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2091 int friendCounter = 0;
2092 for (String friendId : sone.getFriends()) {
2093 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2095 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2097 /* save albums. first, collect in a flat structure, top-level first. */
2098 List<Album> albums = sone.getAllAlbums();
2100 int albumCounter = 0;
2101 for (Album album : albums) {
2102 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2103 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2104 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2105 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2106 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2107 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2109 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2112 int imageCounter = 0;
2113 for (Album album : albums) {
2114 for (Image image : album.getImages()) {
2115 if (!image.isInserted()) {
2118 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2119 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2120 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2121 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2122 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2123 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2124 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2125 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2126 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2129 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2132 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2133 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2134 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2135 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2136 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2137 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2139 configuration.save();
2141 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2143 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2144 } catch (ConfigurationException ce1) {
2145 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2146 } catch (WebOfTrustException wote1) {
2147 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2152 * Saves the current options.
2154 private void saveConfiguration() {
2155 synchronized (configuration) {
2156 if (storingConfiguration) {
2157 logger.log(Level.FINE, "Already storing configuration…");
2160 storingConfiguration = true;
2163 /* store the options first. */
2165 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2166 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2167 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2168 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2169 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2170 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2171 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2172 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2173 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2174 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2175 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2176 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2177 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2178 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2179 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2181 /* save known Sones. */
2182 int soneCounter = 0;
2183 synchronized (knownSones) {
2184 for (String knownSoneId : knownSones) {
2185 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2187 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2190 /* save Sone following times. */
2192 synchronized (soneFollowingTimes) {
2193 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2194 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2195 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2198 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2201 /* save known posts. */
2202 int postCounter = 0;
2203 synchronized (knownPosts) {
2204 for (String knownPostId : knownPosts) {
2205 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2207 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2210 /* save known replies. */
2211 int replyCounter = 0;
2212 synchronized (knownReplies) {
2213 for (String knownReplyId : knownReplies) {
2214 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2216 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2219 /* save bookmarked posts. */
2220 int bookmarkedPostCounter = 0;
2221 synchronized (bookmarkedPosts) {
2222 for (String bookmarkedPostId : bookmarkedPosts) {
2223 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2226 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2229 configuration.save();
2231 } catch (ConfigurationException ce1) {
2232 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2234 synchronized (configuration) {
2235 storingConfiguration = false;
2241 * Loads the configuration.
2243 @SuppressWarnings("unchecked")
2244 private void loadConfiguration() {
2245 /* create options. */
2246 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2249 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2250 SoneInserter.setInsertionDelay(newValue);
2254 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2255 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2256 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2257 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2258 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2259 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2260 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2261 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2262 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2265 @SuppressWarnings("synthetic-access")
2266 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2267 fcpInterface.setActive(newValue);
2270 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2273 @SuppressWarnings("synthetic-access")
2274 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2275 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2279 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2280 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2281 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2283 /* read options from configuration. */
2284 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2285 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2286 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2287 options.getBooleanOption("ClearOnNextRestart").set(null);
2288 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2289 if (clearConfiguration) {
2290 /* stop loading the configuration. */
2294 loadConfigurationValue("InsertionDelay");
2295 loadConfigurationValue("PostsPerPage");
2296 loadConfigurationValue("ImagesPerPage");
2297 loadConfigurationValue("CharactersPerPost");
2298 loadConfigurationValue("PostCutOffLength");
2299 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2300 loadConfigurationValue("PositiveTrust");
2301 loadConfigurationValue("NegativeTrust");
2302 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2303 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2304 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2305 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2307 /* load known Sones. */
2308 int soneCounter = 0;
2310 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2311 if (knownSoneId == null) {
2314 synchronized (knownSones) {
2315 knownSones.add(knownSoneId);
2319 /* load Sone following times. */
2322 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2323 if (soneId == null) {
2326 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2327 Sone followedSone = getSone(soneId);
2328 if (followedSone == null) {
2329 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2331 synchronized (soneFollowingTimes) {
2332 soneFollowingTimes.put(getSone(soneId), time);
2338 /* load known posts. */
2339 int postCounter = 0;
2341 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2342 if (knownPostId == null) {
2345 synchronized (knownPosts) {
2346 knownPosts.add(knownPostId);
2350 /* load known replies. */
2351 int replyCounter = 0;
2353 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2354 if (knownReplyId == null) {
2357 synchronized (knownReplies) {
2358 knownReplies.add(knownReplyId);
2362 /* load bookmarked posts. */
2363 int bookmarkedPostCounter = 0;
2365 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2366 if (bookmarkedPostId == null) {
2369 synchronized (bookmarkedPosts) {
2370 bookmarkedPosts.add(bookmarkedPostId);
2377 * Loads an {@link Integer} configuration value for the option with the
2378 * given name, logging validation failures.
2381 * The name of the option to load
2383 private void loadConfigurationValue(String optionName) {
2385 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2386 } catch (IllegalArgumentException iae1) {
2387 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2392 * Generate a Sone URI from the given URI and latest edition.
2395 * The URI to derive the Sone URI from
2396 * @return The derived URI
2398 private FreenetURI getSoneUri(String uriString) {
2400 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2402 } catch (MalformedURLException mue1) {
2403 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2409 // INTERFACE IdentityListener
2416 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2417 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2418 if (ownIdentity.hasContext("Sone")) {
2419 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2420 addLocalSone(ownIdentity);
2428 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2429 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2430 trustedIdentities.remove(ownIdentity);
2437 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2438 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2439 trustedIdentities.get(ownIdentity).add(identity);
2440 addRemoteSone(identity);
2447 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2448 new Thread(new Runnable() {
2451 @SuppressWarnings("synthetic-access")
2453 Sone sone = getRemoteSone(identity.getId(), false);
2454 sone.setIdentity(identity);
2455 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2456 soneDownloader.addSone(sone);
2457 soneDownloader.fetchSone(sone);
2466 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2467 trustedIdentities.get(ownIdentity).remove(identity);
2468 boolean foundIdentity = false;
2469 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2470 if (trustedIdentity.getKey().equals(ownIdentity)) {
2473 if (trustedIdentity.getValue().contains(identity)) {
2474 foundIdentity = true;
2477 if (foundIdentity) {
2478 /* some local identity still trusts this identity, don’t remove. */
2481 Sone sone = getSone(identity.getId(), false);
2483 /* TODO - we don’t have the Sone anymore. should this happen? */
2486 synchronized (posts) {
2487 synchronized (knownPosts) {
2488 for (Post post : sone.getPosts()) {
2489 posts.remove(post.getId());
2490 coreListenerManager.firePostRemoved(post);
2494 synchronized (replies) {
2495 synchronized (knownReplies) {
2496 for (PostReply reply : sone.getReplies()) {
2497 replies.remove(reply.getId());
2498 coreListenerManager.fireReplyRemoved(reply);
2502 synchronized (remoteSones) {
2503 remoteSones.remove(identity.getId());
2505 coreListenerManager.fireSoneRemoved(sone);
2509 // INTERFACE UpdateListener
2516 public void updateFound(Version version, long releaseTime, long latestEdition) {
2517 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2521 // INTERFACE ImageInsertListener
2528 public void insertStarted(Sone sone) {
2529 coreListenerManager.fireSoneInserting(sone);
2536 public void insertFinished(Sone sone, long insertDuration) {
2537 coreListenerManager.fireSoneInserted(sone, insertDuration);
2544 public void insertAborted(Sone sone, Throwable cause) {
2545 coreListenerManager.fireSoneInsertAborted(sone, cause);
2549 // SONEINSERTLISTENER METHODS
2556 public void imageInsertStarted(Image image) {
2557 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2558 coreListenerManager.fireImageInsertStarted(image);
2565 public void imageInsertAborted(Image image) {
2566 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2567 coreListenerManager.fireImageInsertAborted(image);
2574 public void imageInsertFinished(Image image, FreenetURI key) {
2575 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2576 image.setKey(key.toString());
2577 deleteTemporaryImage(image.getId());
2578 saveSone(image.getSone());
2579 coreListenerManager.fireImageInsertFinished(image);
2586 public void imageInsertFailed(Image image, Throwable cause) {
2587 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2588 coreListenerManager.fireImageInsertFailed(image, cause);
2592 * Convenience interface for external classes that want to access the core’s
2595 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2597 public static class Preferences {
2599 /** The wrapped options. */
2600 private final Options options;
2603 * Creates a new preferences object wrapped around the given options.
2606 * The options to wrap
2608 public Preferences(Options options) {
2609 this.options = options;
2613 * Returns the insertion delay.
2615 * @return The insertion delay
2617 public int getInsertionDelay() {
2618 return options.getIntegerOption("InsertionDelay").get();
2622 * Validates the given insertion delay.
2624 * @param insertionDelay
2625 * The insertion delay to validate
2626 * @return {@code true} if the given insertion delay was valid,
2627 * {@code false} otherwise
2629 public boolean validateInsertionDelay(Integer insertionDelay) {
2630 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2634 * Sets the insertion delay
2636 * @param insertionDelay
2637 * The new insertion delay, or {@code null} to restore it to
2639 * @return This preferences
2641 public Preferences setInsertionDelay(Integer insertionDelay) {
2642 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2647 * Returns the number of posts to show per page.
2649 * @return The number of posts to show per page
2651 public int getPostsPerPage() {
2652 return options.getIntegerOption("PostsPerPage").get();
2656 * Validates the number of posts per page.
2658 * @param postsPerPage
2659 * The number of posts per page
2660 * @return {@code true} if the number of posts per page was valid,
2661 * {@code false} otherwise
2663 public boolean validatePostsPerPage(Integer postsPerPage) {
2664 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2668 * Sets the number of posts to show per page.
2670 * @param postsPerPage
2671 * The number of posts to show per page
2672 * @return This preferences object
2674 public Preferences setPostsPerPage(Integer postsPerPage) {
2675 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2680 * Returns the number of images to show per page.
2682 * @return The number of images to show per page
2684 public int getImagesPerPage() {
2685 return options.getIntegerOption("ImagesPerPage").get();
2689 * Validates the number of images per page.
2691 * @param imagesPerPage
2692 * The number of images per page
2693 * @return {@code true} if the number of images per page was valid,
2694 * {@code false} otherwise
2696 public boolean validateImagesPerPage(Integer imagesPerPage) {
2697 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2701 * Sets the number of images per page.
2703 * @param imagesPerPage
2704 * The number of images per page
2705 * @return This preferences object
2707 public Preferences setImagesPerPage(Integer imagesPerPage) {
2708 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2713 * Returns the number of characters per post, or <code>-1</code> if the
2714 * posts should not be cut off.
2716 * @return The numbers of characters per post
2718 public int getCharactersPerPost() {
2719 return options.getIntegerOption("CharactersPerPost").get();
2723 * Validates the number of characters per post.
2725 * @param charactersPerPost
2726 * The number of characters per post
2727 * @return {@code true} if the number of characters per post was valid,
2728 * {@code false} otherwise
2730 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2731 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2735 * Sets the number of characters per post.
2737 * @param charactersPerPost
2738 * The number of characters per post, or <code>-1</code> to
2739 * not cut off the posts
2740 * @return This preferences objects
2742 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2743 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2748 * Returns the number of characters the shortened post should have.
2750 * @return The number of characters of the snippet
2752 public int getPostCutOffLength() {
2753 return options.getIntegerOption("PostCutOffLength").get();
2757 * Validates the number of characters after which to cut off the post.
2759 * @param postCutOffLength
2760 * The number of characters of the snippet
2761 * @return {@code true} if the number of characters of the snippet is
2762 * valid, {@code false} otherwise
2764 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2765 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2769 * Sets the number of characters the shortened post should have.
2771 * @param postCutOffLength
2772 * The number of characters of the snippet
2773 * @return This preferences
2775 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2776 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2781 * Returns whether Sone requires full access to be even visible.
2783 * @return {@code true} if Sone requires full access, {@code false}
2786 public boolean isRequireFullAccess() {
2787 return options.getBooleanOption("RequireFullAccess").get();
2791 * Sets whether Sone requires full access to be even visible.
2793 * @param requireFullAccess
2794 * {@code true} if Sone requires full access, {@code false}
2797 public void setRequireFullAccess(Boolean requireFullAccess) {
2798 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2802 * Returns the positive trust.
2804 * @return The positive trust
2806 public int getPositiveTrust() {
2807 return options.getIntegerOption("PositiveTrust").get();
2811 * Validates the positive trust.
2813 * @param positiveTrust
2814 * The positive trust to validate
2815 * @return {@code true} if the positive trust was valid, {@code false}
2818 public boolean validatePositiveTrust(Integer positiveTrust) {
2819 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2823 * Sets the positive trust.
2825 * @param positiveTrust
2826 * The new positive trust, or {@code null} to restore it to
2828 * @return This preferences
2830 public Preferences setPositiveTrust(Integer positiveTrust) {
2831 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2836 * Returns the negative trust.
2838 * @return The negative trust
2840 public int getNegativeTrust() {
2841 return options.getIntegerOption("NegativeTrust").get();
2845 * Validates the negative trust.
2847 * @param negativeTrust
2848 * The negative trust to validate
2849 * @return {@code true} if the negative trust was valid, {@code false}
2852 public boolean validateNegativeTrust(Integer negativeTrust) {
2853 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2857 * Sets the negative trust.
2859 * @param negativeTrust
2860 * The negative trust, or {@code null} to restore it to the
2862 * @return The preferences
2864 public Preferences setNegativeTrust(Integer negativeTrust) {
2865 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2870 * Returns the trust comment. This is the comment that is set in the web
2871 * of trust when a trust value is assigned to an identity.
2873 * @return The trust comment
2875 public String getTrustComment() {
2876 return options.getStringOption("TrustComment").get();
2880 * Sets the trust comment.
2882 * @param trustComment
2883 * The trust comment, or {@code null} to restore it to the
2885 * @return This preferences
2887 public Preferences setTrustComment(String trustComment) {
2888 options.getStringOption("TrustComment").set(trustComment);
2893 * Returns whether the {@link FcpInterface FCP interface} is currently
2896 * @see FcpInterface#setActive(boolean)
2897 * @return {@code true} if the FCP interface is currently active,
2898 * {@code false} otherwise
2900 public boolean isFcpInterfaceActive() {
2901 return options.getBooleanOption("ActivateFcpInterface").get();
2905 * Sets whether the {@link FcpInterface FCP interface} is currently
2908 * @see FcpInterface#setActive(boolean)
2909 * @param fcpInterfaceActive
2910 * {@code true} to activate the FCP interface, {@code false}
2911 * to deactivate the FCP interface
2912 * @return This preferences object
2914 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2915 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2920 * Returns the action level for which full access to the FCP interface
2923 * @return The action level for which full access to the FCP interface
2926 public FullAccessRequired getFcpFullAccessRequired() {
2927 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2931 * Sets the action level for which full access to the FCP interface is
2934 * @param fcpFullAccessRequired
2936 * @return This preferences
2938 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2939 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2944 * Returns whether Sone should clear its settings on the next restart.
2945 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2946 * to return {@code true} as well!
2948 * @return {@code true} if Sone should clear its settings on the next
2949 * restart, {@code false} otherwise
2951 public boolean isClearOnNextRestart() {
2952 return options.getBooleanOption("ClearOnNextRestart").get();
2956 * Sets whether Sone will clear its settings on the next restart.
2958 * @param clearOnNextRestart
2959 * {@code true} if Sone should clear its settings on the next
2960 * restart, {@code false} otherwise
2961 * @return This preferences
2963 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2964 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2969 * Returns whether Sone should really clear its settings on next
2970 * restart. This is a confirmation option that needs to be set in
2971 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2972 * settings on the next restart.
2974 * @return {@code true} if Sone should really clear its settings on the
2975 * next restart, {@code false} otherwise
2977 public boolean isReallyClearOnNextRestart() {
2978 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2982 * Sets whether Sone should really clear its settings on the next
2985 * @param reallyClearOnNextRestart
2986 * {@code true} if Sone should really clear its settings on
2987 * the next restart, {@code false} otherwise
2988 * @return This preferences
2990 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2991 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);