2 * Sone - Core.java - Copyright © 2010–2016 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static java.util.logging.Logger.getLogger;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import javax.annotation.Nonnull;
44 import javax.annotation.Nullable;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
51 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
52 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
53 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
54 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
55 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
56 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
57 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
58 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
59 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
60 import net.pterodactylus.sone.core.event.PostRemovedEvent;
61 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneLockedEvent;
63 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
64 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
65 import net.pterodactylus.sone.data.Album;
66 import net.pterodactylus.sone.data.Client;
67 import net.pterodactylus.sone.data.Image;
68 import net.pterodactylus.sone.data.Post;
69 import net.pterodactylus.sone.data.PostReply;
70 import net.pterodactylus.sone.data.Profile;
71 import net.pterodactylus.sone.data.Profile.Field;
72 import net.pterodactylus.sone.data.Reply;
73 import net.pterodactylus.sone.data.Sone;
74 import net.pterodactylus.sone.data.Sone.SoneStatus;
75 import net.pterodactylus.sone.data.SoneOptions.LoadExternalContent;
76 import net.pterodactylus.sone.data.TemporaryImage;
77 import net.pterodactylus.sone.database.AlbumBuilder;
78 import net.pterodactylus.sone.database.Database;
79 import net.pterodactylus.sone.database.DatabaseException;
80 import net.pterodactylus.sone.database.ImageBuilder;
81 import net.pterodactylus.sone.database.PostBuilder;
82 import net.pterodactylus.sone.database.PostProvider;
83 import net.pterodactylus.sone.database.PostReplyBuilder;
84 import net.pterodactylus.sone.database.PostReplyProvider;
85 import net.pterodactylus.sone.database.SoneBuilder;
86 import net.pterodactylus.sone.database.SoneProvider;
87 import net.pterodactylus.sone.freenet.wot.Identity;
88 import net.pterodactylus.sone.freenet.wot.IdentityManager;
89 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
95 import net.pterodactylus.sone.main.SonePlugin;
96 import net.pterodactylus.util.config.Configuration;
97 import net.pterodactylus.util.config.ConfigurationException;
98 import net.pterodactylus.util.service.AbstractService;
99 import net.pterodactylus.util.thread.NamedThreadFactory;
101 import com.google.common.annotations.VisibleForTesting;
102 import com.google.common.base.Optional;
103 import com.google.common.collect.FluentIterable;
104 import com.google.common.collect.HashMultimap;
105 import com.google.common.collect.Multimap;
106 import com.google.common.collect.Multimaps;
107 import com.google.common.eventbus.EventBus;
108 import com.google.common.eventbus.Subscribe;
109 import com.google.inject.Inject;
110 import com.google.inject.Singleton;
111 import kotlin.jvm.functions.Function1;
116 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
119 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
122 private static final Logger logger = getLogger(Core.class.getName());
124 /** The start time. */
125 private final long startupTime = System.currentTimeMillis();
127 /** The preferences. */
128 private final Preferences preferences;
130 /** The event bus. */
131 private final EventBus eventBus;
133 /** The configuration. */
134 private final Configuration configuration;
136 /** Whether we’re currently saving the configuration. */
137 private boolean storingConfiguration = false;
139 /** The identity manager. */
140 private final IdentityManager identityManager;
142 /** Interface to freenet. */
143 private final FreenetInterface freenetInterface;
145 /** The Sone downloader. */
146 private final SoneDownloader soneDownloader;
148 /** The image inserter. */
149 private final ImageInserter imageInserter;
151 /** Sone downloader thread-pool. */
152 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
154 /** The update checker. */
155 private final UpdateChecker updateChecker;
157 /** The trust updater. */
158 private final WebOfTrustUpdater webOfTrustUpdater;
160 /** The times Sones were followed. */
161 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163 /** Locked local Sones. */
164 /* synchronize on itself. */
165 private final Set<Sone> lockedSones = new HashSet<Sone>();
167 /** Sone inserters. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171 /** Sone rescuers. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175 /** All known Sones. */
176 private final Set<String> knownSones = new HashSet<String>();
178 /** The post database. */
179 private final Database database;
181 /** Trusted identities, sorted by own identities. */
182 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
184 /** All temporary images. */
185 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
187 /** Ticker for threads that mark own elements as known. */
188 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
190 /** The time the configuration was last touched. */
191 private volatile long lastConfigurationUpdate;
194 * Creates a new core.
196 * @param configuration
197 * The configuration of the core
198 * @param freenetInterface
199 * The freenet interface
200 * @param identityManager
201 * The identity manager
202 * @param webOfTrustUpdater
203 * The WebOfTrust updater
210 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
212 this.configuration = configuration;
213 this.freenetInterface = freenetInterface;
214 this.identityManager = identityManager;
215 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
216 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
217 this.updateChecker = updateChecker;
218 this.webOfTrustUpdater = webOfTrustUpdater;
219 this.eventBus = eventBus;
220 this.database = database;
221 preferences = new Preferences(eventBus);
225 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
227 this.configuration = configuration;
228 this.freenetInterface = freenetInterface;
229 this.identityManager = identityManager;
230 this.soneDownloader = soneDownloader;
231 this.imageInserter = imageInserter;
232 this.updateChecker = updateChecker;
233 this.webOfTrustUpdater = webOfTrustUpdater;
234 this.eventBus = eventBus;
235 this.database = database;
236 preferences = new Preferences(eventBus);
244 * Returns the time Sone was started.
246 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
248 public long getStartupTime() {
253 * Returns the options used by the core.
255 * @return The options of the core
257 public Preferences getPreferences() {
262 * Returns the identity manager used by the core.
264 * @return The identity manager
266 public IdentityManager getIdentityManager() {
267 return identityManager;
271 * Returns the update checker.
273 * @return The update checker
275 public UpdateChecker getUpdateChecker() {
276 return updateChecker;
280 * Returns the Sone rescuer for the given local Sone.
283 * The local Sone to get the rescuer for
284 * @return The Sone rescuer for the given Sone
286 public SoneRescuer getSoneRescuer(Sone sone) {
287 checkNotNull(sone, "sone must not be null");
288 checkArgument(sone.isLocal(), "sone must be local");
289 synchronized (soneRescuers) {
290 SoneRescuer soneRescuer = soneRescuers.get(sone);
291 if (soneRescuer == null) {
292 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
293 soneRescuers.put(sone, soneRescuer);
301 * Returns whether the given Sone is currently locked.
305 * @return {@code true} if the Sone is locked, {@code false} if it is not
307 public boolean isLocked(Sone sone) {
308 synchronized (lockedSones) {
309 return lockedSones.contains(sone);
313 public SoneBuilder soneBuilder() {
314 return database.newSoneBuilder();
322 public Collection<Sone> getSones() {
323 return database.getSones();
328 public Function1<String, Sone> getSoneLoader() {
329 return database.getSoneLoader();
333 * Returns the Sone with the given ID, regardless whether it’s local or
337 * The ID of the Sone to get
338 * @return The Sone with the given ID, or {@code null} if there is no such
343 public Sone getSone(@Nonnull String id) {
344 return database.getSone(id);
351 public Collection<Sone> getLocalSones() {
352 return database.getLocalSones();
356 * Returns the local Sone with the given ID, optionally creating a new Sone.
360 * @return The Sone with the given ID, or {@code null}
362 public Sone getLocalSone(String id) {
363 Sone sone = database.getSone(id);
364 if ((sone != null) && sone.isLocal()) {
374 public Collection<Sone> getRemoteSones() {
375 return database.getRemoteSones();
379 * Returns the remote Sone with the given ID.
383 * The ID of the remote Sone to get
384 * @return The Sone with the given ID
386 public Sone getRemoteSone(String id) {
387 return database.getSone(id);
391 * Returns whether the given Sone has been modified.
394 * The Sone to check for modifications
395 * @return {@code true} if a modification has been detected in the Sone,
396 * {@code false} otherwise
398 public boolean isModifiedSone(Sone sone) {
399 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
403 * Returns the time when the given was first followed by any local Sone.
406 * The Sone to get the time for
407 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
408 * been followed, or {@link Long#MAX_VALUE}
410 public long getSoneFollowingTime(Sone sone) {
411 synchronized (soneFollowingTimes) {
412 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
417 * Returns a post builder.
419 * @return A new post builder
421 public PostBuilder postBuilder() {
422 return database.newPostBuilder();
429 public Optional<Post> getPost(String postId) {
430 return database.getPost(postId);
437 public Collection<Post> getPosts(String soneId) {
438 return database.getPosts(soneId);
445 public Collection<Post> getDirectedPosts(final String recipientId) {
446 checkNotNull(recipientId, "recipient must not be null");
447 return database.getDirectedPosts(recipientId);
451 * Returns a post reply builder.
453 * @return A new post reply builder
455 public PostReplyBuilder postReplyBuilder() {
456 return database.newPostReplyBuilder();
464 public PostReply getPostReply(String replyId) {
465 return database.getPostReply(replyId);
472 public List<PostReply> getReplies(final String postId) {
473 return database.getReplies(postId);
477 * Returns all Sones that have liked the given post.
480 * The post to get the liking Sones for
481 * @return The Sones that like the given post
483 public Set<Sone> getLikes(Post post) {
484 Set<Sone> sones = new HashSet<Sone>();
485 for (Sone sone : getSones()) {
486 if (sone.getLikedPostIds().contains(post.getId())) {
494 * Returns all Sones that have liked the given reply.
497 * The reply to get the liking Sones for
498 * @return The Sones that like the given reply
500 public Set<Sone> getLikes(PostReply reply) {
501 Set<Sone> sones = new HashSet<Sone>();
502 for (Sone sone : getSones()) {
503 if (sone.getLikedReplyIds().contains(reply.getId())) {
511 * Returns whether the given post is bookmarked.
515 * @return {@code true} if the given post is bookmarked, {@code false}
518 public boolean isBookmarked(Post post) {
519 return database.isPostBookmarked(post);
523 * Returns all currently known bookmarked posts.
525 * @return All bookmarked posts
527 public Set<Post> getBookmarkedPosts() {
528 return database.getBookmarkedPosts();
531 public AlbumBuilder albumBuilder() {
532 return database.newAlbumBuilder();
536 * Returns the album with the given ID, optionally creating a new album if
537 * an album with the given ID can not be found.
540 * The ID of the album
541 * @return The album with the given ID, or {@code null} if no album with the
545 public Album getAlbum(@Nonnull String albumId) {
546 return database.getAlbum(albumId).orNull();
549 public ImageBuilder imageBuilder() {
550 return database.newImageBuilder();
554 * Returns the image with the given ID, creating it if necessary.
557 * The ID of the image
558 * @return The image with the given ID
561 public Image getImage(String imageId) {
562 return getImage(imageId, true);
566 * Returns the image with the given ID, optionally creating it if it does
570 * The ID of the image
572 * {@code true} to create an image if none exists with the given
574 * @return The image with the given ID, or {@code null} if none exists and
578 public Image getImage(String imageId, boolean create) {
579 Image image = database.getImage(imageId);
586 Image newImage = database.newImageBuilder().withId(imageId).build();
587 database.storeImage(newImage);
592 * Returns the temporary image with the given ID.
595 * The ID of the temporary image
596 * @return The temporary image, or {@code null} if there is no temporary
597 * image with the given ID
599 public TemporaryImage getTemporaryImage(String imageId) {
600 synchronized (temporaryImages) {
601 return temporaryImages.get(imageId);
610 * Locks the given Sone. A locked Sone will not be inserted by
611 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
617 public void lockSone(Sone sone) {
618 synchronized (lockedSones) {
619 if (lockedSones.add(sone)) {
620 eventBus.post(new SoneLockedEvent(sone));
626 * Unlocks the given Sone.
628 * @see #lockSone(Sone)
632 public void unlockSone(Sone sone) {
633 synchronized (lockedSones) {
634 if (lockedSones.remove(sone)) {
635 eventBus.post(new SoneUnlockedEvent(sone));
641 * Adds a local Sone from the given own identity.
644 * The own identity to create a Sone from
645 * @return The added (or already existing) Sone
647 public Sone addLocalSone(OwnIdentity ownIdentity) {
648 if (ownIdentity == null) {
649 logger.log(Level.WARNING, "Given OwnIdentity is null!");
652 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
653 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
654 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
655 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
656 sone.setClient(new Client("Sone", SonePlugin.getPluginVersion()));
658 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
659 eventBus.register(soneInserter);
660 synchronized (soneInserters) {
661 soneInserters.put(sone, soneInserter);
664 database.storeSone(sone);
665 sone.setStatus(SoneStatus.idle);
666 soneInserter.start();
671 * Creates a new Sone for the given own identity.
674 * The own identity to create a Sone for
675 * @return The created Sone
677 public Sone createSone(OwnIdentity ownIdentity) {
678 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
679 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
682 Sone sone = addLocalSone(ownIdentity);
684 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
685 touchConfiguration();
690 * Adds the Sone of the given identity.
693 * The identity whose Sone to add
694 * @return The added or already existing Sone
696 public Sone addRemoteSone(Identity identity) {
697 if (identity == null) {
698 logger.log(Level.WARNING, "Given Identity is null!");
701 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
702 long latestEdition = fromNullable(tryParse(property)).or(0L);
703 Sone existingSone = getSone(identity.getId());
704 if ((existingSone != null )&& existingSone.isLocal()) {
707 boolean newSone = existingSone == null;
708 Sone sone = !newSone ? existingSone : database.newSoneBuilder().from(identity).build();
709 sone.setLatestEdition(latestEdition);
711 synchronized (knownSones) {
712 newSone = !knownSones.contains(sone.getId());
714 sone.setKnown(!newSone);
716 eventBus.post(new NewSoneFoundEvent(sone));
717 for (Sone localSone : getLocalSones()) {
718 if (localSone.getOptions().isAutoFollow()) {
719 followSone(localSone, sone.getId());
724 database.storeSone(sone);
725 soneDownloader.addSone(sone);
726 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
731 * Lets the given local Sone follow the Sone with the given ID.
734 * The local Sone that should follow another Sone
736 * The ID of the Sone to follow
738 public void followSone(Sone sone, String soneId) {
739 checkNotNull(sone, "sone must not be null");
740 checkNotNull(soneId, "soneId must not be null");
741 database.addFriend(sone, soneId);
742 synchronized (soneFollowingTimes) {
743 if (!soneFollowingTimes.containsKey(soneId)) {
744 long now = System.currentTimeMillis();
745 soneFollowingTimes.put(soneId, now);
746 Sone followedSone = getSone(soneId);
747 if (followedSone == null) {
750 for (Post post : followedSone.getPosts()) {
751 if (post.getTime() < now) {
755 for (PostReply reply : followedSone.getReplies()) {
756 if (reply.getTime() < now) {
757 markReplyKnown(reply);
762 touchConfiguration();
766 * Lets the given local Sone unfollow the Sone with the given ID.
769 * The local Sone that should unfollow another Sone
771 * The ID of the Sone being unfollowed
773 public void unfollowSone(Sone sone, String soneId) {
774 checkNotNull(sone, "sone must not be null");
775 checkNotNull(soneId, "soneId must not be null");
776 database.removeFriend(sone, soneId);
777 boolean unfollowedSoneStillFollowed = false;
778 for (Sone localSone : getLocalSones()) {
779 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
781 if (!unfollowedSoneStillFollowed) {
782 synchronized (soneFollowingTimes) {
783 soneFollowingTimes.remove(soneId);
786 touchConfiguration();
790 * Sets the trust value of the given origin Sone for the target Sone.
797 * The trust value (from {@code -100} to {@code 100})
799 public void setTrust(Sone origin, Sone target, int trustValue) {
800 checkNotNull(origin, "origin must not be null");
801 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
802 checkNotNull(target, "target must not be null");
803 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
804 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
808 * Removes any trust assignment for the given target Sone.
815 public void removeTrust(Sone origin, Sone target) {
816 checkNotNull(origin, "origin must not be null");
817 checkNotNull(target, "target must not be null");
818 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
819 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
823 * Assigns the configured positive trust value for the given target.
830 public void trustSone(Sone origin, Sone target) {
831 setTrust(origin, target, preferences.getPositiveTrust());
835 * Assigns the configured negative trust value for the given target.
842 public void distrustSone(Sone origin, Sone target) {
843 setTrust(origin, target, preferences.getNegativeTrust());
847 * Removes the trust assignment for the given target.
854 public void untrustSone(Sone origin, Sone target) {
855 removeTrust(origin, target);
859 * Updates the stored Sone with the given Sone.
864 public void updateSone(Sone sone) {
865 updateSone(sone, false);
869 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
870 * {@code true}, an older Sone than the current Sone can be given to restore
875 * @param soneRescueMode
876 * {@code true} if the stored Sone should be updated regardless
877 * of the age of the given Sone
879 public void updateSone(final Sone sone, boolean soneRescueMode) {
880 Sone storedSone = getSone(sone.getId());
881 if (storedSone != null) {
882 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
883 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
886 List<Object> events =
887 collectEventsForChangesInSone(storedSone, sone);
888 database.storeSone(sone);
889 for (Object event : events) {
890 eventBus.post(event);
892 sone.setOptions(storedSone.getOptions());
893 sone.setKnown(storedSone.isKnown());
894 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
895 if (sone.isLocal()) {
896 touchConfiguration();
901 private List<Object> collectEventsForChangesInSone(Sone oldSone,
902 final Sone newSone) {
903 final List<Object> events = new ArrayList<Object>();
904 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
906 soneChangeDetector.onNewPosts(new PostProcessor() {
908 public void processPost(Post post) {
909 if (post.getTime() < getSoneFollowingTime(newSone)) {
911 } else if (!post.isKnown()) {
912 events.add(new NewPostFoundEvent(post));
916 soneChangeDetector.onRemovedPosts(new PostProcessor() {
918 public void processPost(Post post) {
919 events.add(new PostRemovedEvent(post));
922 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
924 public void processPostReply(PostReply postReply) {
925 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
926 postReply.setKnown(true);
927 } else if (!postReply.isKnown()) {
928 events.add(new NewPostReplyFoundEvent(postReply));
932 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
934 public void processPostReply(PostReply postReply) {
935 events.add(new PostReplyRemovedEvent(postReply));
938 soneChangeDetector.detectChanges(newSone);
943 * Deletes the given Sone. This will remove the Sone from the
944 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
945 * remove the context from its identity.
950 public void deleteSone(Sone sone) {
951 if (!(sone.getIdentity() instanceof OwnIdentity)) {
952 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
955 if (!getLocalSones().contains(sone)) {
956 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
959 SoneInserter soneInserter = soneInserters.remove(sone);
961 database.removeSone(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 List<Album> topLevelAlbums;
1046 configurationSoneParser.parseTopLevelAlbums(database);
1047 } catch (InvalidAlbumFound iaf) {
1048 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1050 } catch (InvalidParentAlbumFound ipaf) {
1051 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1052 ipaf.getAlbumParentId()));
1058 configurationSoneParser.parseImages(database);
1059 } catch (InvalidImageFound iif) {
1060 logger.log(WARNING, "Invalid image found, aborting load!");
1062 } catch (InvalidParentAlbumFound ipaf) {
1063 logger.log(Level.WARNING,
1064 format("Invalid album image (%s) encountered, aborting load!",
1065 ipaf.getAlbumParentId()));
1070 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1071 if (avatarId != null) {
1072 final Map<String, Image> images =
1073 configurationSoneParser.getImages();
1074 profile.setAvatar(images.get(avatarId));
1078 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1079 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1080 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1081 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1082 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1083 sone.getOptions().setShowCustomAvatars(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(LoadExternalContent.NEVER.name())));
1084 sone.getOptions().setLoadLinkedImages(LoadExternalContent.valueOf(configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").getValue(LoadExternalContent.NEVER.name())));
1086 /* if we’re still here, Sone was loaded successfully. */
1087 synchronized (sone) {
1088 sone.setTime(soneTime);
1089 sone.setProfile(profile);
1090 sone.setPosts(posts);
1091 sone.setReplies(replies);
1092 sone.setLikePostIds(likedPostIds);
1093 sone.setLikeReplyIds(likedReplyIds);
1094 for (Album album : sone.getRootAlbum().getAlbums()) {
1095 sone.getRootAlbum().removeAlbum(album);
1097 for (Album album : topLevelAlbums) {
1098 sone.getRootAlbum().addAlbum(album);
1100 synchronized (soneInserters) {
1101 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1104 for (Post post : posts) {
1105 post.setKnown(true);
1107 for (PostReply reply : replies) {
1108 reply.setKnown(true);
1111 logger.info(String.format("Sone loaded successfully: %s", sone));
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 text of the post
1124 * @return The created post
1126 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1127 checkNotNull(text, "text must not be null");
1128 checkArgument(text.trim().length() > 0, "text must not be empty");
1129 if (!sone.isLocal()) {
1130 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1133 PostBuilder postBuilder = database.newPostBuilder();
1134 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1135 if (recipient.isPresent()) {
1136 postBuilder.to(recipient.get().getId());
1138 final Post post = postBuilder.build();
1139 database.storePost(post);
1140 eventBus.post(new NewPostFoundEvent(post));
1142 touchConfiguration();
1143 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1148 * Deletes the given post.
1151 * The post to delete
1153 public void deletePost(Post post) {
1154 if (!post.getSone().isLocal()) {
1155 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1158 database.removePost(post);
1159 eventBus.post(new PostRemovedEvent(post));
1160 markPostKnown(post);
1161 touchConfiguration();
1165 * Marks the given post as known, if it is currently not a known post
1166 * (according to {@link Post#isKnown()}).
1169 * The post to mark as known
1171 public void markPostKnown(Post post) {
1172 post.setKnown(true);
1173 eventBus.post(new MarkPostKnownEvent(post));
1174 touchConfiguration();
1175 for (PostReply reply : getReplies(post.getId())) {
1176 markReplyKnown(reply);
1180 public void bookmarkPost(Post post) {
1181 database.bookmarkPost(post);
1185 * Removes the given post from the bookmarks.
1188 * The post to unbookmark
1190 public void unbookmarkPost(Post post) {
1191 database.unbookmarkPost(post);
1195 * Creates a new reply.
1198 * The Sone that creates the reply
1200 * The post that this reply refers to
1202 * The text of the reply
1203 * @return The created reply
1205 public PostReply createReply(Sone sone, Post post, String text) {
1206 checkNotNull(text, "text must not be null");
1207 checkArgument(text.trim().length() > 0, "text must not be empty");
1208 if (!sone.isLocal()) {
1209 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1212 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1213 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1214 final PostReply reply = postReplyBuilder.build();
1215 database.storePostReply(reply);
1216 eventBus.post(new NewPostReplyFoundEvent(reply));
1217 sone.addReply(reply);
1218 touchConfiguration();
1219 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1224 * Deletes the given reply.
1227 * The reply to delete
1229 public void deleteReply(PostReply reply) {
1230 Sone sone = reply.getSone();
1231 if (!sone.isLocal()) {
1232 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1235 database.removePostReply(reply);
1236 markReplyKnown(reply);
1237 sone.removeReply(reply);
1238 touchConfiguration();
1242 * Marks the given reply as known, if it is currently not a known reply
1243 * (according to {@link Reply#isKnown()}).
1246 * The reply to mark as known
1248 public void markReplyKnown(PostReply reply) {
1249 boolean previouslyKnown = reply.isKnown();
1250 reply.setKnown(true);
1251 eventBus.post(new MarkPostReplyKnownEvent(reply));
1252 if (!previouslyKnown) {
1253 touchConfiguration();
1258 * Creates a new album for the given Sone.
1261 * The Sone to create the album for
1263 * The parent of the album (may be {@code null} to create a
1265 * @return The new album
1267 public Album createAlbum(Sone sone, Album parent) {
1268 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1269 database.storeAlbum(album);
1270 parent.addAlbum(album);
1275 * Deletes the given album. The owner of the album has to be a local Sone,
1276 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1279 * The album to remove
1281 public void deleteAlbum(Album album) {
1282 checkNotNull(album, "album must not be null");
1283 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1284 if (!album.isEmpty()) {
1287 album.getParent().removeAlbum(album);
1288 database.removeAlbum(album);
1289 touchConfiguration();
1293 * Creates a new image.
1296 * The Sone creating the image
1298 * The album the image will be inserted into
1299 * @param temporaryImage
1300 * The temporary image to create the image from
1301 * @return The newly created image
1303 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1304 checkNotNull(sone, "sone must not be null");
1305 checkNotNull(album, "album must not be null");
1306 checkNotNull(temporaryImage, "temporaryImage must not be null");
1307 checkArgument(sone.isLocal(), "sone must be a local Sone");
1308 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1309 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1310 album.addImage(image);
1311 database.storeImage(image);
1312 imageInserter.insertImage(temporaryImage, image);
1317 * Deletes the given image. This method will also delete a matching
1320 * @see #deleteTemporaryImage(String)
1322 * The image to delete
1324 public void deleteImage(Image image) {
1325 checkNotNull(image, "image must not be null");
1326 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1327 deleteTemporaryImage(image.getId());
1328 image.getAlbum().removeImage(image);
1329 database.removeImage(image);
1330 touchConfiguration();
1334 * Creates a new temporary image.
1337 * The MIME type of the temporary image
1339 * The encoded data of the image
1340 * @return The temporary image
1342 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1343 TemporaryImage temporaryImage = new TemporaryImage();
1344 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1345 synchronized (temporaryImages) {
1346 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1348 return temporaryImage;
1352 * Deletes the temporary image with the given ID.
1355 * The ID of the temporary image to delete
1357 public void deleteTemporaryImage(String imageId) {
1358 checkNotNull(imageId, "imageId must not be null");
1359 synchronized (temporaryImages) {
1360 temporaryImages.remove(imageId);
1362 Image image = getImage(imageId, false);
1363 if (image != null) {
1364 imageInserter.cancelImageInsert(image);
1369 * Notifies the core that the configuration, either of the core or of a
1370 * single local Sone, has changed, and that the configuration should be
1373 public void touchConfiguration() {
1374 lastConfigurationUpdate = System.currentTimeMillis();
1385 public void serviceStart() {
1386 loadConfiguration();
1387 updateChecker.start();
1388 identityManager.start();
1389 webOfTrustUpdater.init();
1390 webOfTrustUpdater.start();
1398 public void serviceRun() {
1399 long lastSaved = System.currentTimeMillis();
1400 while (!shouldStop()) {
1402 long now = System.currentTimeMillis();
1403 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1404 for (Sone localSone : getLocalSones()) {
1405 saveSone(localSone);
1407 saveConfiguration();
1417 public void serviceStop() {
1418 localElementTicker.shutdownNow();
1419 synchronized (soneInserters) {
1420 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1421 soneInserter.getValue().stop();
1422 saveSone(soneInserter.getKey());
1425 synchronized (soneRescuers) {
1426 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1430 saveConfiguration();
1432 webOfTrustUpdater.stop();
1433 updateChecker.stop();
1434 soneDownloader.stop();
1435 soneDownloaders.shutdown();
1436 identityManager.stop();
1444 * Saves the given Sone. This will persist all local settings for the given
1445 * Sone, such as the friends list and similar, private options.
1450 private synchronized void saveSone(Sone sone) {
1451 if (!sone.isLocal()) {
1452 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1455 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1456 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1460 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1462 /* save Sone into configuration. */
1463 String sonePrefix = "Sone/" + sone.getId();
1464 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1465 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1468 Profile profile = sone.getProfile();
1469 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1470 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1471 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1472 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1473 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1474 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1475 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1477 /* save profile fields. */
1478 int fieldCounter = 0;
1479 for (Field profileField : profile.getFields()) {
1480 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1481 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1482 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1484 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1487 int postCounter = 0;
1488 for (Post post : sone.getPosts()) {
1489 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1490 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1491 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1492 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1493 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1495 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1498 int replyCounter = 0;
1499 for (PostReply reply : sone.getReplies()) {
1500 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1501 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1502 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1503 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1504 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1506 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1508 /* save post likes. */
1509 int postLikeCounter = 0;
1510 for (String postId : sone.getLikedPostIds()) {
1511 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1513 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1515 /* save reply likes. */
1516 int replyLikeCounter = 0;
1517 for (String replyId : sone.getLikedReplyIds()) {
1518 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1520 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1522 /* save albums. first, collect in a flat structure, top-level first. */
1523 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1525 int albumCounter = 0;
1526 for (Album album : albums) {
1527 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1528 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1529 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1530 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1531 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1533 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1536 int imageCounter = 0;
1537 for (Album album : albums) {
1538 for (Image image : album.getImages()) {
1539 if (!image.isInserted()) {
1542 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1543 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1544 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1545 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1546 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1547 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1548 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1549 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1550 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1553 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1556 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1557 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1558 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1559 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1560 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1561 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1562 configuration.getStringValue(sonePrefix + "/Options/LoadLinkedImages").setValue(sone.getOptions().getLoadLinkedImages().name());
1564 configuration.save();
1566 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1568 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1569 } catch (ConfigurationException ce1) {
1570 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1575 * Saves the current options.
1577 private void saveConfiguration() {
1578 synchronized (configuration) {
1579 if (storingConfiguration) {
1580 logger.log(Level.FINE, "Already storing configuration…");
1583 storingConfiguration = true;
1586 /* store the options first. */
1588 preferences.saveTo(configuration);
1590 /* save known Sones. */
1591 int soneCounter = 0;
1592 synchronized (knownSones) {
1593 for (String knownSoneId : knownSones) {
1594 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1596 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1599 /* save Sone following times. */
1601 synchronized (soneFollowingTimes) {
1602 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1603 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1604 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1607 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1610 /* save known posts. */
1614 configuration.save();
1616 } catch (ConfigurationException ce1) {
1617 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1618 } catch (DatabaseException de1) {
1619 logger.log(Level.SEVERE, "Could not save database!", de1);
1621 synchronized (configuration) {
1622 storingConfiguration = false;
1628 * Loads the configuration.
1630 private void loadConfiguration() {
1631 new PreferencesLoader(preferences).loadFrom(configuration);
1633 /* load known Sones. */
1634 int soneCounter = 0;
1636 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1637 if (knownSoneId == null) {
1640 synchronized (knownSones) {
1641 knownSones.add(knownSoneId);
1645 /* load Sone following times. */
1648 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1649 if (soneId == null) {
1652 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1653 synchronized (soneFollowingTimes) {
1654 soneFollowingTimes.put(soneId, time);
1661 * Notifies the core that a new {@link OwnIdentity} was added.
1663 * @param ownIdentityAddedEvent
1667 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1668 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1669 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1670 if (ownIdentity.hasContext("Sone")) {
1671 addLocalSone(ownIdentity);
1676 * Notifies the core that an {@link OwnIdentity} was removed.
1678 * @param ownIdentityRemovedEvent
1682 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1683 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1684 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1685 trustedIdentities.removeAll(ownIdentity);
1689 * Notifies the core that a new {@link Identity} was added.
1691 * @param identityAddedEvent
1695 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1696 Identity identity = identityAddedEvent.identity();
1697 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1698 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1699 addRemoteSone(identity);
1703 * Notifies the core that an {@link Identity} was updated.
1705 * @param identityUpdatedEvent
1709 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1710 Identity identity = identityUpdatedEvent.identity();
1711 final Sone sone = getRemoteSone(identity.getId());
1712 if (sone.isLocal()) {
1715 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1716 soneDownloader.addSone(sone);
1717 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1721 * Notifies the core that an {@link Identity} was removed.
1723 * @param identityRemovedEvent
1727 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1728 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1729 Identity identity = identityRemovedEvent.identity();
1730 trustedIdentities.remove(ownIdentity, identity);
1731 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1732 if (trustedIdentity.getKey().equals(ownIdentity)) {
1735 if (trustedIdentity.getValue().contains(identity)) {
1739 Sone sone = getSone(identity.getId());
1741 /* TODO - we don’t have the Sone anymore. should this happen? */
1744 for (PostReply postReply : sone.getReplies()) {
1745 eventBus.post(new PostReplyRemovedEvent(postReply));
1747 for (Post post : sone.getPosts()) {
1748 eventBus.post(new PostRemovedEvent(post));
1750 eventBus.post(new SoneRemovedEvent(sone));
1751 database.removeSone(sone);
1755 * Deletes the temporary image.
1757 * @param imageInsertFinishedEvent
1761 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1762 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1763 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1764 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1765 touchConfiguration();
1769 class MarkPostKnown implements Runnable {
1771 private final Post post;
1773 public MarkPostKnown(Post post) {
1779 markPostKnown(post);
1785 class MarkReplyKnown implements Runnable {
1787 private final PostReply postReply;
1789 public MarkReplyKnown(PostReply postReply) {
1790 this.postReply = postReply;
1795 markReplyKnown(postReply);