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.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.ScheduledExecutorService;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
47 import net.pterodactylus.sone.core.Options.DefaultOption;
48 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
49 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
50 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
51 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
52 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
54 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
55 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
56 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
57 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
58 import net.pterodactylus.sone.core.event.PostRemovedEvent;
59 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
60 import net.pterodactylus.sone.core.event.SoneLockedEvent;
61 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
63 import net.pterodactylus.sone.data.Album;
64 import net.pterodactylus.sone.data.Client;
65 import net.pterodactylus.sone.data.Image;
66 import net.pterodactylus.sone.data.Post;
67 import net.pterodactylus.sone.data.PostReply;
68 import net.pterodactylus.sone.data.Profile;
69 import net.pterodactylus.sone.data.Profile.Field;
70 import net.pterodactylus.sone.data.Reply;
71 import net.pterodactylus.sone.data.Sone;
72 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
73 import net.pterodactylus.sone.data.Sone.SoneStatus;
74 import net.pterodactylus.sone.data.SoneImpl;
75 import net.pterodactylus.sone.data.TemporaryImage;
76 import net.pterodactylus.sone.database.AlbumBuilder;
77 import net.pterodactylus.sone.database.Database;
78 import net.pterodactylus.sone.database.DatabaseException;
79 import net.pterodactylus.sone.database.ImageBuilder;
80 import net.pterodactylus.sone.database.PostBuilder;
81 import net.pterodactylus.sone.database.PostProvider;
82 import net.pterodactylus.sone.database.PostReplyBuilder;
83 import net.pterodactylus.sone.database.PostReplyProvider;
84 import net.pterodactylus.sone.database.SoneBuilder;
85 import net.pterodactylus.sone.database.SoneProvider;
86 import net.pterodactylus.sone.fcp.FcpInterface;
87 import net.pterodactylus.sone.freenet.wot.Identity;
88 import net.pterodactylus.sone.freenet.wot.IdentityManager;
89 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
95 import net.pterodactylus.sone.main.SonePlugin;
96 import net.pterodactylus.sone.utils.IntegerRangePredicate;
97 import net.pterodactylus.util.config.Configuration;
98 import net.pterodactylus.util.config.ConfigurationException;
99 import net.pterodactylus.util.logging.Logging;
100 import net.pterodactylus.util.number.Numbers;
101 import net.pterodactylus.util.service.AbstractService;
102 import net.pterodactylus.util.thread.NamedThreadFactory;
104 import com.google.common.annotations.VisibleForTesting;
105 import com.google.common.base.Optional;
106 import com.google.common.base.Predicates;
107 import com.google.common.collect.FluentIterable;
108 import com.google.common.collect.HashMultimap;
109 import com.google.common.collect.Multimap;
110 import com.google.common.collect.Multimaps;
111 import com.google.common.eventbus.EventBus;
112 import com.google.common.eventbus.Subscribe;
113 import com.google.inject.Inject;
114 import com.google.inject.Singleton;
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>();
184 /** All known Sones. */
185 private final Set<String> knownSones = new HashSet<String>();
187 /** The post database. */
188 private final Database database;
190 /** All bookmarked posts. */
191 /* synchronize access on itself. */
192 private final Set<String> bookmarkedPosts = new HashSet<String>();
194 /** Trusted identities, sorted by own identities. */
195 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
197 /** All temporary images. */
198 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
200 /** Ticker for threads that mark own elements as known. */
201 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
203 /** The time the configuration was last touched. */
204 private volatile long lastConfigurationUpdate;
207 * Creates a new core.
209 * @param configuration
210 * The configuration of the core
211 * @param freenetInterface
212 * The freenet interface
213 * @param identityManager
214 * The identity manager
215 * @param webOfTrustUpdater
216 * The WebOfTrust updater
223 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
225 this.configuration = configuration;
226 this.freenetInterface = freenetInterface;
227 this.identityManager = identityManager;
228 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
229 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
230 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
231 this.webOfTrustUpdater = webOfTrustUpdater;
232 this.eventBus = eventBus;
233 this.database = database;
237 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
239 this.configuration = configuration;
240 this.freenetInterface = freenetInterface;
241 this.identityManager = identityManager;
242 this.soneDownloader = soneDownloader;
243 this.imageInserter = imageInserter;
244 this.updateChecker = updateChecker;
245 this.webOfTrustUpdater = webOfTrustUpdater;
246 this.eventBus = eventBus;
247 this.database = database;
255 * Returns the time Sone was started.
257 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
259 public long getStartupTime() {
264 * Returns the options used by the core.
266 * @return The options of the core
268 public Preferences getPreferences() {
273 * Returns the identity manager used by the core.
275 * @return The identity manager
277 public IdentityManager getIdentityManager() {
278 return identityManager;
282 * Returns the update checker.
284 * @return The update checker
286 public UpdateChecker getUpdateChecker() {
287 return updateChecker;
291 * Sets the FCP interface to use.
293 * @param fcpInterface
294 * The FCP interface to use
296 public void setFcpInterface(FcpInterface fcpInterface) {
297 this.fcpInterface = fcpInterface;
301 * Returns the Sone rescuer for the given local Sone.
304 * The local Sone to get the rescuer for
305 * @return The Sone rescuer for the given Sone
307 public SoneRescuer getSoneRescuer(Sone sone) {
308 checkNotNull(sone, "sone must not be null");
309 checkArgument(sone.isLocal(), "sone must be local");
310 synchronized (soneRescuers) {
311 SoneRescuer soneRescuer = soneRescuers.get(sone);
312 if (soneRescuer == null) {
313 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
314 soneRescuers.put(sone, soneRescuer);
322 * Returns whether the given Sone is currently locked.
326 * @return {@code true} if the Sone is locked, {@code false} if it is not
328 public boolean isLocked(Sone sone) {
329 synchronized (lockedSones) {
330 return lockedSones.contains(sone);
334 public SoneBuilder soneBuilder() {
335 return database.newSoneBuilder();
342 public Collection<Sone> getSones() {
343 return database.getSones();
347 * Returns the Sone with the given ID, regardless whether it’s local or
351 * The ID of the Sone to get
352 * @return The Sone with the given ID, or {@code null} if there is no such
356 public Optional<Sone> getSone(String id) {
357 return database.getSone(id);
364 public Collection<Sone> getLocalSones() {
365 return database.getLocalSones();
369 * Returns the local Sone with the given ID, optionally creating a new Sone.
373 * @return The Sone with the given ID, or {@code null}
375 public Sone getLocalSone(String id) {
376 Optional<Sone> sone = database.getSone(id);
377 if (sone.isPresent() && sone.get().isLocal()) {
387 public Collection<Sone> getRemoteSones() {
388 return database.getRemoteSones();
392 * Returns the remote Sone with the given ID.
396 * The ID of the remote Sone to get
397 * @return The Sone with the given ID
399 public Sone getRemoteSone(String id) {
400 return database.getSone(id).orNull();
404 * Returns whether the given Sone has been modified.
407 * The Sone to check for modifications
408 * @return {@code true} if a modification has been detected in the Sone,
409 * {@code false} otherwise
411 public boolean isModifiedSone(Sone sone) {
412 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
416 * Returns the time when the given was first followed by any local Sone.
419 * The Sone to get the time for
420 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
421 * been followed, or {@link Long#MAX_VALUE}
423 public long getSoneFollowingTime(Sone sone) {
424 synchronized (soneFollowingTimes) {
425 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
430 * Returns a post builder.
432 * @return A new post builder
434 public PostBuilder postBuilder() {
435 return database.newPostBuilder();
442 public Optional<Post> getPost(String postId) {
443 return database.getPost(postId);
450 public Collection<Post> getPosts(String soneId) {
451 return database.getPosts(soneId);
458 public Collection<Post> getDirectedPosts(final String recipientId) {
459 checkNotNull(recipientId, "recipient must not be null");
460 return database.getDirectedPosts(recipientId);
464 * Returns a post reply builder.
466 * @return A new post reply builder
468 public PostReplyBuilder postReplyBuilder() {
469 return database.newPostReplyBuilder();
476 public Optional<PostReply> getPostReply(String replyId) {
477 return database.getPostReply(replyId);
484 public List<PostReply> getReplies(final String postId) {
485 return database.getReplies(postId);
489 * Returns all Sones that have liked the given post.
492 * The post to get the liking Sones for
493 * @return The Sones that like the given post
495 public Set<Sone> getLikes(Post post) {
496 Set<Sone> sones = new HashSet<Sone>();
497 for (Sone sone : getSones()) {
498 if (sone.getLikedPostIds().contains(post.getId())) {
506 * Returns all Sones that have liked the given reply.
509 * The reply to get the liking Sones for
510 * @return The Sones that like the given reply
512 public Set<Sone> getLikes(PostReply reply) {
513 Set<Sone> sones = new HashSet<Sone>();
514 for (Sone sone : getSones()) {
515 if (sone.getLikedReplyIds().contains(reply.getId())) {
523 * Returns whether the given post is bookmarked.
527 * @return {@code true} if the given post is bookmarked, {@code false}
530 public boolean isBookmarked(Post post) {
531 return isPostBookmarked(post.getId());
535 * Returns whether the post with the given ID is bookmarked.
538 * The ID of the post to check
539 * @return {@code true} if the post with the given ID is bookmarked,
540 * {@code false} otherwise
542 public boolean isPostBookmarked(String id) {
543 synchronized (bookmarkedPosts) {
544 return bookmarkedPosts.contains(id);
549 * Returns all currently known bookmarked posts.
551 * @return All bookmarked posts
553 public Set<Post> getBookmarkedPosts() {
554 Set<Post> posts = new HashSet<Post>();
555 synchronized (bookmarkedPosts) {
556 for (String bookmarkedPostId : bookmarkedPosts) {
557 Optional<Post> post = getPost(bookmarkedPostId);
558 if (post.isPresent()) {
559 posts.add(post.get());
566 public AlbumBuilder albumBuilder() {
567 return database.newAlbumBuilder();
571 * Returns the album with the given ID, optionally creating a new album if
572 * an album with the given ID can not be found.
575 * The ID of the album
576 * @return The album with the given ID, or {@code null} if no album with the
579 public Album getAlbum(String albumId) {
580 return database.getAlbum(albumId).orNull();
583 public ImageBuilder imageBuilder() {
584 return database.newImageBuilder();
588 * Returns the image with the given ID, creating it if necessary.
591 * The ID of the image
592 * @return The image with the given ID
594 public Image getImage(String imageId) {
595 return getImage(imageId, true);
599 * Returns the image with the given ID, optionally creating it if it does
603 * The ID of the image
605 * {@code true} to create an image if none exists with the given
607 * @return The image with the given ID, or {@code null} if none exists and
610 public Image getImage(String imageId, boolean create) {
611 Optional<Image> image = database.getImage(imageId);
612 if (image.isPresent()) {
618 Image newImage = database.newImageBuilder().withId(imageId).build();
619 database.storeImage(newImage);
624 * Returns the temporary image with the given ID.
627 * The ID of the temporary image
628 * @return The temporary image, or {@code null} if there is no temporary
629 * image with the given ID
631 public TemporaryImage getTemporaryImage(String imageId) {
632 synchronized (temporaryImages) {
633 return temporaryImages.get(imageId);
642 * Locks the given Sone. A locked Sone will not be inserted by
643 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
649 public void lockSone(Sone sone) {
650 synchronized (lockedSones) {
651 if (lockedSones.add(sone)) {
652 eventBus.post(new SoneLockedEvent(sone));
658 * Unlocks the given Sone.
660 * @see #lockSone(Sone)
664 public void unlockSone(Sone sone) {
665 synchronized (lockedSones) {
666 if (lockedSones.remove(sone)) {
667 eventBus.post(new SoneUnlockedEvent(sone));
673 * Adds a local Sone from the given own identity.
676 * The own identity to create a Sone from
677 * @return The added (or already existing) Sone
679 public Sone addLocalSone(OwnIdentity ownIdentity) {
680 if (ownIdentity == null) {
681 logger.log(Level.WARNING, "Given OwnIdentity is null!");
684 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
685 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
686 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
687 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
689 /* TODO - load posts ’n stuff */
690 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
691 synchronized (soneInserters) {
692 soneInserters.put(sone, soneInserter);
695 sone.setStatus(SoneStatus.idle);
696 soneInserter.start();
701 * Creates a new Sone for the given own identity.
704 * The own identity to create a Sone for
705 * @return The created Sone
707 public Sone createSone(OwnIdentity ownIdentity) {
708 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
709 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
712 Sone sone = addLocalSone(ownIdentity);
714 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
715 touchConfiguration();
720 * Adds the Sone of the given identity.
723 * The identity whose Sone to add
724 * @return The added or already existing Sone
726 public Sone addRemoteSone(Identity identity) {
727 if (identity == null) {
728 logger.log(Level.WARNING, "Given Identity is null!");
731 final Long latestEdition = tryParse(fromNullable(
732 identity.getProperty("Sone.LatestEdition")).or("0"));
733 Optional<Sone> existingSone = getSone(identity.getId());
734 if (existingSone.isPresent() && existingSone.get().isLocal()) {
735 return existingSone.get();
737 boolean newSone = !existingSone.isPresent();
738 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
739 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
740 sone.setLatestEdition(latestEdition);
742 synchronized (knownSones) {
743 newSone = !knownSones.contains(sone.getId());
745 sone.setKnown(!newSone);
747 eventBus.post(new NewSoneFoundEvent(sone));
748 for (Sone localSone : getLocalSones()) {
749 if (localSone.getOptions().isAutoFollow()) {
750 followSone(localSone, sone.getId());
755 database.storeSone(sone);
756 soneDownloader.addSone(sone);
757 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
762 * Lets the given local Sone follow the Sone with the given ID.
765 * The local Sone that should follow another Sone
767 * The ID of the Sone to follow
769 public void followSone(Sone sone, String soneId) {
770 checkNotNull(sone, "sone must not be null");
771 checkNotNull(soneId, "soneId must not be null");
772 sone.addFriend(soneId);
773 synchronized (soneFollowingTimes) {
774 if (!soneFollowingTimes.containsKey(soneId)) {
775 long now = System.currentTimeMillis();
776 soneFollowingTimes.put(soneId, now);
777 Optional<Sone> followedSone = getSone(soneId);
778 if (!followedSone.isPresent()) {
781 for (Post post : followedSone.get().getPosts()) {
782 if (post.getTime() < now) {
786 for (PostReply reply : followedSone.get().getReplies()) {
787 if (reply.getTime() < now) {
788 markReplyKnown(reply);
793 touchConfiguration();
797 * Lets the given local Sone unfollow the Sone with the given ID.
800 * The local Sone that should unfollow another Sone
802 * The ID of the Sone being unfollowed
804 public void unfollowSone(Sone sone, String soneId) {
805 checkNotNull(sone, "sone must not be null");
806 checkNotNull(soneId, "soneId must not be null");
807 sone.removeFriend(soneId);
808 boolean unfollowedSoneStillFollowed = false;
809 for (Sone localSone : getLocalSones()) {
810 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
812 if (!unfollowedSoneStillFollowed) {
813 synchronized (soneFollowingTimes) {
814 soneFollowingTimes.remove(soneId);
817 touchConfiguration();
821 * Sets the trust value of the given origin Sone for the target Sone.
828 * The trust value (from {@code -100} to {@code 100})
830 public void setTrust(Sone origin, Sone target, int trustValue) {
831 checkNotNull(origin, "origin must not be null");
832 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
833 checkNotNull(target, "target must not be null");
834 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
835 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
839 * Removes any trust assignment for the given target Sone.
846 public void removeTrust(Sone origin, Sone target) {
847 checkNotNull(origin, "origin must not be null");
848 checkNotNull(target, "target must not be null");
849 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
850 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
854 * Assigns the configured positive trust value for the given target.
861 public void trustSone(Sone origin, Sone target) {
862 setTrust(origin, target, preferences.getPositiveTrust());
866 * Assigns the configured negative trust value for the given target.
873 public void distrustSone(Sone origin, Sone target) {
874 setTrust(origin, target, preferences.getNegativeTrust());
878 * Removes the trust assignment for the given target.
885 public void untrustSone(Sone origin, Sone target) {
886 removeTrust(origin, target);
890 * Updates the stored Sone with the given Sone.
895 public void updateSone(Sone sone) {
896 updateSone(sone, false);
900 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
901 * {@code true}, an older Sone than the current Sone can be given to restore
906 * @param soneRescueMode
907 * {@code true} if the stored Sone should be updated regardless
908 * of the age of the given Sone
910 public void updateSone(final Sone sone, boolean soneRescueMode) {
911 Optional<Sone> storedSone = getSone(sone.getId());
912 if (storedSone.isPresent()) {
913 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
914 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
917 /* find removed posts. */
918 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
919 soneChangeDetector.onNewPosts(new PostProcessor() {
921 public void processPost(Post post) {
922 if (post.getTime() < getSoneFollowingTime(sone)) {
924 } else if (!post.isKnown()) {
925 eventBus.post(new NewPostFoundEvent(post));
929 soneChangeDetector.onRemovedPosts(new PostProcessor() {
931 public void processPost(Post post) {
932 eventBus.post(new PostRemovedEvent(post));
935 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
937 public void processPostReply(PostReply postReply) {
938 if (postReply.getTime() < getSoneFollowingTime(sone)) {
939 postReply.setKnown(true);
940 } else if (!postReply.isKnown()) {
941 eventBus.post(new NewPostReplyFoundEvent(postReply));
945 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
947 public void processPostReply(PostReply postReply) {
948 eventBus.post(new PostReplyRemovedEvent(postReply));
951 soneChangeDetector.detectChanges(sone);
952 database.storeSone(sone);
953 sone.setOptions(storedSone.get().getOptions());
954 sone.setKnown(storedSone.get().isKnown());
955 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
956 if (sone.isLocal()) {
957 touchConfiguration();
963 * Deletes the given Sone. This will remove the Sone from the
964 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
965 * remove the context from its identity.
970 public void deleteSone(Sone sone) {
971 if (!(sone.getIdentity() instanceof OwnIdentity)) {
972 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
975 if (!getLocalSones().contains(sone)) {
976 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
979 // FIXME – implement in database
980 // sones.remove(sone.getId());
981 SoneInserter soneInserter = soneInserters.remove(sone);
983 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
984 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
986 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
987 } catch (ConfigurationException ce1) {
988 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
993 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
994 * known} before, a {@link MarkSoneKnownEvent} is fired.
997 * The Sone to mark as known
999 public void markSoneKnown(Sone sone) {
1000 if (!sone.isKnown()) {
1001 sone.setKnown(true);
1002 synchronized (knownSones) {
1003 knownSones.add(sone.getId());
1005 eventBus.post(new MarkSoneKnownEvent(sone));
1006 touchConfiguration();
1011 * Loads and updates the given Sone from the configuration. If any error is
1012 * encountered, loading is aborted and the given Sone is not changed.
1015 * The Sone to load and update
1017 public void loadSone(Sone sone) {
1018 if (!sone.isLocal()) {
1019 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1022 logger.info(String.format("Loading local Sone: %s", sone));
1025 String sonePrefix = "Sone/" + sone.getId();
1026 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1027 if (soneTime == null) {
1028 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1031 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1034 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1035 Profile profile = configurationSoneParser.parseProfile();
1038 Collection<Post> posts;
1040 posts = configurationSoneParser.parsePosts(database);
1041 } catch (InvalidPostFound ipf) {
1042 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1047 Collection<PostReply> replies;
1049 replies = configurationSoneParser.parsePostReplies(database);
1050 } catch (InvalidPostReplyFound iprf) {
1051 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1055 /* load post likes. */
1056 Set<String> likedPostIds =
1057 configurationSoneParser.parseLikedPostIds();
1059 /* load reply likes. */
1060 Set<String> likedReplyIds =
1061 configurationSoneParser.parseLikedPostReplyIds();
1064 Set<String> friends = configurationSoneParser.parseFriends();
1067 List<Album> topLevelAlbums;
1070 configurationSoneParser.parseTopLevelAlbums(database);
1071 } catch (InvalidAlbumFound iaf) {
1072 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1074 } catch (InvalidParentAlbumFound ipaf) {
1075 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1076 ipaf.getAlbumParentId()));
1082 configurationSoneParser.parseImages(database);
1083 } catch (InvalidImageFound iif) {
1084 logger.log(WARNING, "Invalid image found, aborting load!");
1086 } catch (InvalidParentAlbumFound ipaf) {
1087 logger.log(Level.WARNING,
1088 format("Invalid album image (%s) encountered, aborting load!",
1089 ipaf.getAlbumParentId()));
1094 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1095 if (avatarId != null) {
1096 final Map<String, Image> images =
1097 configurationSoneParser.getImages();
1098 profile.setAvatar(images.get(avatarId));
1102 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1103 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1104 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1105 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1106 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1107 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1109 /* if we’re still here, Sone was loaded successfully. */
1110 synchronized (sone) {
1111 sone.setTime(soneTime);
1112 sone.setProfile(profile);
1113 sone.setPosts(posts);
1114 sone.setReplies(replies);
1115 sone.setLikePostIds(likedPostIds);
1116 sone.setLikeReplyIds(likedReplyIds);
1117 for (String friendId : friends) {
1118 followSone(sone, friendId);
1120 for (Album album : sone.getRootAlbum().getAlbums()) {
1121 sone.getRootAlbum().removeAlbum(album);
1123 for (Album album : topLevelAlbums) {
1124 sone.getRootAlbum().addAlbum(album);
1126 database.storeSone(sone);
1127 synchronized (soneInserters) {
1128 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1131 synchronized (knownSones) {
1132 for (String friend : friends) {
1133 knownSones.add(friend);
1136 for (Post post : posts) {
1137 post.setKnown(true);
1139 for (PostReply reply : replies) {
1140 reply.setKnown(true);
1143 logger.info(String.format("Sone loaded successfully: %s", sone));
1147 * Creates a new post.
1150 * The Sone that creates the post
1152 * The recipient Sone, or {@code null} if this post does not have
1155 * The text of the post
1156 * @return The created post
1158 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1159 return createPost(sone, recipient, System.currentTimeMillis(), text);
1163 * Creates a new post.
1166 * The Sone that creates the post
1168 * The recipient Sone, or {@code null} if this post does not have
1171 * The time of the post
1173 * The text of the post
1174 * @return The created post
1176 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1177 checkNotNull(text, "text must not be null");
1178 checkArgument(text.trim().length() > 0, "text must not be empty");
1179 if (!sone.isLocal()) {
1180 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1183 PostBuilder postBuilder = database.newPostBuilder();
1184 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1185 if (recipient.isPresent()) {
1186 postBuilder.to(recipient.get().getId());
1188 final Post post = postBuilder.build();
1189 database.storePost(post);
1190 eventBus.post(new NewPostFoundEvent(post));
1192 touchConfiguration();
1193 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1198 * Deletes the given post.
1201 * The post to delete
1203 public void deletePost(Post post) {
1204 if (!post.getSone().isLocal()) {
1205 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1208 database.removePost(post);
1209 eventBus.post(new PostRemovedEvent(post));
1210 markPostKnown(post);
1211 touchConfiguration();
1215 * Marks the given post as known, if it is currently not a known post
1216 * (according to {@link Post#isKnown()}).
1219 * The post to mark as known
1221 public void markPostKnown(Post post) {
1222 post.setKnown(true);
1223 eventBus.post(new MarkPostKnownEvent(post));
1224 touchConfiguration();
1225 for (PostReply reply : getReplies(post.getId())) {
1226 markReplyKnown(reply);
1231 * Bookmarks the post with the given ID.
1234 * The ID of the post to bookmark
1236 public void bookmarkPost(String id) {
1237 synchronized (bookmarkedPosts) {
1238 bookmarkedPosts.add(id);
1243 * Removes the given post from the bookmarks.
1246 * The post to unbookmark
1248 public void unbookmark(Post post) {
1249 unbookmarkPost(post.getId());
1253 * Removes the post with the given ID from the bookmarks.
1256 * The ID of the post to unbookmark
1258 public void unbookmarkPost(String id) {
1259 synchronized (bookmarkedPosts) {
1260 bookmarkedPosts.remove(id);
1265 * Creates a new reply.
1268 * The Sone that creates the reply
1270 * The post that this reply refers to
1272 * The text of the reply
1273 * @return The created reply
1275 public PostReply createReply(Sone sone, Post post, String text) {
1276 checkNotNull(text, "text must not be null");
1277 checkArgument(text.trim().length() > 0, "text must not be empty");
1278 if (!sone.isLocal()) {
1279 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1282 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1283 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1284 final PostReply reply = postReplyBuilder.build();
1285 database.storePostReply(reply);
1286 eventBus.post(new NewPostReplyFoundEvent(reply));
1287 sone.addReply(reply);
1288 touchConfiguration();
1289 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1294 * Deletes the given reply.
1297 * The reply to delete
1299 public void deleteReply(PostReply reply) {
1300 Sone sone = reply.getSone();
1301 if (!sone.isLocal()) {
1302 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1305 database.removePostReply(reply);
1306 markReplyKnown(reply);
1307 sone.removeReply(reply);
1308 touchConfiguration();
1312 * Marks the given reply as known, if it is currently not a known reply
1313 * (according to {@link Reply#isKnown()}).
1316 * The reply to mark as known
1318 public void markReplyKnown(PostReply reply) {
1319 boolean previouslyKnown = reply.isKnown();
1320 reply.setKnown(true);
1321 eventBus.post(new MarkPostReplyKnownEvent(reply));
1322 if (!previouslyKnown) {
1323 touchConfiguration();
1328 * Creates a new album for the given Sone.
1331 * The Sone to create the album for
1333 * The parent of the album (may be {@code null} to create a
1335 * @return The new album
1337 public Album createAlbum(Sone sone, Album parent) {
1338 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1339 database.storeAlbum(album);
1340 parent.addAlbum(album);
1345 * Deletes the given album. The owner of the album has to be a local Sone,
1346 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1349 * The album to remove
1351 public void deleteAlbum(Album album) {
1352 checkNotNull(album, "album must not be null");
1353 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1354 if (!album.isEmpty()) {
1357 album.getParent().removeAlbum(album);
1358 database.removeAlbum(album);
1359 touchConfiguration();
1363 * Creates a new image.
1366 * The Sone creating the image
1368 * The album the image will be inserted into
1369 * @param temporaryImage
1370 * The temporary image to create the image from
1371 * @return The newly created image
1373 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1374 checkNotNull(sone, "sone must not be null");
1375 checkNotNull(album, "album must not be null");
1376 checkNotNull(temporaryImage, "temporaryImage must not be null");
1377 checkArgument(sone.isLocal(), "sone must be a local Sone");
1378 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1379 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1380 album.addImage(image);
1381 database.storeImage(image);
1382 imageInserter.insertImage(temporaryImage, image);
1387 * Deletes the given image. This method will also delete a matching
1390 * @see #deleteTemporaryImage(String)
1392 * The image to delete
1394 public void deleteImage(Image image) {
1395 checkNotNull(image, "image must not be null");
1396 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1397 deleteTemporaryImage(image.getId());
1398 image.getAlbum().removeImage(image);
1399 database.removeImage(image);
1400 touchConfiguration();
1404 * Creates a new temporary image.
1407 * The MIME type of the temporary image
1409 * The encoded data of the image
1410 * @return The temporary image
1412 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1413 TemporaryImage temporaryImage = new TemporaryImage();
1414 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1415 synchronized (temporaryImages) {
1416 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1418 return temporaryImage;
1422 * Deletes the temporary image with the given ID.
1425 * The ID of the temporary image to delete
1427 public void deleteTemporaryImage(String imageId) {
1428 checkNotNull(imageId, "imageId must not be null");
1429 synchronized (temporaryImages) {
1430 temporaryImages.remove(imageId);
1432 Image image = getImage(imageId, false);
1433 if (image != null) {
1434 imageInserter.cancelImageInsert(image);
1439 * Notifies the core that the configuration, either of the core or of a
1440 * single local Sone, has changed, and that the configuration should be
1443 public void touchConfiguration() {
1444 lastConfigurationUpdate = System.currentTimeMillis();
1455 public void serviceStart() {
1456 loadConfiguration();
1457 updateChecker.start();
1458 identityManager.start();
1459 webOfTrustUpdater.init();
1460 webOfTrustUpdater.start();
1468 public void serviceRun() {
1469 long lastSaved = System.currentTimeMillis();
1470 while (!shouldStop()) {
1472 long now = System.currentTimeMillis();
1473 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1474 for (Sone localSone : getLocalSones()) {
1475 saveSone(localSone);
1477 saveConfiguration();
1487 public void serviceStop() {
1488 localElementTicker.shutdownNow();
1489 synchronized (soneInserters) {
1490 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1491 soneInserter.getValue().stop();
1492 saveSone(soneInserter.getKey());
1495 saveConfiguration();
1497 webOfTrustUpdater.stop();
1498 updateChecker.stop();
1499 soneDownloader.stop();
1500 soneDownloaders.shutdown();
1501 identityManager.stop();
1509 * Saves the given Sone. This will persist all local settings for the given
1510 * Sone, such as the friends list and similar, private options.
1515 private synchronized void saveSone(Sone sone) {
1516 if (!sone.isLocal()) {
1517 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1520 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1521 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1525 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1527 /* save Sone into configuration. */
1528 String sonePrefix = "Sone/" + sone.getId();
1529 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1530 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1533 Profile profile = sone.getProfile();
1534 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1535 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1536 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1537 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1538 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1539 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1540 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1542 /* save profile fields. */
1543 int fieldCounter = 0;
1544 for (Field profileField : profile.getFields()) {
1545 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1546 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1547 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1549 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1552 int postCounter = 0;
1553 for (Post post : sone.getPosts()) {
1554 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1555 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1556 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1557 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1558 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1560 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1563 int replyCounter = 0;
1564 for (PostReply reply : sone.getReplies()) {
1565 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1566 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1567 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1568 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1569 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1571 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1573 /* save post likes. */
1574 int postLikeCounter = 0;
1575 for (String postId : sone.getLikedPostIds()) {
1576 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1578 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1580 /* save reply likes. */
1581 int replyLikeCounter = 0;
1582 for (String replyId : sone.getLikedReplyIds()) {
1583 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1585 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1588 int friendCounter = 0;
1589 for (String friendId : sone.getFriends()) {
1590 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1592 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1594 /* save albums. first, collect in a flat structure, top-level first. */
1595 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1597 int albumCounter = 0;
1598 for (Album album : albums) {
1599 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1600 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1601 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1602 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1603 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1604 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1606 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1609 int imageCounter = 0;
1610 for (Album album : albums) {
1611 for (Image image : album.getImages()) {
1612 if (!image.isInserted()) {
1615 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1616 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1617 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1618 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1619 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1620 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1621 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1622 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1623 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1626 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1629 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1630 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1631 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1632 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1633 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1634 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1636 configuration.save();
1638 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1640 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1641 } catch (ConfigurationException ce1) {
1642 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1647 * Saves the current options.
1649 private void saveConfiguration() {
1650 synchronized (configuration) {
1651 if (storingConfiguration) {
1652 logger.log(Level.FINE, "Already storing configuration…");
1655 storingConfiguration = true;
1658 /* store the options first. */
1660 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1661 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1662 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1663 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1664 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1665 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1666 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1667 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1668 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1669 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1670 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1671 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1673 /* save known Sones. */
1674 int soneCounter = 0;
1675 synchronized (knownSones) {
1676 for (String knownSoneId : knownSones) {
1677 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1679 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1682 /* save Sone following times. */
1684 synchronized (soneFollowingTimes) {
1685 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1686 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1687 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1690 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1693 /* save known posts. */
1696 /* save bookmarked posts. */
1697 int bookmarkedPostCounter = 0;
1698 synchronized (bookmarkedPosts) {
1699 for (String bookmarkedPostId : bookmarkedPosts) {
1700 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1703 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1706 configuration.save();
1708 } catch (ConfigurationException ce1) {
1709 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1710 } catch (DatabaseException de1) {
1711 logger.log(Level.SEVERE, "Could not save database!", de1);
1713 synchronized (configuration) {
1714 storingConfiguration = false;
1720 * Loads the configuration.
1722 private void loadConfiguration() {
1723 /* create options. */
1724 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1725 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1726 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1727 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1728 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1729 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1730 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1731 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1732 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1733 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1734 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1736 loadConfigurationValue("InsertionDelay");
1737 loadConfigurationValue("PostsPerPage");
1738 loadConfigurationValue("ImagesPerPage");
1739 loadConfigurationValue("CharactersPerPost");
1740 loadConfigurationValue("PostCutOffLength");
1741 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1742 loadConfigurationValue("PositiveTrust");
1743 loadConfigurationValue("NegativeTrust");
1744 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1745 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1746 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1748 /* load known Sones. */
1749 int soneCounter = 0;
1751 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1752 if (knownSoneId == null) {
1755 synchronized (knownSones) {
1756 knownSones.add(knownSoneId);
1760 /* load Sone following times. */
1763 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1764 if (soneId == null) {
1767 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1768 synchronized (soneFollowingTimes) {
1769 soneFollowingTimes.put(soneId, time);
1774 /* load bookmarked posts. */
1775 int bookmarkedPostCounter = 0;
1777 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1778 if (bookmarkedPostId == null) {
1781 synchronized (bookmarkedPosts) {
1782 bookmarkedPosts.add(bookmarkedPostId);
1789 * Loads an {@link Integer} configuration value for the option with the
1790 * given name, logging validation failures.
1793 * The name of the option to load
1795 private void loadConfigurationValue(String optionName) {
1797 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1798 } catch (IllegalArgumentException iae1) {
1799 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1804 * Notifies the core that a new {@link OwnIdentity} was added.
1806 * @param ownIdentityAddedEvent
1810 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1811 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1812 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1813 if (ownIdentity.hasContext("Sone")) {
1814 addLocalSone(ownIdentity);
1819 * Notifies the core that an {@link OwnIdentity} was removed.
1821 * @param ownIdentityRemovedEvent
1825 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1826 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1827 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1828 trustedIdentities.removeAll(ownIdentity);
1832 * Notifies the core that a new {@link Identity} was added.
1834 * @param identityAddedEvent
1838 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1839 Identity identity = identityAddedEvent.identity();
1840 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1841 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1842 addRemoteSone(identity);
1846 * Notifies the core that an {@link Identity} was updated.
1848 * @param identityUpdatedEvent
1852 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1853 Identity identity = identityUpdatedEvent.identity();
1854 final Sone sone = getRemoteSone(identity.getId());
1855 if (sone.isLocal()) {
1858 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1859 soneDownloader.addSone(sone);
1860 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1864 * Notifies the core that an {@link Identity} was removed.
1866 * @param identityRemovedEvent
1870 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1871 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1872 Identity identity = identityRemovedEvent.identity();
1873 trustedIdentities.remove(ownIdentity, identity);
1874 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1875 if (trustedIdentity.getKey().equals(ownIdentity)) {
1878 if (trustedIdentity.getValue().contains(identity)) {
1882 Optional<Sone> sone = getSone(identity.getId());
1883 if (!sone.isPresent()) {
1884 /* TODO - we don’t have the Sone anymore. should this happen? */
1887 database.removePosts(sone.get());
1888 for (Post post : sone.get().getPosts()) {
1889 eventBus.post(new PostRemovedEvent(post));
1891 database.removePostReplies(sone.get());
1892 for (PostReply reply : sone.get().getReplies()) {
1893 eventBus.post(new PostReplyRemovedEvent(reply));
1895 // TODO – implement in database
1896 // sones.remove(identity.getId());
1897 eventBus.post(new SoneRemovedEvent(sone.get()));
1901 * Deletes the temporary image.
1903 * @param imageInsertFinishedEvent
1907 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1908 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1909 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1910 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1911 touchConfiguration();
1915 class MarkPostKnown implements Runnable {
1917 private final Post post;
1919 public MarkPostKnown(Post post) {
1925 markPostKnown(post);
1931 class MarkReplyKnown implements Runnable {
1933 private final PostReply postReply;
1935 public MarkReplyKnown(PostReply postReply) {
1936 this.postReply = postReply;
1941 markReplyKnown(postReply);