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 /** Trusted identities, sorted by own identities. */
179 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
181 /** All temporary images. */
182 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
184 /** Ticker for threads that mark own elements as known. */
185 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
187 /** The time the configuration was last touched. */
188 private volatile long lastConfigurationUpdate;
191 * Creates a new core.
193 * @param configuration
194 * The configuration of the core
195 * @param freenetInterface
196 * The freenet interface
197 * @param identityManager
198 * The identity manager
199 * @param webOfTrustUpdater
200 * The WebOfTrust updater
207 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
209 this.configuration = configuration;
210 this.freenetInterface = freenetInterface;
211 this.identityManager = identityManager;
212 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
213 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
214 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
215 this.webOfTrustUpdater = webOfTrustUpdater;
216 this.eventBus = eventBus;
217 this.database = database;
218 preferences = new Preferences(eventBus);
222 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
224 this.configuration = configuration;
225 this.freenetInterface = freenetInterface;
226 this.identityManager = identityManager;
227 this.soneDownloader = soneDownloader;
228 this.imageInserter = imageInserter;
229 this.updateChecker = updateChecker;
230 this.webOfTrustUpdater = webOfTrustUpdater;
231 this.eventBus = eventBus;
232 this.database = database;
233 preferences = new Preferences(eventBus);
241 * Returns the time Sone was started.
243 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
245 public long getStartupTime() {
250 * Returns the options used by the core.
252 * @return The options of the core
254 public Preferences getPreferences() {
259 * Returns the identity manager used by the core.
261 * @return The identity manager
263 public IdentityManager getIdentityManager() {
264 return identityManager;
268 * Returns the update checker.
270 * @return The update checker
272 public UpdateChecker getUpdateChecker() {
273 return updateChecker;
277 * Returns the Sone rescuer for the given local Sone.
280 * The local Sone to get the rescuer for
281 * @return The Sone rescuer for the given Sone
283 public SoneRescuer getSoneRescuer(Sone sone) {
284 checkNotNull(sone, "sone must not be null");
285 checkArgument(sone.isLocal(), "sone must be local");
286 synchronized (soneRescuers) {
287 SoneRescuer soneRescuer = soneRescuers.get(sone);
288 if (soneRescuer == null) {
289 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
290 soneRescuers.put(sone, soneRescuer);
298 * Returns whether the given Sone is currently locked.
302 * @return {@code true} if the Sone is locked, {@code false} if it is not
304 public boolean isLocked(Sone sone) {
305 synchronized (lockedSones) {
306 return lockedSones.contains(sone);
310 public SoneBuilder soneBuilder() {
311 return database.newSoneBuilder();
318 public Collection<Sone> getSones() {
319 return database.getSones();
323 * Returns the Sone with the given ID, regardless whether it’s local or
327 * The ID of the Sone to get
328 * @return The Sone with the given ID, or {@code null} if there is no such
332 public Optional<Sone> getSone(String id) {
333 return database.getSone(id);
340 public Collection<Sone> getLocalSones() {
341 return database.getLocalSones();
345 * Returns the local Sone with the given ID, optionally creating a new Sone.
349 * @return The Sone with the given ID, or {@code null}
351 public Sone getLocalSone(String id) {
352 Optional<Sone> sone = database.getSone(id);
353 if (sone.isPresent() && sone.get().isLocal()) {
363 public Collection<Sone> getRemoteSones() {
364 return database.getRemoteSones();
368 * Returns the remote Sone with the given ID.
372 * The ID of the remote Sone to get
373 * @return The Sone with the given ID
375 public Sone getRemoteSone(String id) {
376 return database.getSone(id).orNull();
380 * Returns whether the given Sone has been modified.
383 * The Sone to check for modifications
384 * @return {@code true} if a modification has been detected in the Sone,
385 * {@code false} otherwise
387 public boolean isModifiedSone(Sone sone) {
388 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
392 * Returns the time when the given was first followed by any local Sone.
395 * The Sone to get the time for
396 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
397 * been followed, or {@link Long#MAX_VALUE}
399 public long getSoneFollowingTime(Sone sone) {
400 synchronized (soneFollowingTimes) {
401 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
406 * Returns a post builder.
408 * @return A new post builder
410 public PostBuilder postBuilder() {
411 return database.newPostBuilder();
418 public Optional<Post> getPost(String postId) {
419 return database.getPost(postId);
426 public Collection<Post> getPosts(String soneId) {
427 return database.getPosts(soneId);
434 public Collection<Post> getDirectedPosts(final String recipientId) {
435 checkNotNull(recipientId, "recipient must not be null");
436 return database.getDirectedPosts(recipientId);
440 * Returns a post reply builder.
442 * @return A new post reply builder
444 public PostReplyBuilder postReplyBuilder() {
445 return database.newPostReplyBuilder();
452 public Optional<PostReply> getPostReply(String replyId) {
453 return database.getPostReply(replyId);
460 public List<PostReply> getReplies(final String postId) {
461 return database.getReplies(postId);
465 * Returns all Sones that have liked the given post.
468 * The post to get the liking Sones for
469 * @return The Sones that like the given post
471 public Set<Sone> getLikes(Post post) {
472 Set<Sone> sones = new HashSet<Sone>();
473 for (Sone sone : getSones()) {
474 if (sone.getLikedPostIds().contains(post.getId())) {
482 * Returns all Sones that have liked the given reply.
485 * The reply to get the liking Sones for
486 * @return The Sones that like the given reply
488 public Set<Sone> getLikes(PostReply reply) {
489 Set<Sone> sones = new HashSet<Sone>();
490 for (Sone sone : getSones()) {
491 if (sone.getLikedReplyIds().contains(reply.getId())) {
499 * Returns whether the given post is bookmarked.
503 * @return {@code true} if the given post is bookmarked, {@code false}
506 public boolean isBookmarked(Post post) {
507 return database.isPostBookmarked(post);
511 * Returns all currently known bookmarked posts.
513 * @return All bookmarked posts
515 public Set<Post> getBookmarkedPosts() {
516 return database.getBookmarkedPosts();
519 public AlbumBuilder albumBuilder() {
520 return database.newAlbumBuilder();
524 * Returns the album with the given ID, optionally creating a new album if
525 * an album with the given ID can not be found.
528 * The ID of the album
529 * @return The album with the given ID, or {@code null} if no album with the
532 public Album getAlbum(String albumId) {
533 return database.getAlbum(albumId).orNull();
536 public ImageBuilder imageBuilder() {
537 return database.newImageBuilder();
541 * Returns the image with the given ID, creating it if necessary.
544 * The ID of the image
545 * @return The image with the given ID
547 public Image getImage(String imageId) {
548 return getImage(imageId, true);
552 * Returns the image with the given ID, optionally creating it if it does
556 * The ID of the image
558 * {@code true} to create an image if none exists with the given
560 * @return The image with the given ID, or {@code null} if none exists and
563 public Image getImage(String imageId, boolean create) {
564 Optional<Image> image = database.getImage(imageId);
565 if (image.isPresent()) {
571 Image newImage = database.newImageBuilder().withId(imageId).build();
572 database.storeImage(newImage);
577 * Returns the temporary image with the given ID.
580 * The ID of the temporary image
581 * @return The temporary image, or {@code null} if there is no temporary
582 * image with the given ID
584 public TemporaryImage getTemporaryImage(String imageId) {
585 synchronized (temporaryImages) {
586 return temporaryImages.get(imageId);
595 * Locks the given Sone. A locked Sone will not be inserted by
596 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
602 public void lockSone(Sone sone) {
603 synchronized (lockedSones) {
604 if (lockedSones.add(sone)) {
605 eventBus.post(new SoneLockedEvent(sone));
611 * Unlocks the given Sone.
613 * @see #lockSone(Sone)
617 public void unlockSone(Sone sone) {
618 synchronized (lockedSones) {
619 if (lockedSones.remove(sone)) {
620 eventBus.post(new SoneUnlockedEvent(sone));
626 * Adds a local Sone from the given own identity.
629 * The own identity to create a Sone from
630 * @return The added (or already existing) Sone
632 public Sone addLocalSone(OwnIdentity ownIdentity) {
633 if (ownIdentity == null) {
634 logger.log(Level.WARNING, "Given OwnIdentity is null!");
637 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
638 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
639 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), 0L));
640 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
642 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
643 eventBus.register(soneInserter);
644 synchronized (soneInserters) {
645 soneInserters.put(sone, soneInserter);
648 sone.setStatus(SoneStatus.idle);
649 soneInserter.start();
654 * Creates a new Sone for the given own identity.
657 * The own identity to create a Sone for
658 * @return The created Sone
660 public Sone createSone(OwnIdentity ownIdentity) {
661 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
662 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
665 Sone sone = addLocalSone(ownIdentity);
667 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
668 touchConfiguration();
673 * Adds the Sone of the given identity.
676 * The identity whose Sone to add
677 * @return The added or already existing Sone
679 public Sone addRemoteSone(Identity identity) {
680 if (identity == null) {
681 logger.log(Level.WARNING, "Given Identity is null!");
684 final Long latestEdition = tryParse(fromNullable(
685 identity.getProperty("Sone.LatestEdition")).or("0"));
686 Optional<Sone> existingSone = getSone(identity.getId());
687 if (existingSone.isPresent() && existingSone.get().isLocal()) {
688 return existingSone.get();
690 boolean newSone = !existingSone.isPresent();
691 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
692 sone.setLatestEdition(latestEdition);
694 synchronized (knownSones) {
695 newSone = !knownSones.contains(sone.getId());
697 sone.setKnown(!newSone);
699 eventBus.post(new NewSoneFoundEvent(sone));
700 for (Sone localSone : getLocalSones()) {
701 if (localSone.getOptions().isAutoFollow()) {
702 followSone(localSone, sone.getId());
707 database.storeSone(sone);
708 soneDownloader.addSone(sone);
709 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
714 * Lets the given local Sone follow the Sone with the given ID.
717 * The local Sone that should follow another Sone
719 * The ID of the Sone to follow
721 public void followSone(Sone sone, String soneId) {
722 checkNotNull(sone, "sone must not be null");
723 checkNotNull(soneId, "soneId must not be null");
724 sone.addFriend(soneId);
725 synchronized (soneFollowingTimes) {
726 if (!soneFollowingTimes.containsKey(soneId)) {
727 long now = System.currentTimeMillis();
728 soneFollowingTimes.put(soneId, now);
729 Optional<Sone> followedSone = getSone(soneId);
730 if (!followedSone.isPresent()) {
733 for (Post post : followedSone.get().getPosts()) {
734 if (post.getTime() < now) {
738 for (PostReply reply : followedSone.get().getReplies()) {
739 if (reply.getTime() < now) {
740 markReplyKnown(reply);
745 touchConfiguration();
749 * Lets the given local Sone unfollow the Sone with the given ID.
752 * The local Sone that should unfollow another Sone
754 * The ID of the Sone being unfollowed
756 public void unfollowSone(Sone sone, String soneId) {
757 checkNotNull(sone, "sone must not be null");
758 checkNotNull(soneId, "soneId must not be null");
759 sone.removeFriend(soneId);
760 boolean unfollowedSoneStillFollowed = false;
761 for (Sone localSone : getLocalSones()) {
762 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
764 if (!unfollowedSoneStillFollowed) {
765 synchronized (soneFollowingTimes) {
766 soneFollowingTimes.remove(soneId);
769 touchConfiguration();
773 * Sets the trust value of the given origin Sone for the target Sone.
780 * The trust value (from {@code -100} to {@code 100})
782 public void setTrust(Sone origin, Sone target, int trustValue) {
783 checkNotNull(origin, "origin must not be null");
784 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
785 checkNotNull(target, "target must not be null");
786 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
787 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
791 * Removes any trust assignment for the given target Sone.
798 public void removeTrust(Sone origin, Sone target) {
799 checkNotNull(origin, "origin must not be null");
800 checkNotNull(target, "target must not be null");
801 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
802 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
806 * Assigns the configured positive trust value for the given target.
813 public void trustSone(Sone origin, Sone target) {
814 setTrust(origin, target, preferences.getPositiveTrust());
818 * Assigns the configured negative trust value for the given target.
825 public void distrustSone(Sone origin, Sone target) {
826 setTrust(origin, target, preferences.getNegativeTrust());
830 * Removes the trust assignment for the given target.
837 public void untrustSone(Sone origin, Sone target) {
838 removeTrust(origin, target);
842 * Updates the stored Sone with the given Sone.
847 public void updateSone(Sone sone) {
848 updateSone(sone, false);
852 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
853 * {@code true}, an older Sone than the current Sone can be given to restore
858 * @param soneRescueMode
859 * {@code true} if the stored Sone should be updated regardless
860 * of the age of the given Sone
862 public void updateSone(final Sone sone, boolean soneRescueMode) {
863 Optional<Sone> storedSone = getSone(sone.getId());
864 if (storedSone.isPresent()) {
865 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
866 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
869 /* find removed posts. */
870 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
871 soneChangeDetector.onNewPosts(new PostProcessor() {
873 public void processPost(Post post) {
874 if (post.getTime() < getSoneFollowingTime(sone)) {
876 } else if (!post.isKnown()) {
877 eventBus.post(new NewPostFoundEvent(post));
881 soneChangeDetector.onRemovedPosts(new PostProcessor() {
883 public void processPost(Post post) {
884 eventBus.post(new PostRemovedEvent(post));
887 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
889 public void processPostReply(PostReply postReply) {
890 if (postReply.getTime() < getSoneFollowingTime(sone)) {
891 postReply.setKnown(true);
892 } else if (!postReply.isKnown()) {
893 eventBus.post(new NewPostReplyFoundEvent(postReply));
897 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
899 public void processPostReply(PostReply postReply) {
900 eventBus.post(new PostReplyRemovedEvent(postReply));
903 soneChangeDetector.detectChanges(sone);
904 database.storeSone(sone);
905 sone.setOptions(storedSone.get().getOptions());
906 sone.setKnown(storedSone.get().isKnown());
907 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
908 if (sone.isLocal()) {
909 touchConfiguration();
915 * Deletes the given Sone. This will remove the Sone from the
916 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
917 * remove the context from its identity.
922 public void deleteSone(Sone sone) {
923 if (!(sone.getIdentity() instanceof OwnIdentity)) {
924 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
927 if (!getLocalSones().contains(sone)) {
928 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
931 // FIXME – implement in database
932 // sones.remove(sone.getId());
933 SoneInserter soneInserter = soneInserters.remove(sone);
935 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
936 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
938 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
939 } catch (ConfigurationException ce1) {
940 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
945 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
946 * known} before, a {@link MarkSoneKnownEvent} is fired.
949 * The Sone to mark as known
951 public void markSoneKnown(Sone sone) {
952 if (!sone.isKnown()) {
954 synchronized (knownSones) {
955 knownSones.add(sone.getId());
957 eventBus.post(new MarkSoneKnownEvent(sone));
958 touchConfiguration();
963 * Loads and updates the given Sone from the configuration. If any error is
964 * encountered, loading is aborted and the given Sone is not changed.
967 * The Sone to load and update
969 public void loadSone(Sone sone) {
970 if (!sone.isLocal()) {
971 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
974 logger.info(String.format("Loading local Sone: %s", sone));
977 String sonePrefix = "Sone/" + sone.getId();
978 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
979 if (soneTime == null) {
980 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
983 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
986 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
987 Profile profile = configurationSoneParser.parseProfile();
990 Collection<Post> posts;
992 posts = configurationSoneParser.parsePosts(database);
993 } catch (InvalidPostFound ipf) {
994 logger.log(Level.WARNING, "Invalid post found, aborting load!");
999 Collection<PostReply> replies;
1001 replies = configurationSoneParser.parsePostReplies(database);
1002 } catch (InvalidPostReplyFound iprf) {
1003 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1007 /* load post likes. */
1008 Set<String> likedPostIds =
1009 configurationSoneParser.parseLikedPostIds();
1011 /* load reply likes. */
1012 Set<String> likedReplyIds =
1013 configurationSoneParser.parseLikedPostReplyIds();
1016 Set<String> friends = configurationSoneParser.parseFriends();
1019 List<Album> topLevelAlbums;
1022 configurationSoneParser.parseTopLevelAlbums(database);
1023 } catch (InvalidAlbumFound iaf) {
1024 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1026 } catch (InvalidParentAlbumFound ipaf) {
1027 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1028 ipaf.getAlbumParentId()));
1034 configurationSoneParser.parseImages(database);
1035 } catch (InvalidImageFound iif) {
1036 logger.log(WARNING, "Invalid image found, aborting load!");
1038 } catch (InvalidParentAlbumFound ipaf) {
1039 logger.log(Level.WARNING,
1040 format("Invalid album image (%s) encountered, aborting load!",
1041 ipaf.getAlbumParentId()));
1046 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1047 if (avatarId != null) {
1048 final Map<String, Image> images =
1049 configurationSoneParser.getImages();
1050 profile.setAvatar(images.get(avatarId));
1054 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1055 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1056 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1057 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1058 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1059 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1061 /* if we’re still here, Sone was loaded successfully. */
1062 synchronized (sone) {
1063 sone.setTime(soneTime);
1064 sone.setProfile(profile);
1065 sone.setPosts(posts);
1066 sone.setReplies(replies);
1067 sone.setLikePostIds(likedPostIds);
1068 sone.setLikeReplyIds(likedReplyIds);
1069 for (String friendId : friends) {
1070 followSone(sone, friendId);
1072 for (Album album : sone.getRootAlbum().getAlbums()) {
1073 sone.getRootAlbum().removeAlbum(album);
1075 for (Album album : topLevelAlbums) {
1076 sone.getRootAlbum().addAlbum(album);
1078 database.storeSone(sone);
1079 synchronized (soneInserters) {
1080 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1083 synchronized (knownSones) {
1084 for (String friend : friends) {
1085 knownSones.add(friend);
1088 for (Post post : posts) {
1089 post.setKnown(true);
1091 for (PostReply reply : replies) {
1092 reply.setKnown(true);
1095 logger.info(String.format("Sone loaded successfully: %s", sone));
1099 * Creates a new post.
1102 * The Sone that creates the post
1104 * The recipient Sone, or {@code null} if this post does not have
1107 * The text of the post
1108 * @return The created post
1110 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1111 return createPost(sone, recipient, System.currentTimeMillis(), text);
1115 * Creates a new post.
1118 * The Sone that creates the post
1120 * The recipient Sone, or {@code null} if this post does not have
1123 * The time of the post
1125 * The text of the post
1126 * @return The created post
1128 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1129 checkNotNull(text, "text must not be null");
1130 checkArgument(text.trim().length() > 0, "text must not be empty");
1131 if (!sone.isLocal()) {
1132 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1135 PostBuilder postBuilder = database.newPostBuilder();
1136 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1137 if (recipient.isPresent()) {
1138 postBuilder.to(recipient.get().getId());
1140 final Post post = postBuilder.build();
1141 database.storePost(post);
1142 eventBus.post(new NewPostFoundEvent(post));
1144 touchConfiguration();
1145 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1150 * Deletes the given post.
1153 * The post to delete
1155 public void deletePost(Post post) {
1156 if (!post.getSone().isLocal()) {
1157 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1160 database.removePost(post);
1161 eventBus.post(new PostRemovedEvent(post));
1162 markPostKnown(post);
1163 touchConfiguration();
1167 * Marks the given post as known, if it is currently not a known post
1168 * (according to {@link Post#isKnown()}).
1171 * The post to mark as known
1173 public void markPostKnown(Post post) {
1174 post.setKnown(true);
1175 eventBus.post(new MarkPostKnownEvent(post));
1176 touchConfiguration();
1177 for (PostReply reply : getReplies(post.getId())) {
1178 markReplyKnown(reply);
1182 public void bookmarkPost(Post post) {
1183 database.bookmarkPost(post);
1187 * Removes the given post from the bookmarks.
1190 * The post to unbookmark
1192 public void unbookmarkPost(Post post) {
1193 database.unbookmarkPost(post);
1197 * Creates a new reply.
1200 * The Sone that creates the reply
1202 * The post that this reply refers to
1204 * The text of the reply
1205 * @return The created reply
1207 public PostReply createReply(Sone sone, Post post, String text) {
1208 checkNotNull(text, "text must not be null");
1209 checkArgument(text.trim().length() > 0, "text must not be empty");
1210 if (!sone.isLocal()) {
1211 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1214 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1215 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1216 final PostReply reply = postReplyBuilder.build();
1217 database.storePostReply(reply);
1218 eventBus.post(new NewPostReplyFoundEvent(reply));
1219 sone.addReply(reply);
1220 touchConfiguration();
1221 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1226 * Deletes the given reply.
1229 * The reply to delete
1231 public void deleteReply(PostReply reply) {
1232 Sone sone = reply.getSone();
1233 if (!sone.isLocal()) {
1234 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1237 database.removePostReply(reply);
1238 markReplyKnown(reply);
1239 sone.removeReply(reply);
1240 touchConfiguration();
1244 * Marks the given reply as known, if it is currently not a known reply
1245 * (according to {@link Reply#isKnown()}).
1248 * The reply to mark as known
1250 public void markReplyKnown(PostReply reply) {
1251 boolean previouslyKnown = reply.isKnown();
1252 reply.setKnown(true);
1253 eventBus.post(new MarkPostReplyKnownEvent(reply));
1254 if (!previouslyKnown) {
1255 touchConfiguration();
1260 * Creates a new album for the given Sone.
1263 * The Sone to create the album for
1265 * The parent of the album (may be {@code null} to create a
1267 * @return The new album
1269 public Album createAlbum(Sone sone, Album parent) {
1270 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1271 database.storeAlbum(album);
1272 parent.addAlbum(album);
1277 * Deletes the given album. The owner of the album has to be a local Sone,
1278 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1281 * The album to remove
1283 public void deleteAlbum(Album album) {
1284 checkNotNull(album, "album must not be null");
1285 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1286 if (!album.isEmpty()) {
1289 album.getParent().removeAlbum(album);
1290 database.removeAlbum(album);
1291 touchConfiguration();
1295 * Creates a new image.
1298 * The Sone creating the image
1300 * The album the image will be inserted into
1301 * @param temporaryImage
1302 * The temporary image to create the image from
1303 * @return The newly created image
1305 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1306 checkNotNull(sone, "sone must not be null");
1307 checkNotNull(album, "album must not be null");
1308 checkNotNull(temporaryImage, "temporaryImage must not be null");
1309 checkArgument(sone.isLocal(), "sone must be a local Sone");
1310 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1311 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1312 album.addImage(image);
1313 database.storeImage(image);
1314 imageInserter.insertImage(temporaryImage, image);
1319 * Deletes the given image. This method will also delete a matching
1322 * @see #deleteTemporaryImage(String)
1324 * The image to delete
1326 public void deleteImage(Image image) {
1327 checkNotNull(image, "image must not be null");
1328 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1329 deleteTemporaryImage(image.getId());
1330 image.getAlbum().removeImage(image);
1331 database.removeImage(image);
1332 touchConfiguration();
1336 * Creates a new temporary image.
1339 * The MIME type of the temporary image
1341 * The encoded data of the image
1342 * @return The temporary image
1344 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1345 TemporaryImage temporaryImage = new TemporaryImage();
1346 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1347 synchronized (temporaryImages) {
1348 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1350 return temporaryImage;
1354 * Deletes the temporary image with the given ID.
1357 * The ID of the temporary image to delete
1359 public void deleteTemporaryImage(String imageId) {
1360 checkNotNull(imageId, "imageId must not be null");
1361 synchronized (temporaryImages) {
1362 temporaryImages.remove(imageId);
1364 Image image = getImage(imageId, false);
1365 if (image != null) {
1366 imageInserter.cancelImageInsert(image);
1371 * Notifies the core that the configuration, either of the core or of a
1372 * single local Sone, has changed, and that the configuration should be
1375 public void touchConfiguration() {
1376 lastConfigurationUpdate = System.currentTimeMillis();
1387 public void serviceStart() {
1388 loadConfiguration();
1389 updateChecker.start();
1390 identityManager.start();
1391 webOfTrustUpdater.init();
1392 webOfTrustUpdater.start();
1400 public void serviceRun() {
1401 long lastSaved = System.currentTimeMillis();
1402 while (!shouldStop()) {
1404 long now = System.currentTimeMillis();
1405 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1406 for (Sone localSone : getLocalSones()) {
1407 saveSone(localSone);
1409 saveConfiguration();
1419 public void serviceStop() {
1420 localElementTicker.shutdownNow();
1421 synchronized (soneInserters) {
1422 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1423 soneInserter.getValue().stop();
1424 saveSone(soneInserter.getKey());
1427 saveConfiguration();
1429 webOfTrustUpdater.stop();
1430 updateChecker.stop();
1431 soneDownloader.stop();
1432 soneDownloaders.shutdown();
1433 identityManager.stop();
1441 * Saves the given Sone. This will persist all local settings for the given
1442 * Sone, such as the friends list and similar, private options.
1447 private synchronized void saveSone(Sone sone) {
1448 if (!sone.isLocal()) {
1449 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1452 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1453 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1457 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1459 /* save Sone into configuration. */
1460 String sonePrefix = "Sone/" + sone.getId();
1461 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1462 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1465 Profile profile = sone.getProfile();
1466 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1467 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1468 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1469 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1470 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1471 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1472 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1474 /* save profile fields. */
1475 int fieldCounter = 0;
1476 for (Field profileField : profile.getFields()) {
1477 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1478 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1479 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1481 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1484 int postCounter = 0;
1485 for (Post post : sone.getPosts()) {
1486 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1487 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1488 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1489 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1490 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1492 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1495 int replyCounter = 0;
1496 for (PostReply reply : sone.getReplies()) {
1497 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1498 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1499 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1500 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1501 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1503 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1505 /* save post likes. */
1506 int postLikeCounter = 0;
1507 for (String postId : sone.getLikedPostIds()) {
1508 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1510 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1512 /* save reply likes. */
1513 int replyLikeCounter = 0;
1514 for (String replyId : sone.getLikedReplyIds()) {
1515 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1517 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1520 int friendCounter = 0;
1521 for (String friendId : sone.getFriends()) {
1522 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1524 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1526 /* save albums. first, collect in a flat structure, top-level first. */
1527 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1529 int albumCounter = 0;
1530 for (Album album : albums) {
1531 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1532 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1533 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1534 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1535 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1536 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1538 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1541 int imageCounter = 0;
1542 for (Album album : albums) {
1543 for (Image image : album.getImages()) {
1544 if (!image.isInserted()) {
1547 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1548 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1549 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1550 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1551 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1552 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1553 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1554 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1555 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1558 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1561 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1562 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1563 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1564 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1565 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1566 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1568 configuration.save();
1570 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1572 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1573 } catch (ConfigurationException ce1) {
1574 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1579 * Saves the current options.
1581 private void saveConfiguration() {
1582 synchronized (configuration) {
1583 if (storingConfiguration) {
1584 logger.log(Level.FINE, "Already storing configuration…");
1587 storingConfiguration = true;
1590 /* store the options first. */
1592 preferences.saveTo(configuration);
1594 /* save known Sones. */
1595 int soneCounter = 0;
1596 synchronized (knownSones) {
1597 for (String knownSoneId : knownSones) {
1598 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1600 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1603 /* save Sone following times. */
1605 synchronized (soneFollowingTimes) {
1606 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1607 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1608 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1611 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1614 /* save known posts. */
1617 /* save bookmarked posts. */
1618 int bookmarkedPostCounter = 0;
1619 for (Post bookmarkedPost : getBookmarkedPosts()) {
1620 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPost.getId());
1622 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1625 configuration.save();
1627 } catch (ConfigurationException ce1) {
1628 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1629 } catch (DatabaseException de1) {
1630 logger.log(Level.SEVERE, "Could not save database!", de1);
1632 synchronized (configuration) {
1633 storingConfiguration = false;
1639 * Loads the configuration.
1641 private void loadConfiguration() {
1642 new PreferencesLoader(preferences).loadFrom(configuration);
1644 /* load known Sones. */
1645 int soneCounter = 0;
1647 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1648 if (knownSoneId == null) {
1651 synchronized (knownSones) {
1652 knownSones.add(knownSoneId);
1656 /* load Sone following times. */
1659 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1660 if (soneId == null) {
1663 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1664 synchronized (soneFollowingTimes) {
1665 soneFollowingTimes.put(soneId, time);
1670 /* load bookmarked posts. */
1671 int bookmarkedPostCounter = 0;
1673 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1674 if (bookmarkedPostId == null) {
1677 database.bookmarkPost(bookmarkedPostId);
1683 * Notifies the core that a new {@link OwnIdentity} was added.
1685 * @param ownIdentityAddedEvent
1689 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1690 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1691 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1692 if (ownIdentity.hasContext("Sone")) {
1693 addLocalSone(ownIdentity);
1698 * Notifies the core that an {@link OwnIdentity} was removed.
1700 * @param ownIdentityRemovedEvent
1704 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1705 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1706 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1707 trustedIdentities.removeAll(ownIdentity);
1711 * Notifies the core that a new {@link Identity} was added.
1713 * @param identityAddedEvent
1717 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1718 Identity identity = identityAddedEvent.identity();
1719 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1720 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1721 addRemoteSone(identity);
1725 * Notifies the core that an {@link Identity} was updated.
1727 * @param identityUpdatedEvent
1731 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1732 Identity identity = identityUpdatedEvent.identity();
1733 final Sone sone = getRemoteSone(identity.getId());
1734 if (sone.isLocal()) {
1737 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1738 soneDownloader.addSone(sone);
1739 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1743 * Notifies the core that an {@link Identity} was removed.
1745 * @param identityRemovedEvent
1749 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1750 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1751 Identity identity = identityRemovedEvent.identity();
1752 trustedIdentities.remove(ownIdentity, identity);
1753 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1754 if (trustedIdentity.getKey().equals(ownIdentity)) {
1757 if (trustedIdentity.getValue().contains(identity)) {
1761 Optional<Sone> sone = getSone(identity.getId());
1762 if (!sone.isPresent()) {
1763 /* TODO - we don’t have the Sone anymore. should this happen? */
1766 database.removePosts(sone.get());
1767 for (Post post : sone.get().getPosts()) {
1768 eventBus.post(new PostRemovedEvent(post));
1770 database.removePostReplies(sone.get());
1771 for (PostReply reply : sone.get().getReplies()) {
1772 eventBus.post(new PostReplyRemovedEvent(reply));
1774 // TODO – implement in database
1775 // sones.remove(identity.getId());
1776 eventBus.post(new SoneRemovedEvent(sone.get()));
1780 * Deletes the temporary image.
1782 * @param imageInsertFinishedEvent
1786 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1787 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1788 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1789 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1790 touchConfiguration();
1794 class MarkPostKnown implements Runnable {
1796 private final Post post;
1798 public MarkPostKnown(Post post) {
1804 markPostKnown(post);
1810 class MarkReplyKnown implements Runnable {
1812 private final PostReply postReply;
1814 public MarkReplyKnown(PostReply postReply) {
1815 this.postReply = postReply;
1820 markReplyKnown(postReply);