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.Predicate;
90 import com.google.common.base.Predicates;
91 import com.google.common.collect.Collections2;
92 import com.google.common.eventbus.EventBus;
93 import com.google.common.eventbus.Subscribe;
94 import com.google.inject.Inject;
96 import freenet.keys.FreenetURI;
101 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
103 public class Core extends AbstractService implements SoneProvider, PostProvider {
106 private static final Logger logger = Logging.getLogger(Core.class);
108 /** The start time. */
109 private final long startupTime = System.currentTimeMillis();
112 private final Options options = new Options();
114 /** The preferences. */
115 private final Preferences preferences = new Preferences(options);
117 /** The event bus. */
118 private final EventBus eventBus;
120 /** The configuration. */
121 private Configuration configuration;
123 /** Whether we’re currently saving the configuration. */
124 private boolean storingConfiguration = false;
126 /** The identity manager. */
127 private final IdentityManager identityManager;
129 /** Interface to freenet. */
130 private final FreenetInterface freenetInterface;
132 /** The Sone downloader. */
133 private final SoneDownloader soneDownloader;
135 /** The image inserter. */
136 private final ImageInserter imageInserter;
138 /** Sone downloader thread-pool. */
139 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
141 /** The update checker. */
142 private final UpdateChecker updateChecker;
144 /** The trust updater. */
145 private final WebOfTrustUpdater webOfTrustUpdater;
147 /** The FCP interface. */
148 private volatile FcpInterface fcpInterface;
150 /** The times Sones were followed. */
151 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
153 /** Locked local Sones. */
154 /* synchronize on itself. */
155 private final Set<Sone> lockedSones = new HashSet<Sone>();
157 /** Sone inserters. */
158 /* synchronize access on this on sones. */
159 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
161 /** Sone rescuers. */
162 /* synchronize access on this on sones. */
163 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
166 /* synchronize access on this on itself. */
167 private final Map<String, Sone> sones = new HashMap<String, Sone>();
169 /** All known Sones. */
170 private final Set<String> knownSones = new HashSet<String>();
172 /** The post builder. */
173 private final PostBuilderFactory postBuilderFactory;
176 private final Map<String, Post> posts = new HashMap<String, Post>();
178 /** All known posts. */
179 private final Set<String> knownPosts = new HashSet<String>();
182 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
184 /** All known replies. */
185 private final Set<String> knownReplies = new HashSet<String>();
187 /** All bookmarked posts. */
188 /* synchronize access on itself. */
189 private final Set<String> bookmarkedPosts = new HashSet<String>();
191 /** Trusted identities, sorted by own identities. */
192 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
194 /** All known albums. */
195 private final Map<String, Album> albums = new HashMap<String, Album>();
197 /** All known images. */
198 private final Map<String, Image> images = new HashMap<String, Image>();
200 /** All temporary images. */
201 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
203 /** Ticker for threads that mark own elements as known. */
204 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
206 /** The time the configuration was last touched. */
207 private volatile long lastConfigurationUpdate;
210 * Creates a new core.
212 * @param configuration
213 * The configuration of the core
214 * @param freenetInterface
215 * The freenet interface
216 * @param identityManager
217 * The identity manager
218 * @param webOfTrustUpdater
219 * The WebOfTrust updater
222 * @param postBuilderFactory
226 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, PostBuilderFactory postBuilderFactory) {
228 this.configuration = configuration;
229 this.freenetInterface = freenetInterface;
230 this.identityManager = identityManager;
231 this.soneDownloader = new SoneDownloader(this, freenetInterface);
232 this.imageInserter = new ImageInserter(freenetInterface);
233 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
234 this.webOfTrustUpdater = webOfTrustUpdater;
235 this.eventBus = eventBus;
236 this.postBuilderFactory = postBuilderFactory;
244 * Returns the time Sone was started.
246 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
248 public long getStartupTime() {
253 * Sets the configuration to use. This will automatically save the current
254 * configuration to the given configuration.
256 * @param configuration
257 * The new configuration to use
259 public void setConfiguration(Configuration configuration) {
260 this.configuration = configuration;
261 touchConfiguration();
265 * Returns the options used by the core.
267 * @return The options of the core
269 public Preferences getPreferences() {
274 * Returns the identity manager used by the core.
276 * @return The identity manager
278 public IdentityManager getIdentityManager() {
279 return identityManager;
283 * Returns the update checker.
285 * @return The update checker
287 public UpdateChecker getUpdateChecker() {
288 return updateChecker;
292 * Sets the FCP interface to use.
294 * @param fcpInterface
295 * The FCP interface to use
297 public void setFcpInterface(FcpInterface fcpInterface) {
298 this.fcpInterface = fcpInterface;
302 * Returns the Sone rescuer for the given local Sone.
305 * The local Sone to get the rescuer for
306 * @return The Sone rescuer for the given Sone
308 public SoneRescuer getSoneRescuer(Sone sone) {
309 checkNotNull(sone, "sone must not be null");
310 checkArgument(sone.isLocal(), "sone must be local");
311 synchronized (sones) {
312 SoneRescuer soneRescuer = soneRescuers.get(sone);
313 if (soneRescuer == null) {
314 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
315 soneRescuers.put(sone, soneRescuer);
323 * Returns whether the given Sone is currently locked.
327 * @return {@code true} if the Sone is locked, {@code false} if it is not
329 public boolean isLocked(Sone sone) {
330 synchronized (lockedSones) {
331 return lockedSones.contains(sone);
336 * Returns all Sones, remote and local.
340 public Set<Sone> getSones() {
341 return new HashSet<Sone>(sones.values());
345 * Returns the Sone with the given ID, regardless whether it’s local or
349 * The ID of the Sone to get
350 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Sone getSone(String id) {
354 return getSone(id, true);
358 * Returns the Sone with the given ID, regardless whether it’s local or
362 * The ID of the Sone to get
364 * {@code true} to create a new Sone if none exists,
365 * {@code false} to return {@code null} if a Sone with the given
367 * @return The Sone with the given ID, or {@code null} if there is no such
371 public Sone getSone(String id, boolean create) {
372 synchronized (sones) {
373 if (!sones.containsKey(id) && create) {
374 Sone sone = new Sone(id, false);
377 return sones.get(id);
382 * Checks whether the core knows a Sone with the given ID.
386 * @return {@code true} if there is a Sone with the given ID, {@code false}
389 public boolean hasSone(String id) {
390 synchronized (sones) {
391 return sones.containsKey(id);
396 * Returns all local Sones.
398 * @return All local Sones
400 public Collection<Sone> getLocalSones() {
401 synchronized (sones) {
402 return Collections2.filter(sones.values(), new Predicate<Sone>() {
405 public boolean apply(Sone sone) {
406 return sone.isLocal();
413 * Returns the local Sone with the given ID, optionally creating a new Sone.
418 * {@code true} to create a new Sone if none exists,
419 * {@code false} to return null if none exists
420 * @return The Sone with the given ID, or {@code null}
422 public Sone getLocalSone(String id, boolean create) {
423 synchronized (sones) {
424 Sone sone = sones.get(id);
425 if ((sone == null) && create) {
426 sone = new Sone(id, true);
429 if ((sone != null) && !sone.isLocal()) {
430 sone = new Sone(id, true);
438 * Returns all remote Sones.
440 * @return All remote Sones
442 public Collection<Sone> getRemoteSones() {
443 synchronized (sones) {
444 return Collections2.filter(sones.values(), new Predicate<Sone>() {
447 public boolean apply(Sone sone) {
448 return !sone.isLocal();
455 * Returns the remote Sone with the given ID.
458 * The ID of the remote Sone to get
460 * {@code true} to always create a Sone, {@code false} to return
461 * {@code null} if no Sone with the given ID exists
462 * @return The Sone with the given ID
464 public Sone getRemoteSone(String id, boolean create) {
465 synchronized (sones) {
466 Sone sone = sones.get(id);
467 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
468 sone = new Sone(id, false);
476 * Returns whether the given Sone has been modified.
479 * The Sone to check for modifications
480 * @return {@code true} if a modification has been detected in the Sone,
481 * {@code false} otherwise
483 public boolean isModifiedSone(Sone sone) {
484 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
488 * Returns the time when the given was first followed by any local Sone.
491 * The Sone to get the time for
492 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
493 * been followed, or {@link Long#MAX_VALUE}
495 public long getSoneFollowingTime(Sone sone) {
496 synchronized (soneFollowingTimes) {
497 if (soneFollowingTimes.containsKey(sone)) {
498 return soneFollowingTimes.get(sone);
500 return Long.MAX_VALUE;
505 * Returns whether the target Sone is trusted by the origin Sone.
511 * @return {@code true} if the target Sone is trusted by the origin Sone
513 public boolean isSoneTrusted(Sone origin, Sone target) {
514 checkNotNull(origin, "origin must not be null");
515 checkNotNull(target, "target must not be null");
516 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
517 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
521 * Returns a post builder.
523 * @return A new post builder
525 public PostBuilder postBuilder() {
526 return postBuilderFactory.newPostBuilder();
533 public Post getPost(String postId) {
534 synchronized (posts) {
535 return posts.get(postId);
540 * Returns all posts that have the given Sone as recipient.
542 * @see Post#getRecipient()
544 * The recipient of the posts
545 * @return All posts that have the given Sone as recipient
547 public Set<Post> getDirectedPosts(Sone recipient) {
548 checkNotNull(recipient, "recipient must not be null");
549 Set<Post> directedPosts = new HashSet<Post>();
550 synchronized (posts) {
551 for (Post post : posts.values()) {
552 if (recipient.equals(post.getRecipient())) {
553 directedPosts.add(post);
557 return directedPosts;
561 * Returns the reply with the given ID.
564 * The ID of the reply to get
565 * @return The reply, or {@code null} if there is no such reply
567 public PostReply getPostReply(String replyId) {
568 synchronized (replies) {
569 return replies.get(replyId);
574 * Returns all replies for the given post, order ascending by time.
577 * The post to get all replies for
578 * @return All replies for the given post
580 public List<PostReply> getReplies(Post post) {
581 Set<Sone> sones = getSones();
582 List<PostReply> replies = new ArrayList<PostReply>();
583 for (Sone sone : sones) {
584 for (PostReply reply : sone.getReplies()) {
585 if (reply.getPost().equals(post)) {
590 Collections.sort(replies, Reply.TIME_COMPARATOR);
595 * Returns all Sones that have liked the given post.
598 * The post to get the liking Sones for
599 * @return The Sones that like the given post
601 public Set<Sone> getLikes(Post post) {
602 Set<Sone> sones = new HashSet<Sone>();
603 for (Sone sone : getSones()) {
604 if (sone.getLikedPostIds().contains(post.getId())) {
612 * Returns all Sones that have liked the given reply.
615 * The reply to get the liking Sones for
616 * @return The Sones that like the given reply
618 public Set<Sone> getLikes(PostReply reply) {
619 Set<Sone> sones = new HashSet<Sone>();
620 for (Sone sone : getSones()) {
621 if (sone.getLikedReplyIds().contains(reply.getId())) {
629 * Returns whether the given post is bookmarked.
633 * @return {@code true} if the given post is bookmarked, {@code false}
636 public boolean isBookmarked(Post post) {
637 return isPostBookmarked(post.getId());
641 * Returns whether the post with the given ID is bookmarked.
644 * The ID of the post to check
645 * @return {@code true} if the post with the given ID is bookmarked,
646 * {@code false} otherwise
648 public boolean isPostBookmarked(String id) {
649 synchronized (bookmarkedPosts) {
650 return bookmarkedPosts.contains(id);
655 * Returns all currently known bookmarked posts.
657 * @return All bookmarked posts
659 public Set<Post> getBookmarkedPosts() {
660 Set<Post> posts = new HashSet<Post>();
661 synchronized (bookmarkedPosts) {
662 for (String bookmarkedPostId : bookmarkedPosts) {
663 Post post = getPost(bookmarkedPostId);
673 * Returns the album with the given ID, creating a new album if no album
674 * with the given ID can be found.
677 * The ID of the album
678 * @return The album with the given ID
680 public Album getAlbum(String albumId) {
681 return getAlbum(albumId, true);
685 * Returns the album with the given ID, optionally creating a new album if
686 * an album with the given ID can not be found.
689 * The ID of the album
691 * {@code true} to create a new album if none exists for the
693 * @return The album with the given ID, or {@code null} if no album with the
694 * given ID exists and {@code create} is {@code false}
696 public Album getAlbum(String albumId, boolean create) {
697 synchronized (albums) {
698 Album album = albums.get(albumId);
699 if (create && (album == null)) {
700 album = new Album(albumId);
701 albums.put(albumId, album);
708 * Returns the image with the given ID, creating it if necessary.
711 * The ID of the image
712 * @return The image with the given ID
714 public Image getImage(String imageId) {
715 return getImage(imageId, true);
719 * Returns the image with the given ID, optionally creating it if it does
723 * The ID of the image
725 * {@code true} to create an image if none exists with the given
727 * @return The image with the given ID, or {@code null} if none exists and
730 public Image getImage(String imageId, boolean create) {
731 synchronized (images) {
732 Image image = images.get(imageId);
733 if (create && (image == null)) {
734 image = new Image(imageId);
735 images.put(imageId, image);
742 * Returns the temporary image with the given ID.
745 * The ID of the temporary image
746 * @return The temporary image, or {@code null} if there is no temporary
747 * image with the given ID
749 public TemporaryImage getTemporaryImage(String imageId) {
750 synchronized (temporaryImages) {
751 return temporaryImages.get(imageId);
760 * Locks the given Sone. A locked Sone will not be inserted by
761 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
767 public void lockSone(Sone sone) {
768 synchronized (lockedSones) {
769 if (lockedSones.add(sone)) {
770 eventBus.post(new SoneLockedEvent(sone));
776 * Unlocks the given Sone.
778 * @see #lockSone(Sone)
782 public void unlockSone(Sone sone) {
783 synchronized (lockedSones) {
784 if (lockedSones.remove(sone)) {
785 eventBus.post(new SoneUnlockedEvent(sone));
791 * Adds a local Sone from the given own identity.
794 * The own identity to create a Sone from
795 * @return The added (or already existing) Sone
797 public Sone addLocalSone(OwnIdentity ownIdentity) {
798 if (ownIdentity == null) {
799 logger.log(Level.WARNING, "Given OwnIdentity is null!");
802 synchronized (sones) {
805 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
806 } catch (MalformedURLException mue1) {
807 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
810 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
811 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
813 /* TODO - load posts ’n stuff */
814 sones.put(ownIdentity.getId(), sone);
815 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
816 soneInserters.put(sone, soneInserter);
817 sone.setStatus(SoneStatus.idle);
819 soneInserter.start();
825 * Creates a new Sone for the given own identity.
828 * The own identity to create a Sone for
829 * @return The created Sone
831 public Sone createSone(OwnIdentity ownIdentity) {
832 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
833 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
836 Sone sone = addLocalSone(ownIdentity);
837 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
838 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
839 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
840 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
841 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
842 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
844 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
845 touchConfiguration();
850 * Adds the Sone of the given identity.
853 * The identity whose Sone to add
854 * @return The added or already existing Sone
856 public Sone addRemoteSone(Identity identity) {
857 if (identity == null) {
858 logger.log(Level.WARNING, "Given Identity is null!");
861 synchronized (sones) {
862 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
863 boolean newSone = sone.getRequestUri() == null;
864 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
865 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
867 synchronized (knownSones) {
868 newSone = !knownSones.contains(sone.getId());
870 sone.setKnown(!newSone);
872 eventBus.post(new NewSoneFoundEvent(sone));
873 for (Sone localSone : getLocalSones()) {
874 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
875 followSone(localSone, sone);
880 soneDownloader.addSone(sone);
881 soneDownloaders.execute(new Runnable() {
884 @SuppressWarnings("synthetic-access")
886 soneDownloader.fetchSone(sone, sone.getRequestUri());
895 * Lets the given local Sone follow the Sone with the given ID.
898 * The local Sone that should follow another Sone
900 * The ID of the Sone to follow
902 public void followSone(Sone sone, String soneId) {
903 checkNotNull(sone, "sone must not be null");
904 checkNotNull(soneId, "soneId must not be null");
905 Sone followedSone = getSone(soneId, true);
906 if (followedSone == null) {
907 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
910 followSone(sone, getSone(soneId));
914 * Lets the given local Sone follow the other given Sone. If the given Sone
915 * was not followed by any local Sone before, this will mark all elements of
916 * the followed Sone as read that have been created before the current
920 * The local Sone that should follow the other Sone
921 * @param followedSone
922 * The Sone that should be followed
924 public void followSone(Sone sone, Sone followedSone) {
925 checkNotNull(sone, "sone must not be null");
926 checkNotNull(followedSone, "followedSone must not be null");
927 sone.addFriend(followedSone.getId());
928 synchronized (soneFollowingTimes) {
929 if (!soneFollowingTimes.containsKey(followedSone)) {
930 long now = System.currentTimeMillis();
931 soneFollowingTimes.put(followedSone, now);
932 for (Post post : followedSone.getPosts()) {
933 if (post.getTime() < now) {
937 for (PostReply reply : followedSone.getReplies()) {
938 if (reply.getTime() < now) {
939 markReplyKnown(reply);
944 touchConfiguration();
948 * Lets the given local Sone unfollow the Sone with the given ID.
951 * The local Sone that should unfollow another Sone
953 * The ID of the Sone being unfollowed
955 public void unfollowSone(Sone sone, String soneId) {
956 checkNotNull(sone, "sone must not be null");
957 checkNotNull(soneId, "soneId must not be null");
958 unfollowSone(sone, getSone(soneId, false));
962 * Lets the given local Sone unfollow the other given Sone. If the given
963 * local Sone is the last local Sone that followed the given Sone, its
964 * following time will be removed.
967 * The local Sone that should unfollow another Sone
968 * @param unfollowedSone
969 * The Sone being unfollowed
971 public void unfollowSone(Sone sone, Sone unfollowedSone) {
972 checkNotNull(sone, "sone must not be null");
973 checkNotNull(unfollowedSone, "unfollowedSone must not be null");
974 sone.removeFriend(unfollowedSone.getId());
975 boolean unfollowedSoneStillFollowed = false;
976 for (Sone localSone : getLocalSones()) {
977 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
979 if (!unfollowedSoneStillFollowed) {
980 synchronized (soneFollowingTimes) {
981 soneFollowingTimes.remove(unfollowedSone);
984 touchConfiguration();
988 * Sets the trust value of the given origin Sone for the target Sone.
995 * The trust value (from {@code -100} to {@code 100})
997 public void setTrust(Sone origin, Sone target, int trustValue) {
998 checkNotNull(origin, "origin must not be null");
999 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1000 checkNotNull(target, "target must not be null");
1001 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
1002 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1006 * Removes any trust assignment for the given target Sone.
1013 public void removeTrust(Sone origin, Sone target) {
1014 checkNotNull(origin, "origin must not be null");
1015 checkNotNull(target, "target must not be null");
1016 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
1017 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1021 * Assigns the configured positive trust value for the given target.
1028 public void trustSone(Sone origin, Sone target) {
1029 setTrust(origin, target, preferences.getPositiveTrust());
1033 * Assigns the configured negative trust value for the given target.
1040 public void distrustSone(Sone origin, Sone target) {
1041 setTrust(origin, target, preferences.getNegativeTrust());
1045 * Removes the trust assignment for the given target.
1052 public void untrustSone(Sone origin, Sone target) {
1053 removeTrust(origin, target);
1057 * Updates the stored Sone with the given Sone.
1062 public void updateSone(Sone sone) {
1063 updateSone(sone, false);
1067 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1068 * {@code true}, an older Sone than the current Sone can be given to restore
1072 * The Sone to update
1073 * @param soneRescueMode
1074 * {@code true} if the stored Sone should be updated regardless
1075 * of the age of the given Sone
1077 public void updateSone(Sone sone, boolean soneRescueMode) {
1078 if (hasSone(sone.getId())) {
1079 Sone storedSone = getSone(sone.getId());
1080 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1081 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1084 synchronized (posts) {
1085 if (!soneRescueMode) {
1086 for (Post post : storedSone.getPosts()) {
1087 posts.remove(post.getId());
1088 if (!sone.getPosts().contains(post)) {
1089 eventBus.post(new PostRemovedEvent(post));
1093 List<Post> storedPosts = storedSone.getPosts();
1094 synchronized (knownPosts) {
1095 for (Post post : sone.getPosts()) {
1096 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1097 postBuilder.copyPost(post).from(storedSone);
1098 Post newPost = postBuilder.build().setKnown(knownPosts.contains(post.getId()));
1099 if (!storedPosts.contains(newPost)) {
1100 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1101 knownPosts.add(newPost.getId());
1102 newPost.setKnown(true);
1103 } else if (!knownPosts.contains(newPost.getId())) {
1104 eventBus.post(new NewPostFoundEvent(newPost));
1107 posts.put(newPost.getId(), newPost);
1111 synchronized (replies) {
1112 if (!soneRescueMode) {
1113 for (PostReply reply : storedSone.getReplies()) {
1114 replies.remove(reply.getId());
1115 if (!sone.getReplies().contains(reply)) {
1116 eventBus.post(new PostReplyRemovedEvent(reply));
1120 Set<PostReply> storedReplies = storedSone.getReplies();
1121 synchronized (knownReplies) {
1122 for (PostReply reply : sone.getReplies()) {
1123 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1124 if (!storedReplies.contains(reply)) {
1125 if (reply.getTime() < getSoneFollowingTime(sone)) {
1126 knownReplies.add(reply.getId());
1127 reply.setKnown(true);
1128 } else if (!knownReplies.contains(reply.getId())) {
1129 eventBus.post(new NewPostReplyFoundEvent(reply));
1132 replies.put(reply.getId(), reply);
1136 synchronized (albums) {
1137 synchronized (images) {
1138 for (Album album : storedSone.getAlbums()) {
1139 albums.remove(album.getId());
1140 for (Image image : album.getImages()) {
1141 images.remove(image.getId());
1144 for (Album album : sone.getAlbums()) {
1145 albums.put(album.getId(), album);
1146 for (Image image : album.getImages()) {
1147 images.put(image.getId(), image);
1152 synchronized (storedSone) {
1153 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1154 storedSone.setTime(sone.getTime());
1156 storedSone.setClient(sone.getClient());
1157 storedSone.setProfile(sone.getProfile());
1158 if (soneRescueMode) {
1159 for (Post post : sone.getPosts()) {
1160 storedSone.addPost(post);
1162 for (PostReply reply : sone.getReplies()) {
1163 storedSone.addReply(reply);
1165 for (String likedPostId : sone.getLikedPostIds()) {
1166 storedSone.addLikedPostId(likedPostId);
1168 for (String likedReplyId : sone.getLikedReplyIds()) {
1169 storedSone.addLikedReplyId(likedReplyId);
1171 for (Album album : sone.getAlbums()) {
1172 storedSone.addAlbum(album);
1175 storedSone.setPosts(sone.getPosts());
1176 storedSone.setReplies(sone.getReplies());
1177 storedSone.setLikePostIds(sone.getLikedPostIds());
1178 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1179 storedSone.setAlbums(sone.getAlbums());
1181 storedSone.setLatestEdition(sone.getLatestEdition());
1187 * Deletes the given Sone. This will remove the Sone from the
1188 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1189 * remove the context from its identity.
1192 * The Sone to delete
1194 public void deleteSone(Sone sone) {
1195 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1196 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1199 synchronized (sones) {
1200 if (!getLocalSones().contains(sone)) {
1201 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1204 sones.remove(sone.getId());
1205 SoneInserter soneInserter = soneInserters.remove(sone);
1206 soneInserter.stop();
1208 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1209 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1211 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1212 } catch (ConfigurationException ce1) {
1213 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1218 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1219 * known} before, a {@link MarkSoneKnownEvent} is fired.
1222 * The Sone to mark as known
1224 public void markSoneKnown(Sone sone) {
1225 if (!sone.isKnown()) {
1226 sone.setKnown(true);
1227 synchronized (knownSones) {
1228 knownSones.add(sone.getId());
1230 eventBus.post(new MarkSoneKnownEvent(sone));
1231 touchConfiguration();
1236 * Loads and updates the given Sone from the configuration. If any error is
1237 * encountered, loading is aborted and the given Sone is not changed.
1240 * The Sone to load and update
1242 public void loadSone(Sone sone) {
1243 if (!sone.isLocal()) {
1244 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1248 /* initialize options. */
1249 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1250 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1251 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1252 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1253 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1254 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1257 String sonePrefix = "Sone/" + sone.getId();
1258 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1259 if (soneTime == null) {
1260 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1263 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1266 Profile profile = new Profile(sone);
1267 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1268 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1269 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1270 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1271 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1272 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1274 /* load profile fields. */
1276 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1277 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1278 if (fieldName == null) {
1281 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1282 profile.addField(fieldName).setValue(fieldValue);
1286 Set<Post> posts = new HashSet<Post>();
1288 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1289 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1290 if (postId == null) {
1293 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1294 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1295 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1296 if ((postTime == 0) || (postText == null)) {
1297 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1300 PostBuilder postBuilder = postBuilderFactory.newPostBuilder().withId(postId).from(sone).withTime(postTime).withText(postText);
1301 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1302 postBuilder.to(getSone(postRecipientId));
1304 posts.add(postBuilder.build());
1308 Set<PostReply> replies = new HashSet<PostReply>();
1310 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1311 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1312 if (replyId == null) {
1315 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1316 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1317 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1318 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1319 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1322 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1325 /* load post likes. */
1326 Set<String> likedPostIds = new HashSet<String>();
1328 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1329 if (likedPostId == null) {
1332 likedPostIds.add(likedPostId);
1335 /* load reply likes. */
1336 Set<String> likedReplyIds = new HashSet<String>();
1338 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1339 if (likedReplyId == null) {
1342 likedReplyIds.add(likedReplyId);
1346 Set<String> friends = new HashSet<String>();
1348 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1349 if (friendId == null) {
1352 friends.add(friendId);
1356 List<Album> topLevelAlbums = new ArrayList<Album>();
1357 int albumCounter = 0;
1359 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1360 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1361 if (albumId == null) {
1364 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1365 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1366 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1367 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1368 if ((albumTitle == null) || (albumDescription == null)) {
1369 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1372 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1373 if (albumParentId != null) {
1374 Album parentAlbum = getAlbum(albumParentId, false);
1375 if (parentAlbum == null) {
1376 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1379 parentAlbum.addAlbum(album);
1381 if (!topLevelAlbums.contains(album)) {
1382 topLevelAlbums.add(album);
1388 int imageCounter = 0;
1390 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1391 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1392 if (imageId == null) {
1395 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1396 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1397 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1398 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1399 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1400 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1401 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1402 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1403 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1406 Album album = getAlbum(albumId, false);
1407 if (album == null) {
1408 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1411 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1412 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1413 album.addImage(image);
1417 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1418 if (avatarId != null) {
1419 profile.setAvatar(getImage(avatarId, false));
1423 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1424 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1425 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1426 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1427 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1428 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1430 /* if we’re still here, Sone was loaded successfully. */
1431 synchronized (sone) {
1432 sone.setTime(soneTime);
1433 sone.setProfile(profile);
1434 sone.setPosts(posts);
1435 sone.setReplies(replies);
1436 sone.setLikePostIds(likedPostIds);
1437 sone.setLikeReplyIds(likedReplyIds);
1438 for (String friendId : friends) {
1439 followSone(sone, friendId);
1441 sone.setAlbums(topLevelAlbums);
1442 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1444 synchronized (knownSones) {
1445 for (String friend : friends) {
1446 knownSones.add(friend);
1449 synchronized (knownPosts) {
1450 for (Post post : posts) {
1451 knownPosts.add(post.getId());
1454 synchronized (knownReplies) {
1455 for (PostReply reply : replies) {
1456 knownReplies.add(reply.getId());
1462 * Creates a new post.
1465 * The Sone that creates the post
1467 * The text of the post
1468 * @return The created post
1470 public Post createPost(Sone sone, String text) {
1471 return createPost(sone, System.currentTimeMillis(), text);
1475 * Creates a new post.
1478 * The Sone that creates the post
1480 * The time of the post
1482 * The text of the post
1483 * @return The created post
1485 public Post createPost(Sone sone, long time, String text) {
1486 return createPost(sone, null, time, text);
1490 * Creates a new post.
1493 * The Sone that creates the post
1495 * The recipient Sone, or {@code null} if this post does not have
1498 * The text of the post
1499 * @return The created post
1501 public Post createPost(Sone sone, Sone recipient, String text) {
1502 return createPost(sone, recipient, System.currentTimeMillis(), text);
1506 * Creates a new post.
1509 * The Sone that creates the post
1511 * The recipient Sone, or {@code null} if this post does not have
1514 * The time of the post
1516 * The text of the post
1517 * @return The created post
1519 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1520 checkNotNull(text, "text must not be null");
1521 checkArgument(text.trim().length() > 0, "text must not be empty");
1522 if (!sone.isLocal()) {
1523 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1526 PostBuilder postBuilder = postBuilderFactory.newPostBuilder();
1527 postBuilder.from(sone).randomId().withTime(time).withText(text.trim());
1528 if (recipient != null) {
1529 postBuilder.to(recipient);
1531 final Post post = postBuilder.build();
1532 synchronized (posts) {
1533 posts.put(post.getId(), post);
1535 eventBus.post(new NewPostFoundEvent(post));
1537 touchConfiguration();
1538 localElementTicker.schedule(new Runnable() {
1545 markPostKnown(post);
1547 }, 10, TimeUnit.SECONDS);
1552 * Deletes the given post.
1555 * The post to delete
1557 public void deletePost(Post post) {
1558 if (!post.getSone().isLocal()) {
1559 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1562 post.getSone().removePost(post);
1563 synchronized (posts) {
1564 posts.remove(post.getId());
1566 eventBus.post(new PostRemovedEvent(post));
1567 markPostKnown(post);
1568 touchConfiguration();
1572 * Marks the given post as known, if it is currently not a known post
1573 * (according to {@link Post#isKnown()}).
1576 * The post to mark as known
1578 public void markPostKnown(Post post) {
1579 post.setKnown(true);
1580 synchronized (knownPosts) {
1581 eventBus.post(new MarkPostKnownEvent(post));
1582 if (knownPosts.add(post.getId())) {
1583 touchConfiguration();
1586 for (PostReply reply : getReplies(post)) {
1587 markReplyKnown(reply);
1592 * Bookmarks the given post.
1595 * The post to bookmark
1597 public void bookmark(Post post) {
1598 bookmarkPost(post.getId());
1602 * Bookmarks the post with the given ID.
1605 * The ID of the post to bookmark
1607 public void bookmarkPost(String id) {
1608 synchronized (bookmarkedPosts) {
1609 bookmarkedPosts.add(id);
1614 * Removes the given post from the bookmarks.
1617 * The post to unbookmark
1619 public void unbookmark(Post post) {
1620 unbookmarkPost(post.getId());
1624 * Removes the post with the given ID from the bookmarks.
1627 * The ID of the post to unbookmark
1629 public void unbookmarkPost(String id) {
1630 synchronized (bookmarkedPosts) {
1631 bookmarkedPosts.remove(id);
1636 * Creates a new reply.
1639 * The Sone that creates the reply
1641 * The post that this reply refers to
1643 * The text of the reply
1644 * @return The created reply
1646 public PostReply createReply(Sone sone, Post post, String text) {
1647 return createReply(sone, post, System.currentTimeMillis(), text);
1651 * Creates a new reply.
1654 * The Sone that creates the reply
1656 * The post that this reply refers to
1658 * The time of the reply
1660 * The text of the reply
1661 * @return The created reply
1663 public PostReply createReply(Sone sone, Post post, long time, String text) {
1664 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 final PostReply reply = new PostReplyImpl(sone, post, System.currentTimeMillis(), text.trim());
1671 synchronized (replies) {
1672 replies.put(reply.getId(), reply);
1674 synchronized (knownReplies) {
1675 eventBus.post(new NewPostReplyFoundEvent(reply));
1677 sone.addReply(reply);
1678 touchConfiguration();
1679 localElementTicker.schedule(new Runnable() {
1686 markReplyKnown(reply);
1688 }, 10, TimeUnit.SECONDS);
1693 * Deletes the given reply.
1696 * The reply to delete
1698 public void deleteReply(PostReply reply) {
1699 Sone sone = reply.getSone();
1700 if (!sone.isLocal()) {
1701 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1704 synchronized (replies) {
1705 replies.remove(reply.getId());
1707 synchronized (knownReplies) {
1708 markReplyKnown(reply);
1709 knownReplies.remove(reply.getId());
1711 sone.removeReply(reply);
1712 touchConfiguration();
1716 * Marks the given reply as known, if it is currently not a known reply
1717 * (according to {@link Reply#isKnown()}).
1720 * The reply to mark as known
1722 public void markReplyKnown(PostReply reply) {
1723 reply.setKnown(true);
1724 synchronized (knownReplies) {
1725 eventBus.post(new MarkPostReplyKnownEvent(reply));
1726 if (knownReplies.add(reply.getId())) {
1727 touchConfiguration();
1733 * Creates a new top-level album for the given Sone.
1736 * The Sone to create the album for
1737 * @return The new album
1739 public Album createAlbum(Sone sone) {
1740 return createAlbum(sone, null);
1744 * Creates a new album for the given Sone.
1747 * The Sone to create the album for
1749 * The parent of the album (may be {@code null} to create a
1751 * @return The new album
1753 public Album createAlbum(Sone sone, Album parent) {
1754 Album album = new Album();
1755 synchronized (albums) {
1756 albums.put(album.getId(), album);
1758 album.setSone(sone);
1759 if (parent != null) {
1760 parent.addAlbum(album);
1762 sone.addAlbum(album);
1768 * Deletes the given album. The owner of the album has to be a local Sone,
1769 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1772 * The album to remove
1774 public void deleteAlbum(Album album) {
1775 checkNotNull(album, "album must not be null");
1776 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1777 if (!album.isEmpty()) {
1780 if (album.getParent() == null) {
1781 album.getSone().removeAlbum(album);
1783 album.getParent().removeAlbum(album);
1785 synchronized (albums) {
1786 albums.remove(album.getId());
1788 touchConfiguration();
1792 * Creates a new image.
1795 * The Sone creating the image
1797 * The album the image will be inserted into
1798 * @param temporaryImage
1799 * The temporary image to create the image from
1800 * @return The newly created image
1802 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1803 checkNotNull(sone, "sone must not be null");
1804 checkNotNull(album, "album must not be null");
1805 checkNotNull(temporaryImage, "temporaryImage must not be null");
1806 checkArgument(sone.isLocal(), "sone must be a local Sone");
1807 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1808 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1809 album.addImage(image);
1810 synchronized (images) {
1811 images.put(image.getId(), image);
1813 imageInserter.insertImage(temporaryImage, image);
1818 * Deletes the given image. This method will also delete a matching
1821 * @see #deleteTemporaryImage(TemporaryImage)
1823 * The image to delete
1825 public void deleteImage(Image image) {
1826 checkNotNull(image, "image must not be null");
1827 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1828 deleteTemporaryImage(image.getId());
1829 image.getAlbum().removeImage(image);
1830 synchronized (images) {
1831 images.remove(image.getId());
1833 touchConfiguration();
1837 * Creates a new temporary image.
1840 * The MIME type of the temporary image
1842 * The encoded data of the image
1843 * @return The temporary image
1845 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1846 TemporaryImage temporaryImage = new TemporaryImage();
1847 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1848 synchronized (temporaryImages) {
1849 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1851 return temporaryImage;
1855 * Deletes the given temporary image.
1857 * @param temporaryImage
1858 * The temporary image to delete
1860 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1861 checkNotNull(temporaryImage, "temporaryImage must not be null");
1862 deleteTemporaryImage(temporaryImage.getId());
1866 * Deletes the temporary image with the given ID.
1869 * The ID of the temporary image to delete
1871 public void deleteTemporaryImage(String imageId) {
1872 checkNotNull(imageId, "imageId must not be null");
1873 synchronized (temporaryImages) {
1874 temporaryImages.remove(imageId);
1876 Image image = getImage(imageId, false);
1877 if (image != null) {
1878 imageInserter.cancelImageInsert(image);
1883 * Notifies the core that the configuration, either of the core or of a
1884 * single local Sone, has changed, and that the configuration should be
1887 public void touchConfiguration() {
1888 lastConfigurationUpdate = System.currentTimeMillis();
1899 public void serviceStart() {
1900 loadConfiguration();
1901 updateChecker.start();
1902 identityManager.start();
1903 webOfTrustUpdater.init();
1904 webOfTrustUpdater.start();
1911 public void serviceRun() {
1912 long lastSaved = System.currentTimeMillis();
1913 while (!shouldStop()) {
1915 long now = System.currentTimeMillis();
1916 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1917 for (Sone localSone : getLocalSones()) {
1918 saveSone(localSone);
1920 saveConfiguration();
1930 public void serviceStop() {
1931 localElementTicker.shutdownNow();
1932 synchronized (sones) {
1933 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1934 soneInserter.getValue().stop();
1935 saveSone(soneInserter.getKey());
1938 saveConfiguration();
1939 webOfTrustUpdater.stop();
1940 updateChecker.stop();
1941 soneDownloader.stop();
1942 identityManager.stop();
1950 * Saves the given Sone. This will persist all local settings for the given
1951 * Sone, such as the friends list and similar, private options.
1956 private synchronized void saveSone(Sone sone) {
1957 if (!sone.isLocal()) {
1958 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1961 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1962 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1966 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1968 /* save Sone into configuration. */
1969 String sonePrefix = "Sone/" + sone.getId();
1970 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1971 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1974 Profile profile = sone.getProfile();
1975 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1976 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1977 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1978 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1979 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1980 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1981 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1983 /* save profile fields. */
1984 int fieldCounter = 0;
1985 for (Field profileField : profile.getFields()) {
1986 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1987 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1988 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1990 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1993 int postCounter = 0;
1994 for (Post post : sone.getPosts()) {
1995 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1996 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1997 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1998 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1999 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2001 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2004 int replyCounter = 0;
2005 for (PostReply reply : sone.getReplies()) {
2006 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2007 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2008 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2009 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2010 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2012 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2014 /* save post likes. */
2015 int postLikeCounter = 0;
2016 for (String postId : sone.getLikedPostIds()) {
2017 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2019 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2021 /* save reply likes. */
2022 int replyLikeCounter = 0;
2023 for (String replyId : sone.getLikedReplyIds()) {
2024 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2026 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2029 int friendCounter = 0;
2030 for (String friendId : sone.getFriends()) {
2031 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2033 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2035 /* save albums. first, collect in a flat structure, top-level first. */
2036 List<Album> albums = sone.getAllAlbums();
2038 int albumCounter = 0;
2039 for (Album album : albums) {
2040 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2041 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2042 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2043 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2044 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2045 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2047 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2050 int imageCounter = 0;
2051 for (Album album : albums) {
2052 for (Image image : album.getImages()) {
2053 if (!image.isInserted()) {
2056 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2057 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2058 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2059 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2060 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2061 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2062 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2063 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2064 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2067 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2070 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2071 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2072 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2073 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2074 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2075 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2077 configuration.save();
2079 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2081 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2082 } catch (ConfigurationException ce1) {
2083 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2088 * Saves the current options.
2090 private void saveConfiguration() {
2091 synchronized (configuration) {
2092 if (storingConfiguration) {
2093 logger.log(Level.FINE, "Already storing configuration…");
2096 storingConfiguration = true;
2099 /* store the options first. */
2101 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2102 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2103 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2104 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2105 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2106 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2107 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2108 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2109 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2110 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2111 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2112 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2114 /* save known Sones. */
2115 int soneCounter = 0;
2116 synchronized (knownSones) {
2117 for (String knownSoneId : knownSones) {
2118 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2120 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2123 /* save Sone following times. */
2125 synchronized (soneFollowingTimes) {
2126 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2127 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2128 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2131 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2134 /* save known posts. */
2135 int postCounter = 0;
2136 synchronized (knownPosts) {
2137 for (String knownPostId : knownPosts) {
2138 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2140 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2143 /* save known replies. */
2144 int replyCounter = 0;
2145 synchronized (knownReplies) {
2146 for (String knownReplyId : knownReplies) {
2147 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2149 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2152 /* save bookmarked posts. */
2153 int bookmarkedPostCounter = 0;
2154 synchronized (bookmarkedPosts) {
2155 for (String bookmarkedPostId : bookmarkedPosts) {
2156 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2159 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2162 configuration.save();
2164 } catch (ConfigurationException ce1) {
2165 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2167 synchronized (configuration) {
2168 storingConfiguration = false;
2174 * Loads the configuration.
2176 @SuppressWarnings("unchecked")
2177 private void loadConfiguration() {
2178 /* create options. */
2179 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2182 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2183 SoneInserter.setInsertionDelay(newValue);
2187 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2188 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2189 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2190 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2191 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2192 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2193 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2194 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2195 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2198 @SuppressWarnings("synthetic-access")
2199 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2200 fcpInterface.setActive(newValue);
2203 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2206 @SuppressWarnings("synthetic-access")
2207 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2208 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2213 loadConfigurationValue("InsertionDelay");
2214 loadConfigurationValue("PostsPerPage");
2215 loadConfigurationValue("ImagesPerPage");
2216 loadConfigurationValue("CharactersPerPost");
2217 loadConfigurationValue("PostCutOffLength");
2218 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2219 loadConfigurationValue("PositiveTrust");
2220 loadConfigurationValue("NegativeTrust");
2221 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2222 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2223 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2225 /* load known Sones. */
2226 int soneCounter = 0;
2228 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2229 if (knownSoneId == null) {
2232 synchronized (knownSones) {
2233 knownSones.add(knownSoneId);
2237 /* load Sone following times. */
2240 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2241 if (soneId == null) {
2244 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2245 Sone followedSone = getSone(soneId);
2246 if (followedSone == null) {
2247 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2249 synchronized (soneFollowingTimes) {
2250 soneFollowingTimes.put(getSone(soneId), time);
2256 /* load known posts. */
2257 int postCounter = 0;
2259 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2260 if (knownPostId == null) {
2263 synchronized (knownPosts) {
2264 knownPosts.add(knownPostId);
2268 /* load known replies. */
2269 int replyCounter = 0;
2271 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2272 if (knownReplyId == null) {
2275 synchronized (knownReplies) {
2276 knownReplies.add(knownReplyId);
2280 /* load bookmarked posts. */
2281 int bookmarkedPostCounter = 0;
2283 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2284 if (bookmarkedPostId == null) {
2287 synchronized (bookmarkedPosts) {
2288 bookmarkedPosts.add(bookmarkedPostId);
2295 * Loads an {@link Integer} configuration value for the option with the
2296 * given name, logging validation failures.
2299 * The name of the option to load
2301 private void loadConfigurationValue(String optionName) {
2303 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2304 } catch (IllegalArgumentException iae1) {
2305 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2310 * Generate a Sone URI from the given URI and latest edition.
2313 * The URI to derive the Sone URI from
2314 * @return The derived URI
2316 private static FreenetURI getSoneUri(String uriString) {
2318 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2320 } catch (MalformedURLException mue1) {
2321 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2327 * Notifies the core that a new {@link OwnIdentity} was added.
2329 * @param ownIdentityAddedEvent
2333 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2334 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2335 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2336 if (ownIdentity.hasContext("Sone")) {
2337 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2338 addLocalSone(ownIdentity);
2343 * Notifies the core that an {@link OwnIdentity} was removed.
2345 * @param ownIdentityRemovedEvent
2349 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2350 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2351 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2352 trustedIdentities.remove(ownIdentity);
2356 * Notifies the core that a new {@link Identity} was added.
2358 * @param identityAddedEvent
2362 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2363 Identity identity = identityAddedEvent.identity();
2364 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2365 trustedIdentities.get(identityAddedEvent.ownIdentity()).add(identity);
2366 addRemoteSone(identity);
2370 * Notifies the core that an {@link Identity} was updated.
2372 * @param identityUpdatedEvent
2376 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2377 final Identity identity = identityUpdatedEvent.identity();
2378 soneDownloaders.execute(new Runnable() {
2381 @SuppressWarnings("synthetic-access")
2383 Sone sone = getRemoteSone(identity.getId(), false);
2384 sone.setIdentity(identity);
2385 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2386 soneDownloader.addSone(sone);
2387 soneDownloader.fetchSone(sone);
2393 * Notifies the core that an {@link Identity} was removed.
2395 * @param identityRemovedEvent
2399 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2400 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2401 Identity identity = identityRemovedEvent.identity();
2402 trustedIdentities.get(ownIdentity).remove(identity);
2403 boolean foundIdentity = false;
2404 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2405 if (trustedIdentity.getKey().equals(ownIdentity)) {
2408 if (trustedIdentity.getValue().contains(identity)) {
2409 foundIdentity = true;
2412 if (foundIdentity) {
2413 /* some local identity still trusts this identity, don’t remove. */
2416 Sone sone = getSone(identity.getId(), false);
2418 /* TODO - we don’t have the Sone anymore. should this happen? */
2421 synchronized (posts) {
2422 synchronized (knownPosts) {
2423 for (Post post : sone.getPosts()) {
2424 posts.remove(post.getId());
2425 eventBus.post(new PostRemovedEvent(post));
2429 synchronized (replies) {
2430 synchronized (knownReplies) {
2431 for (PostReply reply : sone.getReplies()) {
2432 replies.remove(reply.getId());
2433 eventBus.post(new PostReplyRemovedEvent(reply));
2437 synchronized (sones) {
2438 sones.remove(identity.getId());
2440 eventBus.post(new SoneRemovedEvent(sone));
2444 * Deletes the temporary image.
2446 * @param imageInsertFinishedEvent
2450 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2451 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2452 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2453 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2454 touchConfiguration();