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.PostReplyBuilder;
63 import net.pterodactylus.sone.data.PostReplyBuilderFactory;
64 import net.pterodactylus.sone.data.Profile;
65 import net.pterodactylus.sone.data.Profile.Field;
66 import net.pterodactylus.sone.data.Reply;
67 import net.pterodactylus.sone.data.Sone;
68 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
69 import net.pterodactylus.sone.data.Sone.SoneStatus;
70 import net.pterodactylus.sone.data.TemporaryImage;
71 import net.pterodactylus.sone.fcp.FcpInterface;
72 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
73 import net.pterodactylus.sone.freenet.wot.Identity;
74 import net.pterodactylus.sone.freenet.wot.IdentityManager;
75 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
76 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
77 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
81 import net.pterodactylus.sone.main.SonePlugin;
82 import net.pterodactylus.sone.utils.IntegerRangePredicate;
83 import net.pterodactylus.util.config.Configuration;
84 import net.pterodactylus.util.config.ConfigurationException;
85 import net.pterodactylus.util.logging.Logging;
86 import net.pterodactylus.util.number.Numbers;
87 import net.pterodactylus.util.service.AbstractService;
88 import net.pterodactylus.util.thread.NamedThreadFactory;
90 import com.google.common.base.Function;
91 import com.google.common.base.Predicate;
92 import com.google.common.base.Predicates;
93 import com.google.common.collect.Collections2;
94 import com.google.common.collect.FluentIterable;
95 import com.google.common.collect.Ordering;
96 import com.google.common.eventbus.EventBus;
97 import com.google.common.eventbus.Subscribe;
98 import com.google.inject.Inject;
100 import freenet.keys.FreenetURI;
105 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
107 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
110 private static final Logger logger = Logging.getLogger(Core.class);
112 /** The start time. */
113 private final long startupTime = System.currentTimeMillis();
116 private final Options options = new Options();
118 /** The preferences. */
119 private final Preferences preferences = new Preferences(options);
121 /** The event bus. */
122 private final EventBus eventBus;
124 /** The configuration. */
125 private Configuration configuration;
127 /** Whether we’re currently saving the configuration. */
128 private boolean storingConfiguration = false;
130 /** The identity manager. */
131 private final IdentityManager identityManager;
133 /** Interface to freenet. */
134 private final FreenetInterface freenetInterface;
136 /** The Sone downloader. */
137 private final SoneDownloader soneDownloader;
139 /** The image inserter. */
140 private final ImageInserter imageInserter;
142 /** Sone downloader thread-pool. */
143 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
145 /** The update checker. */
146 private final UpdateChecker updateChecker;
148 /** The trust updater. */
149 private final WebOfTrustUpdater webOfTrustUpdater;
151 /** The FCP interface. */
152 private volatile FcpInterface fcpInterface;
154 /** The times Sones were followed. */
155 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
157 /** Locked local Sones. */
158 /* synchronize on itself. */
159 private final Set<Sone> lockedSones = new HashSet<Sone>();
161 /** Sone inserters. */
162 /* synchronize access on this on sones. */
163 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
165 /** Sone rescuers. */
166 /* synchronize access on this on sones. */
167 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
170 /* synchronize access on this on itself. */
171 private final Map<String, Sone> sones = new HashMap<String, Sone>();
173 /** All known Sones. */
174 private final Set<String> knownSones = new HashSet<String>();
176 /** The post builder. */
177 private final PostBuilderFactory postBuilderFactory;
180 private final Map<String, Post> posts = new HashMap<String, Post>();
182 /** All known posts. */
183 private final Set<String> knownPosts = new HashSet<String>();
185 /** The post reply builder factory. */
186 private final PostReplyBuilderFactory postReplyBuilderFactory;
189 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
191 /** All known replies. */
192 private final Set<String> knownReplies = new HashSet<String>();
194 /** All bookmarked posts. */
195 /* synchronize access on itself. */
196 private final Set<String> bookmarkedPosts = new HashSet<String>();
198 /** Trusted identities, sorted by own identities. */
199 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
201 /** All known albums. */
202 private final Map<String, Album> albums = new HashMap<String, Album>();
204 /** All known images. */
205 private final Map<String, Image> images = new HashMap<String, Image>();
207 /** All temporary images. */
208 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
210 /** Ticker for threads that mark own elements as known. */
211 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
213 /** The time the configuration was last touched. */
214 private volatile long lastConfigurationUpdate;
217 * Creates a new core.
219 * @param configuration
220 * The configuration of the core
221 * @param freenetInterface
222 * The freenet interface
223 * @param identityManager
224 * The identity manager
225 * @param webOfTrustUpdater
226 * The WebOfTrust updater
229 * @param postBuilderFactory
231 * @param postReplyBuilderFactory
232 * The post reply builder factory
235 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory, PostReplyBuilderFactory postReplyBuilderFactory) {
237 this.configuration = configuration;
238 this.freenetInterface = freenetInterface;
239 this.identityManager = identityManager;
240 this.soneDownloader = new SoneDownloader(this, freenetInterface);
241 this.imageInserter = new ImageInserter(freenetInterface);
242 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
243 this.webOfTrustUpdater = webOfTrustUpdater;
244 this.eventBus = eventBus;
245 this.postBuilderFactory = postBuilderFactory;
246 this.postReplyBuilderFactory = postReplyBuilderFactory;
254 * Returns the time Sone was started.
256 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
258 public long getStartupTime() {
263 * Sets the configuration to use. This will automatically save the current
264 * configuration to the given configuration.
266 * @param configuration
267 * The new configuration to use
269 public void setConfiguration(Configuration configuration) {
270 this.configuration = configuration;
271 touchConfiguration();
275 * Returns the options used by the core.
277 * @return The options of the core
279 public Preferences getPreferences() {
284 * Returns the identity manager used by the core.
286 * @return The identity manager
288 public IdentityManager getIdentityManager() {
289 return identityManager;
293 * Returns the update checker.
295 * @return The update checker
297 public UpdateChecker getUpdateChecker() {
298 return updateChecker;
302 * Sets the FCP interface to use.
304 * @param fcpInterface
305 * The FCP interface to use
307 public void setFcpInterface(FcpInterface fcpInterface) {
308 this.fcpInterface = fcpInterface;
312 * Returns the Sone rescuer for the given local Sone.
315 * The local Sone to get the rescuer for
316 * @return The Sone rescuer for the given Sone
318 public SoneRescuer getSoneRescuer(Sone sone) {
319 checkNotNull(sone, "sone must not be null");
320 checkArgument(sone.isLocal(), "sone must be local");
321 synchronized (sones) {
322 SoneRescuer soneRescuer = soneRescuers.get(sone);
323 if (soneRescuer == null) {
324 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
325 soneRescuers.put(sone, soneRescuer);
333 * Returns whether the given Sone is currently locked.
337 * @return {@code true} if the Sone is locked, {@code false} if it is not
339 public boolean isLocked(Sone sone) {
340 synchronized (lockedSones) {
341 return lockedSones.contains(sone);
346 * Returns all Sones, remote and local.
350 public Set<Sone> getSones() {
351 return new HashSet<Sone>(sones.values());
355 * Returns the Sone with the given ID, regardless whether it’s local or
359 * The ID of the Sone to get
360 * @return The Sone with the given ID, or {@code null} if there is no such
363 public Sone getSone(String id) {
364 return getSone(id, true);
368 * Returns the Sone with the given ID, regardless whether it’s local or
372 * The ID of the Sone to get
374 * {@code true} to create a new Sone if none exists,
375 * {@code false} to return {@code null} if a Sone with the given
377 * @return The Sone with the given ID, or {@code null} if there is no such
381 public Sone getSone(String id, boolean create) {
382 synchronized (sones) {
383 if (!sones.containsKey(id) && create) {
384 Sone sone = new Sone(id, false);
387 return sones.get(id);
392 * Checks whether the core knows a Sone with the given ID.
396 * @return {@code true} if there is a Sone with the given ID, {@code false}
399 public boolean hasSone(String id) {
400 synchronized (sones) {
401 return sones.containsKey(id);
406 * Returns all local Sones.
408 * @return All local Sones
410 public Collection<Sone> getLocalSones() {
411 synchronized (sones) {
412 return Collections2.filter(sones.values(), new Predicate<Sone>() {
415 public boolean apply(Sone sone) {
416 return sone.isLocal();
423 * Returns the local Sone with the given ID, optionally creating a new Sone.
428 * {@code true} to create a new Sone if none exists,
429 * {@code false} to return null if none exists
430 * @return The Sone with the given ID, or {@code null}
432 public Sone getLocalSone(String id, boolean create) {
433 synchronized (sones) {
434 Sone sone = sones.get(id);
435 if ((sone == null) && create) {
436 sone = new Sone(id, true);
439 if ((sone != null) && !sone.isLocal()) {
440 sone = new Sone(id, true);
448 * Returns all remote Sones.
450 * @return All remote Sones
452 public Collection<Sone> getRemoteSones() {
453 synchronized (sones) {
454 return Collections2.filter(sones.values(), new Predicate<Sone>() {
457 public boolean apply(Sone sone) {
458 return !sone.isLocal();
465 * Returns the remote Sone with the given ID.
468 * The ID of the remote Sone to get
470 * {@code true} to always create a Sone, {@code false} to return
471 * {@code null} if no Sone with the given ID exists
472 * @return The Sone with the given ID
474 public Sone getRemoteSone(String id, boolean create) {
475 synchronized (sones) {
476 Sone sone = sones.get(id);
477 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
478 sone = new Sone(id, false);
486 * Returns whether the given Sone has been modified.
489 * The Sone to check for modifications
490 * @return {@code true} if a modification has been detected in the Sone,
491 * {@code false} otherwise
493 public boolean isModifiedSone(Sone sone) {
494 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
498 * Returns the time when the given was first followed by any local Sone.
501 * The Sone to get the time for
502 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
503 * been followed, or {@link Long#MAX_VALUE}
505 public long getSoneFollowingTime(Sone sone) {
506 synchronized (soneFollowingTimes) {
507 if (soneFollowingTimes.containsKey(sone)) {
508 return soneFollowingTimes.get(sone);
510 return Long.MAX_VALUE;
515 * Returns whether the target Sone is trusted by the origin Sone.
521 * @return {@code true} if the target Sone is trusted by the origin Sone
523 public boolean isSoneTrusted(Sone origin, Sone target) {
524 checkNotNull(origin, "origin must not be null");
525 checkNotNull(target, "target must not be null");
526 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
527 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
531 * Returns a post builder.
533 * @return A new post builder
535 public PostBuilder postBuilder() {
536 return postBuilderFactory.newPostBuilder();
543 public Post getPost(String postId) {
544 synchronized (posts) {
545 return posts.get(postId);
550 * Returns all posts that have the given Sone as recipient.
552 * @see Post#getRecipient()
554 * The recipient of the posts
555 * @return All posts that have the given Sone as recipient
557 public Set<Post> getDirectedPosts(Sone recipient) {
558 checkNotNull(recipient, "recipient must not be null");
559 Set<Post> directedPosts = new HashSet<Post>();
560 synchronized (posts) {
561 for (Post post : posts.values()) {
562 if (recipient.equals(post.getRecipient())) {
563 directedPosts.add(post);
567 return directedPosts;
571 * Returns a post reply builder.
573 * @return A new post reply builder
575 public PostReplyBuilder postReplyBuilder() {
576 return postReplyBuilderFactory.newPostReplyBuilder();
583 public PostReply getPostReply(String replyId) {
584 synchronized (replies) {
585 return replies.get(replyId);
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(SoneUri.create(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 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1338 postReplyBuilder.withId(replyId).from(sone).to(postId).withTime(replyTime).withText(replyText);
1339 replies.add(postReplyBuilder.build());
1342 /* load post likes. */
1343 Set<String> likedPostIds = new HashSet<String>();
1345 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1346 if (likedPostId == null) {
1349 likedPostIds.add(likedPostId);
1352 /* load reply likes. */
1353 Set<String> likedReplyIds = new HashSet<String>();
1355 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1356 if (likedReplyId == null) {
1359 likedReplyIds.add(likedReplyId);
1363 Set<String> friends = new HashSet<String>();
1365 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1366 if (friendId == null) {
1369 friends.add(friendId);
1373 List<Album> topLevelAlbums = new ArrayList<Album>();
1374 int albumCounter = 0;
1376 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1377 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1378 if (albumId == null) {
1381 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1382 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1383 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1384 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1385 if ((albumTitle == null) || (albumDescription == null)) {
1386 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1389 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1390 if (albumParentId != null) {
1391 Album parentAlbum = getAlbum(albumParentId, false);
1392 if (parentAlbum == null) {
1393 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1396 parentAlbum.addAlbum(album);
1398 if (!topLevelAlbums.contains(album)) {
1399 topLevelAlbums.add(album);
1405 int imageCounter = 0;
1407 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1408 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1409 if (imageId == null) {
1412 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1413 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1414 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1415 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1416 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1417 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1418 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1419 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1420 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1423 Album album = getAlbum(albumId, false);
1424 if (album == null) {
1425 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1428 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1429 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1430 album.addImage(image);
1434 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1435 if (avatarId != null) {
1436 profile.setAvatar(getImage(avatarId, false));
1440 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1441 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1442 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1443 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1444 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1445 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1447 /* if we’re still here, Sone was loaded successfully. */
1448 synchronized (sone) {
1449 sone.setTime(soneTime);
1450 sone.setProfile(profile);
1451 sone.setPosts(posts);
1452 sone.setReplies(replies);
1453 sone.setLikePostIds(likedPostIds);
1454 sone.setLikeReplyIds(likedReplyIds);
1455 for (String friendId : friends) {
1456 followSone(sone, friendId);
1458 sone.setAlbums(topLevelAlbums);
1459 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1461 synchronized (knownSones) {
1462 for (String friend : friends) {
1463 knownSones.add(friend);
1466 synchronized (knownPosts) {
1467 for (Post post : posts) {
1468 knownPosts.add(post.getId());
1471 synchronized (knownReplies) {
1472 for (PostReply reply : replies) {
1473 knownReplies.add(reply.getId());
1479 * Creates a new post.
1482 * The Sone that creates the post
1484 * The text of the post
1485 * @return The created post
1487 public Post createPost(Sone sone, String text) {
1488 return createPost(sone, System.currentTimeMillis(), text);
1492 * Creates a new post.
1495 * The Sone that creates the post
1497 * The time of the post
1499 * The text of the post
1500 * @return The created post
1502 public Post createPost(Sone sone, long time, String text) {
1503 return createPost(sone, null, time, text);
1507 * Creates a new post.
1510 * The Sone that creates the post
1512 * The recipient Sone, or {@code null} if this post does not have
1515 * The text of the post
1516 * @return The created post
1518 public Post createPost(Sone sone, Sone recipient, String text) {
1519 return createPost(sone, recipient, System.currentTimeMillis(), text);
1523 * Creates a new post.
1526 * The Sone that creates the post
1528 * The recipient Sone, or {@code null} if this post does not have
1531 * The time of the post
1533 * The text of the post
1534 * @return The created post
1536 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1537 checkNotNull(text, "text must not be null");
1538 checkArgument(text.trim().length() > 0, "text must not be empty");
1539 if (!sone.isLocal()) {
1540 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1543 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1544 postBuilder.from(sone).randomId().withTime(time).withText(text.trim());
1545 if (recipient != null) {
1546 postBuilder.to(recipient);
1548 final Post post = postBuilder.build();
1549 synchronized (posts) {
1550 posts.put(post.getId(), post);
1552 eventBus.post(new NewPostFoundEvent(post));
1554 touchConfiguration();
1555 localElementTicker.schedule(new Runnable() {
1562 markPostKnown(post);
1564 }, 10, TimeUnit.SECONDS);
1569 * Deletes the given post.
1572 * The post to delete
1574 public void deletePost(Post post) {
1575 if (!post.getSone().isLocal()) {
1576 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1579 post.getSone().removePost(post);
1580 synchronized (posts) {
1581 posts.remove(post.getId());
1583 eventBus.post(new PostRemovedEvent(post));
1584 markPostKnown(post);
1585 touchConfiguration();
1589 * Marks the given post as known, if it is currently not a known post
1590 * (according to {@link Post#isKnown()}).
1593 * The post to mark as known
1595 public void markPostKnown(Post post) {
1596 post.setKnown(true);
1597 synchronized (knownPosts) {
1598 eventBus.post(new MarkPostKnownEvent(post));
1599 if (knownPosts.add(post.getId())) {
1600 touchConfiguration();
1603 for (PostReply reply : getReplies(post)) {
1604 markReplyKnown(reply);
1609 * Bookmarks the given post.
1612 * The post to bookmark
1614 public void bookmark(Post post) {
1615 bookmarkPost(post.getId());
1619 * Bookmarks the post with the given ID.
1622 * The ID of the post to bookmark
1624 public void bookmarkPost(String id) {
1625 synchronized (bookmarkedPosts) {
1626 bookmarkedPosts.add(id);
1631 * Removes the given post from the bookmarks.
1634 * The post to unbookmark
1636 public void unbookmark(Post post) {
1637 unbookmarkPost(post.getId());
1641 * Removes the post with the given ID from the bookmarks.
1644 * The ID of the post to unbookmark
1646 public void unbookmarkPost(String id) {
1647 synchronized (bookmarkedPosts) {
1648 bookmarkedPosts.remove(id);
1653 * Creates a new reply.
1656 * The Sone that creates the reply
1658 * The post that this reply refers to
1660 * The text of the reply
1661 * @return The created reply
1663 public PostReply createReply(Sone sone, Post post, String text) {
1664 checkNotNull(text, "text must not be null");
1665 checkArgument(text.trim().length() > 0, "text must not be empty");
1666 if (!sone.isLocal()) {
1667 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1670 PostReplyBuilder postReplyBuilder = postReplyBuilderFactory.newPostReplyBuilder();
1671 postReplyBuilder.randomId().from(sone).to(post.getId()).currentTime().withText(text.trim());
1672 final PostReply reply = postReplyBuilder.build();
1673 synchronized (replies) {
1674 replies.put(reply.getId(), reply);
1676 synchronized (knownReplies) {
1677 eventBus.post(new NewPostReplyFoundEvent(reply));
1679 sone.addReply(reply);
1680 touchConfiguration();
1681 localElementTicker.schedule(new Runnable() {
1688 markReplyKnown(reply);
1690 }, 10, TimeUnit.SECONDS);
1695 * Deletes the given reply.
1698 * The reply to delete
1700 public void deleteReply(PostReply reply) {
1701 Sone sone = reply.getSone();
1702 if (!sone.isLocal()) {
1703 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1706 synchronized (replies) {
1707 replies.remove(reply.getId());
1709 synchronized (knownReplies) {
1710 markReplyKnown(reply);
1711 knownReplies.remove(reply.getId());
1713 sone.removeReply(reply);
1714 touchConfiguration();
1718 * Marks the given reply as known, if it is currently not a known reply
1719 * (according to {@link Reply#isKnown()}).
1722 * The reply to mark as known
1724 public void markReplyKnown(PostReply reply) {
1725 reply.setKnown(true);
1726 synchronized (knownReplies) {
1727 eventBus.post(new MarkPostReplyKnownEvent(reply));
1728 if (knownReplies.add(reply.getId())) {
1729 touchConfiguration();
1735 * Creates a new top-level album for the given Sone.
1738 * The Sone to create the album for
1739 * @return The new album
1741 public Album createAlbum(Sone sone) {
1742 return createAlbum(sone, null);
1746 * Creates a new album for the given Sone.
1749 * The Sone to create the album for
1751 * The parent of the album (may be {@code null} to create a
1753 * @return The new album
1755 public Album createAlbum(Sone sone, Album parent) {
1756 Album album = new Album();
1757 synchronized (albums) {
1758 albums.put(album.getId(), album);
1760 album.setSone(sone);
1761 if (parent != null) {
1762 parent.addAlbum(album);
1764 sone.addAlbum(album);
1770 * Deletes the given album. The owner of the album has to be a local Sone,
1771 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1774 * The album to remove
1776 public void deleteAlbum(Album album) {
1777 checkNotNull(album, "album must not be null");
1778 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1779 if (!album.isEmpty()) {
1782 if (album.getParent() == null) {
1783 album.getSone().removeAlbum(album);
1785 album.getParent().removeAlbum(album);
1787 synchronized (albums) {
1788 albums.remove(album.getId());
1790 touchConfiguration();
1794 * Creates a new image.
1797 * The Sone creating the image
1799 * The album the image will be inserted into
1800 * @param temporaryImage
1801 * The temporary image to create the image from
1802 * @return The newly created image
1804 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1805 checkNotNull(sone, "sone must not be null");
1806 checkNotNull(album, "album must not be null");
1807 checkNotNull(temporaryImage, "temporaryImage must not be null");
1808 checkArgument(sone.isLocal(), "sone must be a local Sone");
1809 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1810 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1811 album.addImage(image);
1812 synchronized (images) {
1813 images.put(image.getId(), image);
1815 imageInserter.insertImage(temporaryImage, image);
1820 * Deletes the given image. This method will also delete a matching
1823 * @see #deleteTemporaryImage(TemporaryImage)
1825 * The image to delete
1827 public void deleteImage(Image image) {
1828 checkNotNull(image, "image must not be null");
1829 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1830 deleteTemporaryImage(image.getId());
1831 image.getAlbum().removeImage(image);
1832 synchronized (images) {
1833 images.remove(image.getId());
1835 touchConfiguration();
1839 * Creates a new temporary image.
1842 * The MIME type of the temporary image
1844 * The encoded data of the image
1845 * @return The temporary image
1847 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1848 TemporaryImage temporaryImage = new TemporaryImage();
1849 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1850 synchronized (temporaryImages) {
1851 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1853 return temporaryImage;
1857 * Deletes the given temporary image.
1859 * @param temporaryImage
1860 * The temporary image to delete
1862 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1863 checkNotNull(temporaryImage, "temporaryImage must not be null");
1864 deleteTemporaryImage(temporaryImage.getId());
1868 * Deletes the temporary image with the given ID.
1871 * The ID of the temporary image to delete
1873 public void deleteTemporaryImage(String imageId) {
1874 checkNotNull(imageId, "imageId must not be null");
1875 synchronized (temporaryImages) {
1876 temporaryImages.remove(imageId);
1878 Image image = getImage(imageId, false);
1879 if (image != null) {
1880 imageInserter.cancelImageInsert(image);
1885 * Notifies the core that the configuration, either of the core or of a
1886 * single local Sone, has changed, and that the configuration should be
1889 public void touchConfiguration() {
1890 lastConfigurationUpdate = System.currentTimeMillis();
1901 public void serviceStart() {
1902 loadConfiguration();
1903 updateChecker.start();
1904 identityManager.start();
1905 webOfTrustUpdater.init();
1906 webOfTrustUpdater.start();
1913 public void serviceRun() {
1914 long lastSaved = System.currentTimeMillis();
1915 while (!shouldStop()) {
1917 long now = System.currentTimeMillis();
1918 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1919 for (Sone localSone : getLocalSones()) {
1920 saveSone(localSone);
1922 saveConfiguration();
1932 public void serviceStop() {
1933 localElementTicker.shutdownNow();
1934 synchronized (sones) {
1935 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1936 soneInserter.getValue().stop();
1937 saveSone(soneInserter.getKey());
1940 saveConfiguration();
1941 webOfTrustUpdater.stop();
1942 updateChecker.stop();
1943 soneDownloader.stop();
1944 identityManager.stop();
1952 * Saves the given Sone. This will persist all local settings for the given
1953 * Sone, such as the friends list and similar, private options.
1958 private synchronized void saveSone(Sone sone) {
1959 if (!sone.isLocal()) {
1960 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1963 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1964 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1968 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1970 /* save Sone into configuration. */
1971 String sonePrefix = "Sone/" + sone.getId();
1972 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1973 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1976 Profile profile = sone.getProfile();
1977 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1978 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1979 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1980 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1981 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1982 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1983 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1985 /* save profile fields. */
1986 int fieldCounter = 0;
1987 for (Field profileField : profile.getFields()) {
1988 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1989 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1990 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1992 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1995 int postCounter = 0;
1996 for (Post post : sone.getPosts()) {
1997 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1998 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1999 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2000 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2001 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2003 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2006 int replyCounter = 0;
2007 for (PostReply reply : sone.getReplies()) {
2008 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2009 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2010 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2011 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2012 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2014 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2016 /* save post likes. */
2017 int postLikeCounter = 0;
2018 for (String postId : sone.getLikedPostIds()) {
2019 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2021 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2023 /* save reply likes. */
2024 int replyLikeCounter = 0;
2025 for (String replyId : sone.getLikedReplyIds()) {
2026 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2028 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2031 int friendCounter = 0;
2032 for (String friendId : sone.getFriends()) {
2033 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2035 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2037 /* save albums. first, collect in a flat structure, top-level first. */
2038 List<Album> albums = sone.getAllAlbums();
2040 int albumCounter = 0;
2041 for (Album album : albums) {
2042 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2043 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2044 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2045 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2046 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2047 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2049 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2052 int imageCounter = 0;
2053 for (Album album : albums) {
2054 for (Image image : album.getImages()) {
2055 if (!image.isInserted()) {
2058 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2059 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2060 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2061 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2062 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2063 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2064 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2065 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2066 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2069 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2072 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2073 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2074 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2075 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2076 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2077 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2079 configuration.save();
2081 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2083 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2084 } catch (ConfigurationException ce1) {
2085 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2090 * Saves the current options.
2092 private void saveConfiguration() {
2093 synchronized (configuration) {
2094 if (storingConfiguration) {
2095 logger.log(Level.FINE, "Already storing configuration…");
2098 storingConfiguration = true;
2101 /* store the options first. */
2103 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2104 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2105 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2106 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2107 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2108 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2109 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2110 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2111 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2112 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2113 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2114 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2116 /* save known Sones. */
2117 int soneCounter = 0;
2118 synchronized (knownSones) {
2119 for (String knownSoneId : knownSones) {
2120 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2122 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2125 /* save Sone following times. */
2127 synchronized (soneFollowingTimes) {
2128 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2129 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2130 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2133 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2136 /* save known posts. */
2137 int postCounter = 0;
2138 synchronized (knownPosts) {
2139 for (String knownPostId : knownPosts) {
2140 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2142 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2145 /* save known replies. */
2146 int replyCounter = 0;
2147 synchronized (knownReplies) {
2148 for (String knownReplyId : knownReplies) {
2149 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2151 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2154 /* save bookmarked posts. */
2155 int bookmarkedPostCounter = 0;
2156 synchronized (bookmarkedPosts) {
2157 for (String bookmarkedPostId : bookmarkedPosts) {
2158 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2161 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2164 configuration.save();
2166 } catch (ConfigurationException ce1) {
2167 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2169 synchronized (configuration) {
2170 storingConfiguration = false;
2176 * Loads the configuration.
2178 @SuppressWarnings("unchecked")
2179 private void loadConfiguration() {
2180 /* create options. */
2181 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2184 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2185 SoneInserter.setInsertionDelay(newValue);
2189 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2190 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2191 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2192 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2193 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2194 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2195 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2196 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2197 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2200 @SuppressWarnings("synthetic-access")
2201 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2202 fcpInterface.setActive(newValue);
2205 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2208 @SuppressWarnings("synthetic-access")
2209 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2210 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2215 loadConfigurationValue("InsertionDelay");
2216 loadConfigurationValue("PostsPerPage");
2217 loadConfigurationValue("ImagesPerPage");
2218 loadConfigurationValue("CharactersPerPost");
2219 loadConfigurationValue("PostCutOffLength");
2220 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2221 loadConfigurationValue("PositiveTrust");
2222 loadConfigurationValue("NegativeTrust");
2223 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2224 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2225 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2227 /* load known Sones. */
2228 int soneCounter = 0;
2230 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2231 if (knownSoneId == null) {
2234 synchronized (knownSones) {
2235 knownSones.add(knownSoneId);
2239 /* load Sone following times. */
2242 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2243 if (soneId == null) {
2246 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2247 Sone followedSone = getSone(soneId);
2248 if (followedSone == null) {
2249 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2251 synchronized (soneFollowingTimes) {
2252 soneFollowingTimes.put(getSone(soneId), time);
2258 /* load known posts. */
2259 int postCounter = 0;
2261 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2262 if (knownPostId == null) {
2265 synchronized (knownPosts) {
2266 knownPosts.add(knownPostId);
2270 /* load known replies. */
2271 int replyCounter = 0;
2273 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2274 if (knownReplyId == null) {
2277 synchronized (knownReplies) {
2278 knownReplies.add(knownReplyId);
2282 /* load bookmarked posts. */
2283 int bookmarkedPostCounter = 0;
2285 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2286 if (bookmarkedPostId == null) {
2289 synchronized (bookmarkedPosts) {
2290 bookmarkedPosts.add(bookmarkedPostId);
2297 * Loads an {@link Integer} configuration value for the option with the
2298 * given name, logging validation failures.
2301 * The name of the option to load
2303 private void loadConfigurationValue(String optionName) {
2305 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2306 } catch (IllegalArgumentException iae1) {
2307 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2312 * Notifies the core that a new {@link OwnIdentity} was added.
2314 * @param ownIdentityAddedEvent
2318 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2319 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2320 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2321 if (ownIdentity.hasContext("Sone")) {
2322 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2323 addLocalSone(ownIdentity);
2328 * Notifies the core that an {@link OwnIdentity} was removed.
2330 * @param ownIdentityRemovedEvent
2334 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2335 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2336 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2337 trustedIdentities.remove(ownIdentity);
2341 * Notifies the core that a new {@link Identity} was added.
2343 * @param identityAddedEvent
2347 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2348 Identity identity = identityAddedEvent.identity();
2349 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2350 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2351 addRemoteSone(identity);
2355 * Notifies the core that an {@link Identity} was updated.
2357 * @param identityUpdatedEvent
2361 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2362 final Identity identity = identityUpdatedEvent.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);
2378 * Notifies the core that an {@link Identity} was removed.
2380 * @param identityRemovedEvent
2384 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2385 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2386 Identity identity = identityRemovedEvent.identity();
2387 trustedIdentities.get(ownIdentity).remove(identity);
2388 boolean foundIdentity = false;
2389 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2390 if (trustedIdentity.getKey().equals(ownIdentity)) {
2393 if (trustedIdentity.getValue().contains(identity)) {
2394 foundIdentity = true;
2397 if (foundIdentity) {
2398 /* some local identity still trusts this identity, don’t remove. */
2401 Sone sone = getSone(identity.getId(), false);
2403 /* TODO - we don’t have the Sone anymore. should this happen? */
2406 synchronized (posts) {
2407 synchronized (knownPosts) {
2408 for (Post post : sone.getPosts()) {
2409 posts.remove(post.getId());
2410 eventBus.post(new PostRemovedEvent(post));
2414 synchronized (replies) {
2415 synchronized (knownReplies) {
2416 for (PostReply reply : sone.getReplies()) {
2417 replies.remove(reply.getId());
2418 eventBus.post(new PostReplyRemovedEvent(reply));
2422 synchronized (sones) {
2423 sones.remove(identity.getId());
2425 eventBus.post(new SoneRemovedEvent(sone));
2429 * Deletes the temporary image.
2431 * @param imageInsertFinishedEvent
2435 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2436 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2437 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2438 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2439 touchConfiguration();