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.ImageInsertFinishedEvent;
39 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
40 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
41 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
42 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
43 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
44 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
45 import net.pterodactylus.sone.core.event.PostRemovedEvent;
46 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
47 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
48 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
49 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
50 import net.pterodactylus.sone.core.event.SoneLockedEvent;
51 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
53 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.data.impl.PostImpl;
67 import net.pterodactylus.sone.fcp.FcpInterface;
68 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
69 import net.pterodactylus.sone.freenet.wot.Identity;
70 import net.pterodactylus.sone.freenet.wot.IdentityListener;
71 import net.pterodactylus.sone.freenet.wot.IdentityManager;
72 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
73 import net.pterodactylus.sone.main.SonePlugin;
74 import net.pterodactylus.util.config.Configuration;
75 import net.pterodactylus.util.config.ConfigurationException;
76 import net.pterodactylus.util.logging.Logging;
77 import net.pterodactylus.util.number.Numbers;
78 import net.pterodactylus.util.service.AbstractService;
79 import net.pterodactylus.util.thread.NamedThreadFactory;
80 import net.pterodactylus.util.thread.Ticker;
81 import net.pterodactylus.util.validation.EqualityValidator;
82 import net.pterodactylus.util.validation.IntegerRangeValidator;
83 import net.pterodactylus.util.validation.OrValidator;
84 import net.pterodactylus.util.validation.Validation;
85 import net.pterodactylus.util.version.Version;
87 import com.google.common.base.Predicate;
88 import com.google.common.collect.Collections2;
89 import com.google.common.eventbus.EventBus;
90 import com.google.common.eventbus.Subscribe;
91 import com.google.inject.Inject;
93 import freenet.keys.FreenetURI;
98 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
100 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener {
103 private static final Logger logger = Logging.getLogger(Core.class);
105 /** The start time. */
106 private final long startupTime = System.currentTimeMillis();
109 private final Options options = new Options();
111 /** The preferences. */
112 private final Preferences preferences = new Preferences(options);
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(freenetInterface);
225 this.updateChecker = new UpdateChecker(freenetInterface);
226 this.webOfTrustUpdater = webOfTrustUpdater;
227 this.eventBus = eventBus;
235 * Returns the time Sone was started.
237 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
239 public long getStartupTime() {
244 * Sets the configuration to use. This will automatically save the current
245 * configuration to the given configuration.
247 * @param configuration
248 * The new configuration to use
250 public void setConfiguration(Configuration configuration) {
251 this.configuration = configuration;
252 touchConfiguration();
256 * Returns the options used by the core.
258 * @return The options of the core
260 public Preferences getPreferences() {
265 * Returns the identity manager used by the core.
267 * @return The identity manager
269 public IdentityManager getIdentityManager() {
270 return identityManager;
274 * Returns the update checker.
276 * @return The update checker
278 public UpdateChecker getUpdateChecker() {
279 return updateChecker;
283 * Sets the FCP interface to use.
285 * @param fcpInterface
286 * The FCP interface to use
288 public void setFcpInterface(FcpInterface fcpInterface) {
289 this.fcpInterface = fcpInterface;
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
301 synchronized (sones) {
302 SoneRescuer soneRescuer = soneRescuers.get(sone);
303 if (soneRescuer == null) {
304 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
305 soneRescuers.put(sone, soneRescuer);
313 * Returns whether the given Sone is currently locked.
317 * @return {@code true} if the Sone is locked, {@code false} if it is not
319 public boolean isLocked(Sone sone) {
320 synchronized (lockedSones) {
321 return lockedSones.contains(sone);
326 * Returns all Sones, remote and local.
330 public Set<Sone> getSones() {
331 return new HashSet<Sone>(sones.values());
335 * Returns the Sone with the given ID, regardless whether it’s local or
339 * The ID of the Sone to get
340 * @return The Sone with the given ID, or {@code null} if there is no such
343 public Sone getSone(String id) {
344 return getSone(id, true);
348 * Returns the Sone with the given ID, regardless whether it’s local or
352 * The ID of the Sone to get
354 * {@code true} to create a new Sone if none exists,
355 * {@code false} to return {@code null} if a Sone with the given
357 * @return The Sone with the given ID, or {@code null} if there is no such
361 public Sone getSone(String id, boolean create) {
362 synchronized (sones) {
363 if (!sones.containsKey(id) && create) {
364 Sone sone = new Sone(id, false);
367 return sones.get(id);
372 * Checks whether the core knows a Sone with the given ID.
376 * @return {@code true} if there is a Sone with the given ID, {@code false}
379 public boolean hasSone(String id) {
380 synchronized (sones) {
381 return sones.containsKey(id);
386 * Returns all local Sones.
388 * @return All local Sones
390 public Collection<Sone> getLocalSones() {
391 synchronized (sones) {
392 return Collections2.filter(sones.values(), new Predicate<Sone>() {
395 public boolean apply(Sone sone) {
396 return sone.isLocal();
403 * Returns the local Sone with the given ID, optionally creating a new Sone.
408 * {@code true} to create a new Sone if none exists,
409 * {@code false} to return null if none exists
410 * @return The Sone with the given ID, or {@code null}
412 public Sone getLocalSone(String id, boolean create) {
413 synchronized (sones) {
414 Sone sone = sones.get(id);
415 if ((sone == null) && create) {
416 sone = new Sone(id, true);
419 if ((sone != null) && !sone.isLocal()) {
420 sone = new Sone(id, true);
428 * Returns all remote Sones.
430 * @return All remote Sones
432 public Collection<Sone> getRemoteSones() {
433 synchronized (sones) {
434 return Collections2.filter(sones.values(), new Predicate<Sone>() {
437 public boolean apply(Sone sone) {
438 return !sone.isLocal();
445 * Returns the remote Sone with the given ID.
448 * The ID of the remote Sone to get
450 * {@code true} to always create a Sone, {@code false} to return
451 * {@code null} if no Sone with the given ID exists
452 * @return The Sone with the given ID
454 public Sone getRemoteSone(String id, boolean create) {
455 synchronized (sones) {
456 Sone sone = sones.get(id);
457 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
458 sone = new Sone(id, false);
466 * Returns whether the given Sone has been modified.
469 * The Sone to check for modifications
470 * @return {@code true} if a modification has been detected in the Sone,
471 * {@code false} otherwise
473 public boolean isModifiedSone(Sone sone) {
474 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
478 * Returns the time when the given was first followed by any local Sone.
481 * The Sone to get the time for
482 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
483 * been followed, or {@link Long#MAX_VALUE}
485 public long getSoneFollowingTime(Sone sone) {
486 synchronized (soneFollowingTimes) {
487 if (soneFollowingTimes.containsKey(sone)) {
488 return soneFollowingTimes.get(sone);
490 return Long.MAX_VALUE;
495 * Returns whether the target Sone is trusted by the origin Sone.
501 * @return {@code true} if the target Sone is trusted by the origin Sone
503 public boolean isSoneTrusted(Sone origin, Sone target) {
504 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
505 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
509 * Returns the post with the given ID.
512 * The ID of the post to get
513 * @return The post with the given ID, or a new post with the given ID
515 public Post getPost(String postId) {
516 return getPost(postId, true);
520 * Returns the post with the given ID, optionally creating a new post.
523 * The ID of the post to get
525 * {@code true} it create a new post if no post with the given ID
526 * exists, {@code false} to return {@code null}
527 * @return The post, or {@code null} if there is no such post
530 public Post getPost(String postId, boolean create) {
531 synchronized (posts) {
532 Post post = posts.get(postId);
533 if ((post == null) && create) {
534 post = new PostImpl(postId);
535 posts.put(postId, post);
542 * Returns all posts that have the given Sone as recipient.
544 * @see Post#getRecipient()
546 * The recipient of the posts
547 * @return All posts that have the given Sone as recipient
549 public Set<Post> getDirectedPosts(Sone recipient) {
550 Validation.begin().isNotNull("Recipient", recipient).check();
551 Set<Post> directedPosts = new HashSet<Post>();
552 synchronized (posts) {
553 for (Post post : posts.values()) {
554 if (recipient.equals(post.getRecipient())) {
555 directedPosts.add(post);
559 return directedPosts;
563 * Returns the reply with the given ID. If there is no reply with the given
564 * ID yet, a new one is created, unless {@code create} is false in which
565 * case {@code null} is returned.
568 * The ID of the reply to get
570 * {@code true} to always return a {@link Reply}, {@code false}
571 * to return {@code null} if no reply can be found
572 * @return The reply, or {@code null} if there is no such reply
574 public PostReply getPostReply(String replyId, boolean create) {
575 synchronized (replies) {
576 PostReply reply = replies.get(replyId);
577 if (create && (reply == null)) {
578 reply = new PostReply(replyId);
579 replies.put(replyId, reply);
586 * Returns all replies for the given post, order ascending by time.
589 * The post to get all replies for
590 * @return All replies for the given post
592 public List<PostReply> getReplies(Post post) {
593 Set<Sone> sones = getSones();
594 List<PostReply> replies = new ArrayList<PostReply>();
595 for (Sone sone : sones) {
596 for (PostReply reply : sone.getReplies()) {
597 if (reply.getPost().equals(post)) {
602 Collections.sort(replies, Reply.TIME_COMPARATOR);
607 * Returns all Sones that have liked the given post.
610 * The post to get the liking Sones for
611 * @return The Sones that like the given post
613 public Set<Sone> getLikes(Post post) {
614 Set<Sone> sones = new HashSet<Sone>();
615 for (Sone sone : getSones()) {
616 if (sone.getLikedPostIds().contains(post.getId())) {
624 * Returns all Sones that have liked the given reply.
627 * The reply to get the liking Sones for
628 * @return The Sones that like the given reply
630 public Set<Sone> getLikes(PostReply reply) {
631 Set<Sone> sones = new HashSet<Sone>();
632 for (Sone sone : getSones()) {
633 if (sone.getLikedReplyIds().contains(reply.getId())) {
641 * Returns whether the given post is bookmarked.
645 * @return {@code true} if the given post is bookmarked, {@code false}
648 public boolean isBookmarked(Post post) {
649 return isPostBookmarked(post.getId());
653 * Returns whether the post with the given ID is bookmarked.
656 * The ID of the post to check
657 * @return {@code true} if the post with the given ID is bookmarked,
658 * {@code false} otherwise
660 public boolean isPostBookmarked(String id) {
661 synchronized (bookmarkedPosts) {
662 return bookmarkedPosts.contains(id);
667 * Returns all currently known bookmarked posts.
669 * @return All bookmarked posts
671 public Set<Post> getBookmarkedPosts() {
672 Set<Post> posts = new HashSet<Post>();
673 synchronized (bookmarkedPosts) {
674 for (String bookmarkedPostId : bookmarkedPosts) {
675 Post post = getPost(bookmarkedPostId, false);
685 * Returns the album with the given ID, creating a new album if no album
686 * with the given ID can be found.
689 * The ID of the album
690 * @return The album with the given ID
692 public Album getAlbum(String albumId) {
693 return getAlbum(albumId, true);
697 * Returns the album with the given ID, optionally creating a new album if
698 * an album with the given ID can not be found.
701 * The ID of the album
703 * {@code true} to create a new album if none exists for the
705 * @return The album with the given ID, or {@code null} if no album with the
706 * given ID exists and {@code create} is {@code false}
708 public Album getAlbum(String albumId, boolean create) {
709 synchronized (albums) {
710 Album album = albums.get(albumId);
711 if (create && (album == null)) {
712 album = new Album(albumId);
713 albums.put(albumId, album);
720 * Returns the image with the given ID, creating it if necessary.
723 * The ID of the image
724 * @return The image with the given ID
726 public Image getImage(String imageId) {
727 return getImage(imageId, true);
731 * Returns the image with the given ID, optionally creating it if it does
735 * The ID of the image
737 * {@code true} to create an image if none exists with the given
739 * @return The image with the given ID, or {@code null} if none exists and
742 public Image getImage(String imageId, boolean create) {
743 synchronized (images) {
744 Image image = images.get(imageId);
745 if (create && (image == null)) {
746 image = new Image(imageId);
747 images.put(imageId, image);
754 * Returns the temporary image with the given ID.
757 * The ID of the temporary image
758 * @return The temporary image, or {@code null} if there is no temporary
759 * image with the given ID
761 public TemporaryImage getTemporaryImage(String imageId) {
762 synchronized (temporaryImages) {
763 return temporaryImages.get(imageId);
772 * Locks the given Sone. A locked Sone will not be inserted by
773 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
779 public void lockSone(Sone sone) {
780 synchronized (lockedSones) {
781 if (lockedSones.add(sone)) {
782 eventBus.post(new SoneLockedEvent(sone));
788 * Unlocks the given Sone.
790 * @see #lockSone(Sone)
794 public void unlockSone(Sone sone) {
795 synchronized (lockedSones) {
796 if (lockedSones.remove(sone)) {
797 eventBus.post(new SoneUnlockedEvent(sone));
803 * Adds a local Sone from the given own identity.
806 * The own identity to create a Sone from
807 * @return The added (or already existing) Sone
809 public Sone addLocalSone(OwnIdentity ownIdentity) {
810 if (ownIdentity == null) {
811 logger.log(Level.WARNING, "Given OwnIdentity is null!");
814 synchronized (sones) {
817 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
818 } catch (MalformedURLException mue1) {
819 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
822 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
823 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
825 /* TODO - load posts ’n stuff */
826 sones.put(ownIdentity.getId(), sone);
827 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
828 soneInserter.addSoneInsertListener(this);
829 soneInserters.put(sone, soneInserter);
830 sone.setStatus(SoneStatus.idle);
832 soneInserter.start();
838 * Creates a new Sone for the given own identity.
841 * The own identity to create a Sone for
842 * @return The created Sone
844 public Sone createSone(OwnIdentity ownIdentity) {
845 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
846 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
849 Sone sone = addLocalSone(ownIdentity);
850 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
851 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
852 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
853 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
854 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
855 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
857 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
858 touchConfiguration();
863 * Adds the Sone of the given identity.
866 * The identity whose Sone to add
867 * @return The added or already existing Sone
869 public Sone addRemoteSone(Identity identity) {
870 if (identity == null) {
871 logger.log(Level.WARNING, "Given Identity is null!");
874 synchronized (sones) {
875 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
876 boolean newSone = sone.getRequestUri() == null;
877 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
878 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
880 synchronized (knownSones) {
881 newSone = !knownSones.contains(sone.getId());
883 sone.setKnown(!newSone);
885 eventBus.post(new NewSoneFoundEvent(sone));
886 for (Sone localSone : getLocalSones()) {
887 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
888 followSone(localSone, sone);
893 soneDownloader.addSone(sone);
894 soneDownloaders.execute(new Runnable() {
897 @SuppressWarnings("synthetic-access")
899 soneDownloader.fetchSone(sone, sone.getRequestUri());
908 * Lets the given local Sone follow the Sone with the given ID.
911 * The local Sone that should follow another Sone
913 * The ID of the Sone to follow
915 public void followSone(Sone sone, String soneId) {
916 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
917 Sone followedSone = getSone(soneId, true);
918 if (followedSone == null) {
919 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
922 followSone(sone, getSone(soneId));
926 * Lets the given local Sone follow the other given Sone. If the given Sone
927 * was not followed by any local Sone before, this will mark all elements of
928 * the followed Sone as read that have been created before the current
932 * The local Sone that should follow the other Sone
933 * @param followedSone
934 * The Sone that should be followed
936 public void followSone(Sone sone, Sone followedSone) {
937 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
938 sone.addFriend(followedSone.getId());
939 synchronized (soneFollowingTimes) {
940 if (!soneFollowingTimes.containsKey(followedSone)) {
941 long now = System.currentTimeMillis();
942 soneFollowingTimes.put(followedSone, now);
943 for (Post post : followedSone.getPosts()) {
944 if (post.getTime() < now) {
948 for (PostReply reply : followedSone.getReplies()) {
949 if (reply.getTime() < now) {
950 markReplyKnown(reply);
955 touchConfiguration();
959 * Lets the given local Sone unfollow the Sone with the given ID.
962 * The local Sone that should unfollow another Sone
964 * The ID of the Sone being unfollowed
966 public void unfollowSone(Sone sone, String soneId) {
967 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
968 unfollowSone(sone, getSone(soneId, false));
972 * Lets the given local Sone unfollow the other given Sone. If the given
973 * local Sone is the last local Sone that followed the given Sone, its
974 * following time will be removed.
977 * The local Sone that should unfollow another Sone
978 * @param unfollowedSone
979 * The Sone being unfollowed
981 public void unfollowSone(Sone sone, Sone unfollowedSone) {
982 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
983 sone.removeFriend(unfollowedSone.getId());
984 boolean unfollowedSoneStillFollowed = false;
985 for (Sone localSone : getLocalSones()) {
986 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
988 if (!unfollowedSoneStillFollowed) {
989 synchronized (soneFollowingTimes) {
990 soneFollowingTimes.remove(unfollowedSone);
993 touchConfiguration();
997 * Sets the trust value of the given origin Sone for the target Sone.
1004 * The trust value (from {@code -100} to {@code 100})
1006 public void setTrust(Sone origin, Sone target, int trustValue) {
1007 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();
1008 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1012 * Removes any trust assignment for the given target Sone.
1019 public void removeTrust(Sone origin, Sone target) {
1020 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1021 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1025 * Assigns the configured positive trust value for the given target.
1032 public void trustSone(Sone origin, Sone target) {
1033 setTrust(origin, target, preferences.getPositiveTrust());
1037 * Assigns the configured negative trust value for the given target.
1044 public void distrustSone(Sone origin, Sone target) {
1045 setTrust(origin, target, preferences.getNegativeTrust());
1049 * Removes the trust assignment for the given target.
1056 public void untrustSone(Sone origin, Sone target) {
1057 removeTrust(origin, target);
1061 * Updates the stored Sone with the given Sone.
1066 public void updateSone(Sone sone) {
1067 updateSone(sone, false);
1071 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1072 * {@code true}, an older Sone than the current Sone can be given to restore
1076 * The Sone to update
1077 * @param soneRescueMode
1078 * {@code true} if the stored Sone should be updated regardless
1079 * of the age of the given Sone
1081 public void updateSone(Sone sone, boolean soneRescueMode) {
1082 if (hasSone(sone.getId())) {
1083 Sone storedSone = getSone(sone.getId());
1084 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1085 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1088 synchronized (posts) {
1089 if (!soneRescueMode) {
1090 for (Post post : storedSone.getPosts()) {
1091 posts.remove(post.getId());
1092 if (!sone.getPosts().contains(post)) {
1093 eventBus.post(new PostRemovedEvent(post));
1097 List<Post> storedPosts = storedSone.getPosts();
1098 synchronized (knownPosts) {
1099 for (Post post : sone.getPosts()) {
1100 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1101 if (!storedPosts.contains(post)) {
1102 if (post.getTime() < getSoneFollowingTime(sone)) {
1103 knownPosts.add(post.getId());
1104 post.setKnown(true);
1105 } else if (!knownPosts.contains(post.getId())) {
1106 eventBus.post(new NewPostFoundEvent(post));
1109 posts.put(post.getId(), post);
1113 synchronized (replies) {
1114 if (!soneRescueMode) {
1115 for (PostReply reply : storedSone.getReplies()) {
1116 replies.remove(reply.getId());
1117 if (!sone.getReplies().contains(reply)) {
1118 eventBus.post(new PostReplyRemovedEvent(reply));
1122 Set<PostReply> storedReplies = storedSone.getReplies();
1123 synchronized (knownReplies) {
1124 for (PostReply reply : sone.getReplies()) {
1125 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1126 if (!storedReplies.contains(reply)) {
1127 if (reply.getTime() < getSoneFollowingTime(sone)) {
1128 knownReplies.add(reply.getId());
1129 reply.setKnown(true);
1130 } else if (!knownReplies.contains(reply.getId())) {
1131 eventBus.post(new NewPostReplyFoundEvent(reply));
1134 replies.put(reply.getId(), reply);
1138 synchronized (albums) {
1139 synchronized (images) {
1140 for (Album album : storedSone.getAlbums()) {
1141 albums.remove(album.getId());
1142 for (Image image : album.getImages()) {
1143 images.remove(image.getId());
1146 for (Album album : sone.getAlbums()) {
1147 albums.put(album.getId(), album);
1148 for (Image image : album.getImages()) {
1149 images.put(image.getId(), image);
1154 synchronized (storedSone) {
1155 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1156 storedSone.setTime(sone.getTime());
1158 storedSone.setClient(sone.getClient());
1159 storedSone.setProfile(sone.getProfile());
1160 if (soneRescueMode) {
1161 for (Post post : sone.getPosts()) {
1162 storedSone.addPost(post);
1164 for (PostReply reply : sone.getReplies()) {
1165 storedSone.addReply(reply);
1167 for (String likedPostId : sone.getLikedPostIds()) {
1168 storedSone.addLikedPostId(likedPostId);
1170 for (String likedReplyId : sone.getLikedReplyIds()) {
1171 storedSone.addLikedReplyId(likedReplyId);
1173 for (Album album : sone.getAlbums()) {
1174 storedSone.addAlbum(album);
1177 storedSone.setPosts(sone.getPosts());
1178 storedSone.setReplies(sone.getReplies());
1179 storedSone.setLikePostIds(sone.getLikedPostIds());
1180 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1181 storedSone.setAlbums(sone.getAlbums());
1183 storedSone.setLatestEdition(sone.getLatestEdition());
1189 * Deletes the given Sone. This will remove the Sone from the
1190 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1191 * remove the context from its identity.
1194 * The Sone to delete
1196 public void deleteSone(Sone sone) {
1197 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1198 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1201 synchronized (sones) {
1202 if (!getLocalSones().contains(sone)) {
1203 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1206 sones.remove(sone.getId());
1207 SoneInserter soneInserter = soneInserters.remove(sone);
1208 soneInserter.removeSoneInsertListener(this);
1209 soneInserter.stop();
1211 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1212 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1214 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1215 } catch (ConfigurationException ce1) {
1216 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1221 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1222 * known} before, a {@link MarkSoneKnownEvent} is fired.
1225 * The Sone to mark as known
1227 public void markSoneKnown(Sone sone) {
1228 if (!sone.isKnown()) {
1229 sone.setKnown(true);
1230 synchronized (knownSones) {
1231 knownSones.add(sone.getId());
1233 eventBus.post(new MarkSoneKnownEvent(sone));
1234 touchConfiguration();
1239 * Loads and updates the given Sone from the configuration. If any error is
1240 * encountered, loading is aborted and the given Sone is not changed.
1243 * The Sone to load and update
1245 public void loadSone(Sone sone) {
1246 if (!sone.isLocal()) {
1247 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1251 /* initialize options. */
1252 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1253 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1254 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1255 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1256 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1257 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1260 String sonePrefix = "Sone/" + sone.getId();
1261 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1262 if (soneTime == null) {
1263 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1266 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1269 Profile profile = new Profile(sone);
1270 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1271 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1272 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1273 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1274 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1275 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1277 /* load profile fields. */
1279 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1280 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1281 if (fieldName == null) {
1284 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1285 profile.addField(fieldName).setValue(fieldValue);
1289 Set<Post> posts = new HashSet<Post>();
1291 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1292 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1293 if (postId == null) {
1296 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1297 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1298 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1299 if ((postTime == 0) || (postText == null)) {
1300 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1303 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1304 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1305 post.setRecipient(getSone(postRecipientId));
1311 Set<PostReply> replies = new HashSet<PostReply>();
1313 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1314 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1315 if (replyId == null) {
1318 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1319 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1320 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1321 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1322 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1325 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1328 /* load post likes. */
1329 Set<String> likedPostIds = new HashSet<String>();
1331 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1332 if (likedPostId == null) {
1335 likedPostIds.add(likedPostId);
1338 /* load reply likes. */
1339 Set<String> likedReplyIds = new HashSet<String>();
1341 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1342 if (likedReplyId == null) {
1345 likedReplyIds.add(likedReplyId);
1349 Set<String> friends = new HashSet<String>();
1351 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1352 if (friendId == null) {
1355 friends.add(friendId);
1359 List<Album> topLevelAlbums = new ArrayList<Album>();
1360 int albumCounter = 0;
1362 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1363 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1364 if (albumId == null) {
1367 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1368 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1369 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1370 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1371 if ((albumTitle == null) || (albumDescription == null)) {
1372 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1375 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1376 if (albumParentId != null) {
1377 Album parentAlbum = getAlbum(albumParentId, false);
1378 if (parentAlbum == null) {
1379 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1382 parentAlbum.addAlbum(album);
1384 if (!topLevelAlbums.contains(album)) {
1385 topLevelAlbums.add(album);
1391 int imageCounter = 0;
1393 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1394 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1395 if (imageId == null) {
1398 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1399 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1400 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1401 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1402 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1403 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1404 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1405 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1406 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1409 Album album = getAlbum(albumId, false);
1410 if (album == null) {
1411 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1414 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1415 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1416 album.addImage(image);
1420 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1421 if (avatarId != null) {
1422 profile.setAvatar(getImage(avatarId, false));
1426 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1427 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1428 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1429 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1430 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1431 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1433 /* if we’re still here, Sone was loaded successfully. */
1434 synchronized (sone) {
1435 sone.setTime(soneTime);
1436 sone.setProfile(profile);
1437 sone.setPosts(posts);
1438 sone.setReplies(replies);
1439 sone.setLikePostIds(likedPostIds);
1440 sone.setLikeReplyIds(likedReplyIds);
1441 for (String friendId : friends) {
1442 followSone(sone, friendId);
1444 sone.setAlbums(topLevelAlbums);
1445 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1447 synchronized (knownSones) {
1448 for (String friend : friends) {
1449 knownSones.add(friend);
1452 synchronized (knownPosts) {
1453 for (Post post : posts) {
1454 knownPosts.add(post.getId());
1457 synchronized (knownReplies) {
1458 for (PostReply reply : replies) {
1459 knownReplies.add(reply.getId());
1465 * Creates a new post.
1468 * The Sone that creates the post
1470 * The text of the post
1471 * @return The created post
1473 public Post createPost(Sone sone, String text) {
1474 return createPost(sone, System.currentTimeMillis(), text);
1478 * Creates a new post.
1481 * The Sone that creates the post
1483 * The time of the post
1485 * The text of the post
1486 * @return The created post
1488 public Post createPost(Sone sone, long time, String text) {
1489 return createPost(sone, null, time, text);
1493 * Creates a new post.
1496 * The Sone that creates the post
1498 * The recipient Sone, or {@code null} if this post does not have
1501 * The text of the post
1502 * @return The created post
1504 public Post createPost(Sone sone, Sone recipient, String text) {
1505 return createPost(sone, recipient, System.currentTimeMillis(), text);
1509 * Creates a new post.
1512 * The Sone that creates the post
1514 * The recipient Sone, or {@code null} if this post does not have
1517 * The time of the post
1519 * The text of the post
1520 * @return The created post
1522 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1523 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1524 if (!sone.isLocal()) {
1525 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1528 final Post post = new PostImpl(sone, time, text);
1529 if (recipient != null) {
1530 post.setRecipient(recipient);
1532 synchronized (posts) {
1533 posts.put(post.getId(), post);
1535 eventBus.post(new NewPostFoundEvent(post));
1537 touchConfiguration();
1538 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1545 markPostKnown(post);
1547 }, "Mark " + post + " read.");
1552 * Deletes the given post.
1555 * The post to delete
1557 public void deletePost(Post post) {
1558 if (!post.getSone().isLocal()) {
1559 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1562 post.getSone().removePost(post);
1563 synchronized (posts) {
1564 posts.remove(post.getId());
1566 eventBus.post(new PostRemovedEvent(post));
1567 markPostKnown(post);
1568 touchConfiguration();
1572 * Marks the given post as known, if it is currently not a known post
1573 * (according to {@link Post#isKnown()}).
1576 * The post to mark as known
1578 public void markPostKnown(Post post) {
1579 post.setKnown(true);
1580 synchronized (knownPosts) {
1581 eventBus.post(new MarkPostKnownEvent(post));
1582 if (knownPosts.add(post.getId())) {
1583 touchConfiguration();
1586 for (PostReply reply : getReplies(post)) {
1587 markReplyKnown(reply);
1592 * Bookmarks the given post.
1595 * The post to bookmark
1597 public void bookmark(Post post) {
1598 bookmarkPost(post.getId());
1602 * Bookmarks the post with the given ID.
1605 * The ID of the post to bookmark
1607 public void bookmarkPost(String id) {
1608 synchronized (bookmarkedPosts) {
1609 bookmarkedPosts.add(id);
1614 * Removes the given post from the bookmarks.
1617 * The post to unbookmark
1619 public void unbookmark(Post post) {
1620 unbookmarkPost(post.getId());
1624 * Removes the post with the given ID from the bookmarks.
1627 * The ID of the post to unbookmark
1629 public void unbookmarkPost(String id) {
1630 synchronized (bookmarkedPosts) {
1631 bookmarkedPosts.remove(id);
1636 * Creates a new reply.
1639 * The Sone that creates the reply
1641 * The post that this reply refers to
1643 * The text of the reply
1644 * @return The created reply
1646 public PostReply createReply(Sone sone, Post post, String text) {
1647 return createReply(sone, post, System.currentTimeMillis(), text);
1651 * Creates a new reply.
1654 * The Sone that creates the reply
1656 * The post that this reply refers to
1658 * The time of the reply
1660 * The text of the reply
1661 * @return The created reply
1663 public PostReply createReply(Sone sone, Post post, long time, String text) {
1664 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1665 if (!sone.isLocal()) {
1666 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1669 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1670 synchronized (replies) {
1671 replies.put(reply.getId(), reply);
1673 synchronized (knownReplies) {
1674 eventBus.post(new NewPostReplyFoundEvent(reply));
1676 sone.addReply(reply);
1677 touchConfiguration();
1678 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1685 markReplyKnown(reply);
1687 }, "Mark " + reply + " read.");
1692 * Deletes the given reply.
1695 * The reply to delete
1697 public void deleteReply(PostReply reply) {
1698 Sone sone = reply.getSone();
1699 if (!sone.isLocal()) {
1700 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1703 synchronized (replies) {
1704 replies.remove(reply.getId());
1706 synchronized (knownReplies) {
1707 markReplyKnown(reply);
1708 knownReplies.remove(reply.getId());
1710 sone.removeReply(reply);
1711 touchConfiguration();
1715 * Marks the given reply as known, if it is currently not a known reply
1716 * (according to {@link Reply#isKnown()}).
1719 * The reply to mark as known
1721 public void markReplyKnown(PostReply reply) {
1722 reply.setKnown(true);
1723 synchronized (knownReplies) {
1724 eventBus.post(new MarkPostReplyKnownEvent(reply));
1725 if (knownReplies.add(reply.getId())) {
1726 touchConfiguration();
1732 * Creates a new top-level album for the given Sone.
1735 * The Sone to create the album for
1736 * @return The new album
1738 public Album createAlbum(Sone sone) {
1739 return createAlbum(sone, null);
1743 * Creates a new album for the given Sone.
1746 * The Sone to create the album for
1748 * The parent of the album (may be {@code null} to create a
1750 * @return The new album
1752 public Album createAlbum(Sone sone, Album parent) {
1753 Album album = new Album();
1754 synchronized (albums) {
1755 albums.put(album.getId(), album);
1757 album.setSone(sone);
1758 if (parent != null) {
1759 parent.addAlbum(album);
1761 sone.addAlbum(album);
1767 * Deletes the given album. The owner of the album has to be a local Sone,
1768 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1771 * The album to remove
1773 public void deleteAlbum(Album album) {
1774 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1775 if (!album.isEmpty()) {
1778 if (album.getParent() == null) {
1779 album.getSone().removeAlbum(album);
1781 album.getParent().removeAlbum(album);
1783 synchronized (albums) {
1784 albums.remove(album.getId());
1786 touchConfiguration();
1790 * Creates a new image.
1793 * The Sone creating the image
1795 * The album the image will be inserted into
1796 * @param temporaryImage
1797 * The temporary image to create the image from
1798 * @return The newly created image
1800 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1801 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();
1802 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1803 album.addImage(image);
1804 synchronized (images) {
1805 images.put(image.getId(), image);
1807 imageInserter.insertImage(temporaryImage, image);
1812 * Deletes the given image. This method will also delete a matching
1815 * @see #deleteTemporaryImage(TemporaryImage)
1817 * The image to delete
1819 public void deleteImage(Image image) {
1820 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1821 deleteTemporaryImage(image.getId());
1822 image.getAlbum().removeImage(image);
1823 synchronized (images) {
1824 images.remove(image.getId());
1826 touchConfiguration();
1830 * Creates a new temporary image.
1833 * The MIME type of the temporary image
1835 * The encoded data of the image
1836 * @return The temporary image
1838 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1839 TemporaryImage temporaryImage = new TemporaryImage();
1840 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1841 synchronized (temporaryImages) {
1842 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1844 return temporaryImage;
1848 * Deletes the given temporary image.
1850 * @param temporaryImage
1851 * The temporary image to delete
1853 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1854 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1855 deleteTemporaryImage(temporaryImage.getId());
1859 * Deletes the temporary image with the given ID.
1862 * The ID of the temporary image to delete
1864 public void deleteTemporaryImage(String imageId) {
1865 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1866 synchronized (temporaryImages) {
1867 temporaryImages.remove(imageId);
1869 Image image = getImage(imageId, false);
1870 if (image != null) {
1871 imageInserter.cancelImageInsert(image);
1876 * Notifies the core that the configuration, either of the core or of a
1877 * single local Sone, has changed, and that the configuration should be
1880 public void touchConfiguration() {
1881 lastConfigurationUpdate = System.currentTimeMillis();
1892 public void serviceStart() {
1893 loadConfiguration();
1894 updateChecker.addUpdateListener(this);
1895 updateChecker.start();
1896 identityManager.addIdentityListener(this);
1897 identityManager.start();
1898 webOfTrustUpdater.init();
1899 webOfTrustUpdater.start();
1906 public void serviceRun() {
1907 long lastSaved = System.currentTimeMillis();
1908 while (!shouldStop()) {
1910 long now = System.currentTimeMillis();
1911 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1912 for (Sone localSone : getLocalSones()) {
1913 saveSone(localSone);
1915 saveConfiguration();
1925 public void serviceStop() {
1926 synchronized (sones) {
1927 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1928 soneInserter.getValue().removeSoneInsertListener(this);
1929 soneInserter.getValue().stop();
1930 saveSone(soneInserter.getKey());
1933 saveConfiguration();
1934 webOfTrustUpdater.stop();
1935 updateChecker.stop();
1936 updateChecker.removeUpdateListener(this);
1937 soneDownloader.stop();
1938 identityManager.removeIdentityListener(this);
1939 identityManager.stop();
1947 * Saves the given Sone. This will persist all local settings for the given
1948 * Sone, such as the friends list and similar, private options.
1953 private synchronized void saveSone(Sone sone) {
1954 if (!sone.isLocal()) {
1955 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1958 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1959 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1963 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1965 /* save Sone into configuration. */
1966 String sonePrefix = "Sone/" + sone.getId();
1967 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1968 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1971 Profile profile = sone.getProfile();
1972 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1973 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1974 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1975 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1976 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1977 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1978 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1980 /* save profile fields. */
1981 int fieldCounter = 0;
1982 for (Field profileField : profile.getFields()) {
1983 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1984 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1985 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1987 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1990 int postCounter = 0;
1991 for (Post post : sone.getPosts()) {
1992 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1993 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1994 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1995 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1996 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1998 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2001 int replyCounter = 0;
2002 for (PostReply reply : sone.getReplies()) {
2003 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2004 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2005 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2006 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2007 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2009 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2011 /* save post likes. */
2012 int postLikeCounter = 0;
2013 for (String postId : sone.getLikedPostIds()) {
2014 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2016 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2018 /* save reply likes. */
2019 int replyLikeCounter = 0;
2020 for (String replyId : sone.getLikedReplyIds()) {
2021 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2023 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2026 int friendCounter = 0;
2027 for (String friendId : sone.getFriends()) {
2028 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2030 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2032 /* save albums. first, collect in a flat structure, top-level first. */
2033 List<Album> albums = sone.getAllAlbums();
2035 int albumCounter = 0;
2036 for (Album album : albums) {
2037 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2038 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2039 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2040 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2041 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2042 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2044 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2047 int imageCounter = 0;
2048 for (Album album : albums) {
2049 for (Image image : album.getImages()) {
2050 if (!image.isInserted()) {
2053 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2054 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2055 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2056 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2057 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2058 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2059 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2060 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2061 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2064 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2067 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2068 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2069 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2070 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2071 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2072 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2074 configuration.save();
2076 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2078 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2079 } catch (ConfigurationException ce1) {
2080 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2085 * Saves the current options.
2087 private void saveConfiguration() {
2088 synchronized (configuration) {
2089 if (storingConfiguration) {
2090 logger.log(Level.FINE, "Already storing configuration…");
2093 storingConfiguration = true;
2096 /* store the options first. */
2098 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2099 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2100 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2101 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2102 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2103 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2104 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2105 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2106 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2107 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2108 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2109 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2111 /* save known Sones. */
2112 int soneCounter = 0;
2113 synchronized (knownSones) {
2114 for (String knownSoneId : knownSones) {
2115 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2117 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2120 /* save Sone following times. */
2122 synchronized (soneFollowingTimes) {
2123 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2124 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2125 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2128 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2131 /* save known posts. */
2132 int postCounter = 0;
2133 synchronized (knownPosts) {
2134 for (String knownPostId : knownPosts) {
2135 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2137 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2140 /* save known replies. */
2141 int replyCounter = 0;
2142 synchronized (knownReplies) {
2143 for (String knownReplyId : knownReplies) {
2144 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2146 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2149 /* save bookmarked posts. */
2150 int bookmarkedPostCounter = 0;
2151 synchronized (bookmarkedPosts) {
2152 for (String bookmarkedPostId : bookmarkedPosts) {
2153 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2156 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2159 configuration.save();
2161 } catch (ConfigurationException ce1) {
2162 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2164 synchronized (configuration) {
2165 storingConfiguration = false;
2171 * Loads the configuration.
2173 @SuppressWarnings("unchecked")
2174 private void loadConfiguration() {
2175 /* create options. */
2176 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2179 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2180 SoneInserter.setInsertionDelay(newValue);
2184 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2185 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2186 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2187 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2188 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2189 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2190 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2191 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2192 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2195 @SuppressWarnings("synthetic-access")
2196 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2197 fcpInterface.setActive(newValue);
2200 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2203 @SuppressWarnings("synthetic-access")
2204 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2205 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2210 loadConfigurationValue("InsertionDelay");
2211 loadConfigurationValue("PostsPerPage");
2212 loadConfigurationValue("ImagesPerPage");
2213 loadConfigurationValue("CharactersPerPost");
2214 loadConfigurationValue("PostCutOffLength");
2215 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2216 loadConfigurationValue("PositiveTrust");
2217 loadConfigurationValue("NegativeTrust");
2218 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2219 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2220 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2222 /* load known Sones. */
2223 int soneCounter = 0;
2225 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2226 if (knownSoneId == null) {
2229 synchronized (knownSones) {
2230 knownSones.add(knownSoneId);
2234 /* load Sone following times. */
2237 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2238 if (soneId == null) {
2241 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2242 Sone followedSone = getSone(soneId);
2243 if (followedSone == null) {
2244 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2246 synchronized (soneFollowingTimes) {
2247 soneFollowingTimes.put(getSone(soneId), time);
2253 /* load known posts. */
2254 int postCounter = 0;
2256 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2257 if (knownPostId == null) {
2260 synchronized (knownPosts) {
2261 knownPosts.add(knownPostId);
2265 /* load known replies. */
2266 int replyCounter = 0;
2268 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2269 if (knownReplyId == null) {
2272 synchronized (knownReplies) {
2273 knownReplies.add(knownReplyId);
2277 /* load bookmarked posts. */
2278 int bookmarkedPostCounter = 0;
2280 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2281 if (bookmarkedPostId == null) {
2284 synchronized (bookmarkedPosts) {
2285 bookmarkedPosts.add(bookmarkedPostId);
2292 * Loads an {@link Integer} configuration value for the option with the
2293 * given name, logging validation failures.
2296 * The name of the option to load
2298 private void loadConfigurationValue(String optionName) {
2300 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2301 } catch (IllegalArgumentException iae1) {
2302 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2307 * Generate a Sone URI from the given URI and latest edition.
2310 * The URI to derive the Sone URI from
2311 * @return The derived URI
2313 private static FreenetURI getSoneUri(String uriString) {
2315 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2317 } catch (MalformedURLException mue1) {
2318 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2324 // INTERFACE IdentityListener
2331 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2332 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2333 if (ownIdentity.hasContext("Sone")) {
2334 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2335 addLocalSone(ownIdentity);
2343 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2344 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2345 trustedIdentities.remove(ownIdentity);
2352 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2353 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2354 trustedIdentities.get(ownIdentity).add(identity);
2355 addRemoteSone(identity);
2362 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2363 soneDownloaders.execute(new Runnable() {
2366 @SuppressWarnings("synthetic-access")
2368 Sone sone = getRemoteSone(identity.getId(), false);
2369 sone.setIdentity(identity);
2370 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2371 soneDownloader.addSone(sone);
2372 soneDownloader.fetchSone(sone);
2381 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2382 trustedIdentities.get(ownIdentity).remove(identity);
2383 boolean foundIdentity = false;
2384 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2385 if (trustedIdentity.getKey().equals(ownIdentity)) {
2388 if (trustedIdentity.getValue().contains(identity)) {
2389 foundIdentity = true;
2392 if (foundIdentity) {
2393 /* some local identity still trusts this identity, don’t remove. */
2396 Sone sone = getSone(identity.getId(), false);
2398 /* TODO - we don’t have the Sone anymore. should this happen? */
2401 synchronized (posts) {
2402 synchronized (knownPosts) {
2403 for (Post post : sone.getPosts()) {
2404 posts.remove(post.getId());
2405 eventBus.post(new PostRemovedEvent(post));
2409 synchronized (replies) {
2410 synchronized (knownReplies) {
2411 for (PostReply reply : sone.getReplies()) {
2412 replies.remove(reply.getId());
2413 eventBus.post(new PostReplyRemovedEvent(reply));
2417 synchronized (sones) {
2418 sones.remove(identity.getId());
2420 eventBus.post(new SoneRemovedEvent(sone));
2424 // INTERFACE UpdateListener
2431 public void updateFound(Version version, long releaseTime, long latestEdition) {
2432 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2436 // INTERFACE ImageInsertListener
2443 public void insertStarted(Sone sone) {
2444 eventBus.post(new SoneInsertingEvent(sone));
2451 public void insertFinished(Sone sone, long insertDuration) {
2452 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2459 public void insertAborted(Sone sone, Throwable cause) {
2460 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2464 * Deletes the temporary image.
2466 * @param imageInsertFinishedEvent
2470 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2471 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2472 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2473 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2474 touchConfiguration();
2478 * Convenience interface for external classes that want to access the core’s
2481 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2483 public static class Preferences {
2485 /** The wrapped options. */
2486 private final Options options;
2489 * Creates a new preferences object wrapped around the given options.
2492 * The options to wrap
2494 public Preferences(Options options) {
2495 this.options = options;
2499 * Returns the insertion delay.
2501 * @return The insertion delay
2503 public int getInsertionDelay() {
2504 return options.getIntegerOption("InsertionDelay").get();
2508 * Validates the given insertion delay.
2510 * @param insertionDelay
2511 * The insertion delay to validate
2512 * @return {@code true} if the given insertion delay was valid,
2513 * {@code false} otherwise
2515 public boolean validateInsertionDelay(Integer insertionDelay) {
2516 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2520 * Sets the insertion delay
2522 * @param insertionDelay
2523 * The new insertion delay, or {@code null} to restore it to
2525 * @return This preferences
2527 public Preferences setInsertionDelay(Integer insertionDelay) {
2528 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2533 * Returns the number of posts to show per page.
2535 * @return The number of posts to show per page
2537 public int getPostsPerPage() {
2538 return options.getIntegerOption("PostsPerPage").get();
2542 * Validates the number of posts per page.
2544 * @param postsPerPage
2545 * The number of posts per page
2546 * @return {@code true} if the number of posts per page was valid,
2547 * {@code false} otherwise
2549 public boolean validatePostsPerPage(Integer postsPerPage) {
2550 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2554 * Sets the number of posts to show per page.
2556 * @param postsPerPage
2557 * The number of posts to show per page
2558 * @return This preferences object
2560 public Preferences setPostsPerPage(Integer postsPerPage) {
2561 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2566 * Returns the number of images to show per page.
2568 * @return The number of images to show per page
2570 public int getImagesPerPage() {
2571 return options.getIntegerOption("ImagesPerPage").get();
2575 * Validates the number of images per page.
2577 * @param imagesPerPage
2578 * The number of images per page
2579 * @return {@code true} if the number of images per page was valid,
2580 * {@code false} otherwise
2582 public boolean validateImagesPerPage(Integer imagesPerPage) {
2583 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2587 * Sets the number of images per page.
2589 * @param imagesPerPage
2590 * The number of images per page
2591 * @return This preferences object
2593 public Preferences setImagesPerPage(Integer imagesPerPage) {
2594 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2599 * Returns the number of characters per post, or <code>-1</code> if the
2600 * posts should not be cut off.
2602 * @return The numbers of characters per post
2604 public int getCharactersPerPost() {
2605 return options.getIntegerOption("CharactersPerPost").get();
2609 * Validates the number of characters per post.
2611 * @param charactersPerPost
2612 * The number of characters per post
2613 * @return {@code true} if the number of characters per post was valid,
2614 * {@code false} otherwise
2616 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2617 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2621 * Sets the number of characters per post.
2623 * @param charactersPerPost
2624 * The number of characters per post, or <code>-1</code> to
2625 * not cut off the posts
2626 * @return This preferences objects
2628 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2629 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2634 * Returns the number of characters the shortened post should have.
2636 * @return The number of characters of the snippet
2638 public int getPostCutOffLength() {
2639 return options.getIntegerOption("PostCutOffLength").get();
2643 * Validates the number of characters after which to cut off the post.
2645 * @param postCutOffLength
2646 * The number of characters of the snippet
2647 * @return {@code true} if the number of characters of the snippet is
2648 * valid, {@code false} otherwise
2650 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2651 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2655 * Sets the number of characters the shortened post should have.
2657 * @param postCutOffLength
2658 * The number of characters of the snippet
2659 * @return This preferences
2661 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2662 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2667 * Returns whether Sone requires full access to be even visible.
2669 * @return {@code true} if Sone requires full access, {@code false}
2672 public boolean isRequireFullAccess() {
2673 return options.getBooleanOption("RequireFullAccess").get();
2677 * Sets whether Sone requires full access to be even visible.
2679 * @param requireFullAccess
2680 * {@code true} if Sone requires full access, {@code false}
2683 public void setRequireFullAccess(Boolean requireFullAccess) {
2684 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2688 * Returns the positive trust.
2690 * @return The positive trust
2692 public int getPositiveTrust() {
2693 return options.getIntegerOption("PositiveTrust").get();
2697 * Validates the positive trust.
2699 * @param positiveTrust
2700 * The positive trust to validate
2701 * @return {@code true} if the positive trust was valid, {@code false}
2704 public boolean validatePositiveTrust(Integer positiveTrust) {
2705 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2709 * Sets the positive trust.
2711 * @param positiveTrust
2712 * The new positive trust, or {@code null} to restore it to
2714 * @return This preferences
2716 public Preferences setPositiveTrust(Integer positiveTrust) {
2717 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2722 * Returns the negative trust.
2724 * @return The negative trust
2726 public int getNegativeTrust() {
2727 return options.getIntegerOption("NegativeTrust").get();
2731 * Validates the negative trust.
2733 * @param negativeTrust
2734 * The negative trust to validate
2735 * @return {@code true} if the negative trust was valid, {@code false}
2738 public boolean validateNegativeTrust(Integer negativeTrust) {
2739 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2743 * Sets the negative trust.
2745 * @param negativeTrust
2746 * The negative trust, or {@code null} to restore it to the
2748 * @return The preferences
2750 public Preferences setNegativeTrust(Integer negativeTrust) {
2751 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2756 * Returns the trust comment. This is the comment that is set in the web
2757 * of trust when a trust value is assigned to an identity.
2759 * @return The trust comment
2761 public String getTrustComment() {
2762 return options.getStringOption("TrustComment").get();
2766 * Sets the trust comment.
2768 * @param trustComment
2769 * The trust comment, or {@code null} to restore it to the
2771 * @return This preferences
2773 public Preferences setTrustComment(String trustComment) {
2774 options.getStringOption("TrustComment").set(trustComment);
2779 * Returns whether the {@link FcpInterface FCP interface} is currently
2782 * @see FcpInterface#setActive(boolean)
2783 * @return {@code true} if the FCP interface is currently active,
2784 * {@code false} otherwise
2786 public boolean isFcpInterfaceActive() {
2787 return options.getBooleanOption("ActivateFcpInterface").get();
2791 * Sets whether the {@link FcpInterface FCP interface} is currently
2794 * @see FcpInterface#setActive(boolean)
2795 * @param fcpInterfaceActive
2796 * {@code true} to activate the FCP interface, {@code false}
2797 * to deactivate the FCP interface
2798 * @return This preferences object
2800 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2801 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2806 * Returns the action level for which full access to the FCP interface
2809 * @return The action level for which full access to the FCP interface
2812 public FullAccessRequired getFcpFullAccessRequired() {
2813 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2817 * Sets the action level for which full access to the FCP interface is
2820 * @param fcpFullAccessRequired
2822 * @return This preferences
2824 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2825 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);