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())) {
518 if (isCompatibilityMode(CompatibilityMode.oldElementIds)) {
519 if (sone.getLikedPostIds().contains(post.getInternalId())) {
528 * Returns all Sones that have liked the given reply.
531 * The reply to get the liking Sones for
532 * @return The Sones that like the given reply
534 public Set<Sone> getLikes(PostReply reply) {
535 Set<Sone> sones = new HashSet<Sone>();
536 for (Sone sone : getSones()) {
537 if (sone.getLikedReplyIds().contains(reply.getId())) {
540 if (isCompatibilityMode(CompatibilityMode.oldElementIds)) {
541 if (sone.getLikedReplyIds().contains(reply.getInternalId())) {
550 * Returns whether the given post is bookmarked.
554 * @return {@code true} if the given post is bookmarked, {@code false}
557 public boolean isBookmarked(Post post) {
558 return database.isPostBookmarked(post);
562 * Returns all currently known bookmarked posts.
564 * @return All bookmarked posts
566 public Set<Post> getBookmarkedPosts() {
567 return database.getBookmarkedPosts();
570 public AlbumBuilder albumBuilder() {
571 return database.newAlbumBuilder();
575 * Returns the album with the given ID, optionally creating a new album if
576 * an album with the given ID can not be found.
579 * The ID of the album
580 * @return The album with the given ID, or {@code null} if no album with the
583 public Optional<Album> getAlbum(String albumId) {
584 return database.getAlbum(albumId);
587 public ImageBuilder imageBuilder() {
588 return database.newImageBuilder();
592 * Returns the image with the given ID, creating it if necessary.
595 * The ID of the image
596 * @return The image with the given ID
598 public Image getImage(String imageId) {
599 return getImage(imageId, true);
603 * Returns the image with the given ID, optionally creating it if it does
607 * The ID of the image
609 * {@code true} to create an image if none exists with the given
611 * @return The image with the given ID, or {@code null} if none exists and
614 public Image getImage(String imageId, boolean create) {
615 Optional<Image> image = database.getImage(imageId);
616 if (image.isPresent()) {
622 Image newImage = database.newImageBuilder().withId(imageId).build();
623 database.storeImage(newImage);
628 * Returns the temporary image with the given ID.
631 * The ID of the temporary image
632 * @return The temporary image, or {@code null} if there is no temporary
633 * image with the given ID
635 public TemporaryImage getTemporaryImage(String imageId) {
636 synchronized (temporaryImages) {
637 return temporaryImages.get(imageId);
646 * Locks the given Sone. A locked Sone will not be inserted by
647 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
653 public void lockSone(Sone sone) {
654 synchronized (lockedSones) {
655 if (lockedSones.add(sone)) {
656 eventBus.post(new SoneLockedEvent(sone));
662 * Unlocks the given Sone.
664 * @see #lockSone(Sone)
668 public void unlockSone(Sone sone) {
669 synchronized (lockedSones) {
670 if (lockedSones.remove(sone)) {
671 eventBus.post(new SoneUnlockedEvent(sone));
677 * Adds a local Sone from the given own identity.
680 * The own identity to create a Sone from
681 * @return The added (or already existing) Sone
683 public Sone addLocalSone(OwnIdentity ownIdentity) {
684 if (ownIdentity == null) {
685 logger.log(Level.WARNING, "Given OwnIdentity is null!");
688 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
689 Sone sone = database.newSoneBuilder().local().from(ownIdentity).build();
690 String property = fromNullable(ownIdentity.getProperty("Sone.LatestEdition")).or("0");
691 sone.setLatestEdition(fromNullable(tryParse(property)).or(0L));
692 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
694 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
695 eventBus.register(soneInserter);
696 synchronized (soneInserters) {
697 soneInserters.put(sone, soneInserter);
700 database.storeSone(sone);
701 sone.setStatus(SoneStatus.idle);
702 soneInserter.start();
707 * Creates a new Sone for the given own identity.
710 * The own identity to create a Sone for
711 * @return The created Sone
713 public Sone createSone(OwnIdentity ownIdentity) {
714 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
715 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
718 Sone sone = addLocalSone(ownIdentity);
720 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
721 touchConfiguration();
726 * Adds the Sone of the given identity.
729 * The identity whose Sone to add
730 * @return The added or already existing Sone
732 public Sone addRemoteSone(Identity identity) {
733 if (identity == null) {
734 logger.log(Level.WARNING, "Given Identity is null!");
737 String property = fromNullable(identity.getProperty("Sone.LatestEdition")).or("0");
738 long latestEdition = fromNullable(tryParse(property)).or(0L);
739 Optional<Sone> existingSone = getSone(identity.getId());
740 if (existingSone.isPresent() && existingSone.get().isLocal()) {
741 return existingSone.get();
743 boolean newSone = !existingSone.isPresent();
744 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
745 sone.setLatestEdition(latestEdition);
747 synchronized (knownSones) {
748 newSone = !knownSones.contains(sone.getId());
750 sone.setKnown(!newSone);
752 eventBus.post(new NewSoneFoundEvent(sone));
753 for (Sone localSone : getLocalSones()) {
754 if (localSone.getOptions().isAutoFollow()) {
755 followSone(localSone, sone.getId());
760 database.storeSone(sone);
761 soneDownloader.addSone(sone);
762 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
767 * Lets the given local Sone follow the Sone with the given ID.
770 * The local Sone that should follow another Sone
772 * The ID of the Sone to follow
774 public void followSone(Sone sone, String soneId) {
775 checkNotNull(sone, "sone must not be null");
776 checkNotNull(soneId, "soneId must not be null");
777 database.addFriend(sone, soneId);
778 synchronized (soneFollowingTimes) {
779 if (!soneFollowingTimes.containsKey(soneId)) {
780 long now = System.currentTimeMillis();
781 soneFollowingTimes.put(soneId, now);
782 Optional<Sone> followedSone = getSone(soneId);
783 if (!followedSone.isPresent()) {
786 for (Post post : followedSone.get().getPosts()) {
787 if (post.getTime() < now) {
791 for (PostReply reply : followedSone.get().getReplies()) {
792 if (reply.getTime() < now) {
793 markReplyKnown(reply);
798 touchConfiguration();
802 * Lets the given local Sone unfollow the Sone with the given ID.
805 * The local Sone that should unfollow another Sone
807 * The ID of the Sone being unfollowed
809 public void unfollowSone(Sone sone, String soneId) {
810 checkNotNull(sone, "sone must not be null");
811 checkNotNull(soneId, "soneId must not be null");
812 database.removeFriend(sone, soneId);
813 boolean unfollowedSoneStillFollowed = false;
814 for (Sone localSone : getLocalSones()) {
815 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
817 if (!unfollowedSoneStillFollowed) {
818 synchronized (soneFollowingTimes) {
819 soneFollowingTimes.remove(soneId);
822 touchConfiguration();
826 * Sets the trust value of the given origin Sone for the target Sone.
833 * The trust value (from {@code -100} to {@code 100})
835 public void setTrust(Sone origin, Sone target, int trustValue) {
836 checkNotNull(origin, "origin must not be null");
837 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
838 checkNotNull(target, "target must not be null");
839 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
840 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
844 * Removes any trust assignment for the given target Sone.
851 public void removeTrust(Sone origin, Sone target) {
852 checkNotNull(origin, "origin must not be null");
853 checkNotNull(target, "target must not be null");
854 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
855 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
859 * Assigns the configured positive trust value for the given target.
866 public void trustSone(Sone origin, Sone target) {
867 setTrust(origin, target, preferences.getPositiveTrust());
871 * Assigns the configured negative trust value for the given target.
878 public void distrustSone(Sone origin, Sone target) {
879 setTrust(origin, target, preferences.getNegativeTrust());
883 * Removes the trust assignment for the given target.
890 public void untrustSone(Sone origin, Sone target) {
891 removeTrust(origin, target);
895 * Updates the stored Sone with the given Sone.
900 public void updateSone(Sone sone) {
901 updateSone(sone, false);
905 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
906 * {@code true}, an older Sone than the current Sone can be given to restore
911 * @param soneRescueMode
912 * {@code true} if the stored Sone should be updated regardless
913 * of the age of the given Sone
915 public void updateSone(final Sone sone, boolean soneRescueMode) {
916 Optional<Sone> storedSone = getSone(sone.getId());
917 if (storedSone.isPresent()) {
918 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
919 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
922 List<Object> events =
923 collectEventsForChangesInSone(storedSone.get(), sone);
924 database.storeSone(sone);
925 for (Object event : events) {
926 eventBus.post(event);
928 sone.setOptions(storedSone.get().getOptions());
929 sone.setKnown(storedSone.get().isKnown());
930 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
931 if (sone.isLocal()) {
932 touchConfiguration();
937 private List<Object> collectEventsForChangesInSone(Sone oldSone,
938 final Sone newSone) {
939 final List<Object> events = new ArrayList<Object>();
940 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
942 soneChangeDetector.onNewPosts(new PostProcessor() {
944 public void processPost(Post post) {
945 if (post.getTime() < getSoneFollowingTime(newSone)) {
947 } else if (!post.isKnown()) {
948 events.add(new NewPostFoundEvent(post));
952 soneChangeDetector.onRemovedPosts(new PostProcessor() {
954 public void processPost(Post post) {
955 events.add(new PostRemovedEvent(post));
958 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
960 public void processPostReply(PostReply postReply) {
961 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
962 postReply.setKnown(true);
963 } else if (!postReply.isKnown()) {
964 events.add(new NewPostReplyFoundEvent(postReply));
968 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
970 public void processPostReply(PostReply postReply) {
971 events.add(new PostReplyRemovedEvent(postReply));
974 soneChangeDetector.detectChanges(newSone);
979 * Deletes the given Sone. This will remove the Sone from the
980 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
981 * remove the context from its identity.
986 public void deleteSone(Sone sone) {
987 if (!(sone.getIdentity() instanceof OwnIdentity)) {
988 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
991 if (!getLocalSones().contains(sone)) {
992 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
995 SoneInserter soneInserter = soneInserters.remove(sone);
997 database.removeSone(sone);
998 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
999 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1001 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1002 } catch (ConfigurationException ce1) {
1003 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1008 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1009 * known} before, a {@link MarkSoneKnownEvent} is fired.
1012 * The Sone to mark as known
1014 public void markSoneKnown(Sone sone) {
1015 if (!sone.isKnown()) {
1016 sone.setKnown(true);
1017 synchronized (knownSones) {
1018 knownSones.add(sone.getId());
1020 eventBus.post(new MarkSoneKnownEvent(sone));
1021 touchConfiguration();
1026 * Loads and updates the given Sone from the configuration. If any error is
1027 * encountered, loading is aborted and the given Sone is not changed.
1030 * The Sone to load and update
1032 public void loadSone(Sone sone) {
1033 if (!sone.isLocal()) {
1034 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1037 logger.info(String.format("Loading local Sone: %s", sone));
1040 String sonePrefix = "Sone/" + sone.getId();
1041 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1042 if (soneTime == null) {
1043 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1046 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1049 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1050 Profile profile = configurationSoneParser.parseProfile();
1053 Collection<Post> posts;
1055 posts = configurationSoneParser.parsePosts(database);
1056 } catch (InvalidPostFound ipf) {
1057 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1062 Collection<PostReply> replies;
1064 replies = configurationSoneParser.parsePostReplies(database);
1065 } catch (InvalidPostReplyFound iprf) {
1066 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1070 /* load post likes. */
1071 Set<String> likedPostIds =
1072 configurationSoneParser.parseLikedPostIds();
1074 /* load reply likes. */
1075 Set<String> likedReplyIds =
1076 configurationSoneParser.parseLikedPostReplyIds();
1079 List<Album> topLevelAlbums;
1082 configurationSoneParser.parseTopLevelAlbums(database);
1083 } catch (InvalidAlbumFound iaf) {
1084 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1086 } catch (InvalidParentAlbumFound ipaf) {
1087 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1088 ipaf.getAlbumParentId()));
1094 configurationSoneParser.parseImages(database);
1095 } catch (InvalidImageFound iif) {
1096 logger.log(WARNING, "Invalid image found, aborting load!");
1098 } catch (InvalidParentAlbumFound ipaf) {
1099 logger.log(Level.WARNING,
1100 format("Invalid album image (%s) encountered, aborting load!",
1101 ipaf.getAlbumParentId()));
1106 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1107 if (avatarId != null) {
1108 final Map<String, Image> images =
1109 configurationSoneParser.getImages();
1110 profile.setAvatar(images.get(avatarId));
1114 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(false));
1115 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(false));
1116 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(true));
1117 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(true));
1118 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(true));
1119 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1121 /* if we’re still here, Sone was loaded successfully. */
1122 synchronized (sone) {
1123 sone.setTime(soneTime);
1124 sone.setProfile(profile);
1125 sone.setPosts(posts);
1126 sone.setReplies(replies);
1127 sone.setLikePostIds(likedPostIds);
1128 sone.setLikeReplyIds(likedReplyIds);
1129 for (Album album : sone.getRootAlbum().getAlbums()) {
1130 sone.getRootAlbum().removeAlbum(album);
1132 for (Album album : topLevelAlbums) {
1133 sone.getRootAlbum().addAlbum(album);
1135 synchronized (soneInserters) {
1136 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1139 for (Post post : posts) {
1140 post.setKnown(true);
1142 for (PostReply reply : replies) {
1143 reply.setKnown(true);
1146 logger.info(String.format("Sone loaded successfully: %s", sone));
1150 * Creates a new post.
1153 * The Sone that creates the post
1155 * The recipient Sone, or {@code null} if this post does not have
1158 * The text of the post
1159 * @return The created post
1161 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1162 checkNotNull(text, "text must not be null");
1163 checkArgument(text.trim().length() > 0, "text must not be empty");
1164 if (!sone.isLocal()) {
1165 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1168 PostBuilder postBuilder = database.newPostBuilder();
1169 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
1170 if (recipient.isPresent()) {
1171 postBuilder.to(recipient.get().getId());
1173 final Post post = postBuilder.build();
1174 database.storePost(post);
1175 eventBus.post(new NewPostFoundEvent(post));
1177 touchConfiguration();
1178 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1183 * Deletes the given post.
1186 * The post to delete
1188 public void deletePost(Post post) {
1189 if (!post.getSone().isLocal()) {
1190 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1193 database.removePost(post);
1194 eventBus.post(new PostRemovedEvent(post));
1195 markPostKnown(post);
1196 touchConfiguration();
1200 * Marks the given post as known, if it is currently not a known post
1201 * (according to {@link Post#isKnown()}).
1204 * The post to mark as known
1206 public void markPostKnown(Post post) {
1207 post.setKnown(true);
1208 eventBus.post(new MarkPostKnownEvent(post));
1209 touchConfiguration();
1210 for (PostReply reply : getReplies(post.getId())) {
1211 markReplyKnown(reply);
1215 public void bookmarkPost(Post post) {
1216 database.bookmarkPost(post);
1220 * Removes the given post from the bookmarks.
1223 * The post to unbookmark
1225 public void unbookmarkPost(Post post) {
1226 database.unbookmarkPost(post);
1230 * Creates a new reply.
1233 * The Sone that creates the reply
1235 * The post that this reply refers to
1237 * The text of the reply
1238 * @return The created reply
1240 public PostReply createReply(Sone sone, Post post, String text) {
1241 checkNotNull(text, "text must not be null");
1242 checkArgument(text.trim().length() > 0, "text must not be empty");
1243 if (!sone.isLocal()) {
1244 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1247 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1248 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1249 final PostReply reply = postReplyBuilder.build();
1250 database.storePostReply(reply);
1251 eventBus.post(new NewPostReplyFoundEvent(reply));
1252 sone.addReply(reply);
1253 touchConfiguration();
1254 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1259 * Deletes the given reply.
1262 * The reply to delete
1264 public void deleteReply(PostReply reply) {
1265 Sone sone = reply.getSone();
1266 if (!sone.isLocal()) {
1267 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1270 database.removePostReply(reply);
1271 markReplyKnown(reply);
1272 sone.removeReply(reply);
1273 touchConfiguration();
1277 * Marks the given reply as known, if it is currently not a known reply
1278 * (according to {@link Reply#isKnown()}).
1281 * The reply to mark as known
1283 public void markReplyKnown(PostReply reply) {
1284 boolean previouslyKnown = reply.isKnown();
1285 reply.setKnown(true);
1286 eventBus.post(new MarkPostReplyKnownEvent(reply));
1287 if (!previouslyKnown) {
1288 touchConfiguration();
1293 * Creates a new album for the given Sone.
1296 * The Sone to create the album for
1298 * The parent of the album (may be {@code null} to create a
1300 * @return The new album
1302 public Album createAlbum(Sone sone, Album parent) {
1303 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1304 database.storeAlbum(album);
1305 parent.addAlbum(album);
1310 * Deletes the given album. The owner of the album has to be a local Sone,
1311 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1314 * The album to remove
1316 public void deleteAlbum(Album album) {
1317 checkNotNull(album, "album must not be null");
1318 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1319 if (!album.isEmpty()) {
1322 album.getParent().removeAlbum(album);
1323 database.removeAlbum(album);
1324 touchConfiguration();
1328 * Creates a new image.
1331 * The Sone creating the image
1333 * The album the image will be inserted into
1334 * @param temporaryImage
1335 * The temporary image to create the image from
1336 * @return The newly created image
1338 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1339 checkNotNull(sone, "sone must not be null");
1340 checkNotNull(album, "album must not be null");
1341 checkNotNull(temporaryImage, "temporaryImage must not be null");
1342 checkArgument(sone.isLocal(), "sone must be a local Sone");
1343 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1344 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1345 album.addImage(image);
1346 database.storeImage(image);
1347 imageInserter.insertImage(temporaryImage, image);
1352 * Deletes the given image. This method will also delete a matching
1355 * @see #deleteTemporaryImage(String)
1357 * The image to delete
1359 public void deleteImage(Image image) {
1360 checkNotNull(image, "image must not be null");
1361 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1362 deleteTemporaryImage(image.getId());
1363 image.getAlbum().removeImage(image);
1364 database.removeImage(image);
1365 touchConfiguration();
1369 * Creates a new temporary image.
1372 * The MIME type of the temporary image
1374 * The encoded data of the image
1375 * @return The temporary image
1377 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1378 TemporaryImage temporaryImage = new TemporaryImage();
1379 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1380 synchronized (temporaryImages) {
1381 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1383 return temporaryImage;
1387 * Deletes the temporary image with the given ID.
1390 * The ID of the temporary image to delete
1392 public void deleteTemporaryImage(String imageId) {
1393 checkNotNull(imageId, "imageId must not be null");
1394 synchronized (temporaryImages) {
1395 temporaryImages.remove(imageId);
1397 Image image = getImage(imageId, false);
1398 if (image != null) {
1399 imageInserter.cancelImageInsert(image);
1404 * Notifies the core that the configuration, either of the core or of a
1405 * single local Sone, has changed, and that the configuration should be
1408 public void touchConfiguration() {
1409 lastConfigurationUpdate = System.currentTimeMillis();
1420 public void serviceStart() {
1421 loadConfiguration();
1422 updateChecker.start();
1423 identityManager.start();
1424 webOfTrustUpdater.init();
1425 webOfTrustUpdater.start();
1433 public void serviceRun() {
1434 long lastSaved = System.currentTimeMillis();
1435 while (!shouldStop()) {
1437 long now = System.currentTimeMillis();
1438 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1439 for (Sone localSone : getLocalSones()) {
1440 saveSone(localSone);
1442 saveConfiguration();
1452 public void serviceStop() {
1453 localElementTicker.shutdownNow();
1454 synchronized (soneInserters) {
1455 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1456 soneInserter.getValue().stop();
1457 saveSone(soneInserter.getKey());
1460 synchronized (soneRescuers) {
1461 for (SoneRescuer soneRescuer : soneRescuers.values()) {
1465 saveConfiguration();
1467 webOfTrustUpdater.stop();
1468 updateChecker.stop();
1469 soneDownloader.stop();
1470 soneDownloaders.shutdown();
1471 identityManager.stop();
1479 * Saves the given Sone. This will persist all local settings for the given
1480 * Sone, such as the friends list and similar, private options.
1485 private synchronized void saveSone(Sone sone) {
1486 if (!sone.isLocal()) {
1487 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1490 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1491 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1495 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1497 /* save Sone into configuration. */
1498 String sonePrefix = "Sone/" + sone.getId();
1499 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1500 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1503 Profile profile = sone.getProfile();
1504 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1505 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1506 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1507 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1508 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1509 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1510 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1512 /* save profile fields. */
1513 int fieldCounter = 0;
1514 for (Field profileField : profile.getFields()) {
1515 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1516 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1517 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1519 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1522 int postCounter = 0;
1523 for (Post post : sone.getPosts()) {
1524 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1525 configuration.getStringValue(postPrefix + "/ID").setValue(post.getInternalId());
1526 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1527 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1528 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1530 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1533 int replyCounter = 0;
1534 for (PostReply reply : sone.getReplies()) {
1535 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1536 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getInternalId());
1537 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1538 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1539 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1541 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1543 /* save post likes. */
1544 int postLikeCounter = 0;
1545 for (String postId : sone.getLikedPostIds()) {
1546 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1548 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1550 /* save reply likes. */
1551 int replyLikeCounter = 0;
1552 for (String replyId : sone.getLikedReplyIds()) {
1553 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1555 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1557 /* save albums. first, collect in a flat structure, top-level first. */
1558 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1560 int albumCounter = 0;
1561 for (Album album : albums) {
1562 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1563 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getInternalId());
1564 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1565 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1566 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1567 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1569 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1572 int imageCounter = 0;
1573 for (Album album : albums) {
1574 for (Image image : album.getImages()) {
1575 if (!image.isInserted()) {
1578 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1579 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getInternalId());
1580 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getInternalId());
1581 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1582 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1583 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1584 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1585 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1586 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1589 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1592 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1593 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1594 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1595 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1596 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1597 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1599 configuration.save();
1601 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1603 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1604 } catch (ConfigurationException ce1) {
1605 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1610 * Saves the current options.
1612 private void saveConfiguration() {
1613 synchronized (configuration) {
1614 if (storingConfiguration) {
1615 logger.log(Level.FINE, "Already storing configuration…");
1618 storingConfiguration = true;
1621 /* store the options first. */
1623 preferences.saveTo(configuration);
1625 /* save known Sones. */
1626 int soneCounter = 0;
1627 synchronized (knownSones) {
1628 for (String knownSoneId : knownSones) {
1629 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1631 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1634 /* save Sone following times. */
1636 synchronized (soneFollowingTimes) {
1637 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1638 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1639 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1642 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1645 /* save compatibility modes. */
1646 configuration.getBooleanValue("CompatibilityModes/OldElementIds").setValue(compatibilityModes.contains(CompatibilityMode.oldElementIds));
1648 /* save known posts. */
1652 configuration.save();
1654 } catch (ConfigurationException ce1) {
1655 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1656 } catch (DatabaseException de1) {
1657 logger.log(Level.SEVERE, "Could not save database!", de1);
1659 synchronized (configuration) {
1660 storingConfiguration = false;
1666 * Loads the configuration.
1668 private void loadConfiguration() {
1669 new PreferencesLoader(preferences).loadFrom(configuration);
1671 /* load known Sones. */
1672 int soneCounter = 0;
1674 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1675 if (knownSoneId == null) {
1678 synchronized (knownSones) {
1679 knownSones.add(knownSoneId);
1683 /* load Sone following times. */
1686 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1687 if (soneId == null) {
1690 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1691 synchronized (soneFollowingTimes) {
1692 soneFollowingTimes.put(soneId, time);
1697 /* load compatibility modes. */
1698 if (configuration.getBooleanValue("CompatibilityModes/OldElementIds").getValue(false)) {
1699 setCompatibilityMode(CompatibilityMode.oldElementIds);
1704 * Notifies the core that a new {@link OwnIdentity} was added.
1706 * @param ownIdentityAddedEvent
1710 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1711 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1712 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1713 if (ownIdentity.hasContext("Sone")) {
1714 addLocalSone(ownIdentity);
1719 * Notifies the core that an {@link OwnIdentity} was removed.
1721 * @param ownIdentityRemovedEvent
1725 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1726 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1727 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1728 trustedIdentities.removeAll(ownIdentity);
1732 * Notifies the core that a new {@link Identity} was added.
1734 * @param identityAddedEvent
1738 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1739 Identity identity = identityAddedEvent.identity();
1740 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1741 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1742 addRemoteSone(identity);
1746 * Notifies the core that an {@link Identity} was updated.
1748 * @param identityUpdatedEvent
1752 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1753 Identity identity = identityUpdatedEvent.identity();
1754 final Sone sone = getRemoteSone(identity.getId());
1755 if (sone.isLocal()) {
1758 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1759 soneDownloader.addSone(sone);
1760 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1764 * Notifies the core that an {@link Identity} was removed.
1766 * @param identityRemovedEvent
1770 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1771 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1772 Identity identity = identityRemovedEvent.identity();
1773 trustedIdentities.remove(ownIdentity, identity);
1774 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1775 if (trustedIdentity.getKey().equals(ownIdentity)) {
1778 if (trustedIdentity.getValue().contains(identity)) {
1782 Optional<Sone> sone = getSone(identity.getId());
1783 if (!sone.isPresent()) {
1784 /* TODO - we don’t have the Sone anymore. should this happen? */
1787 database.removeSone(sone.get());
1788 eventBus.post(new SoneRemovedEvent(sone.get()));
1792 * Deletes the temporary image.
1794 * @param imageInsertFinishedEvent
1798 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1799 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1800 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1801 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1802 touchConfiguration();
1806 class MarkPostKnown implements Runnable {
1808 private final Post post;
1810 public MarkPostKnown(Post post) {
1816 markPostKnown(post);
1822 class MarkReplyKnown implements Runnable {
1824 private final PostReply postReply;
1826 public MarkReplyKnown(PostReply postReply) {
1827 this.postReply = postReply;
1832 markReplyKnown(postReply);