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.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
39 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
41 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
42 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
43 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
44 import net.pterodactylus.sone.core.event.PostRemovedEvent;
45 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
46 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
47 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
48 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
49 import net.pterodactylus.sone.core.event.SoneLockedEvent;
50 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
52 import net.pterodactylus.sone.data.Album;
53 import net.pterodactylus.sone.data.Client;
54 import net.pterodactylus.sone.data.Image;
55 import net.pterodactylus.sone.data.Post;
56 import net.pterodactylus.sone.data.PostReply;
57 import net.pterodactylus.sone.data.Profile;
58 import net.pterodactylus.sone.data.Profile.Field;
59 import net.pterodactylus.sone.data.Reply;
60 import net.pterodactylus.sone.data.Sone;
61 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
62 import net.pterodactylus.sone.data.Sone.SoneStatus;
63 import net.pterodactylus.sone.data.TemporaryImage;
64 import net.pterodactylus.sone.data.impl.PostImpl;
65 import net.pterodactylus.sone.fcp.FcpInterface;
66 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
67 import net.pterodactylus.sone.freenet.wot.Identity;
68 import net.pterodactylus.sone.freenet.wot.IdentityListener;
69 import net.pterodactylus.sone.freenet.wot.IdentityManager;
70 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
71 import net.pterodactylus.sone.main.SonePlugin;
72 import net.pterodactylus.util.config.Configuration;
73 import net.pterodactylus.util.config.ConfigurationException;
74 import net.pterodactylus.util.logging.Logging;
75 import net.pterodactylus.util.number.Numbers;
76 import net.pterodactylus.util.service.AbstractService;
77 import net.pterodactylus.util.thread.NamedThreadFactory;
78 import net.pterodactylus.util.thread.Ticker;
79 import net.pterodactylus.util.validation.EqualityValidator;
80 import net.pterodactylus.util.validation.IntegerRangeValidator;
81 import net.pterodactylus.util.validation.OrValidator;
82 import net.pterodactylus.util.validation.Validation;
83 import net.pterodactylus.util.version.Version;
85 import com.google.common.base.Predicate;
86 import com.google.common.collect.Collections2;
87 import com.google.common.eventbus.EventBus;
88 import com.google.inject.Inject;
90 import freenet.keys.FreenetURI;
95 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
97 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
100 private static final Logger logger = Logging.getLogger(Core.class);
102 /** The start time. */
103 private final long startupTime = System.currentTimeMillis();
106 private final Options options = new Options();
108 /** The preferences. */
109 private final Preferences preferences = new Preferences(options);
111 /** The core listener manager. */
112 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
114 /** The event bus. */
115 private final EventBus eventBus;
117 /** The configuration. */
118 private Configuration configuration;
120 /** Whether we’re currently saving the configuration. */
121 private boolean storingConfiguration = false;
123 /** The identity manager. */
124 private final IdentityManager identityManager;
126 /** Interface to freenet. */
127 private final FreenetInterface freenetInterface;
129 /** The Sone downloader. */
130 private final SoneDownloader soneDownloader;
132 /** The image inserter. */
133 private final ImageInserter imageInserter;
135 /** Sone downloader thread-pool. */
136 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
138 /** The update checker. */
139 private final UpdateChecker updateChecker;
141 /** The trust updater. */
142 private final WebOfTrustUpdater webOfTrustUpdater;
144 /** The FCP interface. */
145 private volatile FcpInterface fcpInterface;
147 /** The times Sones were followed. */
148 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
150 /** Locked local Sones. */
151 /* synchronize on itself. */
152 private final Set<Sone> lockedSones = new HashSet<Sone>();
154 /** Sone inserters. */
155 /* synchronize access on this on sones. */
156 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
158 /** Sone rescuers. */
159 /* synchronize access on this on sones. */
160 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
163 /* synchronize access on this on itself. */
164 private final Map<String, Sone> sones = new HashMap<String, Sone>();
166 /** All known Sones. */
167 private final Set<String> knownSones = new HashSet<String>();
170 private final Map<String, Post> posts = new HashMap<String, Post>();
172 /** All known posts. */
173 private final Set<String> knownPosts = new HashSet<String>();
176 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
178 /** All known replies. */
179 private final Set<String> knownReplies = new HashSet<String>();
181 /** All bookmarked posts. */
182 /* synchronize access on itself. */
183 private final Set<String> bookmarkedPosts = new HashSet<String>();
185 /** Trusted identities, sorted by own identities. */
186 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
188 /** All known albums. */
189 private final Map<String, Album> albums = new HashMap<String, Album>();
191 /** All known images. */
192 private final Map<String, Image> images = new HashMap<String, Image>();
194 /** All temporary images. */
195 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
197 /** Ticker for threads that mark own elements as known. */
198 private final Ticker localElementTicker = new Ticker();
200 /** The time the configuration was last touched. */
201 private volatile long lastConfigurationUpdate;
204 * Creates a new core.
206 * @param configuration
207 * The configuration of the core
208 * @param freenetInterface
209 * The freenet interface
210 * @param identityManager
211 * The identity manager
212 * @param webOfTrustUpdater
213 * The WebOfTrust updater
218 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
220 this.configuration = configuration;
221 this.freenetInterface = freenetInterface;
222 this.identityManager = identityManager;
223 this.soneDownloader = new SoneDownloader(this, freenetInterface);
224 this.imageInserter = new ImageInserter(this, freenetInterface);
225 this.updateChecker = new UpdateChecker(freenetInterface);
226 this.webOfTrustUpdater = webOfTrustUpdater;
227 this.eventBus = eventBus;
231 // LISTENER MANAGEMENT
235 * Adds a new core listener.
237 * @param coreListener
238 * The listener to add
240 public void addCoreListener(CoreListener coreListener) {
241 coreListenerManager.addListener(coreListener);
245 * Removes a core listener.
247 * @param coreListener
248 * The listener to remove
250 public void removeCoreListener(CoreListener coreListener) {
251 coreListenerManager.removeListener(coreListener);
259 * Returns the time Sone was started.
261 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
263 public long getStartupTime() {
268 * Sets the configuration to use. This will automatically save the current
269 * configuration to the given configuration.
271 * @param configuration
272 * The new configuration to use
274 public void setConfiguration(Configuration configuration) {
275 this.configuration = configuration;
276 touchConfiguration();
280 * Returns the options used by the core.
282 * @return The options of the core
284 public Preferences getPreferences() {
289 * Returns the identity manager used by the core.
291 * @return The identity manager
293 public IdentityManager getIdentityManager() {
294 return identityManager;
298 * Returns the update checker.
300 * @return The update checker
302 public UpdateChecker getUpdateChecker() {
303 return updateChecker;
307 * Sets the FCP interface to use.
309 * @param fcpInterface
310 * The FCP interface to use
312 public void setFcpInterface(FcpInterface fcpInterface) {
313 this.fcpInterface = fcpInterface;
317 * Returns the Sone rescuer for the given local Sone.
320 * The local Sone to get the rescuer for
321 * @return The Sone rescuer for the given Sone
323 public SoneRescuer getSoneRescuer(Sone sone) {
324 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
325 synchronized (sones) {
326 SoneRescuer soneRescuer = soneRescuers.get(sone);
327 if (soneRescuer == null) {
328 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
329 soneRescuers.put(sone, soneRescuer);
337 * Returns whether the given Sone is currently locked.
341 * @return {@code true} if the Sone is locked, {@code false} if it is not
343 public boolean isLocked(Sone sone) {
344 synchronized (lockedSones) {
345 return lockedSones.contains(sone);
350 * Returns all Sones, remote and local.
354 public Set<Sone> getSones() {
355 return new HashSet<Sone>(sones.values());
359 * Returns the Sone with the given ID, regardless whether it’s local or
363 * The ID of the Sone to get
364 * @return The Sone with the given ID, or {@code null} if there is no such
367 public Sone getSone(String id) {
368 return getSone(id, true);
372 * Returns the Sone with the given ID, regardless whether it’s local or
376 * The ID of the Sone to get
378 * {@code true} to create a new Sone if none exists,
379 * {@code false} to return {@code null} if a Sone with the given
381 * @return The Sone with the given ID, or {@code null} if there is no such
385 public Sone getSone(String id, boolean create) {
386 synchronized (sones) {
387 if (!sones.containsKey(id)) {
388 Sone sone = new Sone(id, false);
391 return sones.get(id);
396 * Checks whether the core knows a Sone with the given ID.
400 * @return {@code true} if there is a Sone with the given ID, {@code false}
403 public boolean hasSone(String id) {
404 synchronized (sones) {
405 return sones.containsKey(id);
410 * Returns all local Sones.
412 * @return All local Sones
414 public Collection<Sone> getLocalSones() {
415 synchronized (sones) {
416 return Collections2.filter(sones.values(), new Predicate<Sone>() {
419 public boolean apply(Sone sone) {
420 return sone.isLocal();
427 * Returns the local Sone with the given ID, optionally creating a new Sone.
432 * {@code true} to create a new Sone if none exists,
433 * {@code false} to return null if none exists
434 * @return The Sone with the given ID, or {@code null}
436 public Sone getLocalSone(String id, boolean create) {
437 synchronized (sones) {
438 Sone sone = sones.get(id);
439 if ((sone == null) && create) {
440 sone = new Sone(id, true);
443 if ((sone != null) && !sone.isLocal()) {
444 sone = new Sone(id, true);
452 * Returns all remote Sones.
454 * @return All remote Sones
456 public Collection<Sone> getRemoteSones() {
457 synchronized (sones) {
458 return Collections2.filter(sones.values(), new Predicate<Sone>() {
461 public boolean apply(Sone sone) {
462 return !sone.isLocal();
469 * Returns the remote Sone with the given ID.
472 * The ID of the remote Sone to get
474 * {@code true} to always create a Sone, {@code false} to return
475 * {@code null} if no Sone with the given ID exists
476 * @return The Sone with the given ID
478 public Sone getRemoteSone(String id, boolean create) {
479 synchronized (sones) {
480 Sone sone = sones.get(id);
481 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
482 sone = new Sone(id, false);
490 * Returns whether the given Sone has been modified.
493 * The Sone to check for modifications
494 * @return {@code true} if a modification has been detected in the Sone,
495 * {@code false} otherwise
497 public boolean isModifiedSone(Sone sone) {
498 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
502 * Returns the time when the given was first followed by any local Sone.
505 * The Sone to get the time for
506 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
507 * been followed, or {@link Long#MAX_VALUE}
509 public long getSoneFollowingTime(Sone sone) {
510 synchronized (soneFollowingTimes) {
511 if (soneFollowingTimes.containsKey(sone)) {
512 return soneFollowingTimes.get(sone);
514 return Long.MAX_VALUE;
519 * Returns whether the target Sone is trusted by the origin Sone.
525 * @return {@code true} if the target Sone is trusted by the origin Sone
527 public boolean isSoneTrusted(Sone origin, Sone target) {
528 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
529 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
533 * Returns the post with the given ID.
536 * The ID of the post to get
537 * @return The post with the given ID, or a new post with the given ID
539 public Post getPost(String postId) {
540 return getPost(postId, true);
544 * Returns the post with the given ID, optionally creating a new post.
547 * The ID of the post to get
549 * {@code true} it create a new post if no post with the given ID
550 * exists, {@code false} to return {@code null}
551 * @return The post, or {@code null} if there is no such post
554 public Post getPost(String postId, boolean create) {
555 synchronized (posts) {
556 Post post = posts.get(postId);
557 if ((post == null) && create) {
558 post = new PostImpl(postId);
559 posts.put(postId, post);
566 * Returns all posts that have the given Sone as recipient.
568 * @see Post#getRecipient()
570 * The recipient of the posts
571 * @return All posts that have the given Sone as recipient
573 public Set<Post> getDirectedPosts(Sone recipient) {
574 Validation.begin().isNotNull("Recipient", recipient).check();
575 Set<Post> directedPosts = new HashSet<Post>();
576 synchronized (posts) {
577 for (Post post : posts.values()) {
578 if (recipient.equals(post.getRecipient())) {
579 directedPosts.add(post);
583 return directedPosts;
587 * Returns the reply with the given ID. If there is no reply with the given
588 * ID yet, a new one is created, unless {@code create} is false in which
589 * case {@code null} is returned.
592 * The ID of the reply to get
594 * {@code true} to always return a {@link Reply}, {@code false}
595 * to return {@code null} if no reply can be found
596 * @return The reply, or {@code null} if there is no such reply
598 public PostReply getPostReply(String replyId, boolean create) {
599 synchronized (replies) {
600 PostReply reply = replies.get(replyId);
601 if (create && (reply == null)) {
602 reply = new PostReply(replyId);
603 replies.put(replyId, reply);
610 * Returns all replies for the given post, order ascending by time.
613 * The post to get all replies for
614 * @return All replies for the given post
616 public List<PostReply> getReplies(Post post) {
617 Set<Sone> sones = getSones();
618 List<PostReply> replies = new ArrayList<PostReply>();
619 for (Sone sone : sones) {
620 for (PostReply reply : sone.getReplies()) {
621 if (reply.getPost().equals(post)) {
626 Collections.sort(replies, Reply.TIME_COMPARATOR);
631 * Returns all Sones that have liked the given post.
634 * The post to get the liking Sones for
635 * @return The Sones that like the given post
637 public Set<Sone> getLikes(Post post) {
638 Set<Sone> sones = new HashSet<Sone>();
639 for (Sone sone : getSones()) {
640 if (sone.getLikedPostIds().contains(post.getId())) {
648 * Returns all Sones that have liked the given reply.
651 * The reply to get the liking Sones for
652 * @return The Sones that like the given reply
654 public Set<Sone> getLikes(PostReply reply) {
655 Set<Sone> sones = new HashSet<Sone>();
656 for (Sone sone : getSones()) {
657 if (sone.getLikedReplyIds().contains(reply.getId())) {
665 * Returns whether the given post is bookmarked.
669 * @return {@code true} if the given post is bookmarked, {@code false}
672 public boolean isBookmarked(Post post) {
673 return isPostBookmarked(post.getId());
677 * Returns whether the post with the given ID is bookmarked.
680 * The ID of the post to check
681 * @return {@code true} if the post with the given ID is bookmarked,
682 * {@code false} otherwise
684 public boolean isPostBookmarked(String id) {
685 synchronized (bookmarkedPosts) {
686 return bookmarkedPosts.contains(id);
691 * Returns all currently known bookmarked posts.
693 * @return All bookmarked posts
695 public Set<Post> getBookmarkedPosts() {
696 Set<Post> posts = new HashSet<Post>();
697 synchronized (bookmarkedPosts) {
698 for (String bookmarkedPostId : bookmarkedPosts) {
699 Post post = getPost(bookmarkedPostId, false);
709 * Returns the album with the given ID, creating a new album if no album
710 * with the given ID can be found.
713 * The ID of the album
714 * @return The album with the given ID
716 public Album getAlbum(String albumId) {
717 return getAlbum(albumId, true);
721 * Returns the album with the given ID, optionally creating a new album if
722 * an album with the given ID can not be found.
725 * The ID of the album
727 * {@code true} to create a new album if none exists for the
729 * @return The album with the given ID, or {@code null} if no album with the
730 * given ID exists and {@code create} is {@code false}
732 public Album getAlbum(String albumId, boolean create) {
733 synchronized (albums) {
734 Album album = albums.get(albumId);
735 if (create && (album == null)) {
736 album = new Album(albumId);
737 albums.put(albumId, album);
744 * Returns the image with the given ID, creating it if necessary.
747 * The ID of the image
748 * @return The image with the given ID
750 public Image getImage(String imageId) {
751 return getImage(imageId, true);
755 * Returns the image with the given ID, optionally creating it if it does
759 * The ID of the image
761 * {@code true} to create an image if none exists with the given
763 * @return The image with the given ID, or {@code null} if none exists and
766 public Image getImage(String imageId, boolean create) {
767 synchronized (images) {
768 Image image = images.get(imageId);
769 if (create && (image == null)) {
770 image = new Image(imageId);
771 images.put(imageId, image);
778 * Returns the temporary image with the given ID.
781 * The ID of the temporary image
782 * @return The temporary image, or {@code null} if there is no temporary
783 * image with the given ID
785 public TemporaryImage getTemporaryImage(String imageId) {
786 synchronized (temporaryImages) {
787 return temporaryImages.get(imageId);
796 * Locks the given Sone. A locked Sone will not be inserted by
797 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
803 public void lockSone(Sone sone) {
804 synchronized (lockedSones) {
805 if (lockedSones.add(sone)) {
806 eventBus.post(new SoneLockedEvent(sone));
812 * Unlocks the given Sone.
814 * @see #lockSone(Sone)
818 public void unlockSone(Sone sone) {
819 synchronized (lockedSones) {
820 if (lockedSones.remove(sone)) {
821 eventBus.post(new SoneUnlockedEvent(sone));
827 * Adds a local Sone from the given own identity.
830 * The own identity to create a Sone from
831 * @return The added (or already existing) Sone
833 public Sone addLocalSone(OwnIdentity ownIdentity) {
834 if (ownIdentity == null) {
835 logger.log(Level.WARNING, "Given OwnIdentity is null!");
838 synchronized (sones) {
841 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
842 } catch (MalformedURLException mue1) {
843 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
846 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
847 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
849 /* TODO - load posts ’n stuff */
850 sones.put(ownIdentity.getId(), sone);
851 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
852 soneInserter.addSoneInsertListener(this);
853 soneInserters.put(sone, soneInserter);
854 sone.setStatus(SoneStatus.idle);
856 soneInserter.start();
862 * Creates a new Sone for the given own identity.
865 * The own identity to create a Sone for
866 * @return The created Sone
868 public Sone createSone(OwnIdentity ownIdentity) {
869 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
870 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
873 Sone sone = addLocalSone(ownIdentity);
874 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
875 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
876 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
877 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
878 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
879 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
881 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
882 touchConfiguration();
887 * Adds the Sone of the given identity.
890 * The identity whose Sone to add
891 * @return The added or already existing Sone
893 public Sone addRemoteSone(Identity identity) {
894 if (identity == null) {
895 logger.log(Level.WARNING, "Given Identity is null!");
898 synchronized (sones) {
899 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
900 boolean newSone = sone.getRequestUri() == null;
901 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
902 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
904 synchronized (knownSones) {
905 newSone = !knownSones.contains(sone.getId());
907 sone.setKnown(!newSone);
909 eventBus.post(new NewSoneFoundEvent(sone));
910 for (Sone localSone : getLocalSones()) {
911 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
912 followSone(localSone, sone);
917 soneDownloader.addSone(sone);
918 soneDownloaders.execute(new Runnable() {
921 @SuppressWarnings("synthetic-access")
923 soneDownloader.fetchSone(sone, sone.getRequestUri());
932 * Lets the given local Sone follow the Sone with the given ID.
935 * The local Sone that should follow another Sone
937 * The ID of the Sone to follow
939 public void followSone(Sone sone, String soneId) {
940 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
941 Sone followedSone = getSone(soneId, true);
942 if (followedSone == null) {
943 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
946 followSone(sone, getSone(soneId));
950 * Lets the given local Sone follow the other given Sone. If the given Sone
951 * was not followed by any local Sone before, this will mark all elements of
952 * the followed Sone as read that have been created before the current
956 * The local Sone that should follow the other Sone
957 * @param followedSone
958 * The Sone that should be followed
960 public void followSone(Sone sone, Sone followedSone) {
961 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
962 sone.addFriend(followedSone.getId());
963 synchronized (soneFollowingTimes) {
964 if (!soneFollowingTimes.containsKey(followedSone)) {
965 long now = System.currentTimeMillis();
966 soneFollowingTimes.put(followedSone, now);
967 for (Post post : followedSone.getPosts()) {
968 if (post.getTime() < now) {
972 for (PostReply reply : followedSone.getReplies()) {
973 if (reply.getTime() < now) {
974 markReplyKnown(reply);
979 touchConfiguration();
983 * Lets the given local Sone unfollow the Sone with the given ID.
986 * The local Sone that should unfollow another Sone
988 * The ID of the Sone being unfollowed
990 public void unfollowSone(Sone sone, String soneId) {
991 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
992 unfollowSone(sone, getSone(soneId, false));
996 * Lets the given local Sone unfollow the other given Sone. If the given
997 * local Sone is the last local Sone that followed the given Sone, its
998 * following time will be removed.
1001 * The local Sone that should unfollow another Sone
1002 * @param unfollowedSone
1003 * The Sone being unfollowed
1005 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1006 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1007 sone.removeFriend(unfollowedSone.getId());
1008 boolean unfollowedSoneStillFollowed = false;
1009 for (Sone localSone : getLocalSones()) {
1010 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1012 if (!unfollowedSoneStillFollowed) {
1013 synchronized (soneFollowingTimes) {
1014 soneFollowingTimes.remove(unfollowedSone);
1017 touchConfiguration();
1021 * Sets the trust value of the given origin Sone for the target Sone.
1028 * The trust value (from {@code -100} to {@code 100})
1030 public void setTrust(Sone origin, Sone target, int trustValue) {
1031 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();
1032 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1036 * Removes any trust assignment for the given target Sone.
1043 public void removeTrust(Sone origin, Sone target) {
1044 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1045 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1049 * Assigns the configured positive trust value for the given target.
1056 public void trustSone(Sone origin, Sone target) {
1057 setTrust(origin, target, preferences.getPositiveTrust());
1061 * Assigns the configured negative trust value for the given target.
1068 public void distrustSone(Sone origin, Sone target) {
1069 setTrust(origin, target, preferences.getNegativeTrust());
1073 * Removes the trust assignment for the given target.
1080 public void untrustSone(Sone origin, Sone target) {
1081 removeTrust(origin, target);
1085 * Updates the stored Sone with the given Sone.
1090 public void updateSone(Sone sone) {
1091 updateSone(sone, false);
1095 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1096 * {@code true}, an older Sone than the current Sone can be given to restore
1100 * The Sone to update
1101 * @param soneRescueMode
1102 * {@code true} if the stored Sone should be updated regardless
1103 * of the age of the given Sone
1105 public void updateSone(Sone sone, boolean soneRescueMode) {
1106 if (hasSone(sone.getId())) {
1107 Sone storedSone = getSone(sone.getId());
1108 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1109 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1112 synchronized (posts) {
1113 if (!soneRescueMode) {
1114 for (Post post : storedSone.getPosts()) {
1115 posts.remove(post.getId());
1116 if (!sone.getPosts().contains(post)) {
1117 eventBus.post(new PostRemovedEvent(post));
1121 List<Post> storedPosts = storedSone.getPosts();
1122 synchronized (knownPosts) {
1123 for (Post post : sone.getPosts()) {
1124 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1125 if (!storedPosts.contains(post)) {
1126 if (post.getTime() < getSoneFollowingTime(sone)) {
1127 knownPosts.add(post.getId());
1128 post.setKnown(true);
1129 } else if (!knownPosts.contains(post.getId())) {
1130 eventBus.post(new NewPostFoundEvent(post));
1133 posts.put(post.getId(), post);
1137 synchronized (replies) {
1138 if (!soneRescueMode) {
1139 for (PostReply reply : storedSone.getReplies()) {
1140 replies.remove(reply.getId());
1141 if (!sone.getReplies().contains(reply)) {
1142 eventBus.post(new PostReplyRemovedEvent(reply));
1146 Set<PostReply> storedReplies = storedSone.getReplies();
1147 synchronized (knownReplies) {
1148 for (PostReply reply : sone.getReplies()) {
1149 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1150 if (!storedReplies.contains(reply)) {
1151 if (reply.getTime() < getSoneFollowingTime(sone)) {
1152 knownReplies.add(reply.getId());
1153 reply.setKnown(true);
1154 } else if (!knownReplies.contains(reply.getId())) {
1155 eventBus.post(new NewPostReplyFoundEvent(reply));
1158 replies.put(reply.getId(), reply);
1162 synchronized (albums) {
1163 synchronized (images) {
1164 for (Album album : storedSone.getAlbums()) {
1165 albums.remove(album.getId());
1166 for (Image image : album.getImages()) {
1167 images.remove(image.getId());
1170 for (Album album : sone.getAlbums()) {
1171 albums.put(album.getId(), album);
1172 for (Image image : album.getImages()) {
1173 images.put(image.getId(), image);
1178 synchronized (storedSone) {
1179 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1180 storedSone.setTime(sone.getTime());
1182 storedSone.setClient(sone.getClient());
1183 storedSone.setProfile(sone.getProfile());
1184 if (soneRescueMode) {
1185 for (Post post : sone.getPosts()) {
1186 storedSone.addPost(post);
1188 for (PostReply reply : sone.getReplies()) {
1189 storedSone.addReply(reply);
1191 for (String likedPostId : sone.getLikedPostIds()) {
1192 storedSone.addLikedPostId(likedPostId);
1194 for (String likedReplyId : sone.getLikedReplyIds()) {
1195 storedSone.addLikedReplyId(likedReplyId);
1197 for (Album album : sone.getAlbums()) {
1198 storedSone.addAlbum(album);
1201 storedSone.setPosts(sone.getPosts());
1202 storedSone.setReplies(sone.getReplies());
1203 storedSone.setLikePostIds(sone.getLikedPostIds());
1204 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1205 storedSone.setAlbums(sone.getAlbums());
1207 storedSone.setLatestEdition(sone.getLatestEdition());
1213 * Deletes the given Sone. This will remove the Sone from the
1214 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1215 * remove the context from its identity.
1218 * The Sone to delete
1220 public void deleteSone(Sone sone) {
1221 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1222 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1225 synchronized (sones) {
1226 if (!getLocalSones().contains(sone)) {
1227 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1230 sones.remove(sone.getId());
1231 SoneInserter soneInserter = soneInserters.remove(sone);
1232 soneInserter.removeSoneInsertListener(this);
1233 soneInserter.stop();
1235 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1236 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1238 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1239 } catch (ConfigurationException ce1) {
1240 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1245 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1246 * known} before, a {@link MarkSoneKnownEvent} is fired.
1249 * The Sone to mark as known
1251 public void markSoneKnown(Sone sone) {
1252 if (!sone.isKnown()) {
1253 sone.setKnown(true);
1254 synchronized (knownSones) {
1255 knownSones.add(sone.getId());
1257 eventBus.post(new MarkSoneKnownEvent(sone));
1258 touchConfiguration();
1263 * Loads and updates the given Sone from the configuration. If any error is
1264 * encountered, loading is aborted and the given Sone is not changed.
1267 * The Sone to load and update
1269 public void loadSone(Sone sone) {
1270 if (!sone.isLocal()) {
1271 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1275 /* initialize options. */
1276 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1277 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1278 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1279 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1280 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1281 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1284 String sonePrefix = "Sone/" + sone.getId();
1285 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1286 if (soneTime == null) {
1287 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1290 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1293 Profile profile = new Profile(sone);
1294 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1295 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1296 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1297 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1298 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1299 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1301 /* load profile fields. */
1303 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1304 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1305 if (fieldName == null) {
1308 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1309 profile.addField(fieldName).setValue(fieldValue);
1313 Set<Post> posts = new HashSet<Post>();
1315 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1316 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1317 if (postId == null) {
1320 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1321 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1322 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1323 if ((postTime == 0) || (postText == null)) {
1324 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1327 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1328 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1329 post.setRecipient(getSone(postRecipientId));
1335 Set<PostReply> replies = new HashSet<PostReply>();
1337 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1338 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1339 if (replyId == null) {
1342 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1343 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1344 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1345 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1346 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1349 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1352 /* load post likes. */
1353 Set<String> likedPostIds = new HashSet<String>();
1355 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1356 if (likedPostId == null) {
1359 likedPostIds.add(likedPostId);
1362 /* load reply likes. */
1363 Set<String> likedReplyIds = new HashSet<String>();
1365 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1366 if (likedReplyId == null) {
1369 likedReplyIds.add(likedReplyId);
1373 Set<String> friends = new HashSet<String>();
1375 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1376 if (friendId == null) {
1379 friends.add(friendId);
1383 List<Album> topLevelAlbums = new ArrayList<Album>();
1384 int albumCounter = 0;
1386 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1387 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1388 if (albumId == null) {
1391 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1392 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1393 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1394 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1395 if ((albumTitle == null) || (albumDescription == null)) {
1396 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1399 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1400 if (albumParentId != null) {
1401 Album parentAlbum = getAlbum(albumParentId, false);
1402 if (parentAlbum == null) {
1403 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1406 parentAlbum.addAlbum(album);
1408 if (!topLevelAlbums.contains(album)) {
1409 topLevelAlbums.add(album);
1415 int imageCounter = 0;
1417 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1418 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1419 if (imageId == null) {
1422 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1423 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1424 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1425 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1426 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1427 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1428 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1429 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1430 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1433 Album album = getAlbum(albumId, false);
1434 if (album == null) {
1435 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1438 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1439 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1440 album.addImage(image);
1444 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1445 if (avatarId != null) {
1446 profile.setAvatar(getImage(avatarId, false));
1450 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1451 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1452 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1453 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1454 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1455 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1457 /* if we’re still here, Sone was loaded successfully. */
1458 synchronized (sone) {
1459 sone.setTime(soneTime);
1460 sone.setProfile(profile);
1461 sone.setPosts(posts);
1462 sone.setReplies(replies);
1463 sone.setLikePostIds(likedPostIds);
1464 sone.setLikeReplyIds(likedReplyIds);
1465 for (String friendId : friends) {
1466 followSone(sone, friendId);
1468 sone.setAlbums(topLevelAlbums);
1469 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1471 synchronized (knownSones) {
1472 for (String friend : friends) {
1473 knownSones.add(friend);
1476 synchronized (knownPosts) {
1477 for (Post post : posts) {
1478 knownPosts.add(post.getId());
1481 synchronized (knownReplies) {
1482 for (PostReply reply : replies) {
1483 knownReplies.add(reply.getId());
1489 * Creates a new post.
1492 * The Sone that creates the post
1494 * The text of the post
1495 * @return The created post
1497 public Post createPost(Sone sone, String text) {
1498 return createPost(sone, System.currentTimeMillis(), text);
1502 * Creates a new post.
1505 * The Sone that creates the post
1507 * The time of the post
1509 * The text of the post
1510 * @return The created post
1512 public Post createPost(Sone sone, long time, String text) {
1513 return createPost(sone, null, time, text);
1517 * Creates a new post.
1520 * The Sone that creates the post
1522 * The recipient Sone, or {@code null} if this post does not have
1525 * The text of the post
1526 * @return The created post
1528 public Post createPost(Sone sone, Sone recipient, String text) {
1529 return createPost(sone, recipient, System.currentTimeMillis(), text);
1533 * Creates a new post.
1536 * The Sone that creates the post
1538 * The recipient Sone, or {@code null} if this post does not have
1541 * The time of the post
1543 * The text of the post
1544 * @return The created post
1546 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1547 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1548 if (!sone.isLocal()) {
1549 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1552 final Post post = new PostImpl(sone, time, text);
1553 if (recipient != null) {
1554 post.setRecipient(recipient);
1556 synchronized (posts) {
1557 posts.put(post.getId(), post);
1559 eventBus.post(new NewPostFoundEvent(post));
1561 touchConfiguration();
1562 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1569 markPostKnown(post);
1571 }, "Mark " + post + " read.");
1576 * Deletes the given post.
1579 * The post to delete
1581 public void deletePost(Post post) {
1582 if (!post.getSone().isLocal()) {
1583 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1586 post.getSone().removePost(post);
1587 synchronized (posts) {
1588 posts.remove(post.getId());
1590 eventBus.post(new PostRemovedEvent(post));
1591 markPostKnown(post);
1592 touchConfiguration();
1596 * Marks the given post as known, if it is currently not a known post
1597 * (according to {@link Post#isKnown()}).
1600 * The post to mark as known
1602 public void markPostKnown(Post post) {
1603 post.setKnown(true);
1604 synchronized (knownPosts) {
1605 eventBus.post(new MarkPostKnownEvent(post));
1606 if (knownPosts.add(post.getId())) {
1607 touchConfiguration();
1610 for (PostReply reply : getReplies(post)) {
1611 markReplyKnown(reply);
1616 * Bookmarks the given post.
1619 * The post to bookmark
1621 public void bookmark(Post post) {
1622 bookmarkPost(post.getId());
1626 * Bookmarks the post with the given ID.
1629 * The ID of the post to bookmark
1631 public void bookmarkPost(String id) {
1632 synchronized (bookmarkedPosts) {
1633 bookmarkedPosts.add(id);
1638 * Removes the given post from the bookmarks.
1641 * The post to unbookmark
1643 public void unbookmark(Post post) {
1644 unbookmarkPost(post.getId());
1648 * Removes the post with the given ID from the bookmarks.
1651 * The ID of the post to unbookmark
1653 public void unbookmarkPost(String id) {
1654 synchronized (bookmarkedPosts) {
1655 bookmarkedPosts.remove(id);
1660 * Creates a new reply.
1663 * The Sone that creates the reply
1665 * The post that this reply refers to
1667 * The text of the reply
1668 * @return The created reply
1670 public PostReply createReply(Sone sone, Post post, String text) {
1671 return createReply(sone, post, System.currentTimeMillis(), text);
1675 * Creates a new reply.
1678 * The Sone that creates the reply
1680 * The post that this reply refers to
1682 * The time of the reply
1684 * The text of the reply
1685 * @return The created reply
1687 public PostReply createReply(Sone sone, Post post, long time, String text) {
1688 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1689 if (!sone.isLocal()) {
1690 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1693 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1694 synchronized (replies) {
1695 replies.put(reply.getId(), reply);
1697 synchronized (knownReplies) {
1698 eventBus.post(new NewPostReplyFoundEvent(reply));
1700 sone.addReply(reply);
1701 touchConfiguration();
1702 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1709 markReplyKnown(reply);
1711 }, "Mark " + reply + " read.");
1716 * Deletes the given reply.
1719 * The reply to delete
1721 public void deleteReply(PostReply reply) {
1722 Sone sone = reply.getSone();
1723 if (!sone.isLocal()) {
1724 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1727 synchronized (replies) {
1728 replies.remove(reply.getId());
1730 synchronized (knownReplies) {
1731 markReplyKnown(reply);
1732 knownReplies.remove(reply.getId());
1734 sone.removeReply(reply);
1735 touchConfiguration();
1739 * Marks the given reply as known, if it is currently not a known reply
1740 * (according to {@link Reply#isKnown()}).
1743 * The reply to mark as known
1745 public void markReplyKnown(PostReply reply) {
1746 reply.setKnown(true);
1747 synchronized (knownReplies) {
1748 eventBus.post(new MarkPostReplyKnownEvent(reply));
1749 if (knownReplies.add(reply.getId())) {
1750 touchConfiguration();
1756 * Creates a new top-level album for the given Sone.
1759 * The Sone to create the album for
1760 * @return The new album
1762 public Album createAlbum(Sone sone) {
1763 return createAlbum(sone, null);
1767 * Creates a new album for the given Sone.
1770 * The Sone to create the album for
1772 * The parent of the album (may be {@code null} to create a
1774 * @return The new album
1776 public Album createAlbum(Sone sone, Album parent) {
1777 Album album = new Album();
1778 synchronized (albums) {
1779 albums.put(album.getId(), album);
1781 album.setSone(sone);
1782 if (parent != null) {
1783 parent.addAlbum(album);
1785 sone.addAlbum(album);
1791 * Deletes the given album. The owner of the album has to be a local Sone,
1792 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1795 * The album to remove
1797 public void deleteAlbum(Album album) {
1798 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1799 if (!album.isEmpty()) {
1802 if (album.getParent() == null) {
1803 album.getSone().removeAlbum(album);
1805 album.getParent().removeAlbum(album);
1807 synchronized (albums) {
1808 albums.remove(album.getId());
1810 touchConfiguration();
1814 * Creates a new image.
1817 * The Sone creating the image
1819 * The album the image will be inserted into
1820 * @param temporaryImage
1821 * The temporary image to create the image from
1822 * @return The newly created image
1824 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1825 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1826 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1827 album.addImage(image);
1828 synchronized (images) {
1829 images.put(image.getId(), image);
1831 imageInserter.insertImage(temporaryImage, image);
1836 * Deletes the given image. This method will also delete a matching
1839 * @see #deleteTemporaryImage(TemporaryImage)
1841 * The image to delete
1843 public void deleteImage(Image image) {
1844 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1845 deleteTemporaryImage(image.getId());
1846 image.getAlbum().removeImage(image);
1847 synchronized (images) {
1848 images.remove(image.getId());
1850 touchConfiguration();
1854 * Creates a new temporary image.
1857 * The MIME type of the temporary image
1859 * The encoded data of the image
1860 * @return The temporary image
1862 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1863 TemporaryImage temporaryImage = new TemporaryImage();
1864 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1865 synchronized (temporaryImages) {
1866 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1868 return temporaryImage;
1872 * Deletes the given temporary image.
1874 * @param temporaryImage
1875 * The temporary image to delete
1877 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1878 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1879 deleteTemporaryImage(temporaryImage.getId());
1883 * Deletes the temporary image with the given ID.
1886 * The ID of the temporary image to delete
1888 public void deleteTemporaryImage(String imageId) {
1889 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1890 synchronized (temporaryImages) {
1891 temporaryImages.remove(imageId);
1893 Image image = getImage(imageId, false);
1894 if (image != null) {
1895 imageInserter.cancelImageInsert(image);
1900 * Notifies the core that the configuration, either of the core or of a
1901 * single local Sone, has changed, and that the configuration should be
1904 public void touchConfiguration() {
1905 lastConfigurationUpdate = System.currentTimeMillis();
1916 public void serviceStart() {
1917 loadConfiguration();
1918 updateChecker.addUpdateListener(this);
1919 updateChecker.start();
1920 identityManager.addIdentityListener(this);
1921 identityManager.start();
1922 webOfTrustUpdater.init();
1923 webOfTrustUpdater.start();
1930 public void serviceRun() {
1931 long lastSaved = System.currentTimeMillis();
1932 while (!shouldStop()) {
1934 long now = System.currentTimeMillis();
1935 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1936 for (Sone localSone : getLocalSones()) {
1937 saveSone(localSone);
1939 saveConfiguration();
1949 public void serviceStop() {
1950 synchronized (sones) {
1951 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1952 soneInserter.getValue().removeSoneInsertListener(this);
1953 soneInserter.getValue().stop();
1954 saveSone(soneInserter.getKey());
1957 saveConfiguration();
1958 webOfTrustUpdater.stop();
1959 updateChecker.stop();
1960 updateChecker.removeUpdateListener(this);
1961 soneDownloader.stop();
1962 identityManager.removeIdentityListener(this);
1963 identityManager.stop();
1971 * Saves the given Sone. This will persist all local settings for the given
1972 * Sone, such as the friends list and similar, private options.
1977 private synchronized void saveSone(Sone sone) {
1978 if (!sone.isLocal()) {
1979 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1982 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1983 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1987 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1989 /* save Sone into configuration. */
1990 String sonePrefix = "Sone/" + sone.getId();
1991 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1992 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1995 Profile profile = sone.getProfile();
1996 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1997 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1998 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1999 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2000 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2001 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2002 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2004 /* save profile fields. */
2005 int fieldCounter = 0;
2006 for (Field profileField : profile.getFields()) {
2007 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2008 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2009 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2011 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2014 int postCounter = 0;
2015 for (Post post : sone.getPosts()) {
2016 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2017 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2018 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2019 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2020 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2022 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2025 int replyCounter = 0;
2026 for (PostReply reply : sone.getReplies()) {
2027 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2028 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2029 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2030 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2031 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2033 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2035 /* save post likes. */
2036 int postLikeCounter = 0;
2037 for (String postId : sone.getLikedPostIds()) {
2038 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2040 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2042 /* save reply likes. */
2043 int replyLikeCounter = 0;
2044 for (String replyId : sone.getLikedReplyIds()) {
2045 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2047 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2050 int friendCounter = 0;
2051 for (String friendId : sone.getFriends()) {
2052 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2054 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2056 /* save albums. first, collect in a flat structure, top-level first. */
2057 List<Album> albums = sone.getAllAlbums();
2059 int albumCounter = 0;
2060 for (Album album : albums) {
2061 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2062 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2063 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2064 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2065 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2066 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2068 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2071 int imageCounter = 0;
2072 for (Album album : albums) {
2073 for (Image image : album.getImages()) {
2074 if (!image.isInserted()) {
2077 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2078 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2079 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2080 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2081 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2082 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2083 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2084 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2085 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2088 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2091 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2092 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2093 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2094 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2095 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2096 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2098 configuration.save();
2100 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2102 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2103 } catch (ConfigurationException ce1) {
2104 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2109 * Saves the current options.
2111 private void saveConfiguration() {
2112 synchronized (configuration) {
2113 if (storingConfiguration) {
2114 logger.log(Level.FINE, "Already storing configuration…");
2117 storingConfiguration = true;
2120 /* store the options first. */
2122 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2123 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2124 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2125 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2126 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2127 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2128 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2129 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2130 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2131 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2132 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2133 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2135 /* save known Sones. */
2136 int soneCounter = 0;
2137 synchronized (knownSones) {
2138 for (String knownSoneId : knownSones) {
2139 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2141 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2144 /* save Sone following times. */
2146 synchronized (soneFollowingTimes) {
2147 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2148 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2149 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2152 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2155 /* save known posts. */
2156 int postCounter = 0;
2157 synchronized (knownPosts) {
2158 for (String knownPostId : knownPosts) {
2159 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2161 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2164 /* save known replies. */
2165 int replyCounter = 0;
2166 synchronized (knownReplies) {
2167 for (String knownReplyId : knownReplies) {
2168 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2170 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2173 /* save bookmarked posts. */
2174 int bookmarkedPostCounter = 0;
2175 synchronized (bookmarkedPosts) {
2176 for (String bookmarkedPostId : bookmarkedPosts) {
2177 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2180 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2183 configuration.save();
2185 } catch (ConfigurationException ce1) {
2186 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2188 synchronized (configuration) {
2189 storingConfiguration = false;
2195 * Loads the configuration.
2197 @SuppressWarnings("unchecked")
2198 private void loadConfiguration() {
2199 /* create options. */
2200 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2203 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2204 SoneInserter.setInsertionDelay(newValue);
2208 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2209 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2210 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2211 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2212 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2213 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2214 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2215 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2216 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2219 @SuppressWarnings("synthetic-access")
2220 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2221 fcpInterface.setActive(newValue);
2224 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2227 @SuppressWarnings("synthetic-access")
2228 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2229 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2234 loadConfigurationValue("InsertionDelay");
2235 loadConfigurationValue("PostsPerPage");
2236 loadConfigurationValue("ImagesPerPage");
2237 loadConfigurationValue("CharactersPerPost");
2238 loadConfigurationValue("PostCutOffLength");
2239 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2240 loadConfigurationValue("PositiveTrust");
2241 loadConfigurationValue("NegativeTrust");
2242 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2243 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2244 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2246 /* load known Sones. */
2247 int soneCounter = 0;
2249 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2250 if (knownSoneId == null) {
2253 synchronized (knownSones) {
2254 knownSones.add(knownSoneId);
2258 /* load Sone following times. */
2261 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2262 if (soneId == null) {
2265 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2266 Sone followedSone = getSone(soneId);
2267 if (followedSone == null) {
2268 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2270 synchronized (soneFollowingTimes) {
2271 soneFollowingTimes.put(getSone(soneId), time);
2277 /* load known posts. */
2278 int postCounter = 0;
2280 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2281 if (knownPostId == null) {
2284 synchronized (knownPosts) {
2285 knownPosts.add(knownPostId);
2289 /* load known replies. */
2290 int replyCounter = 0;
2292 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2293 if (knownReplyId == null) {
2296 synchronized (knownReplies) {
2297 knownReplies.add(knownReplyId);
2301 /* load bookmarked posts. */
2302 int bookmarkedPostCounter = 0;
2304 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2305 if (bookmarkedPostId == null) {
2308 synchronized (bookmarkedPosts) {
2309 bookmarkedPosts.add(bookmarkedPostId);
2316 * Loads an {@link Integer} configuration value for the option with the
2317 * given name, logging validation failures.
2320 * The name of the option to load
2322 private void loadConfigurationValue(String optionName) {
2324 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2325 } catch (IllegalArgumentException iae1) {
2326 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2331 * Generate a Sone URI from the given URI and latest edition.
2334 * The URI to derive the Sone URI from
2335 * @return The derived URI
2337 private static FreenetURI getSoneUri(String uriString) {
2339 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2341 } catch (MalformedURLException mue1) {
2342 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2348 // INTERFACE IdentityListener
2355 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2356 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2357 if (ownIdentity.hasContext("Sone")) {
2358 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2359 addLocalSone(ownIdentity);
2367 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2368 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2369 trustedIdentities.remove(ownIdentity);
2376 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2377 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2378 trustedIdentities.get(ownIdentity).add(identity);
2379 addRemoteSone(identity);
2386 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2387 soneDownloaders.execute(new Runnable() {
2390 @SuppressWarnings("synthetic-access")
2392 Sone sone = getRemoteSone(identity.getId(), false);
2393 sone.setIdentity(identity);
2394 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2395 soneDownloader.addSone(sone);
2396 soneDownloader.fetchSone(sone);
2405 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2406 trustedIdentities.get(ownIdentity).remove(identity);
2407 boolean foundIdentity = false;
2408 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2409 if (trustedIdentity.getKey().equals(ownIdentity)) {
2412 if (trustedIdentity.getValue().contains(identity)) {
2413 foundIdentity = true;
2416 if (foundIdentity) {
2417 /* some local identity still trusts this identity, don’t remove. */
2420 Sone sone = getSone(identity.getId(), false);
2422 /* TODO - we don’t have the Sone anymore. should this happen? */
2425 synchronized (posts) {
2426 synchronized (knownPosts) {
2427 for (Post post : sone.getPosts()) {
2428 posts.remove(post.getId());
2429 eventBus.post(new PostRemovedEvent(post));
2433 synchronized (replies) {
2434 synchronized (knownReplies) {
2435 for (PostReply reply : sone.getReplies()) {
2436 replies.remove(reply.getId());
2437 eventBus.post(new PostReplyRemovedEvent(reply));
2441 synchronized (sones) {
2442 sones.remove(identity.getId());
2444 eventBus.post(new SoneRemovedEvent(sone));
2448 // INTERFACE UpdateListener
2455 public void updateFound(Version version, long releaseTime, long latestEdition) {
2456 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2460 // INTERFACE ImageInsertListener
2467 public void insertStarted(Sone sone) {
2468 eventBus.post(new SoneInsertingEvent(sone));
2475 public void insertFinished(Sone sone, long insertDuration) {
2476 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2483 public void insertAborted(Sone sone, Throwable cause) {
2484 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2488 // SONEINSERTLISTENER METHODS
2495 public void imageInsertStarted(Image image) {
2496 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2497 coreListenerManager.fireImageInsertStarted(image);
2504 public void imageInsertAborted(Image image) {
2505 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2506 coreListenerManager.fireImageInsertAborted(image);
2513 public void imageInsertFinished(Image image, FreenetURI key) {
2514 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2515 image.setKey(key.toString());
2516 deleteTemporaryImage(image.getId());
2517 touchConfiguration();
2518 coreListenerManager.fireImageInsertFinished(image);
2525 public void imageInsertFailed(Image image, Throwable cause) {
2526 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2527 coreListenerManager.fireImageInsertFailed(image, cause);
2531 * Convenience interface for external classes that want to access the core’s
2534 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2536 public static class Preferences {
2538 /** The wrapped options. */
2539 private final Options options;
2542 * Creates a new preferences object wrapped around the given options.
2545 * The options to wrap
2547 public Preferences(Options options) {
2548 this.options = options;
2552 * Returns the insertion delay.
2554 * @return The insertion delay
2556 public int getInsertionDelay() {
2557 return options.getIntegerOption("InsertionDelay").get();
2561 * Validates the given insertion delay.
2563 * @param insertionDelay
2564 * The insertion delay to validate
2565 * @return {@code true} if the given insertion delay was valid,
2566 * {@code false} otherwise
2568 public boolean validateInsertionDelay(Integer insertionDelay) {
2569 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2573 * Sets the insertion delay
2575 * @param insertionDelay
2576 * The new insertion delay, or {@code null} to restore it to
2578 * @return This preferences
2580 public Preferences setInsertionDelay(Integer insertionDelay) {
2581 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2586 * Returns the number of posts to show per page.
2588 * @return The number of posts to show per page
2590 public int getPostsPerPage() {
2591 return options.getIntegerOption("PostsPerPage").get();
2595 * Validates the number of posts per page.
2597 * @param postsPerPage
2598 * The number of posts per page
2599 * @return {@code true} if the number of posts per page was valid,
2600 * {@code false} otherwise
2602 public boolean validatePostsPerPage(Integer postsPerPage) {
2603 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2607 * Sets the number of posts to show per page.
2609 * @param postsPerPage
2610 * The number of posts to show per page
2611 * @return This preferences object
2613 public Preferences setPostsPerPage(Integer postsPerPage) {
2614 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2619 * Returns the number of images to show per page.
2621 * @return The number of images to show per page
2623 public int getImagesPerPage() {
2624 return options.getIntegerOption("ImagesPerPage").get();
2628 * Validates the number of images per page.
2630 * @param imagesPerPage
2631 * The number of images per page
2632 * @return {@code true} if the number of images per page was valid,
2633 * {@code false} otherwise
2635 public boolean validateImagesPerPage(Integer imagesPerPage) {
2636 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2640 * Sets the number of images per page.
2642 * @param imagesPerPage
2643 * The number of images per page
2644 * @return This preferences object
2646 public Preferences setImagesPerPage(Integer imagesPerPage) {
2647 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2652 * Returns the number of characters per post, or <code>-1</code> if the
2653 * posts should not be cut off.
2655 * @return The numbers of characters per post
2657 public int getCharactersPerPost() {
2658 return options.getIntegerOption("CharactersPerPost").get();
2662 * Validates the number of characters per post.
2664 * @param charactersPerPost
2665 * The number of characters per post
2666 * @return {@code true} if the number of characters per post was valid,
2667 * {@code false} otherwise
2669 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2670 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2674 * Sets the number of characters per post.
2676 * @param charactersPerPost
2677 * The number of characters per post, or <code>-1</code> to
2678 * not cut off the posts
2679 * @return This preferences objects
2681 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2682 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2687 * Returns the number of characters the shortened post should have.
2689 * @return The number of characters of the snippet
2691 public int getPostCutOffLength() {
2692 return options.getIntegerOption("PostCutOffLength").get();
2696 * Validates the number of characters after which to cut off the post.
2698 * @param postCutOffLength
2699 * The number of characters of the snippet
2700 * @return {@code true} if the number of characters of the snippet is
2701 * valid, {@code false} otherwise
2703 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2704 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2708 * Sets the number of characters the shortened post should have.
2710 * @param postCutOffLength
2711 * The number of characters of the snippet
2712 * @return This preferences
2714 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2715 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2720 * Returns whether Sone requires full access to be even visible.
2722 * @return {@code true} if Sone requires full access, {@code false}
2725 public boolean isRequireFullAccess() {
2726 return options.getBooleanOption("RequireFullAccess").get();
2730 * Sets whether Sone requires full access to be even visible.
2732 * @param requireFullAccess
2733 * {@code true} if Sone requires full access, {@code false}
2736 public void setRequireFullAccess(Boolean requireFullAccess) {
2737 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2741 * Returns the positive trust.
2743 * @return The positive trust
2745 public int getPositiveTrust() {
2746 return options.getIntegerOption("PositiveTrust").get();
2750 * Validates the positive trust.
2752 * @param positiveTrust
2753 * The positive trust to validate
2754 * @return {@code true} if the positive trust was valid, {@code false}
2757 public boolean validatePositiveTrust(Integer positiveTrust) {
2758 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2762 * Sets the positive trust.
2764 * @param positiveTrust
2765 * The new positive trust, or {@code null} to restore it to
2767 * @return This preferences
2769 public Preferences setPositiveTrust(Integer positiveTrust) {
2770 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2775 * Returns the negative trust.
2777 * @return The negative trust
2779 public int getNegativeTrust() {
2780 return options.getIntegerOption("NegativeTrust").get();
2784 * Validates the negative trust.
2786 * @param negativeTrust
2787 * The negative trust to validate
2788 * @return {@code true} if the negative trust was valid, {@code false}
2791 public boolean validateNegativeTrust(Integer negativeTrust) {
2792 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2796 * Sets the negative trust.
2798 * @param negativeTrust
2799 * The negative trust, or {@code null} to restore it to the
2801 * @return The preferences
2803 public Preferences setNegativeTrust(Integer negativeTrust) {
2804 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2809 * Returns the trust comment. This is the comment that is set in the web
2810 * of trust when a trust value is assigned to an identity.
2812 * @return The trust comment
2814 public String getTrustComment() {
2815 return options.getStringOption("TrustComment").get();
2819 * Sets the trust comment.
2821 * @param trustComment
2822 * The trust comment, or {@code null} to restore it to the
2824 * @return This preferences
2826 public Preferences setTrustComment(String trustComment) {
2827 options.getStringOption("TrustComment").set(trustComment);
2832 * Returns whether the {@link FcpInterface FCP interface} is currently
2835 * @see FcpInterface#setActive(boolean)
2836 * @return {@code true} if the FCP interface is currently active,
2837 * {@code false} otherwise
2839 public boolean isFcpInterfaceActive() {
2840 return options.getBooleanOption("ActivateFcpInterface").get();
2844 * Sets whether the {@link FcpInterface FCP interface} is currently
2847 * @see FcpInterface#setActive(boolean)
2848 * @param fcpInterfaceActive
2849 * {@code true} to activate the FCP interface, {@code false}
2850 * to deactivate the FCP interface
2851 * @return This preferences object
2853 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2854 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2859 * Returns the action level for which full access to the FCP interface
2862 * @return The action level for which full access to the FCP interface
2865 public FullAccessRequired getFcpFullAccessRequired() {
2866 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2870 * Sets the action level for which full access to the FCP interface is
2873 * @param fcpFullAccessRequired
2875 * @return This preferences
2877 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2878 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);