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;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.TimeUnit;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
46 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
47 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
48 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
49 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
51 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
52 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
53 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
54 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
55 import net.pterodactylus.sone.core.event.PostRemovedEvent;
56 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneLockedEvent;
58 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
60 import net.pterodactylus.sone.data.Album;
61 import net.pterodactylus.sone.data.Client;
62 import net.pterodactylus.sone.data.Image;
63 import net.pterodactylus.sone.data.Post;
64 import net.pterodactylus.sone.data.PostReply;
65 import net.pterodactylus.sone.data.Profile;
66 import net.pterodactylus.sone.data.Profile.Field;
67 import net.pterodactylus.sone.data.Reply;
68 import net.pterodactylus.sone.data.Sone;
69 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
70 import net.pterodactylus.sone.data.Sone.SoneStatus;
71 import net.pterodactylus.sone.data.TemporaryImage;
72 import net.pterodactylus.sone.database.AlbumBuilder;
73 import net.pterodactylus.sone.database.Database;
74 import net.pterodactylus.sone.database.DatabaseException;
75 import net.pterodactylus.sone.database.ImageBuilder;
76 import net.pterodactylus.sone.database.PostBuilder;
77 import net.pterodactylus.sone.database.PostProvider;
78 import net.pterodactylus.sone.database.PostReplyBuilder;
79 import net.pterodactylus.sone.database.PostReplyProvider;
80 import net.pterodactylus.sone.database.SoneBuilder;
81 import net.pterodactylus.sone.database.SoneProvider;
82 import net.pterodactylus.sone.fcp.FcpInterface;
83 import net.pterodactylus.sone.freenet.wot.Identity;
84 import net.pterodactylus.sone.freenet.wot.IdentityManager;
85 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
86 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
91 import net.pterodactylus.sone.main.SonePlugin;
92 import net.pterodactylus.util.config.Configuration;
93 import net.pterodactylus.util.config.ConfigurationException;
94 import net.pterodactylus.util.logging.Logging;
95 import net.pterodactylus.util.number.Numbers;
96 import net.pterodactylus.util.service.AbstractService;
97 import net.pterodactylus.util.thread.NamedThreadFactory;
99 import com.google.common.annotations.VisibleForTesting;
100 import com.google.common.base.Optional;
101 import com.google.common.collect.FluentIterable;
102 import com.google.common.collect.HashMultimap;
103 import com.google.common.collect.Multimap;
104 import com.google.common.collect.Multimaps;
105 import com.google.common.eventbus.EventBus;
106 import com.google.common.eventbus.Subscribe;
107 import com.google.inject.Inject;
108 import com.google.inject.Singleton;
113 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
116 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
119 private static final Logger logger = Logging.getLogger(Core.class);
121 /** The start time. */
122 private final long startupTime = System.currentTimeMillis();
124 /** The preferences. */
125 private final Preferences preferences;
127 /** The event bus. */
128 private final EventBus eventBus;
130 /** The configuration. */
131 private final Configuration configuration;
133 /** Whether we’re currently saving the configuration. */
134 private boolean storingConfiguration = false;
136 /** The identity manager. */
137 private final IdentityManager identityManager;
139 /** Interface to freenet. */
140 private final FreenetInterface freenetInterface;
142 /** The Sone downloader. */
143 private final SoneDownloader soneDownloader;
145 /** The image inserter. */
146 private final ImageInserter imageInserter;
148 /** Sone downloader thread-pool. */
149 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
151 /** The update checker. */
152 private final UpdateChecker updateChecker;
154 /** The trust updater. */
155 private final WebOfTrustUpdater webOfTrustUpdater;
157 /** The times Sones were followed. */
158 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
160 /** Locked local Sones. */
161 /* synchronize on itself. */
162 private final Set<Sone> lockedSones = new HashSet<Sone>();
164 /** Sone inserters. */
165 /* synchronize access on this on sones. */
166 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
168 /** Sone rescuers. */
169 /* synchronize access on this on sones. */
170 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
172 /** All known Sones. */
173 private final Set<String> knownSones = new HashSet<String>();
175 /** The post database. */
176 private final Database database;
178 /** All bookmarked posts. */
179 /* synchronize access on itself. */
180 private final Set<String> bookmarkedPosts = new HashSet<String>();
182 /** Trusted identities, sorted by own identities. */
183 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
185 /** All temporary images. */
186 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
188 /** Ticker for threads that mark own elements as known. */
189 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
191 /** The time the configuration was last touched. */
192 private volatile long lastConfigurationUpdate;
195 * Creates a new core.
197 * @param configuration
198 * The configuration of the core
199 * @param freenetInterface
200 * The freenet interface
201 * @param identityManager
202 * The identity manager
203 * @param webOfTrustUpdater
204 * The WebOfTrust updater
211 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
213 this.configuration = configuration;
214 this.freenetInterface = freenetInterface;
215 this.identityManager = identityManager;
216 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
217 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
218 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
219 this.webOfTrustUpdater = webOfTrustUpdater;
220 this.eventBus = eventBus;
221 this.database = database;
222 preferences = new Preferences(eventBus);
226 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
228 this.configuration = configuration;
229 this.freenetInterface = freenetInterface;
230 this.identityManager = identityManager;
231 this.soneDownloader = soneDownloader;
232 this.imageInserter = imageInserter;
233 this.updateChecker = updateChecker;
234 this.webOfTrustUpdater = webOfTrustUpdater;
235 this.eventBus = eventBus;
236 this.database = database;
237 preferences = new Preferences(eventBus);
245 * Returns the time Sone was started.
247 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
249 public long getStartupTime() {
254 * Returns the options used by the core.
256 * @return The options of the core
258 public Preferences getPreferences() {
263 * Returns the identity manager used by the core.
265 * @return The identity manager
267 public IdentityManager getIdentityManager() {
268 return identityManager;
272 * Returns the update checker.
274 * @return The update checker
276 public UpdateChecker getUpdateChecker() {
277 return updateChecker;
281 * Returns the Sone rescuer for the given local Sone.
284 * The local Sone to get the rescuer for
285 * @return The Sone rescuer for the given Sone
287 public SoneRescuer getSoneRescuer(Sone sone) {
288 checkNotNull(sone, "sone must not be null");
289 checkArgument(sone.isLocal(), "sone must be local");
290 synchronized (soneRescuers) {
291 SoneRescuer soneRescuer = soneRescuers.get(sone);
292 if (soneRescuer == null) {
293 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
294 soneRescuers.put(sone, soneRescuer);
302 * Returns whether the given Sone is currently locked.
306 * @return {@code true} if the Sone is locked, {@code false} if it is not
308 public boolean isLocked(Sone sone) {
309 synchronized (lockedSones) {
310 return lockedSones.contains(sone);
314 public SoneBuilder soneBuilder() {
315 return database.newSoneBuilder();
322 public Collection<Sone> getSones() {
323 return database.getSones();
327 * Returns the Sone with the given ID, regardless whether it’s local or
331 * The ID of the Sone to get
332 * @return The Sone with the given ID, or {@code null} if there is no such
336 public Optional<Sone> getSone(String id) {
337 return database.getSone(id);
344 public Collection<Sone> getLocalSones() {
345 return database.getLocalSones();
349 * Returns the local Sone with the given ID, optionally creating a new Sone.
353 * @return The Sone with the given ID, or {@code null}
355 public Sone getLocalSone(String id) {
356 Optional<Sone> sone = database.getSone(id);
357 if (sone.isPresent() && sone.get().isLocal()) {
367 public Collection<Sone> getRemoteSones() {
368 return database.getRemoteSones();
372 * Returns the remote Sone with the given ID.
376 * The ID of the remote Sone to get
377 * @return The Sone with the given ID
379 public Sone getRemoteSone(String id) {
380 return database.getSone(id).orNull();
384 * Returns whether the given Sone has been modified.
387 * The Sone to check for modifications
388 * @return {@code true} if a modification has been detected in the Sone,
389 * {@code false} otherwise
391 public boolean isModifiedSone(Sone sone) {
392 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
396 * Returns the time when the given was first followed by any local Sone.
399 * The Sone to get the time for
400 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
401 * been followed, or {@link Long#MAX_VALUE}
403 public long getSoneFollowingTime(Sone sone) {
404 synchronized (soneFollowingTimes) {
405 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
410 * Returns a post builder.
412 * @return A new post builder
414 public PostBuilder postBuilder() {
415 return database.newPostBuilder();
422 public Optional<Post> getPost(String postId) {
423 return database.getPost(postId);
430 public Collection<Post> getPosts(String soneId) {
431 return database.getPosts(soneId);
438 public Collection<Post> getDirectedPosts(final String recipientId) {
439 checkNotNull(recipientId, "recipient must not be null");
440 return database.getDirectedPosts(recipientId);
444 * Returns a post reply builder.
446 * @return A new post reply builder
448 public PostReplyBuilder postReplyBuilder() {
449 return database.newPostReplyBuilder();
456 public Optional<PostReply> getPostReply(String replyId) {
457 return database.getPostReply(replyId);
464 public List<PostReply> getReplies(final String postId) {
465 return database.getReplies(postId);
469 * Returns all Sones that have liked the given post.
472 * The post to get the liking Sones for
473 * @return The Sones that like the given post
475 public Set<Sone> getLikes(Post post) {
476 Set<Sone> sones = new HashSet<Sone>();
477 for (Sone sone : getSones()) {
478 if (sone.getLikedPostIds().contains(post.getId())) {
486 * Returns all Sones that have liked the given reply.
489 * The reply to get the liking Sones for
490 * @return The Sones that like the given reply
492 public Set<Sone> getLikes(PostReply reply) {
493 Set<Sone> sones = new HashSet<Sone>();
494 for (Sone sone : getSones()) {
495 if (sone.getLikedReplyIds().contains(reply.getId())) {
503 * Returns whether the given post is bookmarked.
507 * @return {@code true} if the given post is bookmarked, {@code false}
510 public boolean isBookmarked(Post post) {
511 return isPostBookmarked(post.getId());
515 * Returns whether the post with the given ID is bookmarked.
518 * The ID of the post to check
519 * @return {@code true} if the post with the given ID is bookmarked,
520 * {@code false} otherwise
522 public boolean isPostBookmarked(String id) {
523 synchronized (bookmarkedPosts) {
524 return bookmarkedPosts.contains(id);
529 * Returns all currently known bookmarked posts.
531 * @return All bookmarked posts
533 public Set<Post> getBookmarkedPosts() {
534 Set<Post> posts = new HashSet<Post>();
535 synchronized (bookmarkedPosts) {
536 for (String bookmarkedPostId : bookmarkedPosts) {
537 Optional<Post> post = getPost(bookmarkedPostId);
538 if (post.isPresent()) {
539 posts.add(post.get());
546 public AlbumBuilder albumBuilder() {
547 return database.newAlbumBuilder();
551 * Returns the album with the given ID, optionally creating a new album if
552 * an album with the given ID can not be found.
555 * The ID of the album
556 * @return The album with the given ID, or {@code null} if no album with the
559 public Album getAlbum(String albumId) {
560 return database.getAlbum(albumId).orNull();
563 public ImageBuilder imageBuilder() {
564 return database.newImageBuilder();
568 * Returns the image with the given ID, creating it if necessary.
571 * The ID of the image
572 * @return The image with the given ID
574 public Image getImage(String imageId) {
575 return getImage(imageId, true);
579 * Returns the image with the given ID, optionally creating it if it does
583 * The ID of the image
585 * {@code true} to create an image if none exists with the given
587 * @return The image with the given ID, or {@code null} if none exists and
590 public Image getImage(String imageId, boolean create) {
591 Optional<Image> image = database.getImage(imageId);
592 if (image.isPresent()) {
598 Image newImage = database.newImageBuilder().withId(imageId).build();
599 database.storeImage(newImage);
604 * Returns the temporary image with the given ID.
607 * The ID of the temporary image
608 * @return The temporary image, or {@code null} if there is no temporary
609 * image with the given ID
611 public TemporaryImage getTemporaryImage(String imageId) {
612 synchronized (temporaryImages) {
613 return temporaryImages.get(imageId);
622 * Locks the given Sone. A locked Sone will not be inserted by
623 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
629 public void lockSone(Sone sone) {
630 synchronized (lockedSones) {
631 if (lockedSones.add(sone)) {
632 eventBus.post(new SoneLockedEvent(sone));
638 * Unlocks the given Sone.
640 * @see #lockSone(Sone)
644 public void unlockSone(Sone sone) {
645 synchronized (lockedSones) {
646 if (lockedSones.remove(sone)) {
647 eventBus.post(new SoneUnlockedEvent(sone));
653 * Adds a local Sone from the given own identity.
656 * The own identity to create a Sone from
657 * @return The added (or already existing) Sone
659 public Sone addLocalSone(OwnIdentity ownIdentity) {
660 if (ownIdentity == null) {
661 logger.log(Level.WARNING, "Given OwnIdentity is null!");
664 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
665 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
666 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
667 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
669 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
670 eventBus.register(soneInserter);
671 synchronized (soneInserters) {
672 soneInserters.put(sone, soneInserter);
675 sone.setStatus(SoneStatus.idle);
676 soneInserter.start();
681 * Creates a new Sone for the given own identity.
684 * The own identity to create a Sone for
685 * @return The created Sone
687 public Sone createSone(OwnIdentity ownIdentity) {
688 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
689 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
692 Sone sone = addLocalSone(ownIdentity);
694 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
695 touchConfiguration();
700 * Adds the Sone of the given identity.
703 * The identity whose Sone to add
704 * @return The added or already existing Sone
706 public Sone addRemoteSone(Identity identity) {
707 if (identity == null) {
708 logger.log(Level.WARNING, "Given Identity is null!");
711 final Long latestEdition = tryParse(fromNullable(
712 identity.getProperty("Sone.LatestEdition")).or("0"));
713 Optional<Sone> existingSone = getSone(identity.getId());
714 if (existingSone.isPresent() && existingSone.get().isLocal()) {
715 return existingSone.get();
717 boolean newSone = !existingSone.isPresent();
718 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
719 sone.setLatestEdition(latestEdition);
721 synchronized (knownSones) {
722 newSone = !knownSones.contains(sone.getId());
724 sone.setKnown(!newSone);
726 eventBus.post(new NewSoneFoundEvent(sone));
727 for (Sone localSone : getLocalSones()) {
728 if (localSone.getOptions().isAutoFollow()) {
729 followSone(localSone, sone.getId());
734 database.storeSone(sone);
735 soneDownloader.addSone(sone);
736 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
741 * Lets the given local Sone follow the Sone with the given ID.
744 * The local Sone that should follow another Sone
746 * The ID of the Sone to follow
748 public void followSone(Sone sone, String soneId) {
749 checkNotNull(sone, "sone must not be null");
750 checkNotNull(soneId, "soneId must not be null");
751 sone.addFriend(soneId);
752 synchronized (soneFollowingTimes) {
753 if (!soneFollowingTimes.containsKey(soneId)) {
754 long now = System.currentTimeMillis();
755 soneFollowingTimes.put(soneId, now);
756 Optional<Sone> followedSone = getSone(soneId);
757 if (!followedSone.isPresent()) {
760 for (Post post : followedSone.get().getPosts()) {
761 if (post.getTime() < now) {
765 for (PostReply reply : followedSone.get().getReplies()) {
766 if (reply.getTime() < now) {
767 markReplyKnown(reply);
772 touchConfiguration();
776 * Lets the given local Sone unfollow the Sone with the given ID.
779 * The local Sone that should unfollow another Sone
781 * The ID of the Sone being unfollowed
783 public void unfollowSone(Sone sone, String soneId) {
784 checkNotNull(sone, "sone must not be null");
785 checkNotNull(soneId, "soneId must not be null");
786 sone.removeFriend(soneId);
787 boolean unfollowedSoneStillFollowed = false;
788 for (Sone localSone : getLocalSones()) {
789 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
791 if (!unfollowedSoneStillFollowed) {
792 synchronized (soneFollowingTimes) {
793 soneFollowingTimes.remove(soneId);
796 touchConfiguration();
800 * Sets the trust value of the given origin Sone for the target Sone.
807 * The trust value (from {@code -100} to {@code 100})
809 public void setTrust(Sone origin, Sone target, int trustValue) {
810 checkNotNull(origin, "origin must not be null");
811 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
812 checkNotNull(target, "target must not be null");
813 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
814 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
818 * Removes any trust assignment for the given target Sone.
825 public void removeTrust(Sone origin, Sone target) {
826 checkNotNull(origin, "origin must not be null");
827 checkNotNull(target, "target must not be null");
828 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
829 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
833 * Assigns the configured positive trust value for the given target.
840 public void trustSone(Sone origin, Sone target) {
841 setTrust(origin, target, preferences.getPositiveTrust());
845 * Assigns the configured negative trust value for the given target.
852 public void distrustSone(Sone origin, Sone target) {
853 setTrust(origin, target, preferences.getNegativeTrust());
857 * Removes the trust assignment for the given target.
864 public void untrustSone(Sone origin, Sone target) {
865 removeTrust(origin, target);
869 * Updates the stored Sone with the given Sone.
874 public void updateSone(Sone sone) {
875 updateSone(sone, false);
879 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
880 * {@code true}, an older Sone than the current Sone can be given to restore
885 * @param soneRescueMode
886 * {@code true} if the stored Sone should be updated regardless
887 * of the age of the given Sone
889 public void updateSone(final Sone sone, boolean soneRescueMode) {
890 Optional<Sone> storedSone = getSone(sone.getId());
891 if (storedSone.isPresent()) {
892 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
893 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
896 /* find removed posts. */
897 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
898 soneChangeDetector.onNewPosts(new PostProcessor() {
900 public void processPost(Post post) {
901 if (post.getTime() < getSoneFollowingTime(sone)) {
903 } else if (!post.isKnown()) {
904 eventBus.post(new NewPostFoundEvent(post));
908 soneChangeDetector.onRemovedPosts(new PostProcessor() {
910 public void processPost(Post post) {
911 eventBus.post(new PostRemovedEvent(post));
914 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
916 public void processPostReply(PostReply postReply) {
917 if (postReply.getTime() < getSoneFollowingTime(sone)) {
918 postReply.setKnown(true);
919 } else if (!postReply.isKnown()) {
920 eventBus.post(new NewPostReplyFoundEvent(postReply));
924 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
926 public void processPostReply(PostReply postReply) {
927 eventBus.post(new PostReplyRemovedEvent(postReply));
930 soneChangeDetector.detectChanges(sone);
931 database.storeSone(sone);
932 sone.setOptions(storedSone.get().getOptions());
933 sone.setKnown(storedSone.get().isKnown());
934 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
935 if (sone.isLocal()) {
936 touchConfiguration();
942 * Deletes the given Sone. This will remove the Sone from the
943 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
944 * remove the context from its identity.
949 public void deleteSone(Sone sone) {
950 if (!(sone.getIdentity() instanceof OwnIdentity)) {
951 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
954 if (!getLocalSones().contains(sone)) {
955 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
958 // FIXME – implement in database
959 // sones.remove(sone.getId());
960 SoneInserter soneInserter = soneInserters.remove(sone);
962 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
963 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
965 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
966 } catch (ConfigurationException ce1) {
967 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
972 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
973 * known} before, a {@link MarkSoneKnownEvent} is fired.
976 * The Sone to mark as known
978 public void markSoneKnown(Sone sone) {
979 if (!sone.isKnown()) {
981 synchronized (knownSones) {
982 knownSones.add(sone.getId());
984 eventBus.post(new MarkSoneKnownEvent(sone));
985 touchConfiguration();
990 * Loads and updates the given Sone from the configuration. If any error is
991 * encountered, loading is aborted and the given Sone is not changed.
994 * The Sone to load and update
996 public void loadSone(Sone sone) {
997 if (!sone.isLocal()) {
998 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1001 logger.info(String.format("Loading local Sone: %s", sone));
1004 String sonePrefix = "Sone/" + sone.getId();
1005 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1006 if (soneTime == null) {
1007 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1010 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1013 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1014 Profile profile = configurationSoneParser.parseProfile();
1017 Collection<Post> posts;
1019 posts = configurationSoneParser.parsePosts(database);
1020 } catch (InvalidPostFound ipf) {
1021 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1026 Collection<PostReply> replies;
1028 replies = configurationSoneParser.parsePostReplies(database);
1029 } catch (InvalidPostReplyFound iprf) {
1030 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1034 /* load post likes. */
1035 Set<String> likedPostIds =
1036 configurationSoneParser.parseLikedPostIds();
1038 /* load reply likes. */
1039 Set<String> likedReplyIds =
1040 configurationSoneParser.parseLikedPostReplyIds();
1043 Set<String> friends = configurationSoneParser.parseFriends();
1046 List<Album> topLevelAlbums;
1049 configurationSoneParser.parseTopLevelAlbums(database);
1050 } catch (InvalidAlbumFound iaf) {
1051 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1053 } catch (InvalidParentAlbumFound ipaf) {
1054 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1055 ipaf.getAlbumParentId()));
1061 configurationSoneParser.parseImages(database);
1062 } catch (InvalidImageFound iif) {
1063 logger.log(WARNING, "Invalid image found, aborting load!");
1065 } catch (InvalidParentAlbumFound ipaf) {
1066 logger.log(Level.WARNING,
1067 format("Invalid album image (%s) encountered, aborting load!",
1068 ipaf.getAlbumParentId()));
1073 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1074 if (avatarId != null) {
1075 final Map<String, Image> images =
1076 configurationSoneParser.getImages();
1077 profile.setAvatar(images.get(avatarId));
1081 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1082 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1083 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1084 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1085 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1086 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1088 /* if we’re still here, Sone was loaded successfully. */
1089 synchronized (sone) {
1090 sone.setTime(soneTime);
1091 sone.setProfile(profile);
1092 sone.setPosts(posts);
1093 sone.setReplies(replies);
1094 sone.setLikePostIds(likedPostIds);
1095 sone.setLikeReplyIds(likedReplyIds);
1096 for (String friendId : friends) {
1097 followSone(sone, friendId);
1099 for (Album album : sone.getRootAlbum().getAlbums()) {
1100 sone.getRootAlbum().removeAlbum(album);
1102 for (Album album : topLevelAlbums) {
1103 sone.getRootAlbum().addAlbum(album);
1105 database.storeSone(sone);
1106 synchronized (soneInserters) {
1107 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1110 synchronized (knownSones) {
1111 for (String friend : friends) {
1112 knownSones.add(friend);
1115 for (Post post : posts) {
1116 post.setKnown(true);
1118 for (PostReply reply : replies) {
1119 reply.setKnown(true);
1122 logger.info(String.format("Sone loaded successfully: %s", sone));
1126 * Creates a new post.
1129 * The Sone that creates the post
1131 * The recipient Sone, or {@code null} if this post does not have
1134 * The text of the post
1135 * @return The created post
1137 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1138 return createPost(sone, recipient, System.currentTimeMillis(), text);
1142 * Creates a new post.
1145 * The Sone that creates the post
1147 * The recipient Sone, or {@code null} if this post does not have
1150 * The time of the post
1152 * The text of the post
1153 * @return The created post
1155 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1156 checkNotNull(text, "text must not be null");
1157 checkArgument(text.trim().length() > 0, "text must not be empty");
1158 if (!sone.isLocal()) {
1159 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1162 PostBuilder postBuilder = database.newPostBuilder();
1163 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1164 if (recipient.isPresent()) {
1165 postBuilder.to(recipient.get().getId());
1167 final Post post = postBuilder.build();
1168 database.storePost(post);
1169 eventBus.post(new NewPostFoundEvent(post));
1171 touchConfiguration();
1172 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1177 * Deletes the given post.
1180 * The post to delete
1182 public void deletePost(Post post) {
1183 if (!post.getSone().isLocal()) {
1184 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1187 database.removePost(post);
1188 eventBus.post(new PostRemovedEvent(post));
1189 markPostKnown(post);
1190 touchConfiguration();
1194 * Marks the given post as known, if it is currently not a known post
1195 * (according to {@link Post#isKnown()}).
1198 * The post to mark as known
1200 public void markPostKnown(Post post) {
1201 post.setKnown(true);
1202 eventBus.post(new MarkPostKnownEvent(post));
1203 touchConfiguration();
1204 for (PostReply reply : getReplies(post.getId())) {
1205 markReplyKnown(reply);
1210 * Bookmarks the post with the given ID.
1213 * The ID of the post to bookmark
1215 public void bookmarkPost(String id) {
1216 synchronized (bookmarkedPosts) {
1217 bookmarkedPosts.add(id);
1222 * Removes the given post from the bookmarks.
1225 * The post to unbookmark
1227 public void unbookmark(Post post) {
1228 unbookmarkPost(post.getId());
1232 * Removes the post with the given ID from the bookmarks.
1235 * The ID of the post to unbookmark
1237 public void unbookmarkPost(String id) {
1238 synchronized (bookmarkedPosts) {
1239 bookmarkedPosts.remove(id);
1244 * Creates a new reply.
1247 * The Sone that creates the reply
1249 * The post that this reply refers to
1251 * The text of the reply
1252 * @return The created reply
1254 public PostReply createReply(Sone sone, Post post, String text) {
1255 checkNotNull(text, "text must not be null");
1256 checkArgument(text.trim().length() > 0, "text must not be empty");
1257 if (!sone.isLocal()) {
1258 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1261 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1262 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1263 final PostReply reply = postReplyBuilder.build();
1264 database.storePostReply(reply);
1265 eventBus.post(new NewPostReplyFoundEvent(reply));
1266 sone.addReply(reply);
1267 touchConfiguration();
1268 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1273 * Deletes the given reply.
1276 * The reply to delete
1278 public void deleteReply(PostReply reply) {
1279 Sone sone = reply.getSone();
1280 if (!sone.isLocal()) {
1281 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1284 database.removePostReply(reply);
1285 markReplyKnown(reply);
1286 sone.removeReply(reply);
1287 touchConfiguration();
1291 * Marks the given reply as known, if it is currently not a known reply
1292 * (according to {@link Reply#isKnown()}).
1295 * The reply to mark as known
1297 public void markReplyKnown(PostReply reply) {
1298 boolean previouslyKnown = reply.isKnown();
1299 reply.setKnown(true);
1300 eventBus.post(new MarkPostReplyKnownEvent(reply));
1301 if (!previouslyKnown) {
1302 touchConfiguration();
1307 * Creates a new album for the given Sone.
1310 * The Sone to create the album for
1312 * The parent of the album (may be {@code null} to create a
1314 * @return The new album
1316 public Album createAlbum(Sone sone, Album parent) {
1317 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1318 database.storeAlbum(album);
1319 parent.addAlbum(album);
1324 * Deletes the given album. The owner of the album has to be a local Sone,
1325 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1328 * The album to remove
1330 public void deleteAlbum(Album album) {
1331 checkNotNull(album, "album must not be null");
1332 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1333 if (!album.isEmpty()) {
1336 album.getParent().removeAlbum(album);
1337 database.removeAlbum(album);
1338 touchConfiguration();
1342 * Creates a new image.
1345 * The Sone creating the image
1347 * The album the image will be inserted into
1348 * @param temporaryImage
1349 * The temporary image to create the image from
1350 * @return The newly created image
1352 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1353 checkNotNull(sone, "sone must not be null");
1354 checkNotNull(album, "album must not be null");
1355 checkNotNull(temporaryImage, "temporaryImage must not be null");
1356 checkArgument(sone.isLocal(), "sone must be a local Sone");
1357 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1358 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1359 album.addImage(image);
1360 database.storeImage(image);
1361 imageInserter.insertImage(temporaryImage, image);
1366 * Deletes the given image. This method will also delete a matching
1369 * @see #deleteTemporaryImage(String)
1371 * The image to delete
1373 public void deleteImage(Image image) {
1374 checkNotNull(image, "image must not be null");
1375 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1376 deleteTemporaryImage(image.getId());
1377 image.getAlbum().removeImage(image);
1378 database.removeImage(image);
1379 touchConfiguration();
1383 * Creates a new temporary image.
1386 * The MIME type of the temporary image
1388 * The encoded data of the image
1389 * @return The temporary image
1391 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1392 TemporaryImage temporaryImage = new TemporaryImage();
1393 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1394 synchronized (temporaryImages) {
1395 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1397 return temporaryImage;
1401 * Deletes the temporary image with the given ID.
1404 * The ID of the temporary image to delete
1406 public void deleteTemporaryImage(String imageId) {
1407 checkNotNull(imageId, "imageId must not be null");
1408 synchronized (temporaryImages) {
1409 temporaryImages.remove(imageId);
1411 Image image = getImage(imageId, false);
1412 if (image != null) {
1413 imageInserter.cancelImageInsert(image);
1418 * Notifies the core that the configuration, either of the core or of a
1419 * single local Sone, has changed, and that the configuration should be
1422 public void touchConfiguration() {
1423 lastConfigurationUpdate = System.currentTimeMillis();
1434 public void serviceStart() {
1435 loadConfiguration();
1436 updateChecker.start();
1437 identityManager.start();
1438 webOfTrustUpdater.init();
1439 webOfTrustUpdater.start();
1447 public void serviceRun() {
1448 long lastSaved = System.currentTimeMillis();
1449 while (!shouldStop()) {
1451 long now = System.currentTimeMillis();
1452 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1453 for (Sone localSone : getLocalSones()) {
1454 saveSone(localSone);
1456 saveConfiguration();
1466 public void serviceStop() {
1467 localElementTicker.shutdownNow();
1468 synchronized (soneInserters) {
1469 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1470 soneInserter.getValue().stop();
1471 saveSone(soneInserter.getKey());
1474 saveConfiguration();
1476 webOfTrustUpdater.stop();
1477 updateChecker.stop();
1478 soneDownloader.stop();
1479 soneDownloaders.shutdown();
1480 identityManager.stop();
1488 * Saves the given Sone. This will persist all local settings for the given
1489 * Sone, such as the friends list and similar, private options.
1494 private synchronized void saveSone(Sone sone) {
1495 if (!sone.isLocal()) {
1496 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1499 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1500 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1504 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1506 /* save Sone into configuration. */
1507 String sonePrefix = "Sone/" + sone.getId();
1508 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1509 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1512 Profile profile = sone.getProfile();
1513 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1514 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1515 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1516 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1517 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1518 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1519 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1521 /* save profile fields. */
1522 int fieldCounter = 0;
1523 for (Field profileField : profile.getFields()) {
1524 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1525 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1526 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1528 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1531 int postCounter = 0;
1532 for (Post post : sone.getPosts()) {
1533 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1534 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1535 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1536 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1537 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1539 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1542 int replyCounter = 0;
1543 for (PostReply reply : sone.getReplies()) {
1544 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1545 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1546 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1547 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1548 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1550 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1552 /* save post likes. */
1553 int postLikeCounter = 0;
1554 for (String postId : sone.getLikedPostIds()) {
1555 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1557 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1559 /* save reply likes. */
1560 int replyLikeCounter = 0;
1561 for (String replyId : sone.getLikedReplyIds()) {
1562 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1564 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1567 int friendCounter = 0;
1568 for (String friendId : sone.getFriends()) {
1569 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1571 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1573 /* save albums. first, collect in a flat structure, top-level first. */
1574 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1576 int albumCounter = 0;
1577 for (Album album : albums) {
1578 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1579 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1580 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1581 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1582 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1583 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1585 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1588 int imageCounter = 0;
1589 for (Album album : albums) {
1590 for (Image image : album.getImages()) {
1591 if (!image.isInserted()) {
1594 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1595 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1596 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1597 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1598 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1599 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1600 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1601 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1602 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1605 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1608 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1609 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1610 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1611 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1612 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1613 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1615 configuration.save();
1617 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1619 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1620 } catch (ConfigurationException ce1) {
1621 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1626 * Saves the current options.
1628 private void saveConfiguration() {
1629 synchronized (configuration) {
1630 if (storingConfiguration) {
1631 logger.log(Level.FINE, "Already storing configuration…");
1634 storingConfiguration = true;
1637 /* store the options first. */
1639 preferences.saveTo(configuration);
1641 /* save known Sones. */
1642 int soneCounter = 0;
1643 synchronized (knownSones) {
1644 for (String knownSoneId : knownSones) {
1645 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1647 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1650 /* save Sone following times. */
1652 synchronized (soneFollowingTimes) {
1653 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1654 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1655 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1658 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1661 /* save known posts. */
1664 /* save bookmarked posts. */
1665 int bookmarkedPostCounter = 0;
1666 synchronized (bookmarkedPosts) {
1667 for (String bookmarkedPostId : bookmarkedPosts) {
1668 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1671 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1674 configuration.save();
1676 } catch (ConfigurationException ce1) {
1677 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1678 } catch (DatabaseException de1) {
1679 logger.log(Level.SEVERE, "Could not save database!", de1);
1681 synchronized (configuration) {
1682 storingConfiguration = false;
1688 * Loads the configuration.
1690 private void loadConfiguration() {
1691 new PreferencesLoader(preferences).loadFrom(configuration);
1693 /* load known Sones. */
1694 int soneCounter = 0;
1696 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1697 if (knownSoneId == null) {
1700 synchronized (knownSones) {
1701 knownSones.add(knownSoneId);
1705 /* load Sone following times. */
1708 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1709 if (soneId == null) {
1712 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1713 synchronized (soneFollowingTimes) {
1714 soneFollowingTimes.put(soneId, time);
1719 /* load bookmarked posts. */
1720 int bookmarkedPostCounter = 0;
1722 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1723 if (bookmarkedPostId == null) {
1726 synchronized (bookmarkedPosts) {
1727 bookmarkedPosts.add(bookmarkedPostId);
1734 * Notifies the core that a new {@link OwnIdentity} was added.
1736 * @param ownIdentityAddedEvent
1740 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1741 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1742 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1743 if (ownIdentity.hasContext("Sone")) {
1744 addLocalSone(ownIdentity);
1749 * Notifies the core that an {@link OwnIdentity} was removed.
1751 * @param ownIdentityRemovedEvent
1755 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1756 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1757 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1758 trustedIdentities.removeAll(ownIdentity);
1762 * Notifies the core that a new {@link Identity} was added.
1764 * @param identityAddedEvent
1768 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1769 Identity identity = identityAddedEvent.identity();
1770 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1771 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1772 addRemoteSone(identity);
1776 * Notifies the core that an {@link Identity} was updated.
1778 * @param identityUpdatedEvent
1782 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1783 Identity identity = identityUpdatedEvent.identity();
1784 final Sone sone = getRemoteSone(identity.getId());
1785 if (sone.isLocal()) {
1788 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1789 soneDownloader.addSone(sone);
1790 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1794 * Notifies the core that an {@link Identity} was removed.
1796 * @param identityRemovedEvent
1800 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1801 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1802 Identity identity = identityRemovedEvent.identity();
1803 trustedIdentities.remove(ownIdentity, identity);
1804 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1805 if (trustedIdentity.getKey().equals(ownIdentity)) {
1808 if (trustedIdentity.getValue().contains(identity)) {
1812 Optional<Sone> sone = getSone(identity.getId());
1813 if (!sone.isPresent()) {
1814 /* TODO - we don’t have the Sone anymore. should this happen? */
1817 database.removePosts(sone.get());
1818 for (Post post : sone.get().getPosts()) {
1819 eventBus.post(new PostRemovedEvent(post));
1821 database.removePostReplies(sone.get());
1822 for (PostReply reply : sone.get().getReplies()) {
1823 eventBus.post(new PostReplyRemovedEvent(reply));
1825 // TODO – implement in database
1826 // sones.remove(identity.getId());
1827 eventBus.post(new SoneRemovedEvent(sone.get()));
1831 * Deletes the temporary image.
1833 * @param imageInsertFinishedEvent
1837 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1838 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1839 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1840 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1841 touchConfiguration();
1845 class MarkPostKnown implements Runnable {
1847 private final Post post;
1849 public MarkPostKnown(Post post) {
1855 markPostKnown(post);
1861 class MarkReplyKnown implements Runnable {
1863 private final PostReply postReply;
1865 public MarkReplyKnown(PostReply postReply) {
1866 this.postReply = postReply;
1871 markReplyKnown(postReply);