2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.lang.String.format;
25 import static java.util.logging.Level.WARNING;
26 import static java.util.logging.Logger.getLogger;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.EnumSet;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.List;
35 import java.util.Map.Entry;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
49 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
50 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
51 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
52 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
54 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
55 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
56 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
57 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
58 import net.pterodactylus.sone.core.event.PostRemovedEvent;
59 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
60 import net.pterodactylus.sone.core.event.SoneLockedEvent;
61 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
63 import net.pterodactylus.sone.data.Album;
64 import net.pterodactylus.sone.data.Client;
65 import net.pterodactylus.sone.data.Image;
66 import net.pterodactylus.sone.data.Post;
67 import net.pterodactylus.sone.data.PostReply;
68 import net.pterodactylus.sone.data.Profile;
69 import net.pterodactylus.sone.data.Profile.Field;
70 import net.pterodactylus.sone.data.Reply;
71 import net.pterodactylus.sone.data.Sone;
72 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
73 import net.pterodactylus.sone.data.Sone.SoneStatus;
74 import net.pterodactylus.sone.data.TemporaryImage;
75 import net.pterodactylus.sone.database.AlbumBuilder;
76 import net.pterodactylus.sone.database.Database;
77 import net.pterodactylus.sone.database.DatabaseException;
78 import net.pterodactylus.sone.database.ImageBuilder;
79 import net.pterodactylus.sone.database.PostBuilder;
80 import net.pterodactylus.sone.database.PostProvider;
81 import net.pterodactylus.sone.database.PostReplyBuilder;
82 import net.pterodactylus.sone.database.PostReplyProvider;
83 import net.pterodactylus.sone.database.SoneBuilder;
84 import net.pterodactylus.sone.database.SoneProvider;
85 import net.pterodactylus.sone.freenet.wot.Identity;
86 import net.pterodactylus.sone.freenet.wot.IdentityManager;
87 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
93 import net.pterodactylus.sone.main.SonePlugin;
94 import net.pterodactylus.util.config.Configuration;
95 import net.pterodactylus.util.config.ConfigurationException;
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.Function;
101 import com.google.common.base.Optional;
102 import com.google.common.base.Predicate;
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;
115 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
118 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
121 private static final Logger logger = getLogger(Core.class.getName());
123 /** The start time. */
124 private final long startupTime = System.currentTimeMillis();
126 /** The preferences. */
127 private final Preferences preferences;
129 /** The event bus. */
130 private final EventBus eventBus;
132 /** The configuration. */
133 private final Configuration configuration;
135 /** Whether we’re currently saving the configuration. */
136 private boolean storingConfiguration = false;
138 /** The identity manager. */
139 private final IdentityManager identityManager;
141 /** Interface to freenet. */
142 private final FreenetInterface freenetInterface;
144 /** The Sone downloader. */
145 private final SoneDownloader soneDownloader;
147 /** The image inserter. */
148 private final ImageInserter imageInserter;
150 /** Sone downloader thread-pool. */
151 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
153 /** The update checker. */
154 private final UpdateChecker updateChecker;
156 /** The trust updater. */
157 private final WebOfTrustUpdater webOfTrustUpdater;
159 private final Set<CompatibilityMode> compatibilityModes = EnumSet.noneOf(CompatibilityMode.class);
161 /** The times Sones were followed. */
162 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
164 /** Locked local Sones. */
165 /* synchronize on itself. */
166 private final Set<Sone> lockedSones = new HashSet<Sone>();
168 /** Sone inserters. */
169 /* synchronize access on this on sones. */
170 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
172 /** Sone rescuers. */
173 /* synchronize access on this on sones. */
174 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
176 /** All known Sones. */
177 private final Set<String> knownSones = new HashSet<String>();
179 /** The post database. */
180 private final Database database;
182 /** Trusted identities, sorted by own identities. */
183 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
185 /** All temporary images. */
186 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
188 /** Ticker for threads that mark own elements as known. */
189 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
191 /** The time the configuration was last touched. */
192 private volatile long lastConfigurationUpdate;
195 * Creates a new core.
197 * @param configuration
198 * The configuration of the core
199 * @param freenetInterface
200 * The freenet interface
201 * @param identityManager
202 * The identity manager
203 * @param webOfTrustUpdater
204 * The WebOfTrust updater
211 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
213 this.configuration = configuration;
214 this.freenetInterface = freenetInterface;
215 this.identityManager = identityManager;
216 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
217 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
218 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
219 this.webOfTrustUpdater = webOfTrustUpdater;
220 this.eventBus = eventBus;
221 this.database = database;
222 preferences = new Preferences(eventBus);
226 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
228 this.configuration = configuration;
229 this.freenetInterface = freenetInterface;
230 this.identityManager = identityManager;
231 this.soneDownloader = soneDownloader;
232 this.imageInserter = imageInserter;
233 this.updateChecker = updateChecker;
234 this.webOfTrustUpdater = webOfTrustUpdater;
235 this.eventBus = eventBus;
236 this.database = database;
237 preferences = new Preferences(eventBus);
245 * Returns the time Sone was started.
247 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
249 public long getStartupTime() {
254 * Returns the options used by the core.
256 * @return The options of the core
258 public Preferences getPreferences() {
263 * Returns the identity manager used by the core.
265 * @return The identity manager
267 public IdentityManager getIdentityManager() {
268 return identityManager;
272 * Returns the update checker.
274 * @return The update checker
276 public UpdateChecker getUpdateChecker() {
277 return updateChecker;
280 public boolean isCompatibilityMode(CompatibilityMode compatibilityMode) {
281 return compatibilityModes.contains(compatibilityMode);
284 public void setCompatibilityMode(CompatibilityMode compatibilityMode) {
285 compatibilityModes.add(compatibilityMode);
288 public void clearCompatibilityMod(CompatibilityMode compatibilityMode) {
289 compatibilityModes.remove(compatibilityMode);
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 checkNotNull(sone, "sone must not be null");
301 checkArgument(sone.isLocal(), "sone must be local");
302 synchronized (soneRescuers) {
303 SoneRescuer soneRescuer = soneRescuers.get(sone);
304 if (soneRescuer == null) {
305 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
306 soneRescuers.put(sone, soneRescuer);
314 * Returns whether the given Sone is currently locked.
318 * @return {@code true} if the Sone is locked, {@code false} if it is not
320 public boolean isLocked(Sone sone) {
321 synchronized (lockedSones) {
322 return lockedSones.contains(sone);
326 public SoneBuilder soneBuilder() {
327 return database.newSoneBuilder();
334 public Collection<Sone> getSones() {
335 return database.getSones();
339 public Function<String, Optional<Sone>> soneLoader() {
340 return database.soneLoader();
344 * Returns the Sone with the given ID, regardless whether it’s local or
348 * The ID of the Sone to get
349 * @return The Sone with the given ID, or {@code null} if there is no such
353 public Optional<Sone> getSone(String id) {
354 return database.getSone(id);
361 public Collection<Sone> getLocalSones() {
362 return database.getLocalSones();
366 * Returns the local Sone with the given ID, optionally creating a new Sone.
370 * @return The Sone with the given ID, or {@code null}
372 public Sone getLocalSone(String id) {
373 Optional<Sone> sone = database.getSone(id);
374 if (sone.isPresent() && sone.get().isLocal()) {
384 public Collection<Sone> getRemoteSones() {
385 return database.getRemoteSones();
389 * Returns the remote Sone with the given ID.
393 * The ID of the remote Sone to get
394 * @return The Sone with the given ID
396 public Sone getRemoteSone(String id) {
397 return database.getSone(id).orNull();
401 * Returns whether the given Sone has been modified.
404 * The Sone to check for modifications
405 * @return {@code true} if a modification has been detected in the Sone,
406 * {@code false} otherwise
408 public boolean isModifiedSone(Sone sone) {
409 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
413 * Returns the time when the given was first followed by any local Sone.
416 * The Sone to get the time for
417 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
418 * been followed, or {@link Long#MAX_VALUE}
420 public long getSoneFollowingTime(Sone sone) {
421 synchronized (soneFollowingTimes) {
422 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
427 * Returns a post builder.
429 * @return A new post builder
431 public PostBuilder postBuilder() {
432 return database.newPostBuilder();
439 public Optional<Post> getPost(final String postId) {
440 Optional<Post> post = database.getPost(postId);
441 if (post.isPresent() || !isCompatibilityMode(CompatibilityMode.oldElementIds)) {
444 return FluentIterable.from(getSones()).transformAndConcat(Sone.toAllPosts).filter(new Predicate<Post>() {
446 public boolean apply(Post input) {
447 return (input != null) && input.getInternalId().equals(postId);
456 public Collection<Post> getPosts(String soneId) {
457 return database.getPosts(soneId);
464 public Collection<Post> getDirectedPosts(final String recipientId) {
465 checkNotNull(recipientId, "recipient must not be null");
466 return database.getDirectedPosts(recipientId);
470 * Returns a post reply builder.
472 * @return A new post reply builder
474 public PostReplyBuilder postReplyBuilder() {
475 return database.newPostReplyBuilder();
482 public Optional<PostReply> getPostReply(String replyId) {
483 return database.getPostReply(replyId);
490 public List<PostReply> getReplies(final String postId) {
491 return database.getReplies(postId);
495 * Returns all Sones that have liked the given post.
498 * The post to get the liking Sones for
499 * @return The Sones that like the given post
501 public Set<Sone> getLikes(Post post) {
502 Set<Sone> sones = new HashSet<Sone>();
503 for (Sone sone : getSones()) {
504 if (sone.getLikedPostIds().contains(post.getId())) {
512 * Returns all Sones that have liked the given reply.
515 * The reply to get the liking Sones for
516 * @return The Sones that like the given reply
518 public Set<Sone> getLikes(PostReply reply) {
519 Set<Sone> sones = new HashSet<Sone>();
520 for (Sone sone : getSones()) {
521 if (sone.getLikedReplyIds().contains(reply.getId())) {
529 * Returns whether the given post is bookmarked.
533 * @return {@code true} if the given post is bookmarked, {@code false}
536 public boolean isBookmarked(Post post) {
537 return database.isPostBookmarked(post);
541 * Returns all currently known bookmarked posts.
543 * @return All bookmarked posts
545 public Set<Post> getBookmarkedPosts() {
546 return database.getBookmarkedPosts();
549 public AlbumBuilder albumBuilder() {
550 return database.newAlbumBuilder();
554 * Returns the album with the given ID, optionally creating a new album if
555 * an album with the given ID can not be found.
558 * The ID of the album
559 * @return The album with the given ID, or {@code null} if no album with the
562 public Album getAlbum(String albumId) {
563 return database.getAlbum(albumId).orNull();
566 public ImageBuilder imageBuilder() {
567 return database.newImageBuilder();
571 * Returns the image with the given ID, creating it if necessary.
574 * The ID of the image
575 * @return The image with the given ID
577 public Image getImage(String imageId) {
578 return getImage(imageId, true);
582 * Returns the image with the given ID, optionally creating it if it does
586 * The ID of the image
588 * {@code true} to create an image if none exists with the given
590 * @return The image with the given ID, or {@code null} if none exists and
593 public Image getImage(String imageId, boolean create) {
594 Optional<Image> image = database.getImage(imageId);
595 if (image.isPresent()) {
601 Image newImage = database.newImageBuilder().withId(imageId).build();
602 database.storeImage(newImage);
607 * Returns the temporary image with the given ID.
610 * The ID of the temporary image
611 * @return The temporary image, or {@code null} if there is no temporary
612 * image with the given ID
614 public TemporaryImage getTemporaryImage(String imageId) {
615 synchronized (temporaryImages) {
616 return temporaryImages.get(imageId);
625 * Locks the given Sone. A locked Sone will not be inserted by
626 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
632 public void lockSone(Sone sone) {
633 synchronized (lockedSones) {
634 if (lockedSones.add(sone)) {
635 eventBus.post(new SoneLockedEvent(sone));
641 * Unlocks the given Sone.
643 * @see #lockSone(Sone)
647 public void unlockSone(Sone sone) {
648 synchronized (lockedSones) {
649 if (lockedSones.remove(sone)) {
650 eventBus.post(new SoneUnlockedEvent(sone));
656 * Adds a local Sone from the given own identity.
659 * The own identity to create a Sone from
660 * @return The added (or already existing) Sone
662 public Sone addLocalSone(OwnIdentity ownIdentity) {
663 if (ownIdentity == null) {
664 logger.log(Level.WARNING, "Given OwnIdentity is null!");
667 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
668 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
669 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
670 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
671 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
673 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
674 eventBus.register(soneInserter);
675 synchronized (soneInserters) {
676 soneInserters.put(sone, soneInserter);
679 database.storeSone(sone);
680 sone.setStatus(SoneStatus.idle);
681 soneInserter.start();
686 * Creates a new Sone for the given own identity.
689 * The own identity to create a Sone for
690 * @return The created Sone
692 public Sone createSone(OwnIdentity ownIdentity) {
693 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
694 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
697 Sone sone = addLocalSone(ownIdentity);
699 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
700 touchConfiguration();
705 * Adds the Sone of the given identity.
708 * The identity whose Sone to add
709 * @return The added or already existing Sone
711 public Sone addRemoteSone(Identity identity) {
712 if (identity == null) {
713 logger.log(Level.WARNING, "Given Identity is null!");
716 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
717 long latestEdition = fromNullable(tryParse(property)).or(0L);
718 Optional<Sone> existingSone = getSone(identity.getId());
719 if (existingSone.isPresent() && existingSone.get().isLocal()) {
720 return existingSone.get();
722 boolean newSone = !existingSone.isPresent();
723 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
724 sone.setLatestEdition(latestEdition);
726 synchronized (knownSones) {
727 newSone = !knownSones.contains(sone.getId());
729 sone.setKnown(!newSone);
731 eventBus.post(new NewSoneFoundEvent(sone));
732 for (Sone localSone : getLocalSones()) {
733 if (localSone.getOptions().isAutoFollow()) {
734 followSone(localSone, sone.getId());
739 database.storeSone(sone);
740 soneDownloader.addSone(sone);
741 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
746 * Lets the given local Sone follow the Sone with the given ID.
749 * The local Sone that should follow another Sone
751 * The ID of the Sone to follow
753 public void followSone(Sone sone, String soneId) {
754 checkNotNull(sone, "sone must not be null");
755 checkNotNull(soneId, "soneId must not be null");
756 database.addFriend(sone, soneId);
757 synchronized (soneFollowingTimes) {
758 if (!soneFollowingTimes.containsKey(soneId)) {
759 long now = System.currentTimeMillis();
760 soneFollowingTimes.put(soneId, now);
761 Optional<Sone> followedSone = getSone(soneId);
762 if (!followedSone.isPresent()) {
765 for (Post post : followedSone.get().getPosts()) {
766 if (post.getTime() < now) {
770 for (PostReply reply : followedSone.get().getReplies()) {
771 if (reply.getTime() < now) {
772 markReplyKnown(reply);
777 touchConfiguration();
781 * Lets the given local Sone unfollow the Sone with the given ID.
784 * The local Sone that should unfollow another Sone
786 * The ID of the Sone being unfollowed
788 public void unfollowSone(Sone sone, String soneId) {
789 checkNotNull(sone, "sone must not be null");
790 checkNotNull(soneId, "soneId must not be null");
791 database.removeFriend(sone, soneId);
792 boolean unfollowedSoneStillFollowed = false;
793 for (Sone localSone : getLocalSones()) {
794 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
796 if (!unfollowedSoneStillFollowed) {
797 synchronized (soneFollowingTimes) {
798 soneFollowingTimes.remove(soneId);
801 touchConfiguration();
805 * Sets the trust value of the given origin Sone for the target Sone.
812 * The trust value (from {@code -100} to {@code 100})
814 public void setTrust(Sone origin, Sone target, int trustValue) {
815 checkNotNull(origin, "origin must not be null");
816 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
817 checkNotNull(target, "target must not be null");
818 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
819 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
823 * Removes any trust assignment for the given target Sone.
830 public void removeTrust(Sone origin, Sone target) {
831 checkNotNull(origin, "origin must not be null");
832 checkNotNull(target, "target must not be null");
833 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
834 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
838 * Assigns the configured positive trust value for the given target.
845 public void trustSone(Sone origin, Sone target) {
846 setTrust(origin, target, preferences.getPositiveTrust());
850 * Assigns the configured negative trust value for the given target.
857 public void distrustSone(Sone origin, Sone target) {
858 setTrust(origin, target, preferences.getNegativeTrust());
862 * Removes the trust assignment for the given target.
869 public void untrustSone(Sone origin, Sone target) {
870 removeTrust(origin, target);
874 * Updates the stored Sone with the given Sone.
879 public void updateSone(Sone sone) {
880 updateSone(sone, false);
884 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
885 * {@code true}, an older Sone than the current Sone can be given to restore
890 * @param soneRescueMode
891 * {@code true} if the stored Sone should be updated regardless
892 * of the age of the given Sone
894 public void updateSone(final Sone sone, boolean soneRescueMode) {
895 Optional<Sone> storedSone = getSone(sone.getId());
896 if (storedSone.isPresent()) {
897 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
898 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
901 List<Object> events =
902 collectEventsForChangesInSone(storedSone.get(), sone);
903 database.storeSone(sone);
904 for (Object event : events) {
905 eventBus.post(event);
907 sone.setOptions(storedSone.get().getOptions());
908 sone.setKnown(storedSone.get().isKnown());
909 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
910 if (sone.isLocal()) {
911 touchConfiguration();
916 private List<Object> collectEventsForChangesInSone(Sone oldSone,
917 final Sone newSone) {
918 final List<Object> events = new ArrayList<Object>();
919 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
921 soneChangeDetector.onNewPosts(new PostProcessor() {
923 public void processPost(Post post) {
924 if (post.getTime() < getSoneFollowingTime(newSone)) {
926 } else if (!post.isKnown()) {
927 events.add(new NewPostFoundEvent(post));
931 soneChangeDetector.onRemovedPosts(new PostProcessor() {
933 public void processPost(Post post) {
934 events.add(new PostRemovedEvent(post));
937 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
939 public void processPostReply(PostReply postReply) {
940 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
941 postReply.setKnown(true);
942 } else if (!postReply.isKnown()) {
943 events.add(new NewPostReplyFoundEvent(postReply));
947 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
949 public void processPostReply(PostReply postReply) {
950 events.add(new PostReplyRemovedEvent(postReply));
953 soneChangeDetector.detectChanges(newSone);
958 * Deletes the given Sone. This will remove the Sone from the
959 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
960 * remove the context from its identity.
965 public void deleteSone(Sone sone) {
966 if (!(sone.getIdentity() instanceof OwnIdentity)) {
967 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
970 if (!getLocalSones().contains(sone)) {
971 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
974 SoneInserter soneInserter = soneInserters.remove(sone);
976 database.removeSone(sone);
977 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
978 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
980 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
981 } catch (ConfigurationException ce1) {
982 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
987 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
988 * known} before, a {@link MarkSoneKnownEvent} is fired.
991 * The Sone to mark as known
993 public void markSoneKnown(Sone sone) {
994 if (!sone.isKnown()) {
996 synchronized (knownSones) {
997 knownSones.add(sone.getId());
999 eventBus.post(new MarkSoneKnownEvent(sone));
1000 touchConfiguration();
1005 * Loads and updates the given Sone from the configuration. If any error is
1006 * encountered, loading is aborted and the given Sone is not changed.
1009 * The Sone to load and update
1011 public void loadSone(Sone sone) {
1012 if (!sone.isLocal()) {
1013 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1016 logger.info(String.format("Loading local Sone: %s", sone));
1019 String sonePrefix = "Sone/" + sone.getId();
1020 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1021 if (soneTime == null) {
1022 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1025 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1028 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1029 Profile profile = configurationSoneParser.parseProfile();
1032 Collection<Post> posts;
1034 posts = configurationSoneParser.parsePosts(database);
1035 } catch (InvalidPostFound ipf) {
1036 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1041 Collection<PostReply> replies;
1043 replies = configurationSoneParser.parsePostReplies(database);
1044 } catch (InvalidPostReplyFound iprf) {
1045 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1049 /* load post likes. */
1050 Set<String> likedPostIds =
1051 configurationSoneParser.parseLikedPostIds();
1053 /* load reply likes. */
1054 Set<String> likedReplyIds =
1055 configurationSoneParser.parseLikedPostReplyIds();
1058 List<Album> topLevelAlbums;
1061 configurationSoneParser.parseTopLevelAlbums(database);
1062 } catch (InvalidAlbumFound iaf) {
1063 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1065 } catch (InvalidParentAlbumFound ipaf) {
1066 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1067 ipaf.getAlbumParentId()));
1073 configurationSoneParser.parseImages(database);
1074 } catch (InvalidImageFound iif) {
1075 logger.log(WARNING, "Invalid image found, aborting load!");
1077 } catch (InvalidParentAlbumFound ipaf) {
1078 logger.log(Level.WARNING,
1079 format("Invalid album image (%s) encountered, aborting load!",
1080 ipaf.getAlbumParentId()));
1085 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1086 if (avatarId != null) {
1087 final Map<String, Image> images =
1088 configurationSoneParser.getImages();
1089 profile.setAvatar(images.get(avatarId));
1093 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1094 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1095 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1096 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1097 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1098 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1100 /* if we’re still here, Sone was loaded successfully. */
1101 synchronized (sone) {
1102 sone.setTime(soneTime);
1103 sone.setProfile(profile);
1104 sone.setPosts(posts);
1105 sone.setReplies(replies);
1106 sone.setLikePostIds(likedPostIds);
1107 sone.setLikeReplyIds(likedReplyIds);
1108 for (Album album : sone.getRootAlbum().getAlbums()) {
1109 sone.getRootAlbum().removeAlbum(album);
1111 for (Album album : topLevelAlbums) {
1112 sone.getRootAlbum().addAlbum(album);
1114 synchronized (soneInserters) {
1115 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1118 for (Post post : posts) {
1119 post.setKnown(true);
1121 for (PostReply reply : replies) {
1122 reply.setKnown(true);
1125 logger.info(String.format("Sone loaded successfully: %s", sone));
1129 * Creates a new post.
1132 * The Sone that creates the post
1134 * The recipient Sone, or {@code null} if this post does not have
1137 * The text of the post
1138 * @return The created post
1140 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1141 checkNotNull(text, "text must not be null");
1142 checkArgument(text.trim().length() > 0, "text must not be empty");
1143 if (!sone.isLocal()) {
1144 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1147 PostBuilder postBuilder = database.newPostBuilder();
1148 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1149 if (recipient.isPresent()) {
1150 postBuilder.to(recipient.get().getId());
1152 final Post post = postBuilder.build();
1153 database.storePost(post);
1154 eventBus.post(new NewPostFoundEvent(post));
1156 touchConfiguration();
1157 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1162 * Deletes the given post.
1165 * The post to delete
1167 public void deletePost(Post post) {
1168 if (!post.getSone().isLocal()) {
1169 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1172 database.removePost(post);
1173 eventBus.post(new PostRemovedEvent(post));
1174 markPostKnown(post);
1175 touchConfiguration();
1179 * Marks the given post as known, if it is currently not a known post
1180 * (according to {@link Post#isKnown()}).
1183 * The post to mark as known
1185 public void markPostKnown(Post post) {
1186 post.setKnown(true);
1187 eventBus.post(new MarkPostKnownEvent(post));
1188 touchConfiguration();
1189 for (PostReply reply : getReplies(post.getId())) {
1190 markReplyKnown(reply);
1194 public void bookmarkPost(Post post) {
1195 database.bookmarkPost(post);
1199 * Removes the given post from the bookmarks.
1202 * The post to unbookmark
1204 public void unbookmarkPost(Post post) {
1205 database.unbookmarkPost(post);
1209 * Creates a new reply.
1212 * The Sone that creates the reply
1214 * The post that this reply refers to
1216 * The text of the reply
1217 * @return The created reply
1219 public PostReply createReply(Sone sone, Post post, String text) {
1220 checkNotNull(text, "text must not be null");
1221 checkArgument(text.trim().length() > 0, "text must not be empty");
1222 if (!sone.isLocal()) {
1223 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1226 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1227 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1228 final PostReply reply = postReplyBuilder.build();
1229 database.storePostReply(reply);
1230 eventBus.post(new NewPostReplyFoundEvent(reply));
1231 sone.addReply(reply);
1232 touchConfiguration();
1233 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1238 * Deletes the given reply.
1241 * The reply to delete
1243 public void deleteReply(PostReply reply) {
1244 Sone sone = reply.getSone();
1245 if (!sone.isLocal()) {
1246 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1249 database.removePostReply(reply);
1250 markReplyKnown(reply);
1251 sone.removeReply(reply);
1252 touchConfiguration();
1256 * Marks the given reply as known, if it is currently not a known reply
1257 * (according to {@link Reply#isKnown()}).
1260 * The reply to mark as known
1262 public void markReplyKnown(PostReply reply) {
1263 boolean previouslyKnown = reply.isKnown();
1264 reply.setKnown(true);
1265 eventBus.post(new MarkPostReplyKnownEvent(reply));
1266 if (!previouslyKnown) {
1267 touchConfiguration();
1272 * Creates a new album for the given Sone.
1275 * The Sone to create the album for
1277 * The parent of the album (may be {@code null} to create a
1279 * @return The new album
1281 public Album createAlbum(Sone sone, Album parent) {
1282 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1283 database.storeAlbum(album);
1284 parent.addAlbum(album);
1289 * Deletes the given album. The owner of the album has to be a local Sone,
1290 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1293 * The album to remove
1295 public void deleteAlbum(Album album) {
1296 checkNotNull(album, "album must not be null");
1297 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1298 if (!album.isEmpty()) {
1301 album.getParent().removeAlbum(album);
1302 database.removeAlbum(album);
1303 touchConfiguration();
1307 * Creates a new image.
1310 * The Sone creating the image
1312 * The album the image will be inserted into
1313 * @param temporaryImage
1314 * The temporary image to create the image from
1315 * @return The newly created image
1317 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1318 checkNotNull(sone, "sone must not be null");
1319 checkNotNull(album, "album must not be null");
1320 checkNotNull(temporaryImage, "temporaryImage must not be null");
1321 checkArgument(sone.isLocal(), "sone must be a local Sone");
1322 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1323 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1324 album.addImage(image);
1325 database.storeImage(image);
1326 imageInserter.insertImage(temporaryImage, image);
1331 * Deletes the given image. This method will also delete a matching
1334 * @see #deleteTemporaryImage(String)
1336 * The image to delete
1338 public void deleteImage(Image image) {
1339 checkNotNull(image, "image must not be null");
1340 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1341 deleteTemporaryImage(image.getId());
1342 image.getAlbum().removeImage(image);
1343 database.removeImage(image);
1344 touchConfiguration();
1348 * Creates a new temporary image.
1351 * The MIME type of the temporary image
1353 * The encoded data of the image
1354 * @return The temporary image
1356 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1357 TemporaryImage temporaryImage = new TemporaryImage();
1358 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1359 synchronized (temporaryImages) {
1360 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1362 return temporaryImage;
1366 * Deletes the temporary image with the given ID.
1369 * The ID of the temporary image to delete
1371 public void deleteTemporaryImage(String imageId) {
1372 checkNotNull(imageId, "imageId must not be null");
1373 synchronized (temporaryImages) {
1374 temporaryImages.remove(imageId);
1376 Image image = getImage(imageId, false);
1377 if (image != null) {
1378 imageInserter.cancelImageInsert(image);
1383 * Notifies the core that the configuration, either of the core or of a
1384 * single local Sone, has changed, and that the configuration should be
1387 public void touchConfiguration() {
1388 lastConfigurationUpdate = System.currentTimeMillis();
1399 public void serviceStart() {
1400 loadConfiguration();
1401 updateChecker.start();
1402 identityManager.start();
1403 webOfTrustUpdater.init();
1404 webOfTrustUpdater.start();
1412 public void serviceRun() {
1413 long lastSaved = System.currentTimeMillis();
1414 while (!shouldStop()) {
1416 long now = System.currentTimeMillis();
1417 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1418 for (Sone localSone : getLocalSones()) {
1419 saveSone(localSone);
1421 saveConfiguration();
1431 public void serviceStop() {
1432 localElementTicker.shutdownNow();
1433 synchronized (soneInserters) {
1434 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1435 soneInserter.getValue().stop();
1436 saveSone(soneInserter.getKey());
1439 synchronized (soneRescuers) {
1440 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1444 saveConfiguration();
1446 webOfTrustUpdater.stop();
1447 updateChecker.stop();
1448 soneDownloader.stop();
1449 soneDownloaders.shutdown();
1450 identityManager.stop();
1458 * Saves the given Sone. This will persist all local settings for the given
1459 * Sone, such as the friends list and similar, private options.
1464 private synchronized void saveSone(Sone sone) {
1465 if (!sone.isLocal()) {
1466 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1469 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1470 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1474 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1476 /* save Sone into configuration. */
1477 String sonePrefix = "Sone/" + sone.getId();
1478 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1479 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1482 Profile profile = sone.getProfile();
1483 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1484 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1485 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1486 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1487 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1488 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1489 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1491 /* save profile fields. */
1492 int fieldCounter = 0;
1493 for (Field profileField : profile.getFields()) {
1494 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1495 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1496 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1498 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1501 int postCounter = 0;
1502 for (Post post : sone.getPosts()) {
1503 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1504 configuration.getStringValue(postPrefix + "/ID").setValue(post.getInternalId());
1505 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1506 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1507 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1509 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1512 int replyCounter = 0;
1513 for (PostReply reply : sone.getReplies()) {
1514 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1515 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getInternalId());
1516 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1517 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1518 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1520 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1522 /* save post likes. */
1523 int postLikeCounter = 0;
1524 for (String postId : sone.getLikedPostIds()) {
1525 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1527 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1529 /* save reply likes. */
1530 int replyLikeCounter = 0;
1531 for (String replyId : sone.getLikedReplyIds()) {
1532 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1534 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1536 /* save albums. first, collect in a flat structure, top-level first. */
1537 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1539 int albumCounter = 0;
1540 for (Album album : albums) {
1541 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1542 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getInternalId());
1543 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1544 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1545 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1546 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1548 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1551 int imageCounter = 0;
1552 for (Album album : albums) {
1553 for (Image image : album.getImages()) {
1554 if (!image.isInserted()) {
1557 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1558 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getInternalId());
1559 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getInternalId());
1560 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1561 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1562 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1563 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1564 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1565 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1568 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1571 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1572 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1573 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1574 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1575 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1576 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1578 configuration.save();
1580 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1582 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1583 } catch (ConfigurationException ce1) {
1584 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1589 * Saves the current options.
1591 private void saveConfiguration() {
1592 synchronized (configuration) {
1593 if (storingConfiguration) {
1594 logger.log(Level.FINE, "Already storing configuration…");
1597 storingConfiguration = true;
1600 /* store the options first. */
1602 preferences.saveTo(configuration);
1604 /* save known Sones. */
1605 int soneCounter = 0;
1606 synchronized (knownSones) {
1607 for (String knownSoneId : knownSones) {
1608 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1610 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1613 /* save Sone following times. */
1615 synchronized (soneFollowingTimes) {
1616 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1617 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1618 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1621 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1624 /* save known posts. */
1628 configuration.save();
1630 } catch (ConfigurationException ce1) {
1631 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1632 } catch (DatabaseException de1) {
1633 logger.log(Level.SEVERE, "Could not save database!", de1);
1635 synchronized (configuration) {
1636 storingConfiguration = false;
1642 * Loads the configuration.
1644 private void loadConfiguration() {
1645 new PreferencesLoader(preferences).loadFrom(configuration);
1647 /* load known Sones. */
1648 int soneCounter = 0;
1650 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1651 if (knownSoneId == null) {
1654 synchronized (knownSones) {
1655 knownSones.add(knownSoneId);
1659 /* load Sone following times. */
1662 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1663 if (soneId == null) {
1666 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1667 synchronized (soneFollowingTimes) {
1668 soneFollowingTimes.put(soneId, time);
1675 * Notifies the core that a new {@link OwnIdentity} was added.
1677 * @param ownIdentityAddedEvent
1681 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1682 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1683 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1684 if (ownIdentity.hasContext("Sone")) {
1685 addLocalSone(ownIdentity);
1690 * Notifies the core that an {@link OwnIdentity} was removed.
1692 * @param ownIdentityRemovedEvent
1696 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1697 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1698 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1699 trustedIdentities.removeAll(ownIdentity);
1703 * Notifies the core that a new {@link Identity} was added.
1705 * @param identityAddedEvent
1709 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1710 Identity identity = identityAddedEvent.identity();
1711 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1712 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1713 addRemoteSone(identity);
1717 * Notifies the core that an {@link Identity} was updated.
1719 * @param identityUpdatedEvent
1723 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1724 Identity identity = identityUpdatedEvent.identity();
1725 final Sone sone = getRemoteSone(identity.getId());
1726 if (sone.isLocal()) {
1729 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1730 soneDownloader.addSone(sone);
1731 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1735 * Notifies the core that an {@link Identity} was removed.
1737 * @param identityRemovedEvent
1741 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1742 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1743 Identity identity = identityRemovedEvent.identity();
1744 trustedIdentities.remove(ownIdentity, identity);
1745 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1746 if (trustedIdentity.getKey().equals(ownIdentity)) {
1749 if (trustedIdentity.getValue().contains(identity)) {
1753 Optional<Sone> sone = getSone(identity.getId());
1754 if (!sone.isPresent()) {
1755 /* TODO - we don’t have the Sone anymore. should this happen? */
1758 database.removeSone(sone.get());
1759 eventBus.post(new SoneRemovedEvent(sone.get()));
1763 * Deletes the temporary image.
1765 * @param imageInsertFinishedEvent
1769 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1770 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1771 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1772 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1773 touchConfiguration();
1777 class MarkPostKnown implements Runnable {
1779 private final Post post;
1781 public MarkPostKnown(Post post) {
1787 markPostKnown(post);
1793 class MarkReplyKnown implements Runnable {
1795 private final PostReply postReply;
1797 public MarkReplyKnown(PostReply postReply) {
1798 this.postReply = postReply;
1803 markReplyKnown(postReply);