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.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.base.Predicates.not;
24 import static com.google.common.primitives.Longs.tryParse;
25 import static java.lang.String.format;
26 import static java.util.logging.Level.WARNING;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
30 import java.net.MalformedURLException;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
37 import java.util.Map.Entry;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Executors;
41 import java.util.concurrent.ScheduledExecutorService;
42 import java.util.concurrent.TimeUnit;
43 import java.util.logging.Level;
44 import java.util.logging.Logger;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
51 import net.pterodactylus.sone.core.Options.DefaultOption;
52 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
53 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
54 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
55 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
56 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
57 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
58 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
59 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
60 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
61 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
62 import net.pterodactylus.sone.core.event.PostRemovedEvent;
63 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
64 import net.pterodactylus.sone.core.event.SoneLockedEvent;
65 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
66 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
67 import net.pterodactylus.sone.data.Album;
68 import net.pterodactylus.sone.data.Client;
69 import net.pterodactylus.sone.data.Image;
70 import net.pterodactylus.sone.data.Post;
71 import net.pterodactylus.sone.data.PostReply;
72 import net.pterodactylus.sone.data.Profile;
73 import net.pterodactylus.sone.data.Profile.Field;
74 import net.pterodactylus.sone.data.Reply;
75 import net.pterodactylus.sone.data.Sone;
76 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
77 import net.pterodactylus.sone.data.Sone.SoneStatus;
78 import net.pterodactylus.sone.data.SoneImpl;
79 import net.pterodactylus.sone.data.TemporaryImage;
80 import net.pterodactylus.sone.database.AlbumBuilder;
81 import net.pterodactylus.sone.database.Database;
82 import net.pterodactylus.sone.database.DatabaseException;
83 import net.pterodactylus.sone.database.ImageBuilder;
84 import net.pterodactylus.sone.database.PostBuilder;
85 import net.pterodactylus.sone.database.PostProvider;
86 import net.pterodactylus.sone.database.PostReplyBuilder;
87 import net.pterodactylus.sone.database.PostReplyProvider;
88 import net.pterodactylus.sone.database.SoneProvider;
89 import net.pterodactylus.sone.fcp.FcpInterface;
90 import net.pterodactylus.sone.freenet.wot.Identity;
91 import net.pterodactylus.sone.freenet.wot.IdentityManager;
92 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
93 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
95 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
96 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
97 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
98 import net.pterodactylus.sone.main.SonePlugin;
99 import net.pterodactylus.sone.utils.IntegerRangePredicate;
100 import net.pterodactylus.util.config.Configuration;
101 import net.pterodactylus.util.config.ConfigurationException;
102 import net.pterodactylus.util.logging.Logging;
103 import net.pterodactylus.util.number.Numbers;
104 import net.pterodactylus.util.service.AbstractService;
105 import net.pterodactylus.util.thread.NamedThreadFactory;
107 import com.google.common.annotations.VisibleForTesting;
108 import com.google.common.base.Optional;
109 import com.google.common.base.Predicates;
110 import com.google.common.collect.FluentIterable;
111 import com.google.common.collect.HashMultimap;
112 import com.google.common.collect.ImmutableSet;
113 import com.google.common.collect.Multimap;
114 import com.google.common.collect.Multimaps;
115 import com.google.common.eventbus.EventBus;
116 import com.google.common.eventbus.Subscribe;
117 import com.google.inject.Inject;
118 import com.google.inject.Singleton;
120 import freenet.keys.FreenetURI;
125 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
128 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
131 private static final Logger logger = Logging.getLogger(Core.class);
133 /** The start time. */
134 private final long startupTime = System.currentTimeMillis();
137 private final Options options = new Options();
139 /** The preferences. */
140 private final Preferences preferences = new Preferences(options);
142 /** The event bus. */
143 private final EventBus eventBus;
145 /** The configuration. */
146 private final Configuration configuration;
148 /** Whether we’re currently saving the configuration. */
149 private boolean storingConfiguration = false;
151 /** The identity manager. */
152 private final IdentityManager identityManager;
154 /** Interface to freenet. */
155 private final FreenetInterface freenetInterface;
157 /** The Sone downloader. */
158 private final SoneDownloader soneDownloader;
160 /** The image inserter. */
161 private final ImageInserter imageInserter;
163 /** Sone downloader thread-pool. */
164 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
166 /** The update checker. */
167 private final UpdateChecker updateChecker;
169 /** The trust updater. */
170 private final WebOfTrustUpdater webOfTrustUpdater;
172 /** The FCP interface. */
173 private volatile FcpInterface fcpInterface;
175 /** The times Sones were followed. */
176 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
178 /** Locked local Sones. */
179 /* synchronize on itself. */
180 private final Set<Sone> lockedSones = new HashSet<Sone>();
182 /** Sone inserters. */
183 /* synchronize access on this on sones. */
184 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
186 /** Sone rescuers. */
187 /* synchronize access on this on sones. */
188 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
191 /* synchronize access on this on itself. */
192 private final Map<String, Sone> sones = new HashMap<String, Sone>();
194 /** All known Sones. */
195 private final Set<String> knownSones = new HashSet<String>();
197 /** The post database. */
198 private final Database database;
200 /** All bookmarked posts. */
201 /* synchronize access on itself. */
202 private final Set<String> bookmarkedPosts = new HashSet<String>();
204 /** Trusted identities, sorted by own identities. */
205 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
207 /** All temporary images. */
208 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
210 /** Ticker for threads that mark own elements as known. */
211 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
213 /** The time the configuration was last touched. */
214 private volatile long lastConfigurationUpdate;
217 * Creates a new core.
219 * @param configuration
220 * The configuration of the core
221 * @param freenetInterface
222 * The freenet interface
223 * @param identityManager
224 * The identity manager
225 * @param webOfTrustUpdater
226 * The WebOfTrust updater
233 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
235 this.configuration = configuration;
236 this.freenetInterface = freenetInterface;
237 this.identityManager = identityManager;
238 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
239 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
240 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
241 this.webOfTrustUpdater = webOfTrustUpdater;
242 this.eventBus = eventBus;
243 this.database = database;
247 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
249 this.configuration = configuration;
250 this.freenetInterface = freenetInterface;
251 this.identityManager = identityManager;
252 this.soneDownloader = soneDownloader;
253 this.imageInserter = imageInserter;
254 this.updateChecker = updateChecker;
255 this.webOfTrustUpdater = webOfTrustUpdater;
256 this.eventBus = eventBus;
257 this.database = database;
265 * Returns the time Sone was started.
267 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
269 public long getStartupTime() {
274 * Returns the options used by the core.
276 * @return The options of the core
278 public Preferences getPreferences() {
283 * Returns the identity manager used by the core.
285 * @return The identity manager
287 public IdentityManager getIdentityManager() {
288 return identityManager;
292 * Returns the update checker.
294 * @return The update checker
296 public UpdateChecker getUpdateChecker() {
297 return updateChecker;
301 * Sets the FCP interface to use.
303 * @param fcpInterface
304 * The FCP interface to use
306 public void setFcpInterface(FcpInterface fcpInterface) {
307 this.fcpInterface = fcpInterface;
311 * Returns the Sone rescuer for the given local Sone.
314 * The local Sone to get the rescuer for
315 * @return The Sone rescuer for the given Sone
317 public SoneRescuer getSoneRescuer(Sone sone) {
318 checkNotNull(sone, "sone must not be null");
319 checkArgument(sone.isLocal(), "sone must be local");
320 synchronized (sones) {
321 SoneRescuer soneRescuer = soneRescuers.get(sone);
322 if (soneRescuer == null) {
323 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
324 soneRescuers.put(sone, soneRescuer);
332 * Returns whether the given Sone is currently locked.
336 * @return {@code true} if the Sone is locked, {@code false} if it is not
338 public boolean isLocked(Sone sone) {
339 synchronized (lockedSones) {
340 return lockedSones.contains(sone);
348 public Collection<Sone> getSones() {
349 synchronized (sones) {
350 return ImmutableSet.copyOf(sones.values());
355 * Returns the Sone with the given ID, regardless whether it’s local or
359 * The ID of the Sone to get
360 * @return The Sone with the given ID, or {@code null} if there is no such
364 public Optional<Sone> getSone(String id) {
365 synchronized (sones) {
366 return Optional.fromNullable(sones.get(id));
374 public Collection<Sone> getLocalSones() {
375 synchronized (sones) {
376 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
381 * Returns the local Sone with the given ID, optionally creating a new Sone.
386 * {@code true} to create a new Sone if none exists,
387 * {@code false} to return null if none exists
388 * @return The Sone with the given ID, or {@code null}
390 public Sone getLocalSone(String id, boolean create) {
391 synchronized (sones) {
392 Sone sone = sones.get(id);
393 if ((sone == null) && create) {
394 sone = new SoneImpl(id, true);
397 if ((sone != null) && !sone.isLocal()) {
398 sone = new SoneImpl(id, true);
409 public Collection<Sone> getRemoteSones() {
410 synchronized (sones) {
411 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
416 * Returns the remote Sone with the given ID.
419 * The ID of the remote Sone to get
421 * {@code true} to always create a Sone, {@code false} to return
422 * {@code null} if no Sone with the given ID exists
423 * @return The Sone with the given ID
425 public Sone getRemoteSone(String id, boolean create) {
426 synchronized (sones) {
427 Sone sone = sones.get(id);
428 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
429 sone = new SoneImpl(id, false);
437 * Returns whether the given Sone has been modified.
440 * The Sone to check for modifications
441 * @return {@code true} if a modification has been detected in the Sone,
442 * {@code false} otherwise
444 public boolean isModifiedSone(Sone sone) {
445 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
449 * Returns the time when the given was first followed by any local Sone.
452 * The Sone to get the time for
453 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
454 * been followed, or {@link Long#MAX_VALUE}
456 public long getSoneFollowingTime(Sone sone) {
457 synchronized (soneFollowingTimes) {
458 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
463 * Returns a post builder.
465 * @return A new post builder
467 public PostBuilder postBuilder() {
468 return database.newPostBuilder();
475 public Optional<Post> getPost(String postId) {
476 return database.getPost(postId);
483 public Collection<Post> getPosts(String soneId) {
484 return database.getPosts(soneId);
491 public Collection<Post> getDirectedPosts(final String recipientId) {
492 checkNotNull(recipientId, "recipient must not be null");
493 return database.getDirectedPosts(recipientId);
497 * Returns a post reply builder.
499 * @return A new post reply builder
501 public PostReplyBuilder postReplyBuilder() {
502 return database.newPostReplyBuilder();
509 public Optional<PostReply> getPostReply(String replyId) {
510 return database.getPostReply(replyId);
517 public List<PostReply> getReplies(final String postId) {
518 return database.getReplies(postId);
522 * Returns all Sones that have liked the given post.
525 * The post to get the liking Sones for
526 * @return The Sones that like the given post
528 public Set<Sone> getLikes(Post post) {
529 Set<Sone> sones = new HashSet<Sone>();
530 for (Sone sone : getSones()) {
531 if (sone.getLikedPostIds().contains(post.getId())) {
539 * Returns all Sones that have liked the given reply.
542 * The reply to get the liking Sones for
543 * @return The Sones that like the given reply
545 public Set<Sone> getLikes(PostReply reply) {
546 Set<Sone> sones = new HashSet<Sone>();
547 for (Sone sone : getSones()) {
548 if (sone.getLikedReplyIds().contains(reply.getId())) {
556 * Returns whether the given post is bookmarked.
560 * @return {@code true} if the given post is bookmarked, {@code false}
563 public boolean isBookmarked(Post post) {
564 return isPostBookmarked(post.getId());
568 * Returns whether the post with the given ID is bookmarked.
571 * The ID of the post to check
572 * @return {@code true} if the post with the given ID is bookmarked,
573 * {@code false} otherwise
575 public boolean isPostBookmarked(String id) {
576 synchronized (bookmarkedPosts) {
577 return bookmarkedPosts.contains(id);
582 * Returns all currently known bookmarked posts.
584 * @return All bookmarked posts
586 public Set<Post> getBookmarkedPosts() {
587 Set<Post> posts = new HashSet<Post>();
588 synchronized (bookmarkedPosts) {
589 for (String bookmarkedPostId : bookmarkedPosts) {
590 Optional<Post> post = getPost(bookmarkedPostId);
591 if (post.isPresent()) {
592 posts.add(post.get());
599 public AlbumBuilder albumBuilder() {
600 return database.newAlbumBuilder();
604 * Returns the album with the given ID, optionally creating a new album if
605 * an album with the given ID can not be found.
608 * The ID of the album
609 * @return The album with the given ID, or {@code null} if no album with the
612 public Album getAlbum(String albumId) {
613 return database.getAlbum(albumId).orNull();
616 public ImageBuilder imageBuilder() {
617 return database.newImageBuilder();
621 * Returns the image with the given ID, creating it if necessary.
624 * The ID of the image
625 * @return The image with the given ID
627 public Image getImage(String imageId) {
628 return getImage(imageId, true);
632 * Returns the image with the given ID, optionally creating it if it does
636 * The ID of the image
638 * {@code true} to create an image if none exists with the given
640 * @return The image with the given ID, or {@code null} if none exists and
643 public Image getImage(String imageId, boolean create) {
644 Optional<Image> image = database.getImage(imageId);
645 if (image.isPresent()) {
651 Image newImage = database.newImageBuilder().withId(imageId).build();
652 database.storeImage(newImage);
657 * Returns the temporary image with the given ID.
660 * The ID of the temporary image
661 * @return The temporary image, or {@code null} if there is no temporary
662 * image with the given ID
664 public TemporaryImage getTemporaryImage(String imageId) {
665 synchronized (temporaryImages) {
666 return temporaryImages.get(imageId);
675 * Locks the given Sone. A locked Sone will not be inserted by
676 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
682 public void lockSone(Sone sone) {
683 synchronized (lockedSones) {
684 if (lockedSones.add(sone)) {
685 eventBus.post(new SoneLockedEvent(sone));
691 * Unlocks the given Sone.
693 * @see #lockSone(Sone)
697 public void unlockSone(Sone sone) {
698 synchronized (lockedSones) {
699 if (lockedSones.remove(sone)) {
700 eventBus.post(new SoneUnlockedEvent(sone));
706 * Adds a local Sone from the given own identity.
709 * The own identity to create a Sone from
710 * @return The added (or already existing) Sone
712 public Sone addLocalSone(OwnIdentity ownIdentity) {
713 if (ownIdentity == null) {
714 logger.log(Level.WARNING, "Given OwnIdentity is null!");
717 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
718 synchronized (sones) {
721 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
722 } catch (MalformedURLException mue1) {
723 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
726 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
727 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
729 /* TODO - load posts ’n stuff */
730 sones.put(ownIdentity.getId(), sone);
731 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
732 soneInserters.put(sone, soneInserter);
733 sone.setStatus(SoneStatus.idle);
735 soneInserter.start();
741 * Creates a new Sone for the given own identity.
744 * The own identity to create a Sone for
745 * @return The created Sone
747 public Sone createSone(OwnIdentity ownIdentity) {
748 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
749 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
752 Sone sone = addLocalSone(ownIdentity);
754 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
755 touchConfiguration();
760 * Adds the Sone of the given identity.
763 * The identity whose Sone to add
764 * @return The added or already existing Sone
766 public Sone addRemoteSone(Identity identity) {
767 if (identity == null) {
768 logger.log(Level.WARNING, "Given Identity is null!");
771 final Long latestEdition = tryParse(fromNullable(
772 identity.getProperty("Sone.LatestEdition")).or("0"));
773 synchronized (sones) {
774 final Sone sone = getRemoteSone(identity.getId(), true);
775 if (sone.isLocal()) {
778 sone.setIdentity(identity);
779 boolean newSone = sone.getRequestUri() == null;
780 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
781 sone.setLatestEdition(latestEdition);
783 synchronized (knownSones) {
784 newSone = !knownSones.contains(sone.getId());
786 sone.setKnown(!newSone);
788 eventBus.post(new NewSoneFoundEvent(sone));
789 for (Sone localSone : getLocalSones()) {
790 if (localSone.getOptions().isAutoFollow()) {
791 followSone(localSone, sone.getId());
796 soneDownloader.addSone(sone);
797 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
803 * Lets the given local Sone follow the Sone with the given ID.
806 * The local Sone that should follow another Sone
808 * The ID of the Sone to follow
810 public void followSone(Sone sone, String soneId) {
811 checkNotNull(sone, "sone must not be null");
812 checkNotNull(soneId, "soneId must not be null");
813 sone.addFriend(soneId);
814 synchronized (soneFollowingTimes) {
815 if (!soneFollowingTimes.containsKey(soneId)) {
816 long now = System.currentTimeMillis();
817 soneFollowingTimes.put(soneId, now);
818 Optional<Sone> followedSone = getSone(soneId);
819 if (!followedSone.isPresent()) {
822 for (Post post : followedSone.get().getPosts()) {
823 if (post.getTime() < now) {
827 for (PostReply reply : followedSone.get().getReplies()) {
828 if (reply.getTime() < now) {
829 markReplyKnown(reply);
834 touchConfiguration();
838 * Lets the given local Sone unfollow the Sone with the given ID.
841 * The local Sone that should unfollow another Sone
843 * The ID of the Sone being unfollowed
845 public void unfollowSone(Sone sone, String soneId) {
846 checkNotNull(sone, "sone must not be null");
847 checkNotNull(soneId, "soneId must not be null");
848 sone.removeFriend(soneId);
849 boolean unfollowedSoneStillFollowed = false;
850 for (Sone localSone : getLocalSones()) {
851 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
853 if (!unfollowedSoneStillFollowed) {
854 synchronized (soneFollowingTimes) {
855 soneFollowingTimes.remove(soneId);
858 touchConfiguration();
862 * Sets the trust value of the given origin Sone for the target Sone.
869 * The trust value (from {@code -100} to {@code 100})
871 public void setTrust(Sone origin, Sone target, int trustValue) {
872 checkNotNull(origin, "origin must not be null");
873 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
874 checkNotNull(target, "target must not be null");
875 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
876 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
880 * Removes any trust assignment for the given target Sone.
887 public void removeTrust(Sone origin, Sone target) {
888 checkNotNull(origin, "origin must not be null");
889 checkNotNull(target, "target must not be null");
890 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
891 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
895 * Assigns the configured positive trust value for the given target.
902 public void trustSone(Sone origin, Sone target) {
903 setTrust(origin, target, preferences.getPositiveTrust());
907 * Assigns the configured negative trust value for the given target.
914 public void distrustSone(Sone origin, Sone target) {
915 setTrust(origin, target, preferences.getNegativeTrust());
919 * Removes the trust assignment for the given target.
926 public void untrustSone(Sone origin, Sone target) {
927 removeTrust(origin, target);
931 * Updates the stored Sone with the given Sone.
936 public void updateSone(Sone sone) {
937 updateSone(sone, false);
941 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
942 * {@code true}, an older Sone than the current Sone can be given to restore
947 * @param soneRescueMode
948 * {@code true} if the stored Sone should be updated regardless
949 * of the age of the given Sone
951 public void updateSone(final Sone sone, boolean soneRescueMode) {
952 Optional<Sone> storedSone = getSone(sone.getId());
953 if (storedSone.isPresent()) {
954 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
955 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
958 /* find removed posts. */
959 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
960 soneChangeDetector.onNewPosts(new PostProcessor() {
962 public void processPost(Post post) {
963 if (post.getTime() < getSoneFollowingTime(sone)) {
965 } else if (!post.isKnown()) {
966 eventBus.post(new NewPostFoundEvent(post));
970 soneChangeDetector.onRemovedPosts(new PostProcessor() {
972 public void processPost(Post post) {
973 eventBus.post(new PostRemovedEvent(post));
976 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
978 public void processPostReply(PostReply postReply) {
979 if (postReply.getTime() < getSoneFollowingTime(sone)) {
980 postReply.setKnown(true);
981 } else if (!postReply.isKnown()) {
982 eventBus.post(new NewPostReplyFoundEvent(postReply));
986 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
988 public void processPostReply(PostReply postReply) {
989 eventBus.post(new PostReplyRemovedEvent(postReply));
992 soneChangeDetector.detectChanges(sone);
993 database.storeSone(sone);
994 synchronized (sones) {
995 sone.setOptions(storedSone.get().getOptions());
996 sone.setKnown(storedSone.get().isKnown());
997 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
998 if (sone.isLocal()) {
999 soneInserters.get(storedSone.get()).setSone(sone);
1000 touchConfiguration();
1002 sones.put(sone.getId(), sone);
1008 * Deletes the given Sone. This will remove the Sone from the
1009 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1010 * remove the context from its identity.
1013 * The Sone to delete
1015 public void deleteSone(Sone sone) {
1016 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1017 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1020 synchronized (sones) {
1021 if (!getLocalSones().contains(sone)) {
1022 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1025 sones.remove(sone.getId());
1026 SoneInserter soneInserter = soneInserters.remove(sone);
1027 soneInserter.stop();
1029 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1030 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1032 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1033 } catch (ConfigurationException ce1) {
1034 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1039 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1040 * known} before, a {@link MarkSoneKnownEvent} is fired.
1043 * The Sone to mark as known
1045 public void markSoneKnown(Sone sone) {
1046 if (!sone.isKnown()) {
1047 sone.setKnown(true);
1048 synchronized (knownSones) {
1049 knownSones.add(sone.getId());
1051 eventBus.post(new MarkSoneKnownEvent(sone));
1052 touchConfiguration();
1057 * Loads and updates the given Sone from the configuration. If any error is
1058 * encountered, loading is aborted and the given Sone is not changed.
1061 * The Sone to load and update
1063 public void loadSone(Sone sone) {
1064 if (!sone.isLocal()) {
1065 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1068 logger.info(String.format("Loading local Sone: %s", sone));
1071 String sonePrefix = "Sone/" + sone.getId();
1072 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1073 if (soneTime == null) {
1074 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1077 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1080 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1081 Profile profile = configurationSoneParser.parseProfile();
1084 Collection<Post> posts;
1086 posts = configurationSoneParser.parsePosts(database);
1087 } catch (InvalidPostFound ipf) {
1088 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1093 Collection<PostReply> replies;
1095 replies = configurationSoneParser.parsePostReplies(database);
1096 } catch (InvalidPostReplyFound iprf) {
1097 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1101 /* load post likes. */
1102 Set<String> likedPostIds =
1103 configurationSoneParser.parseLikedPostIds();
1105 /* load reply likes. */
1106 Set<String> likedReplyIds =
1107 configurationSoneParser.parseLikedPostReplyIds();
1110 Set<String> friends = configurationSoneParser.parseFriends();
1113 List<Album> topLevelAlbums;
1116 configurationSoneParser.parseTopLevelAlbums(database);
1117 } catch (InvalidAlbumFound iaf) {
1118 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1120 } catch (InvalidParentAlbumFound ipaf) {
1121 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1122 ipaf.getAlbumParentId()));
1128 configurationSoneParser.parseImages(database);
1129 } catch (InvalidImageFound iif) {
1130 logger.log(WARNING, "Invalid image found, aborting load!");
1132 } catch (InvalidParentAlbumFound ipaf) {
1133 logger.log(Level.WARNING,
1134 format("Invalid album image (%s) encountered, aborting load!",
1135 ipaf.getAlbumParentId()));
1140 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1141 if (avatarId != null) {
1142 final Map<String, Image> images =
1143 configurationSoneParser.getImages();
1144 profile.setAvatar(images.get(avatarId));
1148 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1149 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1150 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1151 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1152 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1153 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1155 /* if we’re still here, Sone was loaded successfully. */
1156 synchronized (sone) {
1157 sone.setTime(soneTime);
1158 sone.setProfile(profile);
1159 sone.setPosts(posts);
1160 sone.setReplies(replies);
1161 sone.setLikePostIds(likedPostIds);
1162 sone.setLikeReplyIds(likedReplyIds);
1163 for (String friendId : friends) {
1164 followSone(sone, friendId);
1166 for (Album album : sone.getRootAlbum().getAlbums()) {
1167 sone.getRootAlbum().removeAlbum(album);
1169 for (Album album : topLevelAlbums) {
1170 sone.getRootAlbum().addAlbum(album);
1172 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1173 for (Album album : toAllAlbums.apply(sone)) {
1174 database.storeAlbum(album);
1175 for (Image image : album.getImages()) {
1176 database.storeImage(image);
1180 synchronized (knownSones) {
1181 for (String friend : friends) {
1182 knownSones.add(friend);
1185 database.storePosts(sone, posts);
1186 for (Post post : posts) {
1187 post.setKnown(true);
1189 database.storePostReplies(sone, replies);
1190 for (PostReply reply : replies) {
1191 reply.setKnown(true);
1194 logger.info(String.format("Sone loaded successfully: %s", sone));
1198 * Creates a new post.
1201 * The Sone that creates the post
1203 * The recipient Sone, or {@code null} if this post does not have
1206 * The text of the post
1207 * @return The created post
1209 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1210 return createPost(sone, recipient, System.currentTimeMillis(), text);
1214 * Creates a new post.
1217 * The Sone that creates the post
1219 * The recipient Sone, or {@code null} if this post does not have
1222 * The time of the post
1224 * The text of the post
1225 * @return The created post
1227 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1228 checkNotNull(text, "text must not be null");
1229 checkArgument(text.trim().length() > 0, "text must not be empty");
1230 if (!sone.isLocal()) {
1231 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1234 PostBuilder postBuilder = database.newPostBuilder();
1235 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1236 if (recipient.isPresent()) {
1237 postBuilder.to(recipient.get().getId());
1239 final Post post = postBuilder.build();
1240 database.storePost(post);
1241 eventBus.post(new NewPostFoundEvent(post));
1243 touchConfiguration();
1244 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1249 * Deletes the given post.
1252 * The post to delete
1254 public void deletePost(Post post) {
1255 if (!post.getSone().isLocal()) {
1256 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1259 database.removePost(post);
1260 eventBus.post(new PostRemovedEvent(post));
1261 markPostKnown(post);
1262 touchConfiguration();
1266 * Marks the given post as known, if it is currently not a known post
1267 * (according to {@link Post#isKnown()}).
1270 * The post to mark as known
1272 public void markPostKnown(Post post) {
1273 post.setKnown(true);
1274 eventBus.post(new MarkPostKnownEvent(post));
1275 touchConfiguration();
1276 for (PostReply reply : getReplies(post.getId())) {
1277 markReplyKnown(reply);
1282 * Bookmarks the post with the given ID.
1285 * The ID of the post to bookmark
1287 public void bookmarkPost(String id) {
1288 synchronized (bookmarkedPosts) {
1289 bookmarkedPosts.add(id);
1294 * Removes the given post from the bookmarks.
1297 * The post to unbookmark
1299 public void unbookmark(Post post) {
1300 unbookmarkPost(post.getId());
1304 * Removes the post with the given ID from the bookmarks.
1307 * The ID of the post to unbookmark
1309 public void unbookmarkPost(String id) {
1310 synchronized (bookmarkedPosts) {
1311 bookmarkedPosts.remove(id);
1316 * Creates a new reply.
1319 * The Sone that creates the reply
1321 * The post that this reply refers to
1323 * The text of the reply
1324 * @return The created reply
1326 public PostReply createReply(Sone sone, Post post, String text) {
1327 checkNotNull(text, "text must not be null");
1328 checkArgument(text.trim().length() > 0, "text must not be empty");
1329 if (!sone.isLocal()) {
1330 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1333 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1334 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1335 final PostReply reply = postReplyBuilder.build();
1336 database.storePostReply(reply);
1337 eventBus.post(new NewPostReplyFoundEvent(reply));
1338 sone.addReply(reply);
1339 touchConfiguration();
1340 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1345 * Deletes the given reply.
1348 * The reply to delete
1350 public void deleteReply(PostReply reply) {
1351 Sone sone = reply.getSone();
1352 if (!sone.isLocal()) {
1353 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1356 database.removePostReply(reply);
1357 markReplyKnown(reply);
1358 sone.removeReply(reply);
1359 touchConfiguration();
1363 * Marks the given reply as known, if it is currently not a known reply
1364 * (according to {@link Reply#isKnown()}).
1367 * The reply to mark as known
1369 public void markReplyKnown(PostReply reply) {
1370 boolean previouslyKnown = reply.isKnown();
1371 reply.setKnown(true);
1372 eventBus.post(new MarkPostReplyKnownEvent(reply));
1373 if (!previouslyKnown) {
1374 touchConfiguration();
1379 * Creates a new album for the given Sone.
1382 * The Sone to create the album for
1384 * The parent of the album (may be {@code null} to create a
1386 * @return The new album
1388 public Album createAlbum(Sone sone, Album parent) {
1389 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1390 database.storeAlbum(album);
1391 parent.addAlbum(album);
1396 * Deletes the given album. The owner of the album has to be a local Sone,
1397 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1400 * The album to remove
1402 public void deleteAlbum(Album album) {
1403 checkNotNull(album, "album must not be null");
1404 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1405 if (!album.isEmpty()) {
1408 album.getParent().removeAlbum(album);
1409 database.removeAlbum(album);
1410 touchConfiguration();
1414 * Creates a new image.
1417 * The Sone creating the image
1419 * The album the image will be inserted into
1420 * @param temporaryImage
1421 * The temporary image to create the image from
1422 * @return The newly created image
1424 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1425 checkNotNull(sone, "sone must not be null");
1426 checkNotNull(album, "album must not be null");
1427 checkNotNull(temporaryImage, "temporaryImage must not be null");
1428 checkArgument(sone.isLocal(), "sone must be a local Sone");
1429 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1430 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1431 album.addImage(image);
1432 database.storeImage(image);
1433 imageInserter.insertImage(temporaryImage, image);
1438 * Deletes the given image. This method will also delete a matching
1441 * @see #deleteTemporaryImage(String)
1443 * The image to delete
1445 public void deleteImage(Image image) {
1446 checkNotNull(image, "image must not be null");
1447 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1448 deleteTemporaryImage(image.getId());
1449 image.getAlbum().removeImage(image);
1450 database.removeImage(image);
1451 touchConfiguration();
1455 * Creates a new temporary image.
1458 * The MIME type of the temporary image
1460 * The encoded data of the image
1461 * @return The temporary image
1463 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1464 TemporaryImage temporaryImage = new TemporaryImage();
1465 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1466 synchronized (temporaryImages) {
1467 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1469 return temporaryImage;
1473 * Deletes the temporary image with the given ID.
1476 * The ID of the temporary image to delete
1478 public void deleteTemporaryImage(String imageId) {
1479 checkNotNull(imageId, "imageId must not be null");
1480 synchronized (temporaryImages) {
1481 temporaryImages.remove(imageId);
1483 Image image = getImage(imageId, false);
1484 if (image != null) {
1485 imageInserter.cancelImageInsert(image);
1490 * Notifies the core that the configuration, either of the core or of a
1491 * single local Sone, has changed, and that the configuration should be
1494 public void touchConfiguration() {
1495 lastConfigurationUpdate = System.currentTimeMillis();
1506 public void serviceStart() {
1507 loadConfiguration();
1508 updateChecker.start();
1509 identityManager.start();
1510 webOfTrustUpdater.init();
1511 webOfTrustUpdater.start();
1519 public void serviceRun() {
1520 long lastSaved = System.currentTimeMillis();
1521 while (!shouldStop()) {
1523 long now = System.currentTimeMillis();
1524 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1525 for (Sone localSone : getLocalSones()) {
1526 saveSone(localSone);
1528 saveConfiguration();
1538 public void serviceStop() {
1539 localElementTicker.shutdownNow();
1540 synchronized (sones) {
1541 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1542 soneInserter.getValue().stop();
1543 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1546 saveConfiguration();
1548 webOfTrustUpdater.stop();
1549 updateChecker.stop();
1550 soneDownloader.stop();
1551 soneDownloaders.shutdown();
1552 identityManager.stop();
1560 * Saves the given Sone. This will persist all local settings for the given
1561 * Sone, such as the friends list and similar, private options.
1566 private synchronized void saveSone(Sone sone) {
1567 if (!sone.isLocal()) {
1568 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1571 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1572 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1576 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1578 /* save Sone into configuration. */
1579 String sonePrefix = "Sone/" + sone.getId();
1580 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1581 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1584 Profile profile = sone.getProfile();
1585 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1586 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1587 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1588 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1589 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1590 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1591 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1593 /* save profile fields. */
1594 int fieldCounter = 0;
1595 for (Field profileField : profile.getFields()) {
1596 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1597 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1598 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1600 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1603 int postCounter = 0;
1604 for (Post post : sone.getPosts()) {
1605 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1606 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1607 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1608 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1609 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1611 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1614 int replyCounter = 0;
1615 for (PostReply reply : sone.getReplies()) {
1616 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1617 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1618 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1619 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1620 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1622 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1624 /* save post likes. */
1625 int postLikeCounter = 0;
1626 for (String postId : sone.getLikedPostIds()) {
1627 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1629 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1631 /* save reply likes. */
1632 int replyLikeCounter = 0;
1633 for (String replyId : sone.getLikedReplyIds()) {
1634 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1636 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1639 int friendCounter = 0;
1640 for (String friendId : sone.getFriends()) {
1641 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1643 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1645 /* save albums. first, collect in a flat structure, top-level first. */
1646 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1648 int albumCounter = 0;
1649 for (Album album : albums) {
1650 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1651 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1652 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1653 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1654 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1655 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1657 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1660 int imageCounter = 0;
1661 for (Album album : albums) {
1662 for (Image image : album.getImages()) {
1663 if (!image.isInserted()) {
1666 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1667 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1668 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1669 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1670 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1671 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1672 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1673 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1674 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1677 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1680 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1681 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1682 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1683 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1684 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1685 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1687 configuration.save();
1689 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1691 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1692 } catch (ConfigurationException ce1) {
1693 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1698 * Saves the current options.
1700 private void saveConfiguration() {
1701 synchronized (configuration) {
1702 if (storingConfiguration) {
1703 logger.log(Level.FINE, "Already storing configuration…");
1706 storingConfiguration = true;
1709 /* store the options first. */
1711 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1712 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1713 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1714 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1715 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1716 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1717 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1718 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1719 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1720 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1721 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1722 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1724 /* save known Sones. */
1725 int soneCounter = 0;
1726 synchronized (knownSones) {
1727 for (String knownSoneId : knownSones) {
1728 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1730 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1733 /* save Sone following times. */
1735 synchronized (soneFollowingTimes) {
1736 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1737 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1738 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1741 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1744 /* save known posts. */
1747 /* save bookmarked posts. */
1748 int bookmarkedPostCounter = 0;
1749 synchronized (bookmarkedPosts) {
1750 for (String bookmarkedPostId : bookmarkedPosts) {
1751 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1754 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1757 configuration.save();
1759 } catch (ConfigurationException ce1) {
1760 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1761 } catch (DatabaseException de1) {
1762 logger.log(Level.SEVERE, "Could not save database!", de1);
1764 synchronized (configuration) {
1765 storingConfiguration = false;
1771 * Loads the configuration.
1773 private void loadConfiguration() {
1774 /* create options. */
1775 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1776 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1777 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1778 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1779 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1780 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1781 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1782 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1783 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1784 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1785 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1787 loadConfigurationValue("InsertionDelay");
1788 loadConfigurationValue("PostsPerPage");
1789 loadConfigurationValue("ImagesPerPage");
1790 loadConfigurationValue("CharactersPerPost");
1791 loadConfigurationValue("PostCutOffLength");
1792 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1793 loadConfigurationValue("PositiveTrust");
1794 loadConfigurationValue("NegativeTrust");
1795 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1796 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1797 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1799 /* load known Sones. */
1800 int soneCounter = 0;
1802 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1803 if (knownSoneId == null) {
1806 synchronized (knownSones) {
1807 knownSones.add(knownSoneId);
1811 /* load Sone following times. */
1814 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1815 if (soneId == null) {
1818 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1819 synchronized (soneFollowingTimes) {
1820 soneFollowingTimes.put(soneId, time);
1825 /* load bookmarked posts. */
1826 int bookmarkedPostCounter = 0;
1828 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1829 if (bookmarkedPostId == null) {
1832 synchronized (bookmarkedPosts) {
1833 bookmarkedPosts.add(bookmarkedPostId);
1840 * Loads an {@link Integer} configuration value for the option with the
1841 * given name, logging validation failures.
1844 * The name of the option to load
1846 private void loadConfigurationValue(String optionName) {
1848 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1849 } catch (IllegalArgumentException iae1) {
1850 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1855 * Notifies the core that a new {@link OwnIdentity} was added.
1857 * @param ownIdentityAddedEvent
1861 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1862 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1863 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1864 if (ownIdentity.hasContext("Sone")) {
1865 addLocalSone(ownIdentity);
1870 * Notifies the core that an {@link OwnIdentity} was removed.
1872 * @param ownIdentityRemovedEvent
1876 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1877 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1878 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1879 trustedIdentities.removeAll(ownIdentity);
1883 * Notifies the core that a new {@link Identity} was added.
1885 * @param identityAddedEvent
1889 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1890 Identity identity = identityAddedEvent.identity();
1891 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1892 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1893 addRemoteSone(identity);
1897 * Notifies the core that an {@link Identity} was updated.
1899 * @param identityUpdatedEvent
1903 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1904 Identity identity = identityUpdatedEvent.identity();
1905 final Sone sone = getRemoteSone(identity.getId(), false);
1906 if (sone.isLocal()) {
1909 sone.setIdentity(identity);
1910 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1911 soneDownloader.addSone(sone);
1912 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1916 * Notifies the core that an {@link Identity} was removed.
1918 * @param identityRemovedEvent
1922 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1923 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1924 Identity identity = identityRemovedEvent.identity();
1925 trustedIdentities.remove(ownIdentity, identity);
1926 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1927 if (trustedIdentity.getKey().equals(ownIdentity)) {
1930 if (trustedIdentity.getValue().contains(identity)) {
1934 Optional<Sone> sone = getSone(identity.getId());
1935 if (!sone.isPresent()) {
1936 /* TODO - we don’t have the Sone anymore. should this happen? */
1939 database.removePosts(sone.get());
1940 for (Post post : sone.get().getPosts()) {
1941 eventBus.post(new PostRemovedEvent(post));
1943 database.removePostReplies(sone.get());
1944 for (PostReply reply : sone.get().getReplies()) {
1945 eventBus.post(new PostReplyRemovedEvent(reply));
1947 synchronized (sones) {
1948 sones.remove(identity.getId());
1950 eventBus.post(new SoneRemovedEvent(sone.get()));
1954 * Deletes the temporary image.
1956 * @param imageInsertFinishedEvent
1960 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1961 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1962 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1963 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1964 touchConfiguration();
1968 class MarkPostKnown implements Runnable {
1970 private final Post post;
1972 public MarkPostKnown(Post post) {
1978 markPostKnown(post);
1984 class MarkReplyKnown implements Runnable {
1986 private final PostReply postReply;
1988 public MarkReplyKnown(PostReply postReply) {
1989 this.postReply = postReply;
1994 markReplyKnown(postReply);