2 * Sone - Core.java - Copyright © 2010–2013 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 static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Map.Entry;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
40 import net.pterodactylus.sone.core.Options.DefaultOption;
41 import net.pterodactylus.sone.core.Options.Option;
42 import net.pterodactylus.sone.core.Options.OptionWatcher;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostBuilder;
60 import net.pterodactylus.sone.data.PostBuilderFactory;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.data.impl.PostReplyImpl;
70 import net.pterodactylus.sone.fcp.FcpInterface;
71 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
72 import net.pterodactylus.sone.freenet.wot.Identity;
73 import net.pterodactylus.sone.freenet.wot.IdentityManager;
74 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
75 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
76 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
77 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
80 import net.pterodactylus.sone.main.SonePlugin;
81 import net.pterodactylus.sone.utils.IntegerRangePredicate;
82 import net.pterodactylus.util.config.Configuration;
83 import net.pterodactylus.util.config.ConfigurationException;
84 import net.pterodactylus.util.logging.Logging;
85 import net.pterodactylus.util.number.Numbers;
86 import net.pterodactylus.util.service.AbstractService;
87 import net.pterodactylus.util.thread.NamedThreadFactory;
89 import com.google.common.base.Function;
90 import com.google.common.base.Predicate;
91 import com.google.common.base.Predicates;
92 import com.google.common.collect.Collections2;
93 import com.google.common.collect.FluentIterable;
94 import com.google.common.collect.Ordering;
95 import com.google.common.eventbus.EventBus;
96 import com.google.common.eventbus.Subscribe;
97 import com.google.inject.Inject;
99 import freenet.keys.FreenetURI;
104 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
106 public class Core extends AbstractService implements SoneProvider, PostProvider {
109 private static final Logger logger = Logging.getLogger(Core.class);
111 /** The start time. */
112 private final long startupTime = System.currentTimeMillis();
115 private final Options options = new Options();
117 /** The preferences. */
118 private final Preferences preferences = new Preferences(options);
120 /** The event bus. */
121 private final EventBus eventBus;
123 /** The configuration. */
124 private Configuration configuration;
126 /** Whether we’re currently saving the configuration. */
127 private boolean storingConfiguration = false;
129 /** The identity manager. */
130 private final IdentityManager identityManager;
132 /** Interface to freenet. */
133 private final FreenetInterface freenetInterface;
135 /** The Sone downloader. */
136 private final SoneDownloader soneDownloader;
138 /** The image inserter. */
139 private final ImageInserter imageInserter;
141 /** Sone downloader thread-pool. */
142 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
144 /** The update checker. */
145 private final UpdateChecker updateChecker;
147 /** The trust updater. */
148 private final WebOfTrustUpdater webOfTrustUpdater;
150 /** The FCP interface. */
151 private volatile FcpInterface fcpInterface;
153 /** The times Sones were followed. */
154 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
156 /** Locked local Sones. */
157 /* synchronize on itself. */
158 private final Set<Sone> lockedSones = new HashSet<Sone>();
160 /** Sone inserters. */
161 /* synchronize access on this on sones. */
162 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
164 /** Sone rescuers. */
165 /* synchronize access on this on sones. */
166 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
169 /* synchronize access on this on itself. */
170 private final Map<String, Sone> sones = new HashMap<String, Sone>();
172 /** All known Sones. */
173 private final Set<String> knownSones = new HashSet<String>();
175 /** The post builder. */
176 private final PostBuilderFactory postBuilderFactory;
179 private final Map<String, Post> posts = new HashMap<String, Post>();
181 /** All known posts. */
182 private final Set<String> knownPosts = new HashSet<String>();
185 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
187 /** All known replies. */
188 private final Set<String> knownReplies = new HashSet<String>();
190 /** All bookmarked posts. */
191 /* synchronize access on itself. */
192 private final Set<String> bookmarkedPosts = new HashSet<String>();
194 /** Trusted identities, sorted by own identities. */
195 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
197 /** All known albums. */
198 private final Map<String, Album> albums = new HashMap<String, Album>();
200 /** All known images. */
201 private final Map<String, Image> images = new HashMap<String, Image>();
203 /** All temporary images. */
204 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
206 /** Ticker for threads that mark own elements as known. */
207 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
209 /** The time the configuration was last touched. */
210 private volatile long lastConfigurationUpdate;
213 * Creates a new core.
215 * @param configuration
216 * The configuration of the core
217 * @param freenetInterface
218 * The freenet interface
219 * @param identityManager
220 * The identity manager
221 * @param webOfTrustUpdater
222 * The WebOfTrust updater
225 * @param postBuilderFactory
229 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory) {
231 this.configuration = configuration;
232 this.freenetInterface = freenetInterface;
233 this.identityManager = identityManager;
234 this.soneDownloader = new SoneDownloader(this, freenetInterface);
235 this.imageInserter = new ImageInserter(freenetInterface);
236 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
237 this.webOfTrustUpdater = webOfTrustUpdater;
238 this.eventBus = eventBus;
239 this.postBuilderFactory = postBuilderFactory;
247 * Returns the time Sone was started.
249 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
251 public long getStartupTime() {
256 * Sets the configuration to use. This will automatically save the current
257 * configuration to the given configuration.
259 * @param configuration
260 * The new configuration to use
262 public void setConfiguration(Configuration configuration) {
263 this.configuration = configuration;
264 touchConfiguration();
268 * Returns the options used by the core.
270 * @return The options of the core
272 public Preferences getPreferences() {
277 * Returns the identity manager used by the core.
279 * @return The identity manager
281 public IdentityManager getIdentityManager() {
282 return identityManager;
286 * Returns the update checker.
288 * @return The update checker
290 public UpdateChecker getUpdateChecker() {
291 return updateChecker;
295 * Sets the FCP interface to use.
297 * @param fcpInterface
298 * The FCP interface to use
300 public void setFcpInterface(FcpInterface fcpInterface) {
301 this.fcpInterface = fcpInterface;
305 * Returns the Sone rescuer for the given local Sone.
308 * The local Sone to get the rescuer for
309 * @return The Sone rescuer for the given Sone
311 public SoneRescuer getSoneRescuer(Sone sone) {
312 checkNotNull(sone, "sone must not be null");
313 checkArgument(sone.isLocal(), "sone must be local");
314 synchronized (sones) {
315 SoneRescuer soneRescuer = soneRescuers.get(sone);
316 if (soneRescuer == null) {
317 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
318 soneRescuers.put(sone, soneRescuer);
326 * Returns whether the given Sone is currently locked.
330 * @return {@code true} if the Sone is locked, {@code false} if it is not
332 public boolean isLocked(Sone sone) {
333 synchronized (lockedSones) {
334 return lockedSones.contains(sone);
339 * Returns all Sones, remote and local.
343 public Set<Sone> getSones() {
344 return new HashSet<Sone>(sones.values());
348 * Returns the Sone with the given ID, regardless whether it’s local or
352 * The ID of the Sone to get
353 * @return The Sone with the given ID, or {@code null} if there is no such
356 public Sone getSone(String id) {
357 return getSone(id, true);
361 * Returns the Sone with the given ID, regardless whether it’s local or
365 * The ID of the Sone to get
367 * {@code true} to create a new Sone if none exists,
368 * {@code false} to return {@code null} if a Sone with the given
370 * @return The Sone with the given ID, or {@code null} if there is no such
374 public Sone getSone(String id, boolean create) {
375 synchronized (sones) {
376 if (!sones.containsKey(id) && create) {
377 Sone sone = new Sone(id, false);
380 return sones.get(id);
385 * Checks whether the core knows a Sone with the given ID.
389 * @return {@code true} if there is a Sone with the given ID, {@code false}
392 public boolean hasSone(String id) {
393 synchronized (sones) {
394 return sones.containsKey(id);
399 * Returns all local Sones.
401 * @return All local Sones
403 public Collection<Sone> getLocalSones() {
404 synchronized (sones) {
405 return Collections2.filter(sones.values(), new Predicate<Sone>() {
408 public boolean apply(Sone sone) {
409 return sone.isLocal();
416 * Returns the local Sone with the given ID, optionally creating a new Sone.
421 * {@code true} to create a new Sone if none exists,
422 * {@code false} to return null if none exists
423 * @return The Sone with the given ID, or {@code null}
425 public Sone getLocalSone(String id, boolean create) {
426 synchronized (sones) {
427 Sone sone = sones.get(id);
428 if ((sone == null) && create) {
429 sone = new Sone(id, true);
432 if ((sone != null) && !sone.isLocal()) {
433 sone = new Sone(id, true);
441 * Returns all remote Sones.
443 * @return All remote Sones
445 public Collection<Sone> getRemoteSones() {
446 synchronized (sones) {
447 return Collections2.filter(sones.values(), new Predicate<Sone>() {
450 public boolean apply(Sone sone) {
451 return !sone.isLocal();
458 * Returns the remote Sone with the given ID.
461 * The ID of the remote Sone to get
463 * {@code true} to always create a Sone, {@code false} to return
464 * {@code null} if no Sone with the given ID exists
465 * @return The Sone with the given ID
467 public Sone getRemoteSone(String id, boolean create) {
468 synchronized (sones) {
469 Sone sone = sones.get(id);
470 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
471 sone = new Sone(id, false);
479 * Returns whether the given Sone has been modified.
482 * The Sone to check for modifications
483 * @return {@code true} if a modification has been detected in the Sone,
484 * {@code false} otherwise
486 public boolean isModifiedSone(Sone sone) {
487 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
491 * Returns the time when the given was first followed by any local Sone.
494 * The Sone to get the time for
495 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
496 * been followed, or {@link Long#MAX_VALUE}
498 public long getSoneFollowingTime(Sone sone) {
499 synchronized (soneFollowingTimes) {
500 if (soneFollowingTimes.containsKey(sone)) {
501 return soneFollowingTimes.get(sone);
503 return Long.MAX_VALUE;
508 * Returns whether the target Sone is trusted by the origin Sone.
514 * @return {@code true} if the target Sone is trusted by the origin Sone
516 public boolean isSoneTrusted(Sone origin, Sone target) {
517 checkNotNull(origin, "origin must not be null");
518 checkNotNull(target, "target must not be null");
519 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
520 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
524 * Returns a post builder.
526 * @return A new post builder
528 public PostBuilder postBuilder() {
529 return postBuilderFactory.newPostBuilder();
536 public Post getPost(String postId) {
537 synchronized (posts) {
538 return posts.get(postId);
543 * Returns all posts that have the given Sone as recipient.
545 * @see Post#getRecipient()
547 * The recipient of the posts
548 * @return All posts that have the given Sone as recipient
550 public Set<Post> getDirectedPosts(Sone recipient) {
551 checkNotNull(recipient, "recipient must not be null");
552 Set<Post> directedPosts = new HashSet<Post>();
553 synchronized (posts) {
554 for (Post post : posts.values()) {
555 if (recipient.equals(post.getRecipient())) {
556 directedPosts.add(post);
560 return directedPosts;
564 * Returns the reply with the given ID. If there is no reply with the given
565 * ID yet, a new one is created, unless {@code create} is false in which
566 * case {@code null} is returned.
569 * The ID of the reply to get
571 * {@code true} to always return a {@link Reply}, {@code false}
572 * to return {@code null} if no reply can be found
573 * @return The reply, or {@code null} if there is no such reply
575 public PostReply getPostReply(String replyId, boolean create) {
576 synchronized (replies) {
577 PostReply reply = replies.get(replyId);
578 if (create && (reply == null)) {
579 reply = new PostReplyImpl(replyId);
580 replies.put(replyId, reply);
587 * Returns all replies for the given post, order ascending by time.
590 * The post to get all replies for
591 * @return All replies for the given post
593 public List<PostReply> getReplies(final Post post) {
594 return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(FluentIterable.from(getSones()).transformAndConcat(new Function<Sone, Iterable<PostReply>>() {
597 public Iterable<PostReply> apply(Sone sone) {
598 return sone.getReplies();
600 }).filter(new Predicate<PostReply>() {
603 public boolean apply(PostReply reply) {
604 return post.equals(reply.getPost());
610 * Returns all Sones that have liked the given post.
613 * The post to get the liking Sones for
614 * @return The Sones that like the given post
616 public Set<Sone> getLikes(Post post) {
617 Set<Sone> sones = new HashSet<Sone>();
618 for (Sone sone : getSones()) {
619 if (sone.getLikedPostIds().contains(post.getId())) {
627 * Returns all Sones that have liked the given reply.
630 * The reply to get the liking Sones for
631 * @return The Sones that like the given reply
633 public Set<Sone> getLikes(PostReply reply) {
634 Set<Sone> sones = new HashSet<Sone>();
635 for (Sone sone : getSones()) {
636 if (sone.getLikedReplyIds().contains(reply.getId())) {
644 * Returns whether the given post is bookmarked.
648 * @return {@code true} if the given post is bookmarked, {@code false}
651 public boolean isBookmarked(Post post) {
652 return isPostBookmarked(post.getId());
656 * Returns whether the post with the given ID is bookmarked.
659 * The ID of the post to check
660 * @return {@code true} if the post with the given ID is bookmarked,
661 * {@code false} otherwise
663 public boolean isPostBookmarked(String id) {
664 synchronized (bookmarkedPosts) {
665 return bookmarkedPosts.contains(id);
670 * Returns all currently known bookmarked posts.
672 * @return All bookmarked posts
674 public Set<Post> getBookmarkedPosts() {
675 Set<Post> posts = new HashSet<Post>();
676 synchronized (bookmarkedPosts) {
677 for (String bookmarkedPostId : bookmarkedPosts) {
678 Post post = getPost(bookmarkedPostId);
688 * Returns the album with the given ID, creating a new album if no album
689 * with the given ID can be found.
692 * The ID of the album
693 * @return The album with the given ID
695 public Album getAlbum(String albumId) {
696 return getAlbum(albumId, true);
700 * Returns the album with the given ID, optionally creating a new album if
701 * an album with the given ID can not be found.
704 * The ID of the album
706 * {@code true} to create a new album if none exists for the
708 * @return The album with the given ID, or {@code null} if no album with the
709 * given ID exists and {@code create} is {@code false}
711 public Album getAlbum(String albumId, boolean create) {
712 synchronized (albums) {
713 Album album = albums.get(albumId);
714 if (create && (album == null)) {
715 album = new Album(albumId);
716 albums.put(albumId, album);
723 * Returns the image with the given ID, creating it if necessary.
726 * The ID of the image
727 * @return The image with the given ID
729 public Image getImage(String imageId) {
730 return getImage(imageId, true);
734 * Returns the image with the given ID, optionally creating it if it does
738 * The ID of the image
740 * {@code true} to create an image if none exists with the given
742 * @return The image with the given ID, or {@code null} if none exists and
745 public Image getImage(String imageId, boolean create) {
746 synchronized (images) {
747 Image image = images.get(imageId);
748 if (create && (image == null)) {
749 image = new Image(imageId);
750 images.put(imageId, image);
757 * Returns the temporary image with the given ID.
760 * The ID of the temporary image
761 * @return The temporary image, or {@code null} if there is no temporary
762 * image with the given ID
764 public TemporaryImage getTemporaryImage(String imageId) {
765 synchronized (temporaryImages) {
766 return temporaryImages.get(imageId);
775 * Locks the given Sone. A locked Sone will not be inserted by
776 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
782 public void lockSone(Sone sone) {
783 synchronized (lockedSones) {
784 if (lockedSones.add(sone)) {
785 eventBus.post(new SoneLockedEvent(sone));
791 * Unlocks the given Sone.
793 * @see #lockSone(Sone)
797 public void unlockSone(Sone sone) {
798 synchronized (lockedSones) {
799 if (lockedSones.remove(sone)) {
800 eventBus.post(new SoneUnlockedEvent(sone));
806 * Adds a local Sone from the given own identity.
809 * The own identity to create a Sone from
810 * @return The added (or already existing) Sone
812 public Sone addLocalSone(OwnIdentity ownIdentity) {
813 if (ownIdentity == null) {
814 logger.log(Level.WARNING, "Given OwnIdentity is null!");
817 synchronized (sones) {
820 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
821 } catch (MalformedURLException mue1) {
822 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
825 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
826 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
828 /* TODO - load posts ’n stuff */
829 sones.put(ownIdentity.getId(), sone);
830 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
831 soneInserters.put(sone, soneInserter);
832 sone.setStatus(SoneStatus.idle);
834 soneInserter.start();
840 * Creates a new Sone for the given own identity.
843 * The own identity to create a Sone for
844 * @return The created Sone
846 public Sone createSone(OwnIdentity ownIdentity) {
847 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
848 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
851 Sone sone = addLocalSone(ownIdentity);
852 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
853 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
854 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
855 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
856 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
857 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
859 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
860 touchConfiguration();
865 * Adds the Sone of the given identity.
868 * The identity whose Sone to add
869 * @return The added or already existing Sone
871 public Sone addRemoteSone(Identity identity) {
872 if (identity == null) {
873 logger.log(Level.WARNING, "Given Identity is null!");
876 synchronized (sones) {
877 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
878 boolean newSone = sone.getRequestUri() == null;
879 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
880 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
882 synchronized (knownSones) {
883 newSone = !knownSones.contains(sone.getId());
885 sone.setKnown(!newSone);
887 eventBus.post(new NewSoneFoundEvent(sone));
888 for (Sone localSone : getLocalSones()) {
889 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
890 followSone(localSone, sone);
895 soneDownloader.addSone(sone);
896 soneDownloaders.execute(new Runnable() {
899 @SuppressWarnings("synthetic-access")
901 soneDownloader.fetchSone(sone, sone.getRequestUri());
910 * Lets the given local Sone follow the Sone with the given ID.
913 * The local Sone that should follow another Sone
915 * The ID of the Sone to follow
917 public void followSone(Sone sone, String soneId) {
918 checkNotNull(sone, "sone must not be null");
919 checkNotNull(soneId, "soneId must not be null");
920 Sone followedSone = getSone(soneId, true);
921 if (followedSone == null) {
922 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
925 followSone(sone, getSone(soneId));
929 * Lets the given local Sone follow the other given Sone. If the given Sone
930 * was not followed by any local Sone before, this will mark all elements of
931 * the followed Sone as read that have been created before the current
935 * The local Sone that should follow the other Sone
936 * @param followedSone
937 * The Sone that should be followed
939 public void followSone(Sone sone, Sone followedSone) {
940 checkNotNull(sone, "sone must not be null");
941 checkNotNull(followedSone, "followedSone must not be null");
942 sone.addFriend(followedSone.getId());
943 synchronized (soneFollowingTimes) {
944 if (!soneFollowingTimes.containsKey(followedSone)) {
945 long now = System.currentTimeMillis();
946 soneFollowingTimes.put(followedSone, now);
947 for (Post post : followedSone.getPosts()) {
948 if (post.getTime() < now) {
952 for (PostReply reply : followedSone.getReplies()) {
953 if (reply.getTime() < now) {
954 markReplyKnown(reply);
959 touchConfiguration();
963 * Lets the given local Sone unfollow the Sone with the given ID.
966 * The local Sone that should unfollow another Sone
968 * The ID of the Sone being unfollowed
970 public void unfollowSone(Sone sone, String soneId) {
971 checkNotNull(sone, "sone must not be null");
972 checkNotNull(soneId, "soneId must not be null");
973 unfollowSone(sone, getSone(soneId, false));
977 * Lets the given local Sone unfollow the other given Sone. If the given
978 * local Sone is the last local Sone that followed the given Sone, its
979 * following time will be removed.
982 * The local Sone that should unfollow another Sone
983 * @param unfollowedSone
984 * The Sone being unfollowed
986 public void unfollowSone(Sone sone, Sone unfollowedSone) {
987 checkNotNull(sone, "sone must not be null");
988 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
989 sone.removeFriend(unfollowedSone.getId());
990 boolean unfollowedSoneStillFollowed = false;
991 for (Sone localSone : getLocalSones()) {
992 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
994 if (!unfollowedSoneStillFollowed) {
995 synchronized (soneFollowingTimes) {
996 soneFollowingTimes.remove(unfollowedSone);
999 touchConfiguration();
1003 * Sets the trust value of the given origin Sone for the target Sone.
1010 * The trust value (from {@code -100} to {@code 100})
1012 public void setTrust(Sone origin, Sone target, int trustValue) {
1013 checkNotNull(origin, "origin must not be null");
1014 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1015 checkNotNull(target, "target must not be null");
1016 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1017 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1021 * Removes any trust assignment for the given target Sone.
1028 public void removeTrust(Sone origin, Sone target) {
1029 checkNotNull(origin, "origin must not be null");
1030 checkNotNull(target, "target must not be null");
1031 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1032 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1036 * Assigns the configured positive trust value for the given target.
1043 public void trustSone(Sone origin, Sone target) {
1044 setTrust(origin, target, preferences.getPositiveTrust());
1048 * Assigns the configured negative trust value for the given target.
1055 public void distrustSone(Sone origin, Sone target) {
1056 setTrust(origin, target, preferences.getNegativeTrust());
1060 * Removes the trust assignment for the given target.
1067 public void untrustSone(Sone origin, Sone target) {
1068 removeTrust(origin, target);
1072 * Updates the stored Sone with the given Sone.
1077 public void updateSone(Sone sone) {
1078 updateSone(sone, false);
1082 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1083 * {@code true}, an older Sone than the current Sone can be given to restore
1087 * The Sone to update
1088 * @param soneRescueMode
1089 * {@code true} if the stored Sone should be updated regardless
1090 * of the age of the given Sone
1092 public void updateSone(Sone sone, boolean soneRescueMode) {
1093 if (hasSone(sone.getId())) {
1094 Sone storedSone = getSone(sone.getId());
1095 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1096 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1099 synchronized (posts) {
1100 if (!soneRescueMode) {
1101 for (Post post : storedSone.getPosts()) {
1102 posts.remove(post.getId());
1103 if (!sone.getPosts().contains(post)) {
1104 eventBus.post(new PostRemovedEvent(post));
1108 List<Post> storedPosts = storedSone.getPosts();
1109 synchronized (knownPosts) {
1110 for (Post post : sone.getPosts()) {
1111 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1112 postBuilder.copyPost(post).from(storedSone);
1113 Post newPost = postBuilder.build().setKnown(knownPosts.contains(post.getId()));
1114 if (!storedPosts.contains(newPost)) {
1115 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1116 knownPosts.add(newPost.getId());
1117 newPost.setKnown(true);
1118 } else if (!knownPosts.contains(newPost.getId())) {
1119 eventBus.post(new NewPostFoundEvent(newPost));
1122 posts.put(newPost.getId(), newPost);
1126 synchronized (replies) {
1127 if (!soneRescueMode) {
1128 for (PostReply reply : storedSone.getReplies()) {
1129 replies.remove(reply.getId());
1130 if (!sone.getReplies().contains(reply)) {
1131 eventBus.post(new PostReplyRemovedEvent(reply));
1135 Set<PostReply> storedReplies = storedSone.getReplies();
1136 synchronized (knownReplies) {
1137 for (PostReply reply : sone.getReplies()) {
1138 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1139 if (!storedReplies.contains(reply)) {
1140 if (reply.getTime() < getSoneFollowingTime(sone)) {
1141 knownReplies.add(reply.getId());
1142 reply.setKnown(true);
1143 } else if (!knownReplies.contains(reply.getId())) {
1144 eventBus.post(new NewPostReplyFoundEvent(reply));
1147 replies.put(reply.getId(), reply);
1151 synchronized (albums) {
1152 synchronized (images) {
1153 for (Album album : storedSone.getAlbums()) {
1154 albums.remove(album.getId());
1155 for (Image image : album.getImages()) {
1156 images.remove(image.getId());
1159 for (Album album : sone.getAlbums()) {
1160 albums.put(album.getId(), album);
1161 for (Image image : album.getImages()) {
1162 images.put(image.getId(), image);
1167 synchronized (storedSone) {
1168 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1169 storedSone.setTime(sone.getTime());
1171 storedSone.setClient(sone.getClient());
1172 storedSone.setProfile(sone.getProfile());
1173 if (soneRescueMode) {
1174 for (Post post : sone.getPosts()) {
1175 storedSone.addPost(post);
1177 for (PostReply reply : sone.getReplies()) {
1178 storedSone.addReply(reply);
1180 for (String likedPostId : sone.getLikedPostIds()) {
1181 storedSone.addLikedPostId(likedPostId);
1183 for (String likedReplyId : sone.getLikedReplyIds()) {
1184 storedSone.addLikedReplyId(likedReplyId);
1186 for (Album album : sone.getAlbums()) {
1187 storedSone.addAlbum(album);
1190 storedSone.setPosts(sone.getPosts());
1191 storedSone.setReplies(sone.getReplies());
1192 storedSone.setLikePostIds(sone.getLikedPostIds());
1193 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1194 storedSone.setAlbums(sone.getAlbums());
1196 storedSone.setLatestEdition(sone.getLatestEdition());
1202 * Deletes the given Sone. This will remove the Sone from the
1203 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1204 * remove the context from its identity.
1207 * The Sone to delete
1209 public void deleteSone(Sone sone) {
1210 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1211 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1214 synchronized (sones) {
1215 if (!getLocalSones().contains(sone)) {
1216 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1219 sones.remove(sone.getId());
1220 SoneInserter soneInserter = soneInserters.remove(sone);
1221 soneInserter.stop();
1223 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1224 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1226 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1227 } catch (ConfigurationException ce1) {
1228 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1233 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1234 * known} before, a {@link MarkSoneKnownEvent} is fired.
1237 * The Sone to mark as known
1239 public void markSoneKnown(Sone sone) {
1240 if (!sone.isKnown()) {
1241 sone.setKnown(true);
1242 synchronized (knownSones) {
1243 knownSones.add(sone.getId());
1245 eventBus.post(new MarkSoneKnownEvent(sone));
1246 touchConfiguration();
1251 * Loads and updates the given Sone from the configuration. If any error is
1252 * encountered, loading is aborted and the given Sone is not changed.
1255 * The Sone to load and update
1257 public void loadSone(Sone sone) {
1258 if (!sone.isLocal()) {
1259 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1263 /* initialize options. */
1264 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1265 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1266 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1267 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1268 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1269 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1272 String sonePrefix = "Sone/" + sone.getId();
1273 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1274 if (soneTime == null) {
1275 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1278 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1281 Profile profile = new Profile(sone);
1282 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1283 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1284 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1285 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1286 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1287 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1289 /* load profile fields. */
1291 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1292 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1293 if (fieldName == null) {
1296 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1297 profile.addField(fieldName).setValue(fieldValue);
1301 Set<Post> posts = new HashSet<Post>();
1303 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1304 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1305 if (postId == null) {
1308 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1309 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1310 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1311 if ((postTime == 0) || (postText == null)) {
1312 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1315 PostBuilder postBuilder = postBuilder().withId(postId).from(sone).withTime(postTime).withText(postText);
1316 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1317 postBuilder.to(getSone(postRecipientId));
1319 posts.add(postBuilder.build());
1323 Set<PostReply> replies = new HashSet<PostReply>();
1325 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1326 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1327 if (replyId == null) {
1330 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1331 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1332 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1333 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1334 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1337 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1340 /* load post likes. */
1341 Set<String> likedPostIds = new HashSet<String>();
1343 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1344 if (likedPostId == null) {
1347 likedPostIds.add(likedPostId);
1350 /* load reply likes. */
1351 Set<String> likedReplyIds = new HashSet<String>();
1353 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1354 if (likedReplyId == null) {
1357 likedReplyIds.add(likedReplyId);
1361 Set<String> friends = new HashSet<String>();
1363 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1364 if (friendId == null) {
1367 friends.add(friendId);
1371 List<Album> topLevelAlbums = new ArrayList<Album>();
1372 int albumCounter = 0;
1374 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1375 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1376 if (albumId == null) {
1379 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1380 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1381 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1382 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1383 if ((albumTitle == null) || (albumDescription == null)) {
1384 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1387 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1388 if (albumParentId != null) {
1389 Album parentAlbum = getAlbum(albumParentId, false);
1390 if (parentAlbum == null) {
1391 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1394 parentAlbum.addAlbum(album);
1396 if (!topLevelAlbums.contains(album)) {
1397 topLevelAlbums.add(album);
1403 int imageCounter = 0;
1405 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1406 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1407 if (imageId == null) {
1410 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1411 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1412 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1413 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1414 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1415 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1416 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1417 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1418 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1421 Album album = getAlbum(albumId, false);
1422 if (album == null) {
1423 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1426 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1427 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1428 album.addImage(image);
1432 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1433 if (avatarId != null) {
1434 profile.setAvatar(getImage(avatarId, false));
1438 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1439 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1440 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1441 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1442 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1443 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1445 /* if we’re still here, Sone was loaded successfully. */
1446 synchronized (sone) {
1447 sone.setTime(soneTime);
1448 sone.setProfile(profile);
1449 sone.setPosts(posts);
1450 sone.setReplies(replies);
1451 sone.setLikePostIds(likedPostIds);
1452 sone.setLikeReplyIds(likedReplyIds);
1453 for (String friendId : friends) {
1454 followSone(sone, friendId);
1456 sone.setAlbums(topLevelAlbums);
1457 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1459 synchronized (knownSones) {
1460 for (String friend : friends) {
1461 knownSones.add(friend);
1464 synchronized (knownPosts) {
1465 for (Post post : posts) {
1466 knownPosts.add(post.getId());
1469 synchronized (knownReplies) {
1470 for (PostReply reply : replies) {
1471 knownReplies.add(reply.getId());
1477 * Creates a new post.
1480 * The Sone that creates the post
1482 * The text of the post
1483 * @return The created post
1485 public Post createPost(Sone sone, String text) {
1486 return createPost(sone, System.currentTimeMillis(), text);
1490 * Creates a new post.
1493 * The Sone that creates the post
1495 * The time of the post
1497 * The text of the post
1498 * @return The created post
1500 public Post createPost(Sone sone, long time, String text) {
1501 return createPost(sone, null, time, text);
1505 * Creates a new post.
1508 * The Sone that creates the post
1510 * The recipient Sone, or {@code null} if this post does not have
1513 * The text of the post
1514 * @return The created post
1516 public Post createPost(Sone sone, Sone recipient, String text) {
1517 return createPost(sone, recipient, System.currentTimeMillis(), text);
1521 * Creates a new post.
1524 * The Sone that creates the post
1526 * The recipient Sone, or {@code null} if this post does not have
1529 * The time of the post
1531 * The text of the post
1532 * @return The created post
1534 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1535 checkNotNull(text, "text must not be null");
1536 checkArgument(text.trim().length() > 0, "text must not be empty");
1537 if (!sone.isLocal()) {
1538 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1541 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1542 postBuilder.from(sone).randomId().withTime(time).withText(text.trim());
1543 if (recipient != null) {
1544 postBuilder.to(recipient);
1546 final Post post = postBuilder.build();
1547 synchronized (posts) {
1548 posts.put(post.getId(), post);
1550 eventBus.post(new NewPostFoundEvent(post));
1552 touchConfiguration();
1553 localElementTicker.schedule(new Runnable() {
1560 markPostKnown(post);
1562 }, 10, TimeUnit.SECONDS);
1567 * Deletes the given post.
1570 * The post to delete
1572 public void deletePost(Post post) {
1573 if (!post.getSone().isLocal()) {
1574 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1577 post.getSone().removePost(post);
1578 synchronized (posts) {
1579 posts.remove(post.getId());
1581 eventBus.post(new PostRemovedEvent(post));
1582 markPostKnown(post);
1583 touchConfiguration();
1587 * Marks the given post as known, if it is currently not a known post
1588 * (according to {@link Post#isKnown()}).
1591 * The post to mark as known
1593 public void markPostKnown(Post post) {
1594 post.setKnown(true);
1595 synchronized (knownPosts) {
1596 eventBus.post(new MarkPostKnownEvent(post));
1597 if (knownPosts.add(post.getId())) {
1598 touchConfiguration();
1601 for (PostReply reply : getReplies(post)) {
1602 markReplyKnown(reply);
1607 * Bookmarks the given post.
1610 * The post to bookmark
1612 public void bookmark(Post post) {
1613 bookmarkPost(post.getId());
1617 * Bookmarks the post with the given ID.
1620 * The ID of the post to bookmark
1622 public void bookmarkPost(String id) {
1623 synchronized (bookmarkedPosts) {
1624 bookmarkedPosts.add(id);
1629 * Removes the given post from the bookmarks.
1632 * The post to unbookmark
1634 public void unbookmark(Post post) {
1635 unbookmarkPost(post.getId());
1639 * Removes the post with the given ID from the bookmarks.
1642 * The ID of the post to unbookmark
1644 public void unbookmarkPost(String id) {
1645 synchronized (bookmarkedPosts) {
1646 bookmarkedPosts.remove(id);
1651 * Creates a new reply.
1654 * The Sone that creates the reply
1656 * The post that this reply refers to
1658 * The text of the reply
1659 * @return The created reply
1661 public PostReply createReply(Sone sone, Post post, String text) {
1662 return createReply(sone, post, System.currentTimeMillis(), text);
1666 * Creates a new reply.
1669 * The Sone that creates the reply
1671 * The post that this reply refers to
1673 * The time of the reply
1675 * The text of the reply
1676 * @return The created reply
1678 public PostReply createReply(Sone sone, Post post, long time, String text) {
1679 checkNotNull(text, "text must not be null");
1680 checkArgument(text.trim().length() > 0, "text must not be empty");
1681 if (!sone.isLocal()) {
1682 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1685 final PostReply reply = new PostReplyImpl(sone, post, System.currentTimeMillis(), text.trim());
1686 synchronized (replies) {
1687 replies.put(reply.getId(), reply);
1689 synchronized (knownReplies) {
1690 eventBus.post(new NewPostReplyFoundEvent(reply));
1692 sone.addReply(reply);
1693 touchConfiguration();
1694 localElementTicker.schedule(new Runnable() {
1701 markReplyKnown(reply);
1703 }, 10, TimeUnit.SECONDS);
1708 * Deletes the given reply.
1711 * The reply to delete
1713 public void deleteReply(PostReply reply) {
1714 Sone sone = reply.getSone();
1715 if (!sone.isLocal()) {
1716 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1719 synchronized (replies) {
1720 replies.remove(reply.getId());
1722 synchronized (knownReplies) {
1723 markReplyKnown(reply);
1724 knownReplies.remove(reply.getId());
1726 sone.removeReply(reply);
1727 touchConfiguration();
1731 * Marks the given reply as known, if it is currently not a known reply
1732 * (according to {@link Reply#isKnown()}).
1735 * The reply to mark as known
1737 public void markReplyKnown(PostReply reply) {
1738 reply.setKnown(true);
1739 synchronized (knownReplies) {
1740 eventBus.post(new MarkPostReplyKnownEvent(reply));
1741 if (knownReplies.add(reply.getId())) {
1742 touchConfiguration();
1748 * Creates a new top-level album for the given Sone.
1751 * The Sone to create the album for
1752 * @return The new album
1754 public Album createAlbum(Sone sone) {
1755 return createAlbum(sone, null);
1759 * Creates a new album for the given Sone.
1762 * The Sone to create the album for
1764 * The parent of the album (may be {@code null} to create a
1766 * @return The new album
1768 public Album createAlbum(Sone sone, Album parent) {
1769 Album album = new Album();
1770 synchronized (albums) {
1771 albums.put(album.getId(), album);
1773 album.setSone(sone);
1774 if (parent != null) {
1775 parent.addAlbum(album);
1777 sone.addAlbum(album);
1783 * Deletes the given album. The owner of the album has to be a local Sone,
1784 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1787 * The album to remove
1789 public void deleteAlbum(Album album) {
1790 checkNotNull(album, "album must not be null");
1791 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1792 if (!album.isEmpty()) {
1795 if (album.getParent() == null) {
1796 album.getSone().removeAlbum(album);
1798 album.getParent().removeAlbum(album);
1800 synchronized (albums) {
1801 albums.remove(album.getId());
1803 touchConfiguration();
1807 * Creates a new image.
1810 * The Sone creating the image
1812 * The album the image will be inserted into
1813 * @param temporaryImage
1814 * The temporary image to create the image from
1815 * @return The newly created image
1817 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1818 checkNotNull(sone, "sone must not be null");
1819 checkNotNull(album, "album must not be null");
1820 checkNotNull(temporaryImage, "temporaryImage must not be null");
1821 checkArgument(sone.isLocal(), "sone must be a local Sone");
1822 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1823 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1824 album.addImage(image);
1825 synchronized (images) {
1826 images.put(image.getId(), image);
1828 imageInserter.insertImage(temporaryImage, image);
1833 * Deletes the given image. This method will also delete a matching
1836 * @see #deleteTemporaryImage(TemporaryImage)
1838 * The image to delete
1840 public void deleteImage(Image image) {
1841 checkNotNull(image, "image must not be null");
1842 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1843 deleteTemporaryImage(image.getId());
1844 image.getAlbum().removeImage(image);
1845 synchronized (images) {
1846 images.remove(image.getId());
1848 touchConfiguration();
1852 * Creates a new temporary image.
1855 * The MIME type of the temporary image
1857 * The encoded data of the image
1858 * @return The temporary image
1860 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1861 TemporaryImage temporaryImage = new TemporaryImage();
1862 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1863 synchronized (temporaryImages) {
1864 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1866 return temporaryImage;
1870 * Deletes the given temporary image.
1872 * @param temporaryImage
1873 * The temporary image to delete
1875 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1876 checkNotNull(temporaryImage, "temporaryImage must not be null");
1877 deleteTemporaryImage(temporaryImage.getId());
1881 * Deletes the temporary image with the given ID.
1884 * The ID of the temporary image to delete
1886 public void deleteTemporaryImage(String imageId) {
1887 checkNotNull(imageId, "imageId must not be null");
1888 synchronized (temporaryImages) {
1889 temporaryImages.remove(imageId);
1891 Image image = getImage(imageId, false);
1892 if (image != null) {
1893 imageInserter.cancelImageInsert(image);
1898 * Notifies the core that the configuration, either of the core or of a
1899 * single local Sone, has changed, and that the configuration should be
1902 public void touchConfiguration() {
1903 lastConfigurationUpdate = System.currentTimeMillis();
1914 public void serviceStart() {
1915 loadConfiguration();
1916 updateChecker.start();
1917 identityManager.start();
1918 webOfTrustUpdater.init();
1919 webOfTrustUpdater.start();
1926 public void serviceRun() {
1927 long lastSaved = System.currentTimeMillis();
1928 while (!shouldStop()) {
1930 long now = System.currentTimeMillis();
1931 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1932 for (Sone localSone : getLocalSones()) {
1933 saveSone(localSone);
1935 saveConfiguration();
1945 public void serviceStop() {
1946 localElementTicker.shutdownNow();
1947 synchronized (sones) {
1948 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1949 soneInserter.getValue().stop();
1950 saveSone(soneInserter.getKey());
1953 saveConfiguration();
1954 webOfTrustUpdater.stop();
1955 updateChecker.stop();
1956 soneDownloader.stop();
1957 identityManager.stop();
1965 * Saves the given Sone. This will persist all local settings for the given
1966 * Sone, such as the friends list and similar, private options.
1971 private synchronized void saveSone(Sone sone) {
1972 if (!sone.isLocal()) {
1973 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1976 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1977 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1981 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1983 /* save Sone into configuration. */
1984 String sonePrefix = "Sone/" + sone.getId();
1985 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1986 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1989 Profile profile = sone.getProfile();
1990 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1991 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1992 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1993 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1994 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1995 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1996 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1998 /* save profile fields. */
1999 int fieldCounter = 0;
2000 for (Field profileField : profile.getFields()) {
2001 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2002 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2003 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2005 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2008 int postCounter = 0;
2009 for (Post post : sone.getPosts()) {
2010 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2011 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2012 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2013 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2014 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2016 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2019 int replyCounter = 0;
2020 for (PostReply reply : sone.getReplies()) {
2021 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2022 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2023 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2024 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2025 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2027 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2029 /* save post likes. */
2030 int postLikeCounter = 0;
2031 for (String postId : sone.getLikedPostIds()) {
2032 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2034 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2036 /* save reply likes. */
2037 int replyLikeCounter = 0;
2038 for (String replyId : sone.getLikedReplyIds()) {
2039 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2041 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2044 int friendCounter = 0;
2045 for (String friendId : sone.getFriends()) {
2046 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2048 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2050 /* save albums. first, collect in a flat structure, top-level first. */
2051 List<Album> albums = sone.getAllAlbums();
2053 int albumCounter = 0;
2054 for (Album album : albums) {
2055 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2056 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2057 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2058 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2059 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2060 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2062 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2065 int imageCounter = 0;
2066 for (Album album : albums) {
2067 for (Image image : album.getImages()) {
2068 if (!image.isInserted()) {
2071 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2072 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2073 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2074 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2075 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2076 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2077 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2078 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2079 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2082 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2085 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2086 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2087 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2088 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2089 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2090 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2092 configuration.save();
2094 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2096 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2097 } catch (ConfigurationException ce1) {
2098 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2103 * Saves the current options.
2105 private void saveConfiguration() {
2106 synchronized (configuration) {
2107 if (storingConfiguration) {
2108 logger.log(Level.FINE, "Already storing configuration…");
2111 storingConfiguration = true;
2114 /* store the options first. */
2116 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2117 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2118 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2119 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2120 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2121 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2122 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2123 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2124 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2125 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2126 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2127 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2129 /* save known Sones. */
2130 int soneCounter = 0;
2131 synchronized (knownSones) {
2132 for (String knownSoneId : knownSones) {
2133 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2135 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2138 /* save Sone following times. */
2140 synchronized (soneFollowingTimes) {
2141 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2142 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2143 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2146 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2149 /* save known posts. */
2150 int postCounter = 0;
2151 synchronized (knownPosts) {
2152 for (String knownPostId : knownPosts) {
2153 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2155 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2158 /* save known replies. */
2159 int replyCounter = 0;
2160 synchronized (knownReplies) {
2161 for (String knownReplyId : knownReplies) {
2162 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2164 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2167 /* save bookmarked posts. */
2168 int bookmarkedPostCounter = 0;
2169 synchronized (bookmarkedPosts) {
2170 for (String bookmarkedPostId : bookmarkedPosts) {
2171 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2174 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2177 configuration.save();
2179 } catch (ConfigurationException ce1) {
2180 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2182 synchronized (configuration) {
2183 storingConfiguration = false;
2189 * Loads the configuration.
2191 @SuppressWarnings("unchecked")
2192 private void loadConfiguration() {
2193 /* create options. */
2194 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2197 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2198 SoneInserter.setInsertionDelay(newValue);
2202 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2203 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2204 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2205 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2206 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2207 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2208 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2209 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2210 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2213 @SuppressWarnings("synthetic-access")
2214 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2215 fcpInterface.setActive(newValue);
2218 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2221 @SuppressWarnings("synthetic-access")
2222 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2223 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2228 loadConfigurationValue("InsertionDelay");
2229 loadConfigurationValue("PostsPerPage");
2230 loadConfigurationValue("ImagesPerPage");
2231 loadConfigurationValue("CharactersPerPost");
2232 loadConfigurationValue("PostCutOffLength");
2233 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2234 loadConfigurationValue("PositiveTrust");
2235 loadConfigurationValue("NegativeTrust");
2236 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2237 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2238 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2240 /* load known Sones. */
2241 int soneCounter = 0;
2243 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2244 if (knownSoneId == null) {
2247 synchronized (knownSones) {
2248 knownSones.add(knownSoneId);
2252 /* load Sone following times. */
2255 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2256 if (soneId == null) {
2259 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2260 Sone followedSone = getSone(soneId);
2261 if (followedSone == null) {
2262 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2264 synchronized (soneFollowingTimes) {
2265 soneFollowingTimes.put(getSone(soneId), time);
2271 /* load known posts. */
2272 int postCounter = 0;
2274 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2275 if (knownPostId == null) {
2278 synchronized (knownPosts) {
2279 knownPosts.add(knownPostId);
2283 /* load known replies. */
2284 int replyCounter = 0;
2286 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2287 if (knownReplyId == null) {
2290 synchronized (knownReplies) {
2291 knownReplies.add(knownReplyId);
2295 /* load bookmarked posts. */
2296 int bookmarkedPostCounter = 0;
2298 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2299 if (bookmarkedPostId == null) {
2302 synchronized (bookmarkedPosts) {
2303 bookmarkedPosts.add(bookmarkedPostId);
2310 * Loads an {@link Integer} configuration value for the option with the
2311 * given name, logging validation failures.
2314 * The name of the option to load
2316 private void loadConfigurationValue(String optionName) {
2318 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2319 } catch (IllegalArgumentException iae1) {
2320 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2325 * Generate a Sone URI from the given URI and latest edition.
2328 * The URI to derive the Sone URI from
2329 * @return The derived URI
2331 private static FreenetURI getSoneUri(String uriString) {
2333 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2335 } catch (MalformedURLException mue1) {
2336 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2342 * Notifies the core that a new {@link OwnIdentity} was added.
2344 * @param ownIdentityAddedEvent
2348 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2349 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2350 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2351 if (ownIdentity.hasContext("Sone")) {
2352 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2353 addLocalSone(ownIdentity);
2358 * Notifies the core that an {@link OwnIdentity} was removed.
2360 * @param ownIdentityRemovedEvent
2364 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2365 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2366 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2367 trustedIdentities.remove(ownIdentity);
2371 * Notifies the core that a new {@link Identity} was added.
2373 * @param identityAddedEvent
2377 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2378 Identity identity = identityAddedEvent.identity();
2379 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2380 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2381 addRemoteSone(identity);
2385 * Notifies the core that an {@link Identity} was updated.
2387 * @param identityUpdatedEvent
2391 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2392 final Identity identity = identityUpdatedEvent.identity();
2393 soneDownloaders.execute(new Runnable() {
2396 @SuppressWarnings("synthetic-access")
2398 Sone sone = getRemoteSone(identity.getId(), false);
2399 sone.setIdentity(identity);
2400 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2401 soneDownloader.addSone(sone);
2402 soneDownloader.fetchSone(sone);
2408 * Notifies the core that an {@link Identity} was removed.
2410 * @param identityRemovedEvent
2414 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2415 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2416 Identity identity = identityRemovedEvent.identity();
2417 trustedIdentities.get(ownIdentity).remove(identity);
2418 boolean foundIdentity = false;
2419 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2420 if (trustedIdentity.getKey().equals(ownIdentity)) {
2423 if (trustedIdentity.getValue().contains(identity)) {
2424 foundIdentity = true;
2427 if (foundIdentity) {
2428 /* some local identity still trusts this identity, don’t remove. */
2431 Sone sone = getSone(identity.getId(), false);
2433 /* TODO - we don’t have the Sone anymore. should this happen? */
2436 synchronized (posts) {
2437 synchronized (knownPosts) {
2438 for (Post post : sone.getPosts()) {
2439 posts.remove(post.getId());
2440 eventBus.post(new PostRemovedEvent(post));
2444 synchronized (replies) {
2445 synchronized (knownReplies) {
2446 for (PostReply reply : sone.getReplies()) {
2447 replies.remove(reply.getId());
2448 eventBus.post(new PostReplyRemovedEvent(reply));
2452 synchronized (sones) {
2453 sones.remove(identity.getId());
2455 eventBus.post(new SoneRemovedEvent(sone));
2459 * Deletes the temporary image.
2461 * @param imageInsertFinishedEvent
2465 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2466 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2467 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2468 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2469 touchConfiguration();