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.AlbumProvider;
77 import net.pterodactylus.sone.database.Database;
78 import net.pterodactylus.sone.database.DatabaseException;
79 import net.pterodactylus.sone.database.ImageBuilder;
80 import net.pterodactylus.sone.database.PostBuilder;
81 import net.pterodactylus.sone.database.PostProvider;
82 import net.pterodactylus.sone.database.PostReplyBuilder;
83 import net.pterodactylus.sone.database.PostReplyProvider;
84 import net.pterodactylus.sone.database.SoneBuilder;
85 import net.pterodactylus.sone.database.SoneProvider;
86 import net.pterodactylus.sone.freenet.wot.Identity;
87 import net.pterodactylus.sone.freenet.wot.IdentityManager;
88 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
94 import net.pterodactylus.sone.main.SonePlugin;
95 import net.pterodactylus.util.config.Configuration;
96 import net.pterodactylus.util.config.ConfigurationException;
97 import net.pterodactylus.util.service.AbstractService;
98 import net.pterodactylus.util.thread.NamedThreadFactory;
100 import com.google.common.annotations.VisibleForTesting;
101 import com.google.common.base.Function;
102 import com.google.common.base.Optional;
103 import com.google.common.base.Predicate;
104 import com.google.common.collect.FluentIterable;
105 import com.google.common.collect.HashMultimap;
106 import com.google.common.collect.ImmutableList;
107 import com.google.common.collect.ImmutableList.Builder;
108 import com.google.common.collect.Multimap;
109 import com.google.common.collect.Multimaps;
110 import com.google.common.collect.Ordering;
111 import com.google.common.eventbus.EventBus;
112 import com.google.common.eventbus.Subscribe;
113 import com.google.inject.Inject;
114 import com.google.inject.Singleton;
119 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
122 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider, AlbumProvider {
125 private static final Logger logger = getLogger(Core.class.getName());
127 /** The start time. */
128 private final long startupTime = System.currentTimeMillis();
130 /** The preferences. */
131 private final Preferences preferences;
133 /** The event bus. */
134 private final EventBus eventBus;
136 /** The configuration. */
137 private final Configuration configuration;
139 /** Whether we’re currently saving the configuration. */
140 private boolean storingConfiguration = false;
142 /** The identity manager. */
143 private final IdentityManager identityManager;
145 /** Interface to freenet. */
146 private final FreenetInterface freenetInterface;
148 /** The Sone downloader. */
149 private final SoneDownloader soneDownloader;
151 /** The image inserter. */
152 private final ImageInserter imageInserter;
154 /** Sone downloader thread-pool. */
155 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
157 /** The update checker. */
158 private final UpdateChecker updateChecker;
160 /** The trust updater. */
161 private final WebOfTrustUpdater webOfTrustUpdater;
163 private final Set<CompatibilityMode> compatibilityModes = EnumSet.noneOf(CompatibilityMode.class);
165 /** The times Sones were followed. */
166 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
168 /** Locked local Sones. */
169 /* synchronize on itself. */
170 private final Set<Sone> lockedSones = new HashSet<Sone>();
172 /** Sone inserters. */
173 /* synchronize access on this on sones. */
174 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
176 /** Sone rescuers. */
177 /* synchronize access on this on sones. */
178 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
180 /** All known Sones. */
181 private final Set<String> knownSones = new HashSet<String>();
183 /** The post database. */
184 private final Database database;
186 /** Trusted identities, sorted by own identities. */
187 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
189 /** All temporary images. */
190 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
192 /** Ticker for threads that mark own elements as known. */
193 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
195 /** The time the configuration was last touched. */
196 private volatile long lastConfigurationUpdate;
199 * Creates a new core.
201 * @param configuration
202 * The configuration of the core
203 * @param freenetInterface
204 * The freenet interface
205 * @param identityManager
206 * The identity manager
207 * @param webOfTrustUpdater
208 * The WebOfTrust updater
215 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
217 this.configuration = configuration;
218 this.freenetInterface = freenetInterface;
219 this.identityManager = identityManager;
220 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
221 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
222 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
223 this.webOfTrustUpdater = webOfTrustUpdater;
224 this.eventBus = eventBus;
225 this.database = database;
226 preferences = new Preferences(eventBus);
230 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
232 this.configuration = configuration;
233 this.freenetInterface = freenetInterface;
234 this.identityManager = identityManager;
235 this.soneDownloader = soneDownloader;
236 this.imageInserter = imageInserter;
237 this.updateChecker = updateChecker;
238 this.webOfTrustUpdater = webOfTrustUpdater;
239 this.eventBus = eventBus;
240 this.database = database;
241 preferences = new Preferences(eventBus);
249 * Returns the time Sone was started.
251 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
253 public long getStartupTime() {
258 * Returns the options used by the core.
260 * @return The options of the core
262 public Preferences getPreferences() {
267 * Returns the identity manager used by the core.
269 * @return The identity manager
271 public IdentityManager getIdentityManager() {
272 return identityManager;
276 * Returns the update checker.
278 * @return The update checker
280 public UpdateChecker getUpdateChecker() {
281 return updateChecker;
284 public boolean isCompatibilityMode(CompatibilityMode compatibilityMode) {
285 return compatibilityModes.contains(compatibilityMode);
288 public void setCompatibilityMode(CompatibilityMode compatibilityMode) {
289 compatibilityModes.add(compatibilityMode);
292 public void clearCompatibilityMod(CompatibilityMode compatibilityMode) {
293 compatibilityModes.remove(compatibilityMode);
297 * Returns the Sone rescuer for the given local Sone.
300 * The local Sone to get the rescuer for
301 * @return The Sone rescuer for the given Sone
303 public SoneRescuer getSoneRescuer(Sone sone) {
304 checkNotNull(sone, "sone must not be null");
305 checkArgument(sone.isLocal(), "sone must be local");
306 synchronized (soneRescuers) {
307 SoneRescuer soneRescuer = soneRescuers.get(sone);
308 if (soneRescuer == null) {
309 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
310 soneRescuers.put(sone, soneRescuer);
318 * Returns whether the given Sone is currently locked.
322 * @return {@code true} if the Sone is locked, {@code false} if it is not
324 public boolean isLocked(Sone sone) {
325 synchronized (lockedSones) {
326 return lockedSones.contains(sone);
330 public SoneBuilder soneBuilder() {
331 return database.newSoneBuilder();
338 public Collection<Sone> getSones() {
339 return database.getSones();
343 public Function<String, Optional<Sone>> soneLoader() {
344 return database.soneLoader();
348 * Returns the Sone with the given ID, regardless whether it’s local or
352 * The ID of the Sone to get
353 * @return The Sone with the given ID, or {@code null} if there is no such
357 public Optional<Sone> getSone(String id) {
358 return database.getSone(id);
365 public Collection<Sone> getLocalSones() {
366 return database.getLocalSones();
370 * Returns the local Sone with the given ID, optionally creating a new Sone.
374 * @return The Sone with the given ID, or {@code null}
376 public Sone getLocalSone(String id) {
377 Optional<Sone> sone = database.getSone(id);
378 if (sone.isPresent() && sone.get().isLocal()) {
388 public Collection<Sone> getRemoteSones() {
389 return database.getRemoteSones();
393 * Returns the remote Sone with the given ID.
397 * The ID of the remote Sone to get
398 * @return The Sone with the given ID
400 public Sone getRemoteSone(String id) {
401 return database.getSone(id).orNull();
405 * Returns whether the given Sone has been modified.
408 * The Sone to check for modifications
409 * @return {@code true} if a modification has been detected in the Sone,
410 * {@code false} otherwise
412 public boolean isModifiedSone(Sone sone) {
413 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
417 * Returns the time when the given was first followed by any local Sone.
420 * The Sone to get the time for
421 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
422 * been followed, or {@link Long#MAX_VALUE}
424 public long getSoneFollowingTime(Sone sone) {
425 synchronized (soneFollowingTimes) {
426 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
431 * Returns a post builder.
433 * @return A new post builder
435 public PostBuilder postBuilder() {
436 return database.newPostBuilder();
443 public Optional<Post> getPost(final String postId) {
444 Optional<Post> post = database.getPost(postId);
445 if (post.isPresent() || !isCompatibilityMode(CompatibilityMode.oldElementIds)) {
448 return FluentIterable.from(getSones()).transformAndConcat(Sone.toAllPosts).filter(new Predicate<Post>() {
450 public boolean apply(Post input) {
451 return (input != null) && input.getInternalId().equals(postId);
460 public Collection<Post> getPosts(String soneId) {
461 return database.getPosts(soneId);
468 public Collection<Post> getDirectedPosts(final String recipientId) {
469 checkNotNull(recipientId, "recipient must not be null");
470 return database.getDirectedPosts(recipientId);
474 * Returns a post reply builder.
476 * @return A new post reply builder
478 public PostReplyBuilder postReplyBuilder() {
479 return database.newPostReplyBuilder();
486 public Optional<PostReply> getPostReply(String replyId) {
487 return database.getPostReply(replyId);
494 public List<PostReply> getReplies(final String postId) {
495 Builder<PostReply> postReplies = ImmutableList.<PostReply>builder().addAll(database.getReplies(postId));
496 if (isCompatibilityMode(CompatibilityMode.oldElementIds)) {
497 Optional<Post> post = getPost(postId);
498 if (post.isPresent()) {
499 postReplies.addAll(database.getReplies(post.get().getInternalId()));
502 return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(postReplies.build());
506 * Returns all Sones that have liked the given post.
509 * The post to get the liking Sones for
510 * @return The Sones that like the given post
512 public Set<Sone> getLikes(Post post) {
513 Set<Sone> sones = new HashSet<Sone>();
514 for (Sone sone : getSones()) {
515 if (sone.getLikedPostIds().contains(post.getId())) {
523 * Returns all Sones that have liked the given reply.
526 * The reply to get the liking Sones for
527 * @return The Sones that like the given reply
529 public Set<Sone> getLikes(PostReply reply) {
530 Set<Sone> sones = new HashSet<Sone>();
531 for (Sone sone : getSones()) {
532 if (sone.getLikedReplyIds().contains(reply.getId())) {
540 * Returns whether the given post is bookmarked.
544 * @return {@code true} if the given post is bookmarked, {@code false}
547 public boolean isBookmarked(Post post) {
548 return database.isPostBookmarked(post);
552 * Returns all currently known bookmarked posts.
554 * @return All bookmarked posts
556 public Set<Post> getBookmarkedPosts() {
557 return database.getBookmarkedPosts();
560 public AlbumBuilder albumBuilder() {
561 return database.newAlbumBuilder();
565 * Returns the album with the given ID, optionally creating a new album if
566 * an album with the given ID can not be found.
569 * The ID of the album
570 * @return The album with the given ID, or {@code null} if no album with the
573 public Optional<Album> getAlbum(String albumId) {
574 return database.getAlbum(albumId);
577 public ImageBuilder imageBuilder() {
578 return database.newImageBuilder();
582 * Returns the image with the given ID, creating it if necessary.
585 * The ID of the image
586 * @return The image with the given ID
588 public Image getImage(String imageId) {
589 return getImage(imageId, true);
593 * Returns the image with the given ID, optionally creating it if it does
597 * The ID of the image
599 * {@code true} to create an image if none exists with the given
601 * @return The image with the given ID, or {@code null} if none exists and
604 public Image getImage(String imageId, boolean create) {
605 Optional<Image> image = database.getImage(imageId);
606 if (image.isPresent()) {
612 Image newImage = database.newImageBuilder().withId(imageId).build();
613 database.storeImage(newImage);
618 * Returns the temporary image with the given ID.
621 * The ID of the temporary image
622 * @return The temporary image, or {@code null} if there is no temporary
623 * image with the given ID
625 public TemporaryImage getTemporaryImage(String imageId) {
626 synchronized (temporaryImages) {
627 return temporaryImages.get(imageId);
636 * Locks the given Sone. A locked Sone will not be inserted by
637 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
643 public void lockSone(Sone sone) {
644 synchronized (lockedSones) {
645 if (lockedSones.add(sone)) {
646 eventBus.post(new SoneLockedEvent(sone));
652 * Unlocks the given Sone.
654 * @see #lockSone(Sone)
658 public void unlockSone(Sone sone) {
659 synchronized (lockedSones) {
660 if (lockedSones.remove(sone)) {
661 eventBus.post(new SoneUnlockedEvent(sone));
667 * Adds a local Sone from the given own identity.
670 * The own identity to create a Sone from
671 * @return The added (or already existing) Sone
673 public Sone addLocalSone(OwnIdentity ownIdentity) {
674 if (ownIdentity == null) {
675 logger.log(Level.WARNING, "Given OwnIdentity is null!");
678 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
679 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
680 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
681 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
682 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
684 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
685 eventBus.register(soneInserter);
686 synchronized (soneInserters) {
687 soneInserters.put(sone, soneInserter);
690 database.storeSone(sone);
691 sone.setStatus(SoneStatus.idle);
692 soneInserter.start();
697 * Creates a new Sone for the given own identity.
700 * The own identity to create a Sone for
701 * @return The created Sone
703 public Sone createSone(OwnIdentity ownIdentity) {
704 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
705 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
708 Sone sone = addLocalSone(ownIdentity);
710 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
711 touchConfiguration();
716 * Adds the Sone of the given identity.
719 * The identity whose Sone to add
720 * @return The added or already existing Sone
722 public Sone addRemoteSone(Identity identity) {
723 if (identity == null) {
724 logger.log(Level.WARNING, "Given Identity is null!");
727 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
728 long latestEdition = fromNullable(tryParse(property)).or(0L);
729 Optional<Sone> existingSone = getSone(identity.getId());
730 if (existingSone.isPresent() && existingSone.get().isLocal()) {
731 return existingSone.get();
733 boolean newSone = !existingSone.isPresent();
734 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
735 sone.setLatestEdition(latestEdition);
737 synchronized (knownSones) {
738 newSone = !knownSones.contains(sone.getId());
740 sone.setKnown(!newSone);
742 eventBus.post(new NewSoneFoundEvent(sone));
743 for (Sone localSone : getLocalSones()) {
744 if (localSone.getOptions().isAutoFollow()) {
745 followSone(localSone, sone.getId());
750 database.storeSone(sone);
751 soneDownloader.addSone(sone);
752 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
757 * Lets the given local Sone follow the Sone with the given ID.
760 * The local Sone that should follow another Sone
762 * The ID of the Sone to follow
764 public void followSone(Sone sone, String soneId) {
765 checkNotNull(sone, "sone must not be null");
766 checkNotNull(soneId, "soneId must not be null");
767 database.addFriend(sone, soneId);
768 synchronized (soneFollowingTimes) {
769 if (!soneFollowingTimes.containsKey(soneId)) {
770 long now = System.currentTimeMillis();
771 soneFollowingTimes.put(soneId, now);
772 Optional<Sone> followedSone = getSone(soneId);
773 if (!followedSone.isPresent()) {
776 for (Post post : followedSone.get().getPosts()) {
777 if (post.getTime() < now) {
781 for (PostReply reply : followedSone.get().getReplies()) {
782 if (reply.getTime() < now) {
783 markReplyKnown(reply);
788 touchConfiguration();
792 * Lets the given local Sone unfollow the Sone with the given ID.
795 * The local Sone that should unfollow another Sone
797 * The ID of the Sone being unfollowed
799 public void unfollowSone(Sone sone, String soneId) {
800 checkNotNull(sone, "sone must not be null");
801 checkNotNull(soneId, "soneId must not be null");
802 database.removeFriend(sone, soneId);
803 boolean unfollowedSoneStillFollowed = false;
804 for (Sone localSone : getLocalSones()) {
805 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
807 if (!unfollowedSoneStillFollowed) {
808 synchronized (soneFollowingTimes) {
809 soneFollowingTimes.remove(soneId);
812 touchConfiguration();
816 * Sets the trust value of the given origin Sone for the target Sone.
823 * The trust value (from {@code -100} to {@code 100})
825 public void setTrust(Sone origin, Sone target, int trustValue) {
826 checkNotNull(origin, "origin must not be null");
827 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
828 checkNotNull(target, "target must not be null");
829 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
830 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
834 * Removes any trust assignment for the given target Sone.
841 public void removeTrust(Sone origin, Sone target) {
842 checkNotNull(origin, "origin must not be null");
843 checkNotNull(target, "target must not be null");
844 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
845 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
849 * Assigns the configured positive trust value for the given target.
856 public void trustSone(Sone origin, Sone target) {
857 setTrust(origin, target, preferences.getPositiveTrust());
861 * Assigns the configured negative trust value for the given target.
868 public void distrustSone(Sone origin, Sone target) {
869 setTrust(origin, target, preferences.getNegativeTrust());
873 * Removes the trust assignment for the given target.
880 public void untrustSone(Sone origin, Sone target) {
881 removeTrust(origin, target);
885 * Updates the stored Sone with the given Sone.
890 public void updateSone(Sone sone) {
891 updateSone(sone, false);
895 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
896 * {@code true}, an older Sone than the current Sone can be given to restore
901 * @param soneRescueMode
902 * {@code true} if the stored Sone should be updated regardless
903 * of the age of the given Sone
905 public void updateSone(final Sone sone, boolean soneRescueMode) {
906 Optional<Sone> storedSone = getSone(sone.getId());
907 if (storedSone.isPresent()) {
908 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
909 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
912 List<Object> events =
913 collectEventsForChangesInSone(storedSone.get(), sone);
914 database.storeSone(sone);
915 for (Object event : events) {
916 eventBus.post(event);
918 sone.setOptions(storedSone.get().getOptions());
919 sone.setKnown(storedSone.get().isKnown());
920 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
921 if (sone.isLocal()) {
922 touchConfiguration();
927 private List<Object> collectEventsForChangesInSone(Sone oldSone,
928 final Sone newSone) {
929 final List<Object> events = new ArrayList<Object>();
930 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
932 soneChangeDetector.onNewPosts(new PostProcessor() {
934 public void processPost(Post post) {
935 if (post.getTime() < getSoneFollowingTime(newSone)) {
937 } else if (!post.isKnown()) {
938 events.add(new NewPostFoundEvent(post));
942 soneChangeDetector.onRemovedPosts(new PostProcessor() {
944 public void processPost(Post post) {
945 events.add(new PostRemovedEvent(post));
948 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
950 public void processPostReply(PostReply postReply) {
951 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
952 postReply.setKnown(true);
953 } else if (!postReply.isKnown()) {
954 events.add(new NewPostReplyFoundEvent(postReply));
958 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
960 public void processPostReply(PostReply postReply) {
961 events.add(new PostReplyRemovedEvent(postReply));
964 soneChangeDetector.detectChanges(newSone);
969 * Deletes the given Sone. This will remove the Sone from the
970 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
971 * remove the context from its identity.
976 public void deleteSone(Sone sone) {
977 if (!(sone.getIdentity() instanceof OwnIdentity)) {
978 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
981 if (!getLocalSones().contains(sone)) {
982 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
985 SoneInserter soneInserter = soneInserters.remove(sone);
987 database.removeSone(sone);
988 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
989 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
991 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
992 } catch (ConfigurationException ce1) {
993 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
998 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
999 * known} before, a {@link MarkSoneKnownEvent} is fired.
1002 * The Sone to mark as known
1004 public void markSoneKnown(Sone sone) {
1005 if (!sone.isKnown()) {
1006 sone.setKnown(true);
1007 synchronized (knownSones) {
1008 knownSones.add(sone.getId());
1010 eventBus.post(new MarkSoneKnownEvent(sone));
1011 touchConfiguration();
1016 * Loads and updates the given Sone from the configuration. If any error is
1017 * encountered, loading is aborted and the given Sone is not changed.
1020 * The Sone to load and update
1022 public void loadSone(Sone sone) {
1023 if (!sone.isLocal()) {
1024 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1027 logger.info(String.format("Loading local Sone: %s", sone));
1030 String sonePrefix = "Sone/" + sone.getId();
1031 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1032 if (soneTime == null) {
1033 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1036 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1039 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1040 Profile profile = configurationSoneParser.parseProfile();
1043 Collection<Post> posts;
1045 posts = configurationSoneParser.parsePosts(database);
1046 } catch (InvalidPostFound ipf) {
1047 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1052 Collection<PostReply> replies;
1054 replies = configurationSoneParser.parsePostReplies(database);
1055 } catch (InvalidPostReplyFound iprf) {
1056 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1060 /* load post likes. */
1061 Set<String> likedPostIds =
1062 configurationSoneParser.parseLikedPostIds();
1064 /* load reply likes. */
1065 Set<String> likedReplyIds =
1066 configurationSoneParser.parseLikedPostReplyIds();
1069 List<Album> topLevelAlbums;
1072 configurationSoneParser.parseTopLevelAlbums(database);
1073 } catch (InvalidAlbumFound iaf) {
1074 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1076 } catch (InvalidParentAlbumFound ipaf) {
1077 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1078 ipaf.getAlbumParentId()));
1084 configurationSoneParser.parseImages(database);
1085 } catch (InvalidImageFound iif) {
1086 logger.log(WARNING, "Invalid image found, aborting load!");
1088 } catch (InvalidParentAlbumFound ipaf) {
1089 logger.log(Level.WARNING,
1090 format("Invalid album image (%s) encountered, aborting load!",
1091 ipaf.getAlbumParentId()));
1096 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1097 if (avatarId != null) {
1098 final Map<String, Image> images =
1099 configurationSoneParser.getImages();
1100 profile.setAvatar(images.get(avatarId));
1104 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1105 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1106 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1107 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1108 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1109 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1111 /* if we’re still here, Sone was loaded successfully. */
1112 synchronized (sone) {
1113 sone.setTime(soneTime);
1114 sone.setProfile(profile);
1115 sone.setPosts(posts);
1116 sone.setReplies(replies);
1117 sone.setLikePostIds(likedPostIds);
1118 sone.setLikeReplyIds(likedReplyIds);
1119 for (Album album : sone.getRootAlbum().getAlbums()) {
1120 sone.getRootAlbum().removeAlbum(album);
1122 for (Album album : topLevelAlbums) {
1123 sone.getRootAlbum().addAlbum(album);
1125 synchronized (soneInserters) {
1126 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1129 for (Post post : posts) {
1130 post.setKnown(true);
1132 for (PostReply reply : replies) {
1133 reply.setKnown(true);
1136 logger.info(String.format("Sone loaded successfully: %s", sone));
1140 * Creates a new post.
1143 * The Sone that creates the post
1145 * The recipient Sone, or {@code null} if this post does not have
1148 * The text of the post
1149 * @return The created post
1151 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1152 checkNotNull(text, "text must not be null");
1153 checkArgument(text.trim().length() > 0, "text must not be empty");
1154 if (!sone.isLocal()) {
1155 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1158 PostBuilder postBuilder = database.newPostBuilder();
1159 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1160 if (recipient.isPresent()) {
1161 postBuilder.to(recipient.get().getId());
1163 final Post post = postBuilder.build();
1164 database.storePost(post);
1165 eventBus.post(new NewPostFoundEvent(post));
1167 touchConfiguration();
1168 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1173 * Deletes the given post.
1176 * The post to delete
1178 public void deletePost(Post post) {
1179 if (!post.getSone().isLocal()) {
1180 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1183 database.removePost(post);
1184 eventBus.post(new PostRemovedEvent(post));
1185 markPostKnown(post);
1186 touchConfiguration();
1190 * Marks the given post as known, if it is currently not a known post
1191 * (according to {@link Post#isKnown()}).
1194 * The post to mark as known
1196 public void markPostKnown(Post post) {
1197 post.setKnown(true);
1198 eventBus.post(new MarkPostKnownEvent(post));
1199 touchConfiguration();
1200 for (PostReply reply : getReplies(post.getId())) {
1201 markReplyKnown(reply);
1205 public void bookmarkPost(Post post) {
1206 database.bookmarkPost(post);
1210 * Removes the given post from the bookmarks.
1213 * The post to unbookmark
1215 public void unbookmarkPost(Post post) {
1216 database.unbookmarkPost(post);
1220 * Creates a new reply.
1223 * The Sone that creates the reply
1225 * The post that this reply refers to
1227 * The text of the reply
1228 * @return The created reply
1230 public PostReply createReply(Sone sone, Post post, String text) {
1231 checkNotNull(text, "text must not be null");
1232 checkArgument(text.trim().length() > 0, "text must not be empty");
1233 if (!sone.isLocal()) {
1234 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1237 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1238 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1239 final PostReply reply = postReplyBuilder.build();
1240 database.storePostReply(reply);
1241 eventBus.post(new NewPostReplyFoundEvent(reply));
1242 sone.addReply(reply);
1243 touchConfiguration();
1244 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1249 * Deletes the given reply.
1252 * The reply to delete
1254 public void deleteReply(PostReply reply) {
1255 Sone sone = reply.getSone();
1256 if (!sone.isLocal()) {
1257 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1260 database.removePostReply(reply);
1261 markReplyKnown(reply);
1262 sone.removeReply(reply);
1263 touchConfiguration();
1267 * Marks the given reply as known, if it is currently not a known reply
1268 * (according to {@link Reply#isKnown()}).
1271 * The reply to mark as known
1273 public void markReplyKnown(PostReply reply) {
1274 boolean previouslyKnown = reply.isKnown();
1275 reply.setKnown(true);
1276 eventBus.post(new MarkPostReplyKnownEvent(reply));
1277 if (!previouslyKnown) {
1278 touchConfiguration();
1283 * Creates a new album for the given Sone.
1286 * The Sone to create the album for
1288 * The parent of the album (may be {@code null} to create a
1290 * @return The new album
1292 public Album createAlbum(Sone sone, Album parent) {
1293 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1294 database.storeAlbum(album);
1295 parent.addAlbum(album);
1300 * Deletes the given album. The owner of the album has to be a local Sone,
1301 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1304 * The album to remove
1306 public void deleteAlbum(Album album) {
1307 checkNotNull(album, "album must not be null");
1308 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1309 if (!album.isEmpty()) {
1312 album.getParent().removeAlbum(album);
1313 database.removeAlbum(album);
1314 touchConfiguration();
1318 * Creates a new image.
1321 * The Sone creating the image
1323 * The album the image will be inserted into
1324 * @param temporaryImage
1325 * The temporary image to create the image from
1326 * @return The newly created image
1328 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1329 checkNotNull(sone, "sone must not be null");
1330 checkNotNull(album, "album must not be null");
1331 checkNotNull(temporaryImage, "temporaryImage must not be null");
1332 checkArgument(sone.isLocal(), "sone must be a local Sone");
1333 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1334 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1335 album.addImage(image);
1336 database.storeImage(image);
1337 imageInserter.insertImage(temporaryImage, image);
1342 * Deletes the given image. This method will also delete a matching
1345 * @see #deleteTemporaryImage(String)
1347 * The image to delete
1349 public void deleteImage(Image image) {
1350 checkNotNull(image, "image must not be null");
1351 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1352 deleteTemporaryImage(image.getId());
1353 image.getAlbum().removeImage(image);
1354 database.removeImage(image);
1355 touchConfiguration();
1359 * Creates a new temporary image.
1362 * The MIME type of the temporary image
1364 * The encoded data of the image
1365 * @return The temporary image
1367 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1368 TemporaryImage temporaryImage = new TemporaryImage();
1369 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1370 synchronized (temporaryImages) {
1371 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1373 return temporaryImage;
1377 * Deletes the temporary image with the given ID.
1380 * The ID of the temporary image to delete
1382 public void deleteTemporaryImage(String imageId) {
1383 checkNotNull(imageId, "imageId must not be null");
1384 synchronized (temporaryImages) {
1385 temporaryImages.remove(imageId);
1387 Image image = getImage(imageId, false);
1388 if (image != null) {
1389 imageInserter.cancelImageInsert(image);
1394 * Notifies the core that the configuration, either of the core or of a
1395 * single local Sone, has changed, and that the configuration should be
1398 public void touchConfiguration() {
1399 lastConfigurationUpdate = System.currentTimeMillis();
1410 public void serviceStart() {
1411 loadConfiguration();
1412 updateChecker.start();
1413 identityManager.start();
1414 webOfTrustUpdater.init();
1415 webOfTrustUpdater.start();
1423 public void serviceRun() {
1424 long lastSaved = System.currentTimeMillis();
1425 while (!shouldStop()) {
1427 long now = System.currentTimeMillis();
1428 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1429 for (Sone localSone : getLocalSones()) {
1430 saveSone(localSone);
1432 saveConfiguration();
1442 public void serviceStop() {
1443 localElementTicker.shutdownNow();
1444 synchronized (soneInserters) {
1445 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1446 soneInserter.getValue().stop();
1447 saveSone(soneInserter.getKey());
1450 synchronized (soneRescuers) {
1451 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1455 saveConfiguration();
1457 webOfTrustUpdater.stop();
1458 updateChecker.stop();
1459 soneDownloader.stop();
1460 soneDownloaders.shutdown();
1461 identityManager.stop();
1469 * Saves the given Sone. This will persist all local settings for the given
1470 * Sone, such as the friends list and similar, private options.
1475 private synchronized void saveSone(Sone sone) {
1476 if (!sone.isLocal()) {
1477 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1480 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1481 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1485 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1487 /* save Sone into configuration. */
1488 String sonePrefix = "Sone/" + sone.getId();
1489 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1490 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1493 Profile profile = sone.getProfile();
1494 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1495 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1496 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1497 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1498 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1499 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1500 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1502 /* save profile fields. */
1503 int fieldCounter = 0;
1504 for (Field profileField : profile.getFields()) {
1505 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1506 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1507 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1509 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1512 int postCounter = 0;
1513 for (Post post : sone.getPosts()) {
1514 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1515 configuration.getStringValue(postPrefix + "/ID").setValue(post.getInternalId());
1516 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1517 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1518 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1520 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1523 int replyCounter = 0;
1524 for (PostReply reply : sone.getReplies()) {
1525 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1526 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getInternalId());
1527 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1528 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1529 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1531 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1533 /* save post likes. */
1534 int postLikeCounter = 0;
1535 for (String postId : sone.getLikedPostIds()) {
1536 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1538 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1540 /* save reply likes. */
1541 int replyLikeCounter = 0;
1542 for (String replyId : sone.getLikedReplyIds()) {
1543 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1545 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1547 /* save albums. first, collect in a flat structure, top-level first. */
1548 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1550 int albumCounter = 0;
1551 for (Album album : albums) {
1552 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1553 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getInternalId());
1554 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1555 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1556 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1557 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1559 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1562 int imageCounter = 0;
1563 for (Album album : albums) {
1564 for (Image image : album.getImages()) {
1565 if (!image.isInserted()) {
1568 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1569 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getInternalId());
1570 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getInternalId());
1571 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1572 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1573 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1574 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1575 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1576 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1579 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1582 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1583 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1584 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1585 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1586 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1587 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1589 configuration.save();
1591 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1593 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1594 } catch (ConfigurationException ce1) {
1595 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1600 * Saves the current options.
1602 private void saveConfiguration() {
1603 synchronized (configuration) {
1604 if (storingConfiguration) {
1605 logger.log(Level.FINE, "Already storing configuration…");
1608 storingConfiguration = true;
1611 /* store the options first. */
1613 preferences.saveTo(configuration);
1615 /* save known Sones. */
1616 int soneCounter = 0;
1617 synchronized (knownSones) {
1618 for (String knownSoneId : knownSones) {
1619 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1621 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1624 /* save Sone following times. */
1626 synchronized (soneFollowingTimes) {
1627 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1628 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1629 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1632 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1635 /* save compatibility modes. */
1636 configuration.getBooleanValue("CompatibilityModes/OldElementIds").setValue(compatibilityModes.contains(CompatibilityMode.oldElementIds));
1638 /* save known posts. */
1642 configuration.save();
1644 } catch (ConfigurationException ce1) {
1645 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1646 } catch (DatabaseException de1) {
1647 logger.log(Level.SEVERE, "Could not save database!", de1);
1649 synchronized (configuration) {
1650 storingConfiguration = false;
1656 * Loads the configuration.
1658 private void loadConfiguration() {
1659 new PreferencesLoader(preferences).loadFrom(configuration);
1661 /* load known Sones. */
1662 int soneCounter = 0;
1664 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1665 if (knownSoneId == null) {
1668 synchronized (knownSones) {
1669 knownSones.add(knownSoneId);
1673 /* load Sone following times. */
1676 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1677 if (soneId == null) {
1680 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1681 synchronized (soneFollowingTimes) {
1682 soneFollowingTimes.put(soneId, time);
1687 /* load compatibility modes. */
1688 if (configuration.getBooleanValue("CompatibilityModes/OldElementIds").getValue(false)) {
1689 setCompatibilityMode(CompatibilityMode.oldElementIds);
1694 * Notifies the core that a new {@link OwnIdentity} was added.
1696 * @param ownIdentityAddedEvent
1700 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1701 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1702 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1703 if (ownIdentity.hasContext("Sone")) {
1704 addLocalSone(ownIdentity);
1709 * Notifies the core that an {@link OwnIdentity} was removed.
1711 * @param ownIdentityRemovedEvent
1715 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1716 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1717 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1718 trustedIdentities.removeAll(ownIdentity);
1722 * Notifies the core that a new {@link Identity} was added.
1724 * @param identityAddedEvent
1728 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1729 Identity identity = identityAddedEvent.identity();
1730 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1731 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1732 addRemoteSone(identity);
1736 * Notifies the core that an {@link Identity} was updated.
1738 * @param identityUpdatedEvent
1742 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1743 Identity identity = identityUpdatedEvent.identity();
1744 final Sone sone = getRemoteSone(identity.getId());
1745 if (sone.isLocal()) {
1748 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1749 soneDownloader.addSone(sone);
1750 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1754 * Notifies the core that an {@link Identity} was removed.
1756 * @param identityRemovedEvent
1760 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1761 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1762 Identity identity = identityRemovedEvent.identity();
1763 trustedIdentities.remove(ownIdentity, identity);
1764 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1765 if (trustedIdentity.getKey().equals(ownIdentity)) {
1768 if (trustedIdentity.getValue().contains(identity)) {
1772 Optional<Sone> sone = getSone(identity.getId());
1773 if (!sone.isPresent()) {
1774 /* TODO - we don’t have the Sone anymore. should this happen? */
1777 database.removeSone(sone.get());
1778 eventBus.post(new SoneRemovedEvent(sone.get()));
1782 * Deletes the temporary image.
1784 * @param imageInsertFinishedEvent
1788 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1789 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1790 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1791 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1792 touchConfiguration();
1796 class MarkPostKnown implements Runnable {
1798 private final Post post;
1800 public MarkPostKnown(Post post) {
1806 markPostKnown(post);
1812 class MarkReplyKnown implements Runnable {
1814 private final PostReply postReply;
1816 public MarkReplyKnown(PostReply postReply) {
1817 this.postReply = postReply;
1822 markReplyKnown(postReply);