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;
22 import static com.google.common.base.Predicates.not;
23 import static java.lang.String.format;
24 import static java.util.logging.Level.WARNING;
25 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
27 import java.net.MalformedURLException;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
48 import net.pterodactylus.sone.core.Options.DefaultOption;
49 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
50 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
51 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
52 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
54 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
55 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
56 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
57 import net.pterodactylus.sone.core.event.PostRemovedEvent;
58 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneLockedEvent;
60 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
61 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
62 import net.pterodactylus.sone.data.Album;
63 import net.pterodactylus.sone.data.Client;
64 import net.pterodactylus.sone.data.Image;
65 import net.pterodactylus.sone.data.Post;
66 import net.pterodactylus.sone.data.PostReply;
67 import net.pterodactylus.sone.data.Profile;
68 import net.pterodactylus.sone.data.Profile.Field;
69 import net.pterodactylus.sone.data.Reply;
70 import net.pterodactylus.sone.data.Sone;
71 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
72 import net.pterodactylus.sone.data.Sone.SoneStatus;
73 import net.pterodactylus.sone.data.SoneImpl;
74 import net.pterodactylus.sone.data.TemporaryImage;
75 import net.pterodactylus.sone.database.AlbumBuilder;
76 import net.pterodactylus.sone.database.Database;
77 import net.pterodactylus.sone.database.DatabaseException;
78 import net.pterodactylus.sone.database.PostBuilder;
79 import net.pterodactylus.sone.database.PostProvider;
80 import net.pterodactylus.sone.database.PostReplyBuilder;
81 import net.pterodactylus.sone.database.PostReplyProvider;
82 import net.pterodactylus.sone.database.SoneProvider;
83 import net.pterodactylus.sone.fcp.FcpInterface;
84 import net.pterodactylus.sone.freenet.wot.Identity;
85 import net.pterodactylus.sone.freenet.wot.IdentityManager;
86 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
92 import net.pterodactylus.sone.main.SonePlugin;
93 import net.pterodactylus.sone.utils.IntegerRangePredicate;
94 import net.pterodactylus.util.config.Configuration;
95 import net.pterodactylus.util.config.ConfigurationException;
96 import net.pterodactylus.util.logging.Logging;
97 import net.pterodactylus.util.number.Numbers;
98 import net.pterodactylus.util.service.AbstractService;
99 import net.pterodactylus.util.thread.NamedThreadFactory;
101 import com.google.common.annotations.VisibleForTesting;
102 import com.google.common.base.Optional;
103 import com.google.common.base.Predicates;
104 import com.google.common.collect.FluentIterable;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.ImmutableSet;
107 import com.google.common.collect.Multimap;
108 import com.google.common.collect.Multimaps;
109 import com.google.common.eventbus.EventBus;
110 import com.google.common.eventbus.Subscribe;
111 import com.google.inject.Inject;
112 import com.google.inject.Singleton;
114 import freenet.keys.FreenetURI;
119 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
122 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
125 private static final Logger logger = Logging.getLogger(Core.class);
127 /** The start time. */
128 private final long startupTime = System.currentTimeMillis();
131 private final Options options = new Options();
133 /** The preferences. */
134 private final Preferences preferences = new Preferences(options);
136 /** The event bus. */
137 private final EventBus eventBus;
139 /** The configuration. */
140 private final Configuration configuration;
142 /** Whether we’re currently saving the configuration. */
143 private boolean storingConfiguration = false;
145 /** The identity manager. */
146 private final IdentityManager identityManager;
148 /** Interface to freenet. */
149 private final FreenetInterface freenetInterface;
151 /** The Sone downloader. */
152 private final SoneDownloader soneDownloader;
154 /** The image inserter. */
155 private final ImageInserter imageInserter;
157 /** Sone downloader thread-pool. */
158 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
160 /** The update checker. */
161 private final UpdateChecker updateChecker;
163 /** The trust updater. */
164 private final WebOfTrustUpdater webOfTrustUpdater;
166 /** The FCP interface. */
167 private volatile FcpInterface fcpInterface;
169 /** The times Sones were followed. */
170 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
172 /** Locked local Sones. */
173 /* synchronize on itself. */
174 private final Set<Sone> lockedSones = new HashSet<Sone>();
176 /** Sone inserters. */
177 /* synchronize access on this on sones. */
178 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
180 /** Sone rescuers. */
181 /* synchronize access on this on sones. */
182 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
185 /* synchronize access on this on itself. */
186 private final Map<String, Sone> sones = new HashMap<String, Sone>();
188 /** All known Sones. */
189 private final Set<String> knownSones = new HashSet<String>();
191 /** The post database. */
192 private final Database database;
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 Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
201 /** All temporary images. */
202 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
204 /** Ticker for threads that mark own elements as known. */
205 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
207 /** The time the configuration was last touched. */
208 private volatile long lastConfigurationUpdate;
211 * Creates a new core.
213 * @param configuration
214 * The configuration of the core
215 * @param freenetInterface
216 * The freenet interface
217 * @param identityManager
218 * The identity manager
219 * @param webOfTrustUpdater
220 * The WebOfTrust updater
227 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
229 this.configuration = configuration;
230 this.freenetInterface = freenetInterface;
231 this.identityManager = identityManager;
232 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
233 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
234 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
235 this.webOfTrustUpdater = webOfTrustUpdater;
236 this.eventBus = eventBus;
237 this.database = database;
241 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
243 this.configuration = configuration;
244 this.freenetInterface = freenetInterface;
245 this.identityManager = identityManager;
246 this.soneDownloader = soneDownloader;
247 this.imageInserter = imageInserter;
248 this.updateChecker = updateChecker;
249 this.webOfTrustUpdater = webOfTrustUpdater;
250 this.eventBus = eventBus;
251 this.database = database;
259 * Returns the time Sone was started.
261 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
263 public long getStartupTime() {
268 * Returns the options used by the core.
270 * @return The options of the core
272 public Preferences getPreferences() {
277 * Returns the identity manager used by the core.
279 * @return The identity manager
281 public IdentityManager getIdentityManager() {
282 return identityManager;
286 * Returns the update checker.
288 * @return The update checker
290 public UpdateChecker getUpdateChecker() {
291 return updateChecker;
295 * Sets the FCP interface to use.
297 * @param fcpInterface
298 * The FCP interface to use
300 public void setFcpInterface(FcpInterface fcpInterface) {
301 this.fcpInterface = fcpInterface;
305 * Returns the Sone rescuer for the given local Sone.
308 * The local Sone to get the rescuer for
309 * @return The Sone rescuer for the given Sone
311 public SoneRescuer getSoneRescuer(Sone sone) {
312 checkNotNull(sone, "sone must not be null");
313 checkArgument(sone.isLocal(), "sone must be local");
314 synchronized (sones) {
315 SoneRescuer soneRescuer = soneRescuers.get(sone);
316 if (soneRescuer == null) {
317 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
318 soneRescuers.put(sone, soneRescuer);
326 * Returns whether the given Sone is currently locked.
330 * @return {@code true} if the Sone is locked, {@code false} if it is not
332 public boolean isLocked(Sone sone) {
333 synchronized (lockedSones) {
334 return lockedSones.contains(sone);
342 public Collection<Sone> getSones() {
343 synchronized (sones) {
344 return ImmutableSet.copyOf(sones.values());
349 * Returns the Sone with the given ID, regardless whether it’s local or
353 * The ID of the Sone to get
354 * @return The Sone with the given ID, or {@code null} if there is no such
358 public Optional<Sone> getSone(String id) {
359 synchronized (sones) {
360 return Optional.fromNullable(sones.get(id));
368 public Collection<Sone> getLocalSones() {
369 synchronized (sones) {
370 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
375 * Returns the local Sone with the given ID, optionally creating a new Sone.
380 * {@code true} to create a new Sone if none exists,
381 * {@code false} to return null if none exists
382 * @return The Sone with the given ID, or {@code null}
384 public Sone getLocalSone(String id, boolean create) {
385 synchronized (sones) {
386 Sone sone = sones.get(id);
387 if ((sone == null) && create) {
388 sone = new SoneImpl(id, true);
391 if ((sone != null) && !sone.isLocal()) {
392 sone = new SoneImpl(id, true);
403 public Collection<Sone> getRemoteSones() {
404 synchronized (sones) {
405 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
410 * Returns the remote Sone with the given ID.
413 * The ID of the remote Sone to get
415 * {@code true} to always create a Sone, {@code false} to return
416 * {@code null} if no Sone with the given ID exists
417 * @return The Sone with the given ID
419 public Sone getRemoteSone(String id, boolean create) {
420 synchronized (sones) {
421 Sone sone = sones.get(id);
422 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
423 sone = new SoneImpl(id, false);
431 * Returns whether the given Sone has been modified.
434 * The Sone to check for modifications
435 * @return {@code true} if a modification has been detected in the Sone,
436 * {@code false} otherwise
438 public boolean isModifiedSone(Sone sone) {
439 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
443 * Returns the time when the given was first followed by any local Sone.
446 * The Sone to get the time for
447 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
448 * been followed, or {@link Long#MAX_VALUE}
450 public long getSoneFollowingTime(Sone sone) {
451 synchronized (soneFollowingTimes) {
452 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
457 * Returns a post builder.
459 * @return A new post builder
461 public PostBuilder postBuilder() {
462 return database.newPostBuilder();
469 public Optional<Post> getPost(String postId) {
470 return database.getPost(postId);
477 public Collection<Post> getPosts(String soneId) {
478 return database.getPosts(soneId);
485 public Collection<Post> getDirectedPosts(final String recipientId) {
486 checkNotNull(recipientId, "recipient must not be null");
487 return database.getDirectedPosts(recipientId);
491 * Returns a post reply builder.
493 * @return A new post reply builder
495 public PostReplyBuilder postReplyBuilder() {
496 return database.newPostReplyBuilder();
503 public Optional<PostReply> getPostReply(String replyId) {
504 return database.getPostReply(replyId);
511 public List<PostReply> getReplies(final String postId) {
512 return database.getReplies(postId);
516 * Returns all Sones that have liked the given post.
519 * The post to get the liking Sones for
520 * @return The Sones that like the given post
522 public Set<Sone> getLikes(Post post) {
523 Set<Sone> sones = new HashSet<Sone>();
524 for (Sone sone : getSones()) {
525 if (sone.getLikedPostIds().contains(post.getId())) {
533 * Returns all Sones that have liked the given reply.
536 * The reply to get the liking Sones for
537 * @return The Sones that like the given reply
539 public Set<Sone> getLikes(PostReply reply) {
540 Set<Sone> sones = new HashSet<Sone>();
541 for (Sone sone : getSones()) {
542 if (sone.getLikedReplyIds().contains(reply.getId())) {
550 * Returns whether the given post is bookmarked.
554 * @return {@code true} if the given post is bookmarked, {@code false}
557 public boolean isBookmarked(Post post) {
558 return isPostBookmarked(post.getId());
562 * Returns whether the post with the given ID is bookmarked.
565 * The ID of the post to check
566 * @return {@code true} if the post with the given ID is bookmarked,
567 * {@code false} otherwise
569 public boolean isPostBookmarked(String id) {
570 synchronized (bookmarkedPosts) {
571 return bookmarkedPosts.contains(id);
576 * Returns all currently known bookmarked posts.
578 * @return All bookmarked posts
580 public Set<Post> getBookmarkedPosts() {
581 Set<Post> posts = new HashSet<Post>();
582 synchronized (bookmarkedPosts) {
583 for (String bookmarkedPostId : bookmarkedPosts) {
584 Optional<Post> post = getPost(bookmarkedPostId);
585 if (post.isPresent()) {
586 posts.add(post.get());
593 public AlbumBuilder albumBuilder() {
594 return database.newAlbumBuilder();
598 * Returns the album with the given ID, optionally creating a new album if
599 * an album with the given ID can not be found.
602 * The ID of the album
603 * @return The album with the given ID, or {@code null} if no album with the
606 public Album getAlbum(String albumId) {
607 return database.getAlbum(albumId).orNull();
611 * Returns the image with the given ID, creating it if necessary.
614 * The ID of the image
615 * @return The image with the given ID
617 public Image getImage(String imageId) {
618 return getImage(imageId, true);
622 * Returns the image with the given ID, optionally creating it if it does
626 * The ID of the image
628 * {@code true} to create an image if none exists with the given
630 * @return The image with the given ID, or {@code null} if none exists and
633 public Image getImage(String imageId, boolean create) {
634 Optional<Image> image = database.getImage(imageId);
635 if (image.isPresent()) {
641 Image newImage = database.newImageBuilder().withId(imageId).build();
642 database.storeImage(newImage);
647 * Returns the temporary image with the given ID.
650 * The ID of the temporary image
651 * @return The temporary image, or {@code null} if there is no temporary
652 * image with the given ID
654 public TemporaryImage getTemporaryImage(String imageId) {
655 synchronized (temporaryImages) {
656 return temporaryImages.get(imageId);
665 * Locks the given Sone. A locked Sone will not be inserted by
666 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
672 public void lockSone(Sone sone) {
673 synchronized (lockedSones) {
674 if (lockedSones.add(sone)) {
675 eventBus.post(new SoneLockedEvent(sone));
681 * Unlocks the given Sone.
683 * @see #lockSone(Sone)
687 public void unlockSone(Sone sone) {
688 synchronized (lockedSones) {
689 if (lockedSones.remove(sone)) {
690 eventBus.post(new SoneUnlockedEvent(sone));
696 * Adds a local Sone from the given own identity.
699 * The own identity to create a Sone from
700 * @return The added (or already existing) Sone
702 public Sone addLocalSone(OwnIdentity ownIdentity) {
703 if (ownIdentity == null) {
704 logger.log(Level.WARNING, "Given OwnIdentity is null!");
707 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
708 synchronized (sones) {
711 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
712 } catch (MalformedURLException mue1) {
713 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
716 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
717 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
719 /* TODO - load posts ’n stuff */
720 sones.put(ownIdentity.getId(), sone);
721 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
722 soneInserters.put(sone, soneInserter);
723 sone.setStatus(SoneStatus.idle);
725 soneInserter.start();
731 * Creates a new Sone for the given own identity.
734 * The own identity to create a Sone for
735 * @return The created Sone
737 public Sone createSone(OwnIdentity ownIdentity) {
738 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
739 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
742 Sone sone = addLocalSone(ownIdentity);
744 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
745 touchConfiguration();
750 * Adds the Sone of the given identity.
753 * The identity whose Sone to add
754 * @return The added or already existing Sone
756 public Sone addRemoteSone(Identity identity) {
757 if (identity == null) {
758 logger.log(Level.WARNING, "Given Identity is null!");
761 synchronized (sones) {
762 final Sone sone = getRemoteSone(identity.getId(), true);
763 if (sone.isLocal()) {
766 sone.setIdentity(identity);
767 boolean newSone = sone.getRequestUri() == null;
768 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
769 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
771 synchronized (knownSones) {
772 newSone = !knownSones.contains(sone.getId());
774 sone.setKnown(!newSone);
776 eventBus.post(new NewSoneFoundEvent(sone));
777 for (Sone localSone : getLocalSones()) {
778 if (localSone.getOptions().isAutoFollow()) {
779 followSone(localSone, sone.getId());
784 soneDownloader.addSone(sone);
785 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
791 * Lets the given local Sone follow the Sone with the given ID.
794 * The local Sone that should follow another Sone
796 * The ID of the Sone to follow
798 public void followSone(Sone sone, String soneId) {
799 checkNotNull(sone, "sone must not be null");
800 checkNotNull(soneId, "soneId must not be null");
801 sone.addFriend(soneId);
802 synchronized (soneFollowingTimes) {
803 if (!soneFollowingTimes.containsKey(soneId)) {
804 long now = System.currentTimeMillis();
805 soneFollowingTimes.put(soneId, now);
806 Optional<Sone> followedSone = getSone(soneId);
807 if (!followedSone.isPresent()) {
810 for (Post post : followedSone.get().getPosts()) {
811 if (post.getTime() < now) {
815 for (PostReply reply : followedSone.get().getReplies()) {
816 if (reply.getTime() < now) {
817 markReplyKnown(reply);
822 touchConfiguration();
826 * Lets the given local Sone unfollow the Sone with the given ID.
829 * The local Sone that should unfollow another Sone
831 * The ID of the Sone being unfollowed
833 public void unfollowSone(Sone sone, String soneId) {
834 checkNotNull(sone, "sone must not be null");
835 checkNotNull(soneId, "soneId must not be null");
836 sone.removeFriend(soneId);
837 boolean unfollowedSoneStillFollowed = false;
838 for (Sone localSone : getLocalSones()) {
839 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
841 if (!unfollowedSoneStillFollowed) {
842 synchronized (soneFollowingTimes) {
843 soneFollowingTimes.remove(soneId);
846 touchConfiguration();
850 * Sets the trust value of the given origin Sone for the target Sone.
857 * The trust value (from {@code -100} to {@code 100})
859 public void setTrust(Sone origin, Sone target, int trustValue) {
860 checkNotNull(origin, "origin must not be null");
861 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
862 checkNotNull(target, "target must not be null");
863 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
864 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
868 * Removes any trust assignment for the given target Sone.
875 public void removeTrust(Sone origin, Sone target) {
876 checkNotNull(origin, "origin must not be null");
877 checkNotNull(target, "target must not be null");
878 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
879 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
883 * Assigns the configured positive trust value for the given target.
890 public void trustSone(Sone origin, Sone target) {
891 setTrust(origin, target, preferences.getPositiveTrust());
895 * Assigns the configured negative trust value for the given target.
902 public void distrustSone(Sone origin, Sone target) {
903 setTrust(origin, target, preferences.getNegativeTrust());
907 * Removes the trust assignment for the given target.
914 public void untrustSone(Sone origin, Sone target) {
915 removeTrust(origin, target);
919 * Updates the stored Sone with the given Sone.
924 public void updateSone(Sone sone) {
925 updateSone(sone, false);
929 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
930 * {@code true}, an older Sone than the current Sone can be given to restore
935 * @param soneRescueMode
936 * {@code true} if the stored Sone should be updated regardless
937 * of the age of the given Sone
939 public void updateSone(Sone sone, boolean soneRescueMode) {
940 Optional<Sone> storedSone = getSone(sone.getId());
941 if (storedSone.isPresent()) {
942 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
943 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
946 /* find removed posts. */
947 Collection<Post> removedPosts = new ArrayList<Post>();
948 Collection<Post> newPosts = new ArrayList<Post>();
949 Collection<Post> existingPosts = database.getPosts(sone.getId());
950 for (Post oldPost : existingPosts) {
951 if (!sone.getPosts().contains(oldPost)) {
952 removedPosts.add(oldPost);
955 /* find new posts. */
956 for (Post newPost : sone.getPosts()) {
957 if (existingPosts.contains(newPost)) {
960 if (newPost.getTime() < getSoneFollowingTime(sone)) {
961 newPost.setKnown(true);
962 } else if (!newPost.isKnown()) {
963 newPosts.add(newPost);
967 database.storePosts(sone, sone.getPosts());
968 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
969 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
970 if (!soneRescueMode) {
971 for (PostReply reply : storedSone.get().getReplies()) {
972 if (!sone.getReplies().contains(reply)) {
973 removedPostReplies.add(reply);
977 Set<PostReply> storedReplies = storedSone.get().getReplies();
978 for (PostReply reply : sone.getReplies()) {
979 if (storedReplies.contains(reply)) {
982 if (reply.getTime() < getSoneFollowingTime(sone)) {
983 reply.setKnown(true);
984 } else if (!reply.isKnown()) {
985 newPostReplies.add(reply);
988 database.storePostReplies(sone, sone.getReplies());
989 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
990 database.removeAlbum(album);
991 for (Image image : album.getImages()) {
992 database.removeImage(image);
995 for (Post removedPost : removedPosts) {
996 eventBus.post(new PostRemovedEvent(removedPost));
998 for (Post newPost : newPosts) {
999 eventBus.post(new NewPostFoundEvent(newPost));
1001 for (PostReply removedPostReply : removedPostReplies) {
1002 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1004 for (PostReply newPostReply : newPostReplies) {
1005 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1007 for (Album album : sone.getRootAlbum().getAlbums()) {
1008 database.storeAlbum(album);
1009 for (Image image : album.getImages()) {
1010 database.storeImage(image);
1013 synchronized (sones) {
1014 sone.setOptions(storedSone.get().getOptions());
1015 sone.setKnown(storedSone.get().isKnown());
1016 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1017 if (sone.isLocal()) {
1018 soneInserters.get(storedSone.get()).setSone(sone);
1019 touchConfiguration();
1021 sones.put(sone.getId(), sone);
1027 * Deletes the given Sone. This will remove the Sone from the
1028 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1029 * remove the context from its identity.
1032 * The Sone to delete
1034 public void deleteSone(Sone sone) {
1035 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1036 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1039 synchronized (sones) {
1040 if (!getLocalSones().contains(sone)) {
1041 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1044 sones.remove(sone.getId());
1045 SoneInserter soneInserter = soneInserters.remove(sone);
1046 soneInserter.stop();
1048 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1049 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1051 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1052 } catch (ConfigurationException ce1) {
1053 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1058 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1059 * known} before, a {@link MarkSoneKnownEvent} is fired.
1062 * The Sone to mark as known
1064 public void markSoneKnown(Sone sone) {
1065 if (!sone.isKnown()) {
1066 sone.setKnown(true);
1067 synchronized (knownSones) {
1068 knownSones.add(sone.getId());
1070 eventBus.post(new MarkSoneKnownEvent(sone));
1071 touchConfiguration();
1076 * Loads and updates the given Sone from the configuration. If any error is
1077 * encountered, loading is aborted and the given Sone is not changed.
1080 * The Sone to load and update
1082 public void loadSone(Sone sone) {
1083 if (!sone.isLocal()) {
1084 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1087 logger.info(String.format("Loading local Sone: %s", sone));
1090 String sonePrefix = "Sone/" + sone.getId();
1091 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1092 if (soneTime == null) {
1093 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1096 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1099 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1100 Profile profile = configurationSoneParser.parseProfile();
1103 Collection<Post> posts;
1105 posts = configurationSoneParser.parsePosts(database);
1106 } catch (InvalidPostFound ipf) {
1107 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1112 Collection<PostReply> replies;
1114 replies = configurationSoneParser.parsePostReplies(database);
1115 } catch (InvalidPostReplyFound iprf) {
1116 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1120 /* load post likes. */
1121 Set<String> likedPostIds =
1122 configurationSoneParser.parseLikedPostIds();
1124 /* load reply likes. */
1125 Set<String> likedReplyIds =
1126 configurationSoneParser.parseLikedPostReplyIds();
1129 Set<String> friends = configurationSoneParser.parseFriends();
1132 List<Album> topLevelAlbums;
1135 configurationSoneParser.parseTopLevelAlbums(database);
1136 } catch (InvalidAlbumFound iaf) {
1137 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1139 } catch (InvalidParentAlbumFound ipaf) {
1140 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1141 ipaf.getAlbumParentId()));
1147 configurationSoneParser.parseImages(database);
1148 } catch (InvalidImageFound iif) {
1149 logger.log(WARNING, "Invalid image found, aborting load!");
1151 } catch (InvalidParentAlbumFound ipaf) {
1152 logger.log(Level.WARNING,
1153 format("Invalid album image (%s) encountered, aborting load!",
1154 ipaf.getAlbumParentId()));
1159 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1160 if (avatarId != null) {
1161 profile.setAvatar(getImage(avatarId, false));
1165 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1166 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1167 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1168 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1169 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1170 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1172 /* if we’re still here, Sone was loaded successfully. */
1173 synchronized (sone) {
1174 sone.setTime(soneTime);
1175 sone.setProfile(profile);
1176 sone.setPosts(posts);
1177 sone.setReplies(replies);
1178 sone.setLikePostIds(likedPostIds);
1179 sone.setLikeReplyIds(likedReplyIds);
1180 for (String friendId : friends) {
1181 followSone(sone, friendId);
1183 for (Album album : sone.getRootAlbum().getAlbums()) {
1184 sone.getRootAlbum().removeAlbum(album);
1186 for (Album album : topLevelAlbums) {
1187 sone.getRootAlbum().addAlbum(album);
1189 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1191 synchronized (knownSones) {
1192 for (String friend : friends) {
1193 knownSones.add(friend);
1196 database.storePosts(sone, posts);
1197 for (Post post : posts) {
1198 post.setKnown(true);
1200 database.storePostReplies(sone, replies);
1201 for (PostReply reply : replies) {
1202 reply.setKnown(true);
1205 logger.info(String.format("Sone loaded successfully: %s", sone));
1209 * Creates a new post.
1212 * The Sone that creates the post
1214 * The recipient Sone, or {@code null} if this post does not have
1217 * The text of the post
1218 * @return The created post
1220 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1221 return createPost(sone, recipient, System.currentTimeMillis(), text);
1225 * Creates a new post.
1228 * The Sone that creates the post
1230 * The recipient Sone, or {@code null} if this post does not have
1233 * The time of the post
1235 * The text of the post
1236 * @return The created post
1238 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1239 checkNotNull(text, "text must not be null");
1240 checkArgument(text.trim().length() > 0, "text must not be empty");
1241 if (!sone.isLocal()) {
1242 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1245 PostBuilder postBuilder = database.newPostBuilder();
1246 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1247 if (recipient.isPresent()) {
1248 postBuilder.to(recipient.get().getId());
1250 final Post post = postBuilder.build();
1251 database.storePost(post);
1252 eventBus.post(new NewPostFoundEvent(post));
1254 touchConfiguration();
1255 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1260 * Deletes the given post.
1263 * The post to delete
1265 public void deletePost(Post post) {
1266 if (!post.getSone().isLocal()) {
1267 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1270 database.removePost(post);
1271 eventBus.post(new PostRemovedEvent(post));
1272 markPostKnown(post);
1273 touchConfiguration();
1277 * Marks the given post as known, if it is currently not a known post
1278 * (according to {@link Post#isKnown()}).
1281 * The post to mark as known
1283 public void markPostKnown(Post post) {
1284 post.setKnown(true);
1285 eventBus.post(new MarkPostKnownEvent(post));
1286 touchConfiguration();
1287 for (PostReply reply : getReplies(post.getId())) {
1288 markReplyKnown(reply);
1293 * Bookmarks the post with the given ID.
1296 * The ID of the post to bookmark
1298 public void bookmarkPost(String id) {
1299 synchronized (bookmarkedPosts) {
1300 bookmarkedPosts.add(id);
1305 * Removes the given post from the bookmarks.
1308 * The post to unbookmark
1310 public void unbookmark(Post post) {
1311 unbookmarkPost(post.getId());
1315 * Removes the post with the given ID from the bookmarks.
1318 * The ID of the post to unbookmark
1320 public void unbookmarkPost(String id) {
1321 synchronized (bookmarkedPosts) {
1322 bookmarkedPosts.remove(id);
1327 * Creates a new reply.
1330 * The Sone that creates the reply
1332 * The post that this reply refers to
1334 * The text of the reply
1335 * @return The created reply
1337 public PostReply createReply(Sone sone, Post post, String text) {
1338 checkNotNull(text, "text must not be null");
1339 checkArgument(text.trim().length() > 0, "text must not be empty");
1340 if (!sone.isLocal()) {
1341 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1344 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1345 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1346 final PostReply reply = postReplyBuilder.build();
1347 database.storePostReply(reply);
1348 eventBus.post(new NewPostReplyFoundEvent(reply));
1349 sone.addReply(reply);
1350 touchConfiguration();
1351 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1356 * Deletes the given reply.
1359 * The reply to delete
1361 public void deleteReply(PostReply reply) {
1362 Sone sone = reply.getSone();
1363 if (!sone.isLocal()) {
1364 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1367 database.removePostReply(reply);
1368 markReplyKnown(reply);
1369 sone.removeReply(reply);
1370 touchConfiguration();
1374 * Marks the given reply as known, if it is currently not a known reply
1375 * (according to {@link Reply#isKnown()}).
1378 * The reply to mark as known
1380 public void markReplyKnown(PostReply reply) {
1381 boolean previouslyKnown = reply.isKnown();
1382 reply.setKnown(true);
1383 eventBus.post(new MarkPostReplyKnownEvent(reply));
1384 if (!previouslyKnown) {
1385 touchConfiguration();
1390 * Creates a new album for the given Sone.
1393 * The Sone to create the album for
1395 * The parent of the album (may be {@code null} to create a
1397 * @return The new album
1399 public Album createAlbum(Sone sone, Album parent) {
1400 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1401 database.storeAlbum(album);
1402 parent.addAlbum(album);
1407 * Deletes the given album. The owner of the album has to be a local Sone,
1408 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1411 * The album to remove
1413 public void deleteAlbum(Album album) {
1414 checkNotNull(album, "album must not be null");
1415 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1416 if (!album.isEmpty()) {
1419 album.getParent().removeAlbum(album);
1420 database.removeAlbum(album);
1421 touchConfiguration();
1425 * Creates a new image.
1428 * The Sone creating the image
1430 * The album the image will be inserted into
1431 * @param temporaryImage
1432 * The temporary image to create the image from
1433 * @return The newly created image
1435 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1436 checkNotNull(sone, "sone must not be null");
1437 checkNotNull(album, "album must not be null");
1438 checkNotNull(temporaryImage, "temporaryImage must not be null");
1439 checkArgument(sone.isLocal(), "sone must be a local Sone");
1440 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1441 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1442 album.addImage(image);
1443 database.storeImage(image);
1444 imageInserter.insertImage(temporaryImage, image);
1449 * Deletes the given image. This method will also delete a matching
1452 * @see #deleteTemporaryImage(String)
1454 * The image to delete
1456 public void deleteImage(Image image) {
1457 checkNotNull(image, "image must not be null");
1458 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1459 deleteTemporaryImage(image.getId());
1460 image.getAlbum().removeImage(image);
1461 database.removeImage(image);
1462 touchConfiguration();
1466 * Creates a new temporary image.
1469 * The MIME type of the temporary image
1471 * The encoded data of the image
1472 * @return The temporary image
1474 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1475 TemporaryImage temporaryImage = new TemporaryImage();
1476 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1477 synchronized (temporaryImages) {
1478 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1480 return temporaryImage;
1484 * Deletes the temporary image with the given ID.
1487 * The ID of the temporary image to delete
1489 public void deleteTemporaryImage(String imageId) {
1490 checkNotNull(imageId, "imageId must not be null");
1491 synchronized (temporaryImages) {
1492 temporaryImages.remove(imageId);
1494 Image image = getImage(imageId, false);
1495 if (image != null) {
1496 imageInserter.cancelImageInsert(image);
1501 * Notifies the core that the configuration, either of the core or of a
1502 * single local Sone, has changed, and that the configuration should be
1505 public void touchConfiguration() {
1506 lastConfigurationUpdate = System.currentTimeMillis();
1517 public void serviceStart() {
1518 loadConfiguration();
1519 updateChecker.start();
1520 identityManager.start();
1521 webOfTrustUpdater.init();
1522 webOfTrustUpdater.start();
1530 public void serviceRun() {
1531 long lastSaved = System.currentTimeMillis();
1532 while (!shouldStop()) {
1534 long now = System.currentTimeMillis();
1535 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1536 for (Sone localSone : getLocalSones()) {
1537 saveSone(localSone);
1539 saveConfiguration();
1549 public void serviceStop() {
1550 localElementTicker.shutdownNow();
1551 synchronized (sones) {
1552 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1553 soneInserter.getValue().stop();
1554 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1557 saveConfiguration();
1559 webOfTrustUpdater.stop();
1560 updateChecker.stop();
1561 soneDownloader.stop();
1562 soneDownloaders.shutdown();
1563 identityManager.stop();
1571 * Saves the given Sone. This will persist all local settings for the given
1572 * Sone, such as the friends list and similar, private options.
1577 private synchronized void saveSone(Sone sone) {
1578 if (!sone.isLocal()) {
1579 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1582 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1583 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1587 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1589 /* save Sone into configuration. */
1590 String sonePrefix = "Sone/" + sone.getId();
1591 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1592 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1595 Profile profile = sone.getProfile();
1596 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1597 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1598 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1599 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1600 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1601 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1602 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1604 /* save profile fields. */
1605 int fieldCounter = 0;
1606 for (Field profileField : profile.getFields()) {
1607 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1608 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1609 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1611 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1614 int postCounter = 0;
1615 for (Post post : sone.getPosts()) {
1616 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1617 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1618 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1619 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1620 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1622 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1625 int replyCounter = 0;
1626 for (PostReply reply : sone.getReplies()) {
1627 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1628 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1629 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1630 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1631 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1633 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1635 /* save post likes. */
1636 int postLikeCounter = 0;
1637 for (String postId : sone.getLikedPostIds()) {
1638 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1640 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1642 /* save reply likes. */
1643 int replyLikeCounter = 0;
1644 for (String replyId : sone.getLikedReplyIds()) {
1645 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1647 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1650 int friendCounter = 0;
1651 for (String friendId : sone.getFriends()) {
1652 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1654 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1656 /* save albums. first, collect in a flat structure, top-level first. */
1657 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1659 int albumCounter = 0;
1660 for (Album album : albums) {
1661 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1662 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1663 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1664 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1665 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1666 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1668 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1671 int imageCounter = 0;
1672 for (Album album : albums) {
1673 for (Image image : album.getImages()) {
1674 if (!image.isInserted()) {
1677 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1678 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1679 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1680 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1681 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1682 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1683 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1684 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1685 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1688 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1691 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1692 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1693 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1694 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1695 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1696 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1698 configuration.save();
1700 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1702 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1703 } catch (ConfigurationException ce1) {
1704 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1709 * Saves the current options.
1711 private void saveConfiguration() {
1712 synchronized (configuration) {
1713 if (storingConfiguration) {
1714 logger.log(Level.FINE, "Already storing configuration…");
1717 storingConfiguration = true;
1720 /* store the options first. */
1722 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1723 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1724 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1725 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1726 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1727 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1728 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1729 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1730 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1731 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1732 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1733 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1735 /* save known Sones. */
1736 int soneCounter = 0;
1737 synchronized (knownSones) {
1738 for (String knownSoneId : knownSones) {
1739 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1741 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1744 /* save Sone following times. */
1746 synchronized (soneFollowingTimes) {
1747 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1748 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1749 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1752 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1755 /* save known posts. */
1758 /* save bookmarked posts. */
1759 int bookmarkedPostCounter = 0;
1760 synchronized (bookmarkedPosts) {
1761 for (String bookmarkedPostId : bookmarkedPosts) {
1762 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1765 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1768 configuration.save();
1770 } catch (ConfigurationException ce1) {
1771 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1772 } catch (DatabaseException de1) {
1773 logger.log(Level.SEVERE, "Could not save database!", de1);
1775 synchronized (configuration) {
1776 storingConfiguration = false;
1782 * Loads the configuration.
1784 private void loadConfiguration() {
1785 /* create options. */
1786 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1787 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1788 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1789 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1790 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1791 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1792 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1793 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1794 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1795 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1796 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1798 loadConfigurationValue("InsertionDelay");
1799 loadConfigurationValue("PostsPerPage");
1800 loadConfigurationValue("ImagesPerPage");
1801 loadConfigurationValue("CharactersPerPost");
1802 loadConfigurationValue("PostCutOffLength");
1803 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1804 loadConfigurationValue("PositiveTrust");
1805 loadConfigurationValue("NegativeTrust");
1806 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1807 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1808 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1810 /* load known Sones. */
1811 int soneCounter = 0;
1813 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1814 if (knownSoneId == null) {
1817 synchronized (knownSones) {
1818 knownSones.add(knownSoneId);
1822 /* load Sone following times. */
1825 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1826 if (soneId == null) {
1829 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1830 synchronized (soneFollowingTimes) {
1831 soneFollowingTimes.put(soneId, time);
1836 /* load bookmarked posts. */
1837 int bookmarkedPostCounter = 0;
1839 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1840 if (bookmarkedPostId == null) {
1843 synchronized (bookmarkedPosts) {
1844 bookmarkedPosts.add(bookmarkedPostId);
1851 * Loads an {@link Integer} configuration value for the option with the
1852 * given name, logging validation failures.
1855 * The name of the option to load
1857 private void loadConfigurationValue(String optionName) {
1859 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1860 } catch (IllegalArgumentException iae1) {
1861 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1866 * Notifies the core that a new {@link OwnIdentity} was added.
1868 * @param ownIdentityAddedEvent
1872 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1873 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1874 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1875 if (ownIdentity.hasContext("Sone")) {
1876 addLocalSone(ownIdentity);
1881 * Notifies the core that an {@link OwnIdentity} was removed.
1883 * @param ownIdentityRemovedEvent
1887 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1888 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1889 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1890 trustedIdentities.removeAll(ownIdentity);
1894 * Notifies the core that a new {@link Identity} was added.
1896 * @param identityAddedEvent
1900 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1901 Identity identity = identityAddedEvent.identity();
1902 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1903 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1904 addRemoteSone(identity);
1908 * Notifies the core that an {@link Identity} was updated.
1910 * @param identityUpdatedEvent
1914 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1915 Identity identity = identityUpdatedEvent.identity();
1916 final Sone sone = getRemoteSone(identity.getId(), false);
1917 if (sone.isLocal()) {
1920 sone.setIdentity(identity);
1921 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1922 soneDownloader.addSone(sone);
1923 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1927 * Notifies the core that an {@link Identity} was removed.
1929 * @param identityRemovedEvent
1933 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1934 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1935 Identity identity = identityRemovedEvent.identity();
1936 trustedIdentities.remove(ownIdentity, identity);
1937 boolean foundIdentity = false;
1938 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1939 if (trustedIdentity.getKey().equals(ownIdentity)) {
1942 if (trustedIdentity.getValue().contains(identity)) {
1943 foundIdentity = true;
1946 if (foundIdentity) {
1947 /* some local identity still trusts this identity, don’t remove. */
1950 Optional<Sone> sone = getSone(identity.getId());
1951 if (!sone.isPresent()) {
1952 /* TODO - we don’t have the Sone anymore. should this happen? */
1955 database.removePosts(sone.get());
1956 for (Post post : sone.get().getPosts()) {
1957 eventBus.post(new PostRemovedEvent(post));
1959 database.removePostReplies(sone.get());
1960 for (PostReply reply : sone.get().getReplies()) {
1961 eventBus.post(new PostReplyRemovedEvent(reply));
1963 synchronized (sones) {
1964 sones.remove(identity.getId());
1966 eventBus.post(new SoneRemovedEvent(sone.get()));
1970 * Deletes the temporary image.
1972 * @param imageInsertFinishedEvent
1976 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1977 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1978 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1979 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1980 touchConfiguration();
1984 class MarkPostKnown implements Runnable {
1986 private final Post post;
1988 public MarkPostKnown(Post post) {
1994 markPostKnown(post);
2000 class MarkReplyKnown implements Runnable {
2002 private final PostReply postReply;
2004 public MarkReplyKnown(PostReply postReply) {
2005 this.postReply = postReply;
2010 markReplyKnown(postReply);