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.HashMap;
31 import java.util.HashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
44 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
45 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
48 import net.pterodactylus.sone.core.SoneChangeDetector.PostProcessor;
49 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
50 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
51 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
52 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
53 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
54 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
55 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
56 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
57 import net.pterodactylus.sone.core.event.PostRemovedEvent;
58 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
59 import net.pterodactylus.sone.core.event.SoneLockedEvent;
60 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
61 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
62 import net.pterodactylus.sone.data.Album;
63 import net.pterodactylus.sone.data.Client;
64 import net.pterodactylus.sone.data.Image;
65 import net.pterodactylus.sone.data.Post;
66 import net.pterodactylus.sone.data.PostReply;
67 import net.pterodactylus.sone.data.Profile;
68 import net.pterodactylus.sone.data.Profile.Field;
69 import net.pterodactylus.sone.data.Reply;
70 import net.pterodactylus.sone.data.Sone;
71 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
72 import net.pterodactylus.sone.data.Sone.SoneStatus;
73 import net.pterodactylus.sone.data.TemporaryImage;
74 import net.pterodactylus.sone.database.AlbumBuilder;
75 import net.pterodactylus.sone.database.Database;
76 import net.pterodactylus.sone.database.DatabaseException;
77 import net.pterodactylus.sone.database.ImageBuilder;
78 import net.pterodactylus.sone.database.PostBuilder;
79 import net.pterodactylus.sone.database.PostProvider;
80 import net.pterodactylus.sone.database.PostReplyBuilder;
81 import net.pterodactylus.sone.database.PostReplyProvider;
82 import net.pterodactylus.sone.database.SoneBuilder;
83 import net.pterodactylus.sone.database.SoneProvider;
84 import net.pterodactylus.sone.freenet.wot.Identity;
85 import net.pterodactylus.sone.freenet.wot.IdentityManager;
86 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
87 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
88 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
89 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
90 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
91 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
92 import net.pterodactylus.sone.main.SonePlugin;
93 import net.pterodactylus.util.config.Configuration;
94 import net.pterodactylus.util.config.ConfigurationException;
95 import net.pterodactylus.util.service.AbstractService;
96 import net.pterodactylus.util.thread.NamedThreadFactory;
98 import com.google.common.annotations.VisibleForTesting;
99 import com.google.common.base.Optional;
100 import com.google.common.collect.FluentIterable;
101 import com.google.common.collect.HashMultimap;
102 import com.google.common.collect.Multimap;
103 import com.google.common.collect.Multimaps;
104 import com.google.common.eventbus.EventBus;
105 import com.google.common.eventbus.Subscribe;
106 import com.google.inject.Inject;
107 import com.google.inject.Singleton;
112 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
115 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
118 private static final Logger logger = getLogger("Sone.Core");
120 /** The start time. */
121 private final long startupTime = System.currentTimeMillis();
123 /** The preferences. */
124 private final Preferences preferences;
126 /** The event bus. */
127 private final EventBus eventBus;
129 /** The configuration. */
130 private final Configuration configuration;
132 /** Whether we’re currently saving the configuration. */
133 private boolean storingConfiguration = false;
135 /** The identity manager. */
136 private final IdentityManager identityManager;
138 /** Interface to freenet. */
139 private final FreenetInterface freenetInterface;
141 /** The Sone downloader. */
142 private final SoneDownloader soneDownloader;
144 /** The image inserter. */
145 private final ImageInserter imageInserter;
147 /** Sone downloader thread-pool. */
148 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
150 /** The update checker. */
151 private final UpdateChecker updateChecker;
153 /** The trust updater. */
154 private final WebOfTrustUpdater webOfTrustUpdater;
156 /** The times Sones were followed. */
157 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
159 /** Locked local Sones. */
160 /* synchronize on itself. */
161 private final Set<Sone> lockedSones = new HashSet<Sone>();
163 /** Sone inserters. */
164 /* synchronize access on this on sones. */
165 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
167 /** Sone rescuers. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
171 /** All known Sones. */
172 private final Set<String> knownSones = new HashSet<String>();
174 /** The post database. */
175 private final Database database;
177 /** Trusted identities, sorted by own identities. */
178 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
180 /** All temporary images. */
181 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
183 /** Ticker for threads that mark own elements as known. */
184 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
186 /** The time the configuration was last touched. */
187 private volatile long lastConfigurationUpdate;
190 * Creates a new core.
192 * @param configuration
193 * The configuration of the core
194 * @param freenetInterface
195 * The freenet interface
196 * @param identityManager
197 * The identity manager
198 * @param webOfTrustUpdater
199 * The WebOfTrust updater
206 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
208 this.configuration = configuration;
209 this.freenetInterface = freenetInterface;
210 this.identityManager = identityManager;
211 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
212 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
213 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
214 this.webOfTrustUpdater = webOfTrustUpdater;
215 this.eventBus = eventBus;
216 this.database = database;
217 preferences = new Preferences(eventBus);
221 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = soneDownloader;
227 this.imageInserter = imageInserter;
228 this.updateChecker = updateChecker;
229 this.webOfTrustUpdater = webOfTrustUpdater;
230 this.eventBus = eventBus;
231 this.database = database;
232 preferences = new Preferences(eventBus);
240 * Returns the time Sone was started.
242 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
244 public long getStartupTime() {
249 * Returns the options used by the core.
251 * @return The options of the core
253 public Preferences getPreferences() {
258 * Returns the identity manager used by the core.
260 * @return The identity manager
262 public IdentityManager getIdentityManager() {
263 return identityManager;
267 * Returns the update checker.
269 * @return The update checker
271 public UpdateChecker getUpdateChecker() {
272 return updateChecker;
276 * Returns the Sone rescuer for the given local Sone.
279 * The local Sone to get the rescuer for
280 * @return The Sone rescuer for the given Sone
282 public SoneRescuer getSoneRescuer(Sone sone) {
283 checkNotNull(sone, "sone must not be null");
284 checkArgument(sone.isLocal(), "sone must be local");
285 synchronized (soneRescuers) {
286 SoneRescuer soneRescuer = soneRescuers.get(sone);
287 if (soneRescuer == null) {
288 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
289 soneRescuers.put(sone, soneRescuer);
297 * Returns whether the given Sone is currently locked.
301 * @return {@code true} if the Sone is locked, {@code false} if it is not
303 public boolean isLocked(Sone sone) {
304 synchronized (lockedSones) {
305 return lockedSones.contains(sone);
309 public SoneBuilder soneBuilder() {
310 return database.newSoneBuilder();
317 public Collection<Sone> getSones() {
318 return database.getSones();
322 * Returns the Sone with the given ID, regardless whether it’s local or
326 * The ID of the Sone to get
327 * @return The Sone with the given ID, or {@code null} if there is no such
331 public Optional<Sone> getSone(String id) {
332 return database.getSone(id);
339 public Collection<Sone> getLocalSones() {
340 return database.getLocalSones();
344 * Returns the local Sone with the given ID, optionally creating a new Sone.
348 * @return The Sone with the given ID, or {@code null}
350 public Sone getLocalSone(String id) {
351 Optional<Sone> sone = database.getSone(id);
352 if (sone.isPresent() && sone.get().isLocal()) {
362 public Collection<Sone> getRemoteSones() {
363 return database.getRemoteSones();
367 * Returns the remote Sone with the given ID.
371 * The ID of the remote Sone to get
372 * @return The Sone with the given ID
374 public Sone getRemoteSone(String id) {
375 return database.getSone(id).orNull();
379 * Returns whether the given Sone has been modified.
382 * The Sone to check for modifications
383 * @return {@code true} if a modification has been detected in the Sone,
384 * {@code false} otherwise
386 public boolean isModifiedSone(Sone sone) {
387 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
391 * Returns the time when the given was first followed by any local Sone.
394 * The Sone to get the time for
395 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
396 * been followed, or {@link Long#MAX_VALUE}
398 public long getSoneFollowingTime(Sone sone) {
399 synchronized (soneFollowingTimes) {
400 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
405 * Returns a post builder.
407 * @return A new post builder
409 public PostBuilder postBuilder() {
410 return database.newPostBuilder();
417 public Optional<Post> getPost(String postId) {
418 return database.getPost(postId);
425 public Collection<Post> getPosts(String soneId) {
426 return database.getPosts(soneId);
433 public Collection<Post> getDirectedPosts(final String recipientId) {
434 checkNotNull(recipientId, "recipient must not be null");
435 return database.getDirectedPosts(recipientId);
439 * Returns a post reply builder.
441 * @return A new post reply builder
443 public PostReplyBuilder postReplyBuilder() {
444 return database.newPostReplyBuilder();
451 public Optional<PostReply> getPostReply(String replyId) {
452 return database.getPostReply(replyId);
459 public List<PostReply> getReplies(final String postId) {
460 return database.getReplies(postId);
464 * Returns all Sones that have liked the given post.
467 * The post to get the liking Sones for
468 * @return The Sones that like the given post
470 public Set<Sone> getLikes(Post post) {
471 Set<Sone> sones = new HashSet<Sone>();
472 for (Sone sone : getSones()) {
473 if (sone.getLikedPostIds().contains(post.getId())) {
481 * Returns all Sones that have liked the given reply.
484 * The reply to get the liking Sones for
485 * @return The Sones that like the given reply
487 public Set<Sone> getLikes(PostReply reply) {
488 Set<Sone> sones = new HashSet<Sone>();
489 for (Sone sone : getSones()) {
490 if (sone.getLikedReplyIds().contains(reply.getId())) {
498 * Returns whether the given post is bookmarked.
502 * @return {@code true} if the given post is bookmarked, {@code false}
505 public boolean isBookmarked(Post post) {
506 return database.isPostBookmarked(post);
510 * Returns all currently known bookmarked posts.
512 * @return All bookmarked posts
514 public Set<Post> getBookmarkedPosts() {
515 return database.getBookmarkedPosts();
518 public AlbumBuilder albumBuilder() {
519 return database.newAlbumBuilder();
523 * Returns the album with the given ID, optionally creating a new album if
524 * an album with the given ID can not be found.
527 * The ID of the album
528 * @return The album with the given ID, or {@code null} if no album with the
531 public Album getAlbum(String albumId) {
532 return database.getAlbum(albumId).orNull();
535 public ImageBuilder imageBuilder() {
536 return database.newImageBuilder();
540 * Returns the image with the given ID, creating it if necessary.
543 * The ID of the image
544 * @return The image with the given ID
546 public Image getImage(String imageId) {
547 return getImage(imageId, true);
551 * Returns the image with the given ID, optionally creating it if it does
555 * The ID of the image
557 * {@code true} to create an image if none exists with the given
559 * @return The image with the given ID, or {@code null} if none exists and
562 public Image getImage(String imageId, boolean create) {
563 Optional<Image> image = database.getImage(imageId);
564 if (image.isPresent()) {
570 Image newImage = database.newImageBuilder().withId(imageId).build();
571 database.storeImage(newImage);
576 * Returns the temporary image with the given ID.
579 * The ID of the temporary image
580 * @return The temporary image, or {@code null} if there is no temporary
581 * image with the given ID
583 public TemporaryImage getTemporaryImage(String imageId) {
584 synchronized (temporaryImages) {
585 return temporaryImages.get(imageId);
594 * Locks the given Sone. A locked Sone will not be inserted by
595 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
601 public void lockSone(Sone sone) {
602 synchronized (lockedSones) {
603 if (lockedSones.add(sone)) {
604 eventBus.post(new SoneLockedEvent(sone));
610 * Unlocks the given Sone.
612 * @see #lockSone(Sone)
616 public void unlockSone(Sone sone) {
617 synchronized (lockedSones) {
618 if (lockedSones.remove(sone)) {
619 eventBus.post(new SoneUnlockedEvent(sone));
625 * Adds a local Sone from the given own identity.
628 * The own identity to create a Sone from
629 * @return The added (or already existing) Sone
631 public Sone addLocalSone(OwnIdentity ownIdentity) {
632 if (ownIdentity == null) {
633 logger.log(Level.WARNING, "Given OwnIdentity is null!");
636 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
637 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
638 sone.setLatestEdition(fromNullable(tryParse(ownIdentity.getProperty("Sone.LatestEdition"))).or(0L));
639 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
641 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
642 eventBus.register(soneInserter);
643 synchronized (soneInserters) {
644 soneInserters.put(sone, soneInserter);
647 sone.setStatus(SoneStatus.idle);
648 soneInserter.start();
653 * Creates a new Sone for the given own identity.
656 * The own identity to create a Sone for
657 * @return The created Sone
659 public Sone createSone(OwnIdentity ownIdentity) {
660 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
661 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
664 Sone sone = addLocalSone(ownIdentity);
666 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
667 touchConfiguration();
672 * Adds the Sone of the given identity.
675 * The identity whose Sone to add
676 * @return The added or already existing Sone
678 public Sone addRemoteSone(Identity identity) {
679 if (identity == null) {
680 logger.log(Level.WARNING, "Given Identity is null!");
683 final Long latestEdition = tryParse(fromNullable(
684 identity.getProperty("Sone.LatestEdition")).or("0"));
685 Optional<Sone> existingSone = getSone(identity.getId());
686 if (existingSone.isPresent() && existingSone.get().isLocal()) {
687 return existingSone.get();
689 boolean newSone = !existingSone.isPresent();
690 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
691 sone.setLatestEdition(latestEdition);
693 synchronized (knownSones) {
694 newSone = !knownSones.contains(sone.getId());
696 sone.setKnown(!newSone);
698 eventBus.post(new NewSoneFoundEvent(sone));
699 for (Sone localSone : getLocalSones()) {
700 if (localSone.getOptions().isAutoFollow()) {
701 followSone(localSone, sone.getId());
706 database.storeSone(sone);
707 soneDownloader.addSone(sone);
708 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
713 * Lets the given local Sone follow the Sone with the given ID.
716 * The local Sone that should follow another Sone
718 * The ID of the Sone to follow
720 public void followSone(Sone sone, String soneId) {
721 checkNotNull(sone, "sone must not be null");
722 checkNotNull(soneId, "soneId must not be null");
723 sone.addFriend(soneId);
724 synchronized (soneFollowingTimes) {
725 if (!soneFollowingTimes.containsKey(soneId)) {
726 long now = System.currentTimeMillis();
727 soneFollowingTimes.put(soneId, now);
728 Optional<Sone> followedSone = getSone(soneId);
729 if (!followedSone.isPresent()) {
732 for (Post post : followedSone.get().getPosts()) {
733 if (post.getTime() < now) {
737 for (PostReply reply : followedSone.get().getReplies()) {
738 if (reply.getTime() < now) {
739 markReplyKnown(reply);
744 touchConfiguration();
748 * Lets the given local Sone unfollow the Sone with the given ID.
751 * The local Sone that should unfollow another Sone
753 * The ID of the Sone being unfollowed
755 public void unfollowSone(Sone sone, String soneId) {
756 checkNotNull(sone, "sone must not be null");
757 checkNotNull(soneId, "soneId must not be null");
758 sone.removeFriend(soneId);
759 boolean unfollowedSoneStillFollowed = false;
760 for (Sone localSone : getLocalSones()) {
761 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
763 if (!unfollowedSoneStillFollowed) {
764 synchronized (soneFollowingTimes) {
765 soneFollowingTimes.remove(soneId);
768 touchConfiguration();
772 * Sets the trust value of the given origin Sone for the target Sone.
779 * The trust value (from {@code -100} to {@code 100})
781 public void setTrust(Sone origin, Sone target, int trustValue) {
782 checkNotNull(origin, "origin must not be null");
783 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
784 checkNotNull(target, "target must not be null");
785 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
786 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
790 * Removes any trust assignment for the given target Sone.
797 public void removeTrust(Sone origin, Sone target) {
798 checkNotNull(origin, "origin must not be null");
799 checkNotNull(target, "target must not be null");
800 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
801 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
805 * Assigns the configured positive trust value for the given target.
812 public void trustSone(Sone origin, Sone target) {
813 setTrust(origin, target, preferences.getPositiveTrust());
817 * Assigns the configured negative trust value for the given target.
824 public void distrustSone(Sone origin, Sone target) {
825 setTrust(origin, target, preferences.getNegativeTrust());
829 * Removes the trust assignment for the given target.
836 public void untrustSone(Sone origin, Sone target) {
837 removeTrust(origin, target);
841 * Updates the stored Sone with the given Sone.
846 public void updateSone(Sone sone) {
847 updateSone(sone, false);
851 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
852 * {@code true}, an older Sone than the current Sone can be given to restore
857 * @param soneRescueMode
858 * {@code true} if the stored Sone should be updated regardless
859 * of the age of the given Sone
861 public void updateSone(final Sone sone, boolean soneRescueMode) {
862 Optional<Sone> storedSone = getSone(sone.getId());
863 if (storedSone.isPresent()) {
864 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
865 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
868 final List<Object> events = new ArrayList<Object>();
869 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(storedSone.get());
870 soneChangeDetector.onNewPosts(new PostProcessor() {
872 public void processPost(Post post) {
873 if (post.getTime() < getSoneFollowingTime(sone)) {
875 } else if (!post.isKnown()) {
876 events.add(new NewPostFoundEvent(post));
880 soneChangeDetector.onRemovedPosts(new PostProcessor() {
882 public void processPost(Post post) {
883 events.add(new PostRemovedEvent(post));
886 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
888 public void processPostReply(PostReply postReply) {
889 if (postReply.getTime() < getSoneFollowingTime(sone)) {
890 postReply.setKnown(true);
891 } else if (!postReply.isKnown()) {
892 events.add(new NewPostReplyFoundEvent(postReply));
896 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
898 public void processPostReply(PostReply postReply) {
899 events.add(new PostReplyRemovedEvent(postReply));
902 soneChangeDetector.detectChanges(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();
917 * Deletes the given Sone. This will remove the Sone from the
918 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
919 * remove the context from its identity.
924 public void deleteSone(Sone sone) {
925 if (!(sone.getIdentity() instanceof OwnIdentity)) {
926 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
929 if (!getLocalSones().contains(sone)) {
930 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
933 SoneInserter soneInserter = soneInserters.remove(sone);
935 database.removeSone(sone);
936 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
937 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
939 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
940 } catch (ConfigurationException ce1) {
941 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
946 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
947 * known} before, a {@link MarkSoneKnownEvent} is fired.
950 * The Sone to mark as known
952 public void markSoneKnown(Sone sone) {
953 if (!sone.isKnown()) {
955 synchronized (knownSones) {
956 knownSones.add(sone.getId());
958 eventBus.post(new MarkSoneKnownEvent(sone));
959 touchConfiguration();
964 * Loads and updates the given Sone from the configuration. If any error is
965 * encountered, loading is aborted and the given Sone is not changed.
968 * The Sone to load and update
970 public void loadSone(Sone sone) {
971 if (!sone.isLocal()) {
972 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
975 logger.info(String.format("Loading local Sone: %s", sone));
978 String sonePrefix = "Sone/" + sone.getId();
979 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
980 if (soneTime == null) {
981 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
984 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
987 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
988 Profile profile = configurationSoneParser.parseProfile();
991 Collection<Post> posts;
993 posts = configurationSoneParser.parsePosts(database);
994 } catch (InvalidPostFound ipf) {
995 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1000 Collection<PostReply> replies;
1002 replies = configurationSoneParser.parsePostReplies(database);
1003 } catch (InvalidPostReplyFound iprf) {
1004 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1008 /* load post likes. */
1009 Set<String> likedPostIds =
1010 configurationSoneParser.parseLikedPostIds();
1012 /* load reply likes. */
1013 Set<String> likedReplyIds =
1014 configurationSoneParser.parseLikedPostReplyIds();
1017 Set<String> friends = configurationSoneParser.parseFriends();
1020 List<Album> topLevelAlbums;
1023 configurationSoneParser.parseTopLevelAlbums(database);
1024 } catch (InvalidAlbumFound iaf) {
1025 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1027 } catch (InvalidParentAlbumFound ipaf) {
1028 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1029 ipaf.getAlbumParentId()));
1035 configurationSoneParser.parseImages(database);
1036 } catch (InvalidImageFound iif) {
1037 logger.log(WARNING, "Invalid image found, aborting load!");
1039 } catch (InvalidParentAlbumFound ipaf) {
1040 logger.log(Level.WARNING,
1041 format("Invalid album image (%s) encountered, aborting load!",
1042 ipaf.getAlbumParentId()));
1047 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1048 if (avatarId != null) {
1049 final Map<String, Image> images =
1050 configurationSoneParser.getImages();
1051 profile.setAvatar(images.get(avatarId));
1055 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1056 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1057 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1058 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1059 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1060 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1062 /* if we’re still here, Sone was loaded successfully. */
1063 synchronized (sone) {
1064 sone.setTime(soneTime);
1065 sone.setProfile(profile);
1066 sone.setPosts(posts);
1067 sone.setReplies(replies);
1068 sone.setLikePostIds(likedPostIds);
1069 sone.setLikeReplyIds(likedReplyIds);
1070 for (String friendId : friends) {
1071 followSone(sone, friendId);
1073 for (Album album : sone.getRootAlbum().getAlbums()) {
1074 sone.getRootAlbum().removeAlbum(album);
1076 for (Album album : topLevelAlbums) {
1077 sone.getRootAlbum().addAlbum(album);
1079 database.storeSone(sone);
1080 synchronized (soneInserters) {
1081 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1084 synchronized (knownSones) {
1085 for (String friend : friends) {
1086 knownSones.add(friend);
1089 for (Post post : posts) {
1090 post.setKnown(true);
1092 for (PostReply reply : replies) {
1093 reply.setKnown(true);
1096 logger.info(String.format("Sone loaded successfully: %s", sone));
1100 * Creates a new post.
1103 * The Sone that creates the post
1105 * The recipient Sone, or {@code null} if this post does not have
1108 * The text of the post
1109 * @return The created post
1111 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1112 checkNotNull(text, "text must not be null");
1113 checkArgument(text.trim().length() > 0, "text must not be empty");
1114 if (!sone.isLocal()) {
1115 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1118 PostBuilder postBuilder = database.newPostBuilder();
1119 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1120 if (recipient.isPresent()) {
1121 postBuilder.to(recipient.get().getId());
1123 final Post post = postBuilder.build();
1124 database.storePost(post);
1125 eventBus.post(new NewPostFoundEvent(post));
1127 touchConfiguration();
1128 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1133 * Deletes the given post.
1136 * The post to delete
1138 public void deletePost(Post post) {
1139 if (!post.getSone().isLocal()) {
1140 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1143 database.removePost(post);
1144 eventBus.post(new PostRemovedEvent(post));
1145 markPostKnown(post);
1146 touchConfiguration();
1150 * Marks the given post as known, if it is currently not a known post
1151 * (according to {@link Post#isKnown()}).
1154 * The post to mark as known
1156 public void markPostKnown(Post post) {
1157 post.setKnown(true);
1158 eventBus.post(new MarkPostKnownEvent(post));
1159 touchConfiguration();
1160 for (PostReply reply : getReplies(post.getId())) {
1161 markReplyKnown(reply);
1165 public void bookmarkPost(Post post) {
1166 database.bookmarkPost(post);
1170 * Removes the given post from the bookmarks.
1173 * The post to unbookmark
1175 public void unbookmarkPost(Post post) {
1176 database.unbookmarkPost(post);
1180 * Creates a new reply.
1183 * The Sone that creates the reply
1185 * The post that this reply refers to
1187 * The text of the reply
1188 * @return The created reply
1190 public PostReply createReply(Sone sone, Post post, String text) {
1191 checkNotNull(text, "text must not be null");
1192 checkArgument(text.trim().length() > 0, "text must not be empty");
1193 if (!sone.isLocal()) {
1194 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1197 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1198 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1199 final PostReply reply = postReplyBuilder.build();
1200 database.storePostReply(reply);
1201 eventBus.post(new NewPostReplyFoundEvent(reply));
1202 sone.addReply(reply);
1203 touchConfiguration();
1204 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1209 * Deletes the given reply.
1212 * The reply to delete
1214 public void deleteReply(PostReply reply) {
1215 Sone sone = reply.getSone();
1216 if (!sone.isLocal()) {
1217 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1220 database.removePostReply(reply);
1221 markReplyKnown(reply);
1222 sone.removeReply(reply);
1223 touchConfiguration();
1227 * Marks the given reply as known, if it is currently not a known reply
1228 * (according to {@link Reply#isKnown()}).
1231 * The reply to mark as known
1233 public void markReplyKnown(PostReply reply) {
1234 boolean previouslyKnown = reply.isKnown();
1235 reply.setKnown(true);
1236 eventBus.post(new MarkPostReplyKnownEvent(reply));
1237 if (!previouslyKnown) {
1238 touchConfiguration();
1243 * Creates a new album for the given Sone.
1246 * The Sone to create the album for
1248 * The parent of the album (may be {@code null} to create a
1250 * @return The new album
1252 public Album createAlbum(Sone sone, Album parent) {
1253 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1254 database.storeAlbum(album);
1255 parent.addAlbum(album);
1260 * Deletes the given album. The owner of the album has to be a local Sone,
1261 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1264 * The album to remove
1266 public void deleteAlbum(Album album) {
1267 checkNotNull(album, "album must not be null");
1268 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1269 if (!album.isEmpty()) {
1272 album.getParent().removeAlbum(album);
1273 database.removeAlbum(album);
1274 touchConfiguration();
1278 * Creates a new image.
1281 * The Sone creating the image
1283 * The album the image will be inserted into
1284 * @param temporaryImage
1285 * The temporary image to create the image from
1286 * @return The newly created image
1288 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1289 checkNotNull(sone, "sone must not be null");
1290 checkNotNull(album, "album must not be null");
1291 checkNotNull(temporaryImage, "temporaryImage must not be null");
1292 checkArgument(sone.isLocal(), "sone must be a local Sone");
1293 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1294 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1295 album.addImage(image);
1296 database.storeImage(image);
1297 imageInserter.insertImage(temporaryImage, image);
1302 * Deletes the given image. This method will also delete a matching
1305 * @see #deleteTemporaryImage(String)
1307 * The image to delete
1309 public void deleteImage(Image image) {
1310 checkNotNull(image, "image must not be null");
1311 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1312 deleteTemporaryImage(image.getId());
1313 image.getAlbum().removeImage(image);
1314 database.removeImage(image);
1315 touchConfiguration();
1319 * Creates a new temporary image.
1322 * The MIME type of the temporary image
1324 * The encoded data of the image
1325 * @return The temporary image
1327 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1328 TemporaryImage temporaryImage = new TemporaryImage();
1329 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1330 synchronized (temporaryImages) {
1331 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1333 return temporaryImage;
1337 * Deletes the temporary image with the given ID.
1340 * The ID of the temporary image to delete
1342 public void deleteTemporaryImage(String imageId) {
1343 checkNotNull(imageId, "imageId must not be null");
1344 synchronized (temporaryImages) {
1345 temporaryImages.remove(imageId);
1347 Image image = getImage(imageId, false);
1348 if (image != null) {
1349 imageInserter.cancelImageInsert(image);
1354 * Notifies the core that the configuration, either of the core or of a
1355 * single local Sone, has changed, and that the configuration should be
1358 public void touchConfiguration() {
1359 lastConfigurationUpdate = System.currentTimeMillis();
1370 public void serviceStart() {
1371 loadConfiguration();
1372 updateChecker.start();
1373 identityManager.start();
1374 webOfTrustUpdater.init();
1375 webOfTrustUpdater.start();
1383 public void serviceRun() {
1384 long lastSaved = System.currentTimeMillis();
1385 while (!shouldStop()) {
1387 long now = System.currentTimeMillis();
1388 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1389 for (Sone localSone : getLocalSones()) {
1390 saveSone(localSone);
1392 saveConfiguration();
1402 public void serviceStop() {
1403 localElementTicker.shutdownNow();
1404 synchronized (soneInserters) {
1405 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1406 soneInserter.getValue().stop();
1407 saveSone(soneInserter.getKey());
1410 saveConfiguration();
1412 webOfTrustUpdater.stop();
1413 updateChecker.stop();
1414 soneDownloader.stop();
1415 soneDownloaders.shutdown();
1416 identityManager.stop();
1424 * Saves the given Sone. This will persist all local settings for the given
1425 * Sone, such as the friends list and similar, private options.
1430 private synchronized void saveSone(Sone sone) {
1431 if (!sone.isLocal()) {
1432 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1435 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1436 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1440 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1442 /* save Sone into configuration. */
1443 String sonePrefix = "Sone/" + sone.getId();
1444 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1445 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1448 Profile profile = sone.getProfile();
1449 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1450 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1451 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1452 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1453 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1454 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1455 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1457 /* save profile fields. */
1458 int fieldCounter = 0;
1459 for (Field profileField : profile.getFields()) {
1460 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1461 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1462 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1464 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1467 int postCounter = 0;
1468 for (Post post : sone.getPosts()) {
1469 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1470 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1471 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1472 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1473 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1475 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1478 int replyCounter = 0;
1479 for (PostReply reply : sone.getReplies()) {
1480 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1481 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1482 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1483 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1484 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1486 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1488 /* save post likes. */
1489 int postLikeCounter = 0;
1490 for (String postId : sone.getLikedPostIds()) {
1491 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1493 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1495 /* save reply likes. */
1496 int replyLikeCounter = 0;
1497 for (String replyId : sone.getLikedReplyIds()) {
1498 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1500 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1503 int friendCounter = 0;
1504 for (String friendId : sone.getFriends()) {
1505 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1507 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1509 /* save albums. first, collect in a flat structure, top-level first. */
1510 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1512 int albumCounter = 0;
1513 for (Album album : albums) {
1514 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1515 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1516 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1517 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1518 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1519 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1521 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1524 int imageCounter = 0;
1525 for (Album album : albums) {
1526 for (Image image : album.getImages()) {
1527 if (!image.isInserted()) {
1530 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1531 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1532 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1533 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1534 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1535 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1536 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1537 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1538 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1541 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1544 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1545 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1546 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1547 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1548 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1549 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1551 configuration.save();
1553 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1555 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1556 } catch (ConfigurationException ce1) {
1557 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1562 * Saves the current options.
1564 private void saveConfiguration() {
1565 synchronized (configuration) {
1566 if (storingConfiguration) {
1567 logger.log(Level.FINE, "Already storing configuration…");
1570 storingConfiguration = true;
1573 /* store the options first. */
1575 preferences.saveTo(configuration);
1577 /* save known Sones. */
1578 int soneCounter = 0;
1579 synchronized (knownSones) {
1580 for (String knownSoneId : knownSones) {
1581 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1583 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1586 /* save Sone following times. */
1588 synchronized (soneFollowingTimes) {
1589 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1590 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1591 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1594 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1597 /* save known posts. */
1601 configuration.save();
1603 } catch (ConfigurationException ce1) {
1604 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1605 } catch (DatabaseException de1) {
1606 logger.log(Level.SEVERE, "Could not save database!", de1);
1608 synchronized (configuration) {
1609 storingConfiguration = false;
1615 * Loads the configuration.
1617 private void loadConfiguration() {
1618 new PreferencesLoader(preferences).loadFrom(configuration);
1620 /* load known Sones. */
1621 int soneCounter = 0;
1623 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1624 if (knownSoneId == null) {
1627 synchronized (knownSones) {
1628 knownSones.add(knownSoneId);
1632 /* load Sone following times. */
1635 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1636 if (soneId == null) {
1639 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1640 synchronized (soneFollowingTimes) {
1641 soneFollowingTimes.put(soneId, time);
1648 * Notifies the core that a new {@link OwnIdentity} was added.
1650 * @param ownIdentityAddedEvent
1654 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1655 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1656 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1657 if (ownIdentity.hasContext("Sone")) {
1658 addLocalSone(ownIdentity);
1663 * Notifies the core that an {@link OwnIdentity} was removed.
1665 * @param ownIdentityRemovedEvent
1669 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1670 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1671 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1672 trustedIdentities.removeAll(ownIdentity);
1676 * Notifies the core that a new {@link Identity} was added.
1678 * @param identityAddedEvent
1682 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1683 Identity identity = identityAddedEvent.identity();
1684 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1685 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1686 addRemoteSone(identity);
1690 * Notifies the core that an {@link Identity} was updated.
1692 * @param identityUpdatedEvent
1696 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1697 Identity identity = identityUpdatedEvent.identity();
1698 final Sone sone = getRemoteSone(identity.getId());
1699 if (sone.isLocal()) {
1702 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1703 soneDownloader.addSone(sone);
1704 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1708 * Notifies the core that an {@link Identity} was removed.
1710 * @param identityRemovedEvent
1714 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1715 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1716 Identity identity = identityRemovedEvent.identity();
1717 trustedIdentities.remove(ownIdentity, identity);
1718 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1719 if (trustedIdentity.getKey().equals(ownIdentity)) {
1722 if (trustedIdentity.getValue().contains(identity)) {
1726 Optional<Sone> sone = getSone(identity.getId());
1727 if (!sone.isPresent()) {
1728 /* TODO - we don’t have the Sone anymore. should this happen? */
1731 database.removeSone(sone.get());
1732 eventBus.post(new SoneRemovedEvent(sone.get()));
1736 * Deletes the temporary image.
1738 * @param imageInsertFinishedEvent
1742 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1743 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1744 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1745 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1746 touchConfiguration();
1750 class MarkPostKnown implements Runnable {
1752 private final Post post;
1754 public MarkPostKnown(Post post) {
1760 markPostKnown(post);
1766 class MarkReplyKnown implements Runnable {
1768 private final PostReply postReply;
1770 public MarkReplyKnown(PostReply postReply) {
1771 this.postReply = postReply;
1776 markReplyKnown(postReply);