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());
2178 /* save known Sones. */
2179 int soneCounter = 0;
2180 synchronized (knownSones) {
2181 for (String knownSoneId : knownSones) {
2182 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2184 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2187 /* save Sone following times. */
2189 synchronized (soneFollowingTimes) {
2190 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2191 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2192 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2195 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2198 /* save known posts. */
2199 int postCounter = 0;
2200 synchronized (knownPosts) {
2201 for (String knownPostId : knownPosts) {
2202 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2204 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2207 /* save known replies. */
2208 int replyCounter = 0;
2209 synchronized (knownReplies) {
2210 for (String knownReplyId : knownReplies) {
2211 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2213 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2216 /* save bookmarked posts. */
2217 int bookmarkedPostCounter = 0;
2218 synchronized (bookmarkedPosts) {
2219 for (String bookmarkedPostId : bookmarkedPosts) {
2220 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2223 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2226 configuration.save();
2228 } catch (ConfigurationException ce1) {
2229 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2231 synchronized (configuration) {
2232 storingConfiguration = false;
2238 * Loads the configuration.
2240 @SuppressWarnings("unchecked")
2241 private void loadConfiguration() {
2242 /* create options. */
2243 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2246 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2247 SoneInserter.setInsertionDelay(newValue);
2251 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2252 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2253 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2254 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2255 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2256 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2257 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2258 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2259 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2262 @SuppressWarnings("synthetic-access")
2263 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2264 fcpInterface.setActive(newValue);
2267 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2270 @SuppressWarnings("synthetic-access")
2271 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2272 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2277 loadConfigurationValue("InsertionDelay");
2278 loadConfigurationValue("PostsPerPage");
2279 loadConfigurationValue("ImagesPerPage");
2280 loadConfigurationValue("CharactersPerPost");
2281 loadConfigurationValue("PostCutOffLength");
2282 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2283 loadConfigurationValue("PositiveTrust");
2284 loadConfigurationValue("NegativeTrust");
2285 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2286 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2287 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2289 /* load known Sones. */
2290 int soneCounter = 0;
2292 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2293 if (knownSoneId == null) {
2296 synchronized (knownSones) {
2297 knownSones.add(knownSoneId);
2301 /* load Sone following times. */
2304 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2305 if (soneId == null) {
2308 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2309 Sone followedSone = getSone(soneId);
2310 if (followedSone == null) {
2311 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2313 synchronized (soneFollowingTimes) {
2314 soneFollowingTimes.put(getSone(soneId), time);
2320 /* load known posts. */
2321 int postCounter = 0;
2323 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2324 if (knownPostId == null) {
2327 synchronized (knownPosts) {
2328 knownPosts.add(knownPostId);
2332 /* load known replies. */
2333 int replyCounter = 0;
2335 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2336 if (knownReplyId == null) {
2339 synchronized (knownReplies) {
2340 knownReplies.add(knownReplyId);
2344 /* load bookmarked posts. */
2345 int bookmarkedPostCounter = 0;
2347 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2348 if (bookmarkedPostId == null) {
2351 synchronized (bookmarkedPosts) {
2352 bookmarkedPosts.add(bookmarkedPostId);
2359 * Loads an {@link Integer} configuration value for the option with the
2360 * given name, logging validation failures.
2363 * The name of the option to load
2365 private void loadConfigurationValue(String optionName) {
2367 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2368 } catch (IllegalArgumentException iae1) {
2369 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2374 * Generate a Sone URI from the given URI and latest edition.
2377 * The URI to derive the Sone URI from
2378 * @return The derived URI
2380 private FreenetURI getSoneUri(String uriString) {
2382 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2384 } catch (MalformedURLException mue1) {
2385 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2391 // INTERFACE IdentityListener
2398 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2399 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2400 if (ownIdentity.hasContext("Sone")) {
2401 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2402 addLocalSone(ownIdentity);
2410 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2411 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2412 trustedIdentities.remove(ownIdentity);
2419 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2420 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2421 trustedIdentities.get(ownIdentity).add(identity);
2422 addRemoteSone(identity);
2429 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2430 new Thread(new Runnable() {
2433 @SuppressWarnings("synthetic-access")
2435 Sone sone = getRemoteSone(identity.getId(), false);
2436 sone.setIdentity(identity);
2437 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2438 soneDownloader.addSone(sone);
2439 soneDownloader.fetchSone(sone);
2448 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2449 trustedIdentities.get(ownIdentity).remove(identity);
2450 boolean foundIdentity = false;
2451 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2452 if (trustedIdentity.getKey().equals(ownIdentity)) {
2455 if (trustedIdentity.getValue().contains(identity)) {
2456 foundIdentity = true;
2459 if (foundIdentity) {
2460 /* some local identity still trusts this identity, don’t remove. */
2463 Sone sone = getSone(identity.getId(), false);
2465 /* TODO - we don’t have the Sone anymore. should this happen? */
2468 synchronized (posts) {
2469 synchronized (knownPosts) {
2470 for (Post post : sone.getPosts()) {
2471 posts.remove(post.getId());
2472 coreListenerManager.firePostRemoved(post);
2476 synchronized (replies) {
2477 synchronized (knownReplies) {
2478 for (PostReply reply : sone.getReplies()) {
2479 replies.remove(reply.getId());
2480 coreListenerManager.fireReplyRemoved(reply);
2484 synchronized (remoteSones) {
2485 remoteSones.remove(identity.getId());
2487 coreListenerManager.fireSoneRemoved(sone);
2491 // INTERFACE UpdateListener
2498 public void updateFound(Version version, long releaseTime, long latestEdition) {
2499 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2503 // INTERFACE ImageInsertListener
2510 public void insertStarted(Sone sone) {
2511 coreListenerManager.fireSoneInserting(sone);
2518 public void insertFinished(Sone sone, long insertDuration) {
2519 coreListenerManager.fireSoneInserted(sone, insertDuration);
2526 public void insertAborted(Sone sone, Throwable cause) {
2527 coreListenerManager.fireSoneInsertAborted(sone, cause);
2531 // SONEINSERTLISTENER METHODS
2538 public void imageInsertStarted(Image image) {
2539 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2540 coreListenerManager.fireImageInsertStarted(image);
2547 public void imageInsertAborted(Image image) {
2548 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2549 coreListenerManager.fireImageInsertAborted(image);
2556 public void imageInsertFinished(Image image, FreenetURI key) {
2557 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2558 image.setKey(key.toString());
2559 deleteTemporaryImage(image.getId());
2560 saveSone(image.getSone());
2561 coreListenerManager.fireImageInsertFinished(image);
2568 public void imageInsertFailed(Image image, Throwable cause) {
2569 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2570 coreListenerManager.fireImageInsertFailed(image, cause);
2574 * Convenience interface for external classes that want to access the core’s
2577 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2579 public static class Preferences {
2581 /** The wrapped options. */
2582 private final Options options;
2585 * Creates a new preferences object wrapped around the given options.
2588 * The options to wrap
2590 public Preferences(Options options) {
2591 this.options = options;
2595 * Returns the insertion delay.
2597 * @return The insertion delay
2599 public int getInsertionDelay() {
2600 return options.getIntegerOption("InsertionDelay").get();
2604 * Validates the given insertion delay.
2606 * @param insertionDelay
2607 * The insertion delay to validate
2608 * @return {@code true} if the given insertion delay was valid,
2609 * {@code false} otherwise
2611 public boolean validateInsertionDelay(Integer insertionDelay) {
2612 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2616 * Sets the insertion delay
2618 * @param insertionDelay
2619 * The new insertion delay, or {@code null} to restore it to
2621 * @return This preferences
2623 public Preferences setInsertionDelay(Integer insertionDelay) {
2624 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2629 * Returns the number of posts to show per page.
2631 * @return The number of posts to show per page
2633 public int getPostsPerPage() {
2634 return options.getIntegerOption("PostsPerPage").get();
2638 * Validates the number of posts per page.
2640 * @param postsPerPage
2641 * The number of posts per page
2642 * @return {@code true} if the number of posts per page was valid,
2643 * {@code false} otherwise
2645 public boolean validatePostsPerPage(Integer postsPerPage) {
2646 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2650 * Sets the number of posts to show per page.
2652 * @param postsPerPage
2653 * The number of posts to show per page
2654 * @return This preferences object
2656 public Preferences setPostsPerPage(Integer postsPerPage) {
2657 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2662 * Returns the number of images to show per page.
2664 * @return The number of images to show per page
2666 public int getImagesPerPage() {
2667 return options.getIntegerOption("ImagesPerPage").get();
2671 * Validates the number of images per page.
2673 * @param imagesPerPage
2674 * The number of images per page
2675 * @return {@code true} if the number of images per page was valid,
2676 * {@code false} otherwise
2678 public boolean validateImagesPerPage(Integer imagesPerPage) {
2679 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2683 * Sets the number of images per page.
2685 * @param imagesPerPage
2686 * The number of images per page
2687 * @return This preferences object
2689 public Preferences setImagesPerPage(Integer imagesPerPage) {
2690 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2695 * Returns the number of characters per post, or <code>-1</code> if the
2696 * posts should not be cut off.
2698 * @return The numbers of characters per post
2700 public int getCharactersPerPost() {
2701 return options.getIntegerOption("CharactersPerPost").get();
2705 * Validates the number of characters per post.
2707 * @param charactersPerPost
2708 * The number of characters per post
2709 * @return {@code true} if the number of characters per post was valid,
2710 * {@code false} otherwise
2712 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2713 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2717 * Sets the number of characters per post.
2719 * @param charactersPerPost
2720 * The number of characters per post, or <code>-1</code> to
2721 * not cut off the posts
2722 * @return This preferences objects
2724 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2725 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2730 * Returns the number of characters the shortened post should have.
2732 * @return The number of characters of the snippet
2734 public int getPostCutOffLength() {
2735 return options.getIntegerOption("PostCutOffLength").get();
2739 * Validates the number of characters after which to cut off the post.
2741 * @param postCutOffLength
2742 * The number of characters of the snippet
2743 * @return {@code true} if the number of characters of the snippet is
2744 * valid, {@code false} otherwise
2746 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2747 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2751 * Sets the number of characters the shortened post should have.
2753 * @param postCutOffLength
2754 * The number of characters of the snippet
2755 * @return This preferences
2757 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2758 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2763 * Returns whether Sone requires full access to be even visible.
2765 * @return {@code true} if Sone requires full access, {@code false}
2768 public boolean isRequireFullAccess() {
2769 return options.getBooleanOption("RequireFullAccess").get();
2773 * Sets whether Sone requires full access to be even visible.
2775 * @param requireFullAccess
2776 * {@code true} if Sone requires full access, {@code false}
2779 public void setRequireFullAccess(Boolean requireFullAccess) {
2780 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2784 * Returns the positive trust.
2786 * @return The positive trust
2788 public int getPositiveTrust() {
2789 return options.getIntegerOption("PositiveTrust").get();
2793 * Validates the positive trust.
2795 * @param positiveTrust
2796 * The positive trust to validate
2797 * @return {@code true} if the positive trust was valid, {@code false}
2800 public boolean validatePositiveTrust(Integer positiveTrust) {
2801 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2805 * Sets the positive trust.
2807 * @param positiveTrust
2808 * The new positive trust, or {@code null} to restore it to
2810 * @return This preferences
2812 public Preferences setPositiveTrust(Integer positiveTrust) {
2813 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2818 * Returns the negative trust.
2820 * @return The negative trust
2822 public int getNegativeTrust() {
2823 return options.getIntegerOption("NegativeTrust").get();
2827 * Validates the negative trust.
2829 * @param negativeTrust
2830 * The negative trust to validate
2831 * @return {@code true} if the negative trust was valid, {@code false}
2834 public boolean validateNegativeTrust(Integer negativeTrust) {
2835 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2839 * Sets the negative trust.
2841 * @param negativeTrust
2842 * The negative trust, or {@code null} to restore it to the
2844 * @return The preferences
2846 public Preferences setNegativeTrust(Integer negativeTrust) {
2847 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2852 * Returns the trust comment. This is the comment that is set in the web
2853 * of trust when a trust value is assigned to an identity.
2855 * @return The trust comment
2857 public String getTrustComment() {
2858 return options.getStringOption("TrustComment").get();
2862 * Sets the trust comment.
2864 * @param trustComment
2865 * The trust comment, or {@code null} to restore it to the
2867 * @return This preferences
2869 public Preferences setTrustComment(String trustComment) {
2870 options.getStringOption("TrustComment").set(trustComment);
2875 * Returns whether the {@link FcpInterface FCP interface} is currently
2878 * @see FcpInterface#setActive(boolean)
2879 * @return {@code true} if the FCP interface is currently active,
2880 * {@code false} otherwise
2882 public boolean isFcpInterfaceActive() {
2883 return options.getBooleanOption("ActivateFcpInterface").get();
2887 * Sets whether the {@link FcpInterface FCP interface} is currently
2890 * @see FcpInterface#setActive(boolean)
2891 * @param fcpInterfaceActive
2892 * {@code true} to activate the FCP interface, {@code false}
2893 * to deactivate the FCP interface
2894 * @return This preferences object
2896 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2897 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2902 * Returns the action level for which full access to the FCP interface
2905 * @return The action level for which full access to the FCP interface
2908 public FullAccessRequired getFcpFullAccessRequired() {
2909 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2913 * Sets the action level for which full access to the FCP interface is
2916 * @param fcpFullAccessRequired
2918 * @return This preferences
2920 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2921 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);