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.base.Predicates.not;
24 import static com.google.common.primitives.Longs.tryParse;
25 import static java.lang.String.format;
26 import static java.util.logging.Level.WARNING;
27 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
28 import static net.pterodactylus.sone.data.Sone.toAllAlbums;
30 import java.net.MalformedURLException;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
37 import java.util.Map.Entry;
39 import java.util.concurrent.ExecutorService;
40 import java.util.concurrent.Executors;
41 import java.util.concurrent.ScheduledExecutorService;
42 import java.util.concurrent.TimeUnit;
43 import java.util.logging.Level;
44 import java.util.logging.Logger;
46 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidAlbumFound;
47 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidImageFound;
48 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidParentAlbumFound;
49 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostFound;
50 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
51 import net.pterodactylus.sone.core.Options.DefaultOption;
52 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
53 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
54 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
55 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
56 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
57 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
58 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
59 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
60 import net.pterodactylus.sone.core.event.PostRemovedEvent;
61 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneLockedEvent;
63 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
64 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
65 import net.pterodactylus.sone.data.Album;
66 import net.pterodactylus.sone.data.Client;
67 import net.pterodactylus.sone.data.Image;
68 import net.pterodactylus.sone.data.Post;
69 import net.pterodactylus.sone.data.PostReply;
70 import net.pterodactylus.sone.data.Profile;
71 import net.pterodactylus.sone.data.Profile.Field;
72 import net.pterodactylus.sone.data.Reply;
73 import net.pterodactylus.sone.data.Sone;
74 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
75 import net.pterodactylus.sone.data.Sone.SoneStatus;
76 import net.pterodactylus.sone.data.SoneImpl;
77 import net.pterodactylus.sone.data.TemporaryImage;
78 import net.pterodactylus.sone.database.AlbumBuilder;
79 import net.pterodactylus.sone.database.Database;
80 import net.pterodactylus.sone.database.DatabaseException;
81 import net.pterodactylus.sone.database.ImageBuilder;
82 import net.pterodactylus.sone.database.PostBuilder;
83 import net.pterodactylus.sone.database.PostProvider;
84 import net.pterodactylus.sone.database.PostReplyBuilder;
85 import net.pterodactylus.sone.database.PostReplyProvider;
86 import net.pterodactylus.sone.database.SoneProvider;
87 import net.pterodactylus.sone.fcp.FcpInterface;
88 import net.pterodactylus.sone.freenet.wot.Identity;
89 import net.pterodactylus.sone.freenet.wot.IdentityManager;
90 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
91 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
92 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
93 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
94 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
95 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
96 import net.pterodactylus.sone.main.SonePlugin;
97 import net.pterodactylus.sone.utils.IntegerRangePredicate;
98 import net.pterodactylus.util.config.Configuration;
99 import net.pterodactylus.util.config.ConfigurationException;
100 import net.pterodactylus.util.logging.Logging;
101 import net.pterodactylus.util.number.Numbers;
102 import net.pterodactylus.util.service.AbstractService;
103 import net.pterodactylus.util.thread.NamedThreadFactory;
105 import com.google.common.annotations.VisibleForTesting;
106 import com.google.common.base.Optional;
107 import com.google.common.base.Predicates;
108 import com.google.common.collect.FluentIterable;
109 import com.google.common.collect.HashMultimap;
110 import com.google.common.collect.ImmutableSet;
111 import com.google.common.collect.Multimap;
112 import com.google.common.collect.Multimaps;
113 import com.google.common.eventbus.EventBus;
114 import com.google.common.eventbus.Subscribe;
115 import com.google.inject.Inject;
116 import com.google.inject.Singleton;
118 import freenet.keys.FreenetURI;
123 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
126 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
129 private static final Logger logger = Logging.getLogger(Core.class);
131 /** The start time. */
132 private final long startupTime = System.currentTimeMillis();
135 private final Options options = new Options();
137 /** The preferences. */
138 private final Preferences preferences = new Preferences(options);
140 /** The event bus. */
141 private final EventBus eventBus;
143 /** The configuration. */
144 private final Configuration configuration;
146 /** Whether we’re currently saving the configuration. */
147 private boolean storingConfiguration = false;
149 /** The identity manager. */
150 private final IdentityManager identityManager;
152 /** Interface to freenet. */
153 private final FreenetInterface freenetInterface;
155 /** The Sone downloader. */
156 private final SoneDownloader soneDownloader;
158 /** The image inserter. */
159 private final ImageInserter imageInserter;
161 /** Sone downloader thread-pool. */
162 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
164 /** The update checker. */
165 private final UpdateChecker updateChecker;
167 /** The trust updater. */
168 private final WebOfTrustUpdater webOfTrustUpdater;
170 /** The FCP interface. */
171 private volatile FcpInterface fcpInterface;
173 /** The times Sones were followed. */
174 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
176 /** Locked local Sones. */
177 /* synchronize on itself. */
178 private final Set<Sone> lockedSones = new HashSet<Sone>();
180 /** Sone inserters. */
181 /* synchronize access on this on sones. */
182 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
184 /** Sone rescuers. */
185 /* synchronize access on this on sones. */
186 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
189 /* synchronize access on this on itself. */
190 private final Map<String, Sone> sones = new HashMap<String, Sone>();
192 /** All known Sones. */
193 private final Set<String> knownSones = new HashSet<String>();
195 /** The post database. */
196 private final Database database;
198 /** All bookmarked posts. */
199 /* synchronize access on itself. */
200 private final Set<String> bookmarkedPosts = new HashSet<String>();
202 /** Trusted identities, sorted by own identities. */
203 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
205 /** All temporary images. */
206 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
208 /** Ticker for threads that mark own elements as known. */
209 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
211 /** The time the configuration was last touched. */
212 private volatile long lastConfigurationUpdate;
215 * Creates a new core.
217 * @param configuration
218 * The configuration of the core
219 * @param freenetInterface
220 * The freenet interface
221 * @param identityManager
222 * The identity manager
223 * @param webOfTrustUpdater
224 * The WebOfTrust updater
231 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
233 this.configuration = configuration;
234 this.freenetInterface = freenetInterface;
235 this.identityManager = identityManager;
236 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
237 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
238 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
239 this.webOfTrustUpdater = webOfTrustUpdater;
240 this.eventBus = eventBus;
241 this.database = database;
245 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
247 this.configuration = configuration;
248 this.freenetInterface = freenetInterface;
249 this.identityManager = identityManager;
250 this.soneDownloader = soneDownloader;
251 this.imageInserter = imageInserter;
252 this.updateChecker = updateChecker;
253 this.webOfTrustUpdater = webOfTrustUpdater;
254 this.eventBus = eventBus;
255 this.database = database;
263 * Returns the time Sone was started.
265 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
267 public long getStartupTime() {
272 * Returns the options used by the core.
274 * @return The options of the core
276 public Preferences getPreferences() {
281 * Returns the identity manager used by the core.
283 * @return The identity manager
285 public IdentityManager getIdentityManager() {
286 return identityManager;
290 * Returns the update checker.
292 * @return The update checker
294 public UpdateChecker getUpdateChecker() {
295 return updateChecker;
299 * Sets the FCP interface to use.
301 * @param fcpInterface
302 * The FCP interface to use
304 public void setFcpInterface(FcpInterface fcpInterface) {
305 this.fcpInterface = fcpInterface;
309 * Returns the Sone rescuer for the given local Sone.
312 * The local Sone to get the rescuer for
313 * @return The Sone rescuer for the given Sone
315 public SoneRescuer getSoneRescuer(Sone sone) {
316 checkNotNull(sone, "sone must not be null");
317 checkArgument(sone.isLocal(), "sone must be local");
318 synchronized (sones) {
319 SoneRescuer soneRescuer = soneRescuers.get(sone);
320 if (soneRescuer == null) {
321 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
322 soneRescuers.put(sone, soneRescuer);
330 * Returns whether the given Sone is currently locked.
334 * @return {@code true} if the Sone is locked, {@code false} if it is not
336 public boolean isLocked(Sone sone) {
337 synchronized (lockedSones) {
338 return lockedSones.contains(sone);
346 public Collection<Sone> getSones() {
347 synchronized (sones) {
348 return ImmutableSet.copyOf(sones.values());
353 * Returns the Sone with the given ID, regardless whether it’s local or
357 * The ID of the Sone to get
358 * @return The Sone with the given ID, or {@code null} if there is no such
362 public Optional<Sone> getSone(String id) {
363 synchronized (sones) {
364 return Optional.fromNullable(sones.get(id));
372 public Collection<Sone> getLocalSones() {
373 synchronized (sones) {
374 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
379 * Returns the local Sone with the given ID, optionally creating a new Sone.
384 * {@code true} to create a new Sone if none exists,
385 * {@code false} to return null if none exists
386 * @return The Sone with the given ID, or {@code null}
388 public Sone getLocalSone(String id, boolean create) {
389 synchronized (sones) {
390 Sone sone = sones.get(id);
391 if ((sone == null) && create) {
392 sone = new SoneImpl(id, true);
395 if ((sone != null) && !sone.isLocal()) {
396 sone = new SoneImpl(id, true);
407 public Collection<Sone> getRemoteSones() {
408 synchronized (sones) {
409 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
414 * Returns the remote Sone with the given ID.
417 * The ID of the remote Sone to get
419 * {@code true} to always create a Sone, {@code false} to return
420 * {@code null} if no Sone with the given ID exists
421 * @return The Sone with the given ID
423 public Sone getRemoteSone(String id, boolean create) {
424 synchronized (sones) {
425 Sone sone = sones.get(id);
426 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
427 sone = new SoneImpl(id, false);
435 * Returns whether the given Sone has been modified.
438 * The Sone to check for modifications
439 * @return {@code true} if a modification has been detected in the Sone,
440 * {@code false} otherwise
442 public boolean isModifiedSone(Sone sone) {
443 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
447 * Returns the time when the given was first followed by any local Sone.
450 * The Sone to get the time for
451 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
452 * been followed, or {@link Long#MAX_VALUE}
454 public long getSoneFollowingTime(Sone sone) {
455 synchronized (soneFollowingTimes) {
456 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
461 * Returns a post builder.
463 * @return A new post builder
465 public PostBuilder postBuilder() {
466 return database.newPostBuilder();
473 public Optional<Post> getPost(String postId) {
474 return database.getPost(postId);
481 public Collection<Post> getPosts(String soneId) {
482 return database.getPosts(soneId);
489 public Collection<Post> getDirectedPosts(final String recipientId) {
490 checkNotNull(recipientId, "recipient must not be null");
491 return database.getDirectedPosts(recipientId);
495 * Returns a post reply builder.
497 * @return A new post reply builder
499 public PostReplyBuilder postReplyBuilder() {
500 return database.newPostReplyBuilder();
507 public Optional<PostReply> getPostReply(String replyId) {
508 return database.getPostReply(replyId);
515 public List<PostReply> getReplies(final String postId) {
516 return database.getReplies(postId);
520 * Returns all Sones that have liked the given post.
523 * The post to get the liking Sones for
524 * @return The Sones that like the given post
526 public Set<Sone> getLikes(Post post) {
527 Set<Sone> sones = new HashSet<Sone>();
528 for (Sone sone : getSones()) {
529 if (sone.getLikedPostIds().contains(post.getId())) {
537 * Returns all Sones that have liked the given reply.
540 * The reply to get the liking Sones for
541 * @return The Sones that like the given reply
543 public Set<Sone> getLikes(PostReply reply) {
544 Set<Sone> sones = new HashSet<Sone>();
545 for (Sone sone : getSones()) {
546 if (sone.getLikedReplyIds().contains(reply.getId())) {
554 * Returns whether the given post is bookmarked.
558 * @return {@code true} if the given post is bookmarked, {@code false}
561 public boolean isBookmarked(Post post) {
562 return isPostBookmarked(post.getId());
566 * Returns whether the post with the given ID is bookmarked.
569 * The ID of the post to check
570 * @return {@code true} if the post with the given ID is bookmarked,
571 * {@code false} otherwise
573 public boolean isPostBookmarked(String id) {
574 synchronized (bookmarkedPosts) {
575 return bookmarkedPosts.contains(id);
580 * Returns all currently known bookmarked posts.
582 * @return All bookmarked posts
584 public Set<Post> getBookmarkedPosts() {
585 Set<Post> posts = new HashSet<Post>();
586 synchronized (bookmarkedPosts) {
587 for (String bookmarkedPostId : bookmarkedPosts) {
588 Optional<Post> post = getPost(bookmarkedPostId);
589 if (post.isPresent()) {
590 posts.add(post.get());
597 public AlbumBuilder albumBuilder() {
598 return database.newAlbumBuilder();
602 * Returns the album with the given ID, optionally creating a new album if
603 * an album with the given ID can not be found.
606 * The ID of the album
607 * @return The album with the given ID, or {@code null} if no album with the
610 public Album getAlbum(String albumId) {
611 return database.getAlbum(albumId).orNull();
614 public ImageBuilder imageBuilder() {
615 return database.newImageBuilder();
619 * Returns the image with the given ID, creating it if necessary.
622 * The ID of the image
623 * @return The image with the given ID
625 public Image getImage(String imageId) {
626 return getImage(imageId, true);
630 * Returns the image with the given ID, optionally creating it if it does
634 * The ID of the image
636 * {@code true} to create an image if none exists with the given
638 * @return The image with the given ID, or {@code null} if none exists and
641 public Image getImage(String imageId, boolean create) {
642 Optional<Image> image = database.getImage(imageId);
643 if (image.isPresent()) {
649 Image newImage = database.newImageBuilder().withId(imageId).build();
650 database.storeImage(newImage);
655 * Returns the temporary image with the given ID.
658 * The ID of the temporary image
659 * @return The temporary image, or {@code null} if there is no temporary
660 * image with the given ID
662 public TemporaryImage getTemporaryImage(String imageId) {
663 synchronized (temporaryImages) {
664 return temporaryImages.get(imageId);
673 * Locks the given Sone. A locked Sone will not be inserted by
674 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
680 public void lockSone(Sone sone) {
681 synchronized (lockedSones) {
682 if (lockedSones.add(sone)) {
683 eventBus.post(new SoneLockedEvent(sone));
689 * Unlocks the given Sone.
691 * @see #lockSone(Sone)
695 public void unlockSone(Sone sone) {
696 synchronized (lockedSones) {
697 if (lockedSones.remove(sone)) {
698 eventBus.post(new SoneUnlockedEvent(sone));
704 * Adds a local Sone from the given own identity.
707 * The own identity to create a Sone from
708 * @return The added (or already existing) Sone
710 public Sone addLocalSone(OwnIdentity ownIdentity) {
711 if (ownIdentity == null) {
712 logger.log(Level.WARNING, "Given OwnIdentity is null!");
715 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
716 synchronized (sones) {
719 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
720 } catch (MalformedURLException mue1) {
721 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
724 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
725 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
727 /* TODO - load posts ’n stuff */
728 sones.put(ownIdentity.getId(), sone);
729 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
730 soneInserters.put(sone, soneInserter);
731 sone.setStatus(SoneStatus.idle);
733 soneInserter.start();
739 * Creates a new Sone for the given own identity.
742 * The own identity to create a Sone for
743 * @return The created Sone
745 public Sone createSone(OwnIdentity ownIdentity) {
746 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
747 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
750 Sone sone = addLocalSone(ownIdentity);
752 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
753 touchConfiguration();
758 * Adds the Sone of the given identity.
761 * The identity whose Sone to add
762 * @return The added or already existing Sone
764 public Sone addRemoteSone(Identity identity) {
765 if (identity == null) {
766 logger.log(Level.WARNING, "Given Identity is null!");
769 final Long latestEdition = fromNullable(tryParse(
770 identity.getProperty("Sone.LatestEdition"))).or(0L);
771 synchronized (sones) {
772 final Sone sone = getRemoteSone(identity.getId(), true);
773 if (sone.isLocal()) {
776 sone.setIdentity(identity);
777 boolean newSone = sone.getRequestUri() == null;
778 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
779 sone.setLatestEdition(latestEdition);
781 synchronized (knownSones) {
782 newSone = !knownSones.contains(sone.getId());
784 sone.setKnown(!newSone);
786 eventBus.post(new NewSoneFoundEvent(sone));
787 for (Sone localSone : getLocalSones()) {
788 if (localSone.getOptions().isAutoFollow()) {
789 followSone(localSone, sone.getId());
794 soneDownloader.addSone(sone);
795 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
801 * Lets the given local Sone follow the Sone with the given ID.
804 * The local Sone that should follow another Sone
806 * The ID of the Sone to follow
808 public void followSone(Sone sone, String soneId) {
809 checkNotNull(sone, "sone must not be null");
810 checkNotNull(soneId, "soneId must not be null");
811 sone.addFriend(soneId);
812 synchronized (soneFollowingTimes) {
813 if (!soneFollowingTimes.containsKey(soneId)) {
814 long now = System.currentTimeMillis();
815 soneFollowingTimes.put(soneId, now);
816 Optional<Sone> followedSone = getSone(soneId);
817 if (!followedSone.isPresent()) {
820 for (Post post : followedSone.get().getPosts()) {
821 if (post.getTime() < now) {
825 for (PostReply reply : followedSone.get().getReplies()) {
826 if (reply.getTime() < now) {
827 markReplyKnown(reply);
832 touchConfiguration();
836 * Lets the given local Sone unfollow the Sone with the given ID.
839 * The local Sone that should unfollow another Sone
841 * The ID of the Sone being unfollowed
843 public void unfollowSone(Sone sone, String soneId) {
844 checkNotNull(sone, "sone must not be null");
845 checkNotNull(soneId, "soneId must not be null");
846 sone.removeFriend(soneId);
847 boolean unfollowedSoneStillFollowed = false;
848 for (Sone localSone : getLocalSones()) {
849 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
851 if (!unfollowedSoneStillFollowed) {
852 synchronized (soneFollowingTimes) {
853 soneFollowingTimes.remove(soneId);
856 touchConfiguration();
860 * Sets the trust value of the given origin Sone for the target Sone.
867 * The trust value (from {@code -100} to {@code 100})
869 public void setTrust(Sone origin, Sone target, int trustValue) {
870 checkNotNull(origin, "origin must not be null");
871 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
872 checkNotNull(target, "target must not be null");
873 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
874 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
878 * Removes any trust assignment for the given target Sone.
885 public void removeTrust(Sone origin, Sone target) {
886 checkNotNull(origin, "origin must not be null");
887 checkNotNull(target, "target must not be null");
888 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
889 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
893 * Assigns the configured positive trust value for the given target.
900 public void trustSone(Sone origin, Sone target) {
901 setTrust(origin, target, preferences.getPositiveTrust());
905 * Assigns the configured negative trust value for the given target.
912 public void distrustSone(Sone origin, Sone target) {
913 setTrust(origin, target, preferences.getNegativeTrust());
917 * Removes the trust assignment for the given target.
924 public void untrustSone(Sone origin, Sone target) {
925 removeTrust(origin, target);
929 * Updates the stored Sone with the given Sone.
934 public void updateSone(Sone sone) {
935 updateSone(sone, false);
939 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
940 * {@code true}, an older Sone than the current Sone can be given to restore
945 * @param soneRescueMode
946 * {@code true} if the stored Sone should be updated regardless
947 * of the age of the given Sone
949 public void updateSone(Sone sone, boolean soneRescueMode) {
950 Optional<Sone> storedSone = getSone(sone.getId());
951 if (storedSone.isPresent()) {
952 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
953 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
956 /* find removed posts. */
957 Collection<Post> removedPosts = new ArrayList<Post>();
958 Collection<Post> newPosts = new ArrayList<Post>();
959 Collection<Post> existingPosts = database.getPosts(sone.getId());
960 for (Post oldPost : existingPosts) {
961 if (!sone.getPosts().contains(oldPost)) {
962 removedPosts.add(oldPost);
965 /* find new posts. */
966 for (Post newPost : sone.getPosts()) {
967 if (existingPosts.contains(newPost)) {
970 if (newPost.getTime() < getSoneFollowingTime(sone)) {
971 newPost.setKnown(true);
972 } else if (!newPost.isKnown()) {
973 newPosts.add(newPost);
977 database.storePosts(sone, sone.getPosts());
978 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
979 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
980 if (!soneRescueMode) {
981 for (PostReply reply : storedSone.get().getReplies()) {
982 if (!sone.getReplies().contains(reply)) {
983 removedPostReplies.add(reply);
987 Set<PostReply> storedReplies = storedSone.get().getReplies();
988 for (PostReply reply : sone.getReplies()) {
989 if (storedReplies.contains(reply)) {
992 if (reply.getTime() < getSoneFollowingTime(sone)) {
993 reply.setKnown(true);
994 } else if (!reply.isKnown()) {
995 newPostReplies.add(reply);
998 database.storePostReplies(sone, sone.getReplies());
999 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1000 database.removeAlbum(album);
1001 for (Image image : album.getImages()) {
1002 database.removeImage(image);
1005 for (Post removedPost : removedPosts) {
1006 eventBus.post(new PostRemovedEvent(removedPost));
1008 for (Post newPost : newPosts) {
1009 eventBus.post(new NewPostFoundEvent(newPost));
1011 for (PostReply removedPostReply : removedPostReplies) {
1012 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1014 for (PostReply newPostReply : newPostReplies) {
1015 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1017 for (Album album : toAllAlbums.apply(sone)) {
1018 database.storeAlbum(album);
1019 for (Image image : album.getImages()) {
1020 database.storeImage(image);
1023 synchronized (sones) {
1024 sone.setOptions(storedSone.get().getOptions());
1025 sone.setKnown(storedSone.get().isKnown());
1026 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1027 if (sone.isLocal()) {
1028 soneInserters.get(storedSone.get()).setSone(sone);
1029 touchConfiguration();
1031 sones.put(sone.getId(), sone);
1037 * Deletes the given Sone. This will remove the Sone from the
1038 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1039 * remove the context from its identity.
1042 * The Sone to delete
1044 public void deleteSone(Sone sone) {
1045 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1046 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1049 synchronized (sones) {
1050 if (!getLocalSones().contains(sone)) {
1051 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1054 sones.remove(sone.getId());
1055 SoneInserter soneInserter = soneInserters.remove(sone);
1056 soneInserter.stop();
1058 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1059 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1061 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1062 } catch (ConfigurationException ce1) {
1063 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1068 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1069 * known} before, a {@link MarkSoneKnownEvent} is fired.
1072 * The Sone to mark as known
1074 public void markSoneKnown(Sone sone) {
1075 if (!sone.isKnown()) {
1076 sone.setKnown(true);
1077 synchronized (knownSones) {
1078 knownSones.add(sone.getId());
1080 eventBus.post(new MarkSoneKnownEvent(sone));
1081 touchConfiguration();
1086 * Loads and updates the given Sone from the configuration. If any error is
1087 * encountered, loading is aborted and the given Sone is not changed.
1090 * The Sone to load and update
1092 public void loadSone(Sone sone) {
1093 if (!sone.isLocal()) {
1094 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1097 logger.info(String.format("Loading local Sone: %s", sone));
1100 String sonePrefix = "Sone/" + sone.getId();
1101 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1102 if (soneTime == null) {
1103 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1106 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1109 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1110 Profile profile = configurationSoneParser.parseProfile();
1113 Collection<Post> posts;
1115 posts = configurationSoneParser.parsePosts(database);
1116 } catch (InvalidPostFound ipf) {
1117 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1122 Collection<PostReply> replies;
1124 replies = configurationSoneParser.parsePostReplies(database);
1125 } catch (InvalidPostReplyFound iprf) {
1126 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1130 /* load post likes. */
1131 Set<String> likedPostIds =
1132 configurationSoneParser.parseLikedPostIds();
1134 /* load reply likes. */
1135 Set<String> likedReplyIds =
1136 configurationSoneParser.parseLikedPostReplyIds();
1139 Set<String> friends = configurationSoneParser.parseFriends();
1142 List<Album> topLevelAlbums;
1145 configurationSoneParser.parseTopLevelAlbums(database);
1146 } catch (InvalidAlbumFound iaf) {
1147 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1149 } catch (InvalidParentAlbumFound ipaf) {
1150 logger.log(Level.WARNING, format("Invalid parent album ID: %s",
1151 ipaf.getAlbumParentId()));
1157 configurationSoneParser.parseImages(database);
1158 } catch (InvalidImageFound iif) {
1159 logger.log(WARNING, "Invalid image found, aborting load!");
1161 } catch (InvalidParentAlbumFound ipaf) {
1162 logger.log(Level.WARNING,
1163 format("Invalid album image (%s) encountered, aborting load!",
1164 ipaf.getAlbumParentId()));
1169 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1170 if (avatarId != null) {
1171 final Map<String, Image> images =
1172 configurationSoneParser.getImages();
1173 profile.setAvatar(images.get(avatarId));
1177 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1178 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1179 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1180 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1181 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1182 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1184 /* if we’re still here, Sone was loaded successfully. */
1185 synchronized (sone) {
1186 sone.setTime(soneTime);
1187 sone.setProfile(profile);
1188 sone.setPosts(posts);
1189 sone.setReplies(replies);
1190 sone.setLikePostIds(likedPostIds);
1191 sone.setLikeReplyIds(likedReplyIds);
1192 for (String friendId : friends) {
1193 followSone(sone, friendId);
1195 for (Album album : sone.getRootAlbum().getAlbums()) {
1196 sone.getRootAlbum().removeAlbum(album);
1198 for (Album album : topLevelAlbums) {
1199 sone.getRootAlbum().addAlbum(album);
1201 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1202 for (Album album : toAllAlbums.apply(sone)) {
1203 database.storeAlbum(album);
1204 for (Image image : album.getImages()) {
1205 database.storeImage(image);
1209 synchronized (knownSones) {
1210 for (String friend : friends) {
1211 knownSones.add(friend);
1214 database.storePosts(sone, posts);
1215 for (Post post : posts) {
1216 post.setKnown(true);
1218 database.storePostReplies(sone, replies);
1219 for (PostReply reply : replies) {
1220 reply.setKnown(true);
1223 logger.info(String.format("Sone loaded successfully: %s", sone));
1227 * Creates a new post.
1230 * The Sone that creates the post
1232 * The recipient Sone, or {@code null} if this post does not have
1235 * The text of the post
1236 * @return The created post
1238 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1239 return createPost(sone, recipient, System.currentTimeMillis(), text);
1243 * Creates a new post.
1246 * The Sone that creates the post
1248 * The recipient Sone, or {@code null} if this post does not have
1251 * The time of the post
1253 * The text of the post
1254 * @return The created post
1256 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1257 checkNotNull(text, "text must not be null");
1258 checkArgument(text.trim().length() > 0, "text must not be empty");
1259 if (!sone.isLocal()) {
1260 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1263 PostBuilder postBuilder = database.newPostBuilder();
1264 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1265 if (recipient.isPresent()) {
1266 postBuilder.to(recipient.get().getId());
1268 final Post post = postBuilder.build();
1269 database.storePost(post);
1270 eventBus.post(new NewPostFoundEvent(post));
1272 touchConfiguration();
1273 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1278 * Deletes the given post.
1281 * The post to delete
1283 public void deletePost(Post post) {
1284 if (!post.getSone().isLocal()) {
1285 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1288 database.removePost(post);
1289 eventBus.post(new PostRemovedEvent(post));
1290 markPostKnown(post);
1291 touchConfiguration();
1295 * Marks the given post as known, if it is currently not a known post
1296 * (according to {@link Post#isKnown()}).
1299 * The post to mark as known
1301 public void markPostKnown(Post post) {
1302 post.setKnown(true);
1303 eventBus.post(new MarkPostKnownEvent(post));
1304 touchConfiguration();
1305 for (PostReply reply : getReplies(post.getId())) {
1306 markReplyKnown(reply);
1311 * Bookmarks the post with the given ID.
1314 * The ID of the post to bookmark
1316 public void bookmarkPost(String id) {
1317 synchronized (bookmarkedPosts) {
1318 bookmarkedPosts.add(id);
1323 * Removes the given post from the bookmarks.
1326 * The post to unbookmark
1328 public void unbookmark(Post post) {
1329 unbookmarkPost(post.getId());
1333 * Removes the post with the given ID from the bookmarks.
1336 * The ID of the post to unbookmark
1338 public void unbookmarkPost(String id) {
1339 synchronized (bookmarkedPosts) {
1340 bookmarkedPosts.remove(id);
1345 * Creates a new reply.
1348 * The Sone that creates the reply
1350 * The post that this reply refers to
1352 * The text of the reply
1353 * @return The created reply
1355 public PostReply createReply(Sone sone, Post post, String text) {
1356 checkNotNull(text, "text must not be null");
1357 checkArgument(text.trim().length() > 0, "text must not be empty");
1358 if (!sone.isLocal()) {
1359 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1362 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1363 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1364 final PostReply reply = postReplyBuilder.build();
1365 database.storePostReply(reply);
1366 eventBus.post(new NewPostReplyFoundEvent(reply));
1367 sone.addReply(reply);
1368 touchConfiguration();
1369 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1374 * Deletes the given reply.
1377 * The reply to delete
1379 public void deleteReply(PostReply reply) {
1380 Sone sone = reply.getSone();
1381 if (!sone.isLocal()) {
1382 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1385 database.removePostReply(reply);
1386 markReplyKnown(reply);
1387 sone.removeReply(reply);
1388 touchConfiguration();
1392 * Marks the given reply as known, if it is currently not a known reply
1393 * (according to {@link Reply#isKnown()}).
1396 * The reply to mark as known
1398 public void markReplyKnown(PostReply reply) {
1399 boolean previouslyKnown = reply.isKnown();
1400 reply.setKnown(true);
1401 eventBus.post(new MarkPostReplyKnownEvent(reply));
1402 if (!previouslyKnown) {
1403 touchConfiguration();
1408 * Creates a new album for the given Sone.
1411 * The Sone to create the album for
1413 * The parent of the album (may be {@code null} to create a
1415 * @return The new album
1417 public Album createAlbum(Sone sone, Album parent) {
1418 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1419 database.storeAlbum(album);
1420 parent.addAlbum(album);
1425 * Deletes the given album. The owner of the album has to be a local Sone,
1426 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1429 * The album to remove
1431 public void deleteAlbum(Album album) {
1432 checkNotNull(album, "album must not be null");
1433 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1434 if (!album.isEmpty()) {
1437 album.getParent().removeAlbum(album);
1438 database.removeAlbum(album);
1439 touchConfiguration();
1443 * Creates a new image.
1446 * The Sone creating the image
1448 * The album the image will be inserted into
1449 * @param temporaryImage
1450 * The temporary image to create the image from
1451 * @return The newly created image
1453 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1454 checkNotNull(sone, "sone must not be null");
1455 checkNotNull(album, "album must not be null");
1456 checkNotNull(temporaryImage, "temporaryImage must not be null");
1457 checkArgument(sone.isLocal(), "sone must be a local Sone");
1458 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1459 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1460 album.addImage(image);
1461 database.storeImage(image);
1462 imageInserter.insertImage(temporaryImage, image);
1467 * Deletes the given image. This method will also delete a matching
1470 * @see #deleteTemporaryImage(String)
1472 * The image to delete
1474 public void deleteImage(Image image) {
1475 checkNotNull(image, "image must not be null");
1476 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1477 deleteTemporaryImage(image.getId());
1478 image.getAlbum().removeImage(image);
1479 database.removeImage(image);
1480 touchConfiguration();
1484 * Creates a new temporary image.
1487 * The MIME type of the temporary image
1489 * The encoded data of the image
1490 * @return The temporary image
1492 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1493 TemporaryImage temporaryImage = new TemporaryImage();
1494 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1495 synchronized (temporaryImages) {
1496 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1498 return temporaryImage;
1502 * Deletes the temporary image with the given ID.
1505 * The ID of the temporary image to delete
1507 public void deleteTemporaryImage(String imageId) {
1508 checkNotNull(imageId, "imageId must not be null");
1509 synchronized (temporaryImages) {
1510 temporaryImages.remove(imageId);
1512 Image image = getImage(imageId, false);
1513 if (image != null) {
1514 imageInserter.cancelImageInsert(image);
1519 * Notifies the core that the configuration, either of the core or of a
1520 * single local Sone, has changed, and that the configuration should be
1523 public void touchConfiguration() {
1524 lastConfigurationUpdate = System.currentTimeMillis();
1535 public void serviceStart() {
1536 loadConfiguration();
1537 updateChecker.start();
1538 identityManager.start();
1539 webOfTrustUpdater.init();
1540 webOfTrustUpdater.start();
1548 public void serviceRun() {
1549 long lastSaved = System.currentTimeMillis();
1550 while (!shouldStop()) {
1552 long now = System.currentTimeMillis();
1553 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1554 for (Sone localSone : getLocalSones()) {
1555 saveSone(localSone);
1557 saveConfiguration();
1567 public void serviceStop() {
1568 localElementTicker.shutdownNow();
1569 synchronized (sones) {
1570 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1571 soneInserter.getValue().stop();
1572 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1575 saveConfiguration();
1577 webOfTrustUpdater.stop();
1578 updateChecker.stop();
1579 soneDownloader.stop();
1580 soneDownloaders.shutdown();
1581 identityManager.stop();
1589 * Saves the given Sone. This will persist all local settings for the given
1590 * Sone, such as the friends list and similar, private options.
1595 private synchronized void saveSone(Sone sone) {
1596 if (!sone.isLocal()) {
1597 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1600 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1601 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1605 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1607 /* save Sone into configuration. */
1608 String sonePrefix = "Sone/" + sone.getId();
1609 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1610 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1613 Profile profile = sone.getProfile();
1614 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1615 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1616 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1617 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1618 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1619 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1620 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1622 /* save profile fields. */
1623 int fieldCounter = 0;
1624 for (Field profileField : profile.getFields()) {
1625 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1626 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1627 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1629 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1632 int postCounter = 0;
1633 for (Post post : sone.getPosts()) {
1634 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1635 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1636 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1637 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1638 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1640 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1643 int replyCounter = 0;
1644 for (PostReply reply : sone.getReplies()) {
1645 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1646 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1647 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1648 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1649 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1651 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1653 /* save post likes. */
1654 int postLikeCounter = 0;
1655 for (String postId : sone.getLikedPostIds()) {
1656 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1658 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1660 /* save reply likes. */
1661 int replyLikeCounter = 0;
1662 for (String replyId : sone.getLikedReplyIds()) {
1663 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1665 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1668 int friendCounter = 0;
1669 for (String friendId : sone.getFriends()) {
1670 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1672 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1674 /* save albums. first, collect in a flat structure, top-level first. */
1675 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1677 int albumCounter = 0;
1678 for (Album album : albums) {
1679 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1680 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1681 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1682 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1683 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1684 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1686 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1689 int imageCounter = 0;
1690 for (Album album : albums) {
1691 for (Image image : album.getImages()) {
1692 if (!image.isInserted()) {
1695 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1696 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1697 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1698 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1699 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1700 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1701 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1702 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1703 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1706 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1709 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1710 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1711 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1712 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1713 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1714 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1716 configuration.save();
1718 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1720 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1721 } catch (ConfigurationException ce1) {
1722 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1727 * Saves the current options.
1729 private void saveConfiguration() {
1730 synchronized (configuration) {
1731 if (storingConfiguration) {
1732 logger.log(Level.FINE, "Already storing configuration…");
1735 storingConfiguration = true;
1738 /* store the options first. */
1740 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1741 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1742 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1743 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1744 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1745 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1746 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1747 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1748 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1749 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1750 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1751 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1753 /* save known Sones. */
1754 int soneCounter = 0;
1755 synchronized (knownSones) {
1756 for (String knownSoneId : knownSones) {
1757 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1759 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1762 /* save Sone following times. */
1764 synchronized (soneFollowingTimes) {
1765 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1766 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1767 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1770 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1773 /* save known posts. */
1776 /* save bookmarked posts. */
1777 int bookmarkedPostCounter = 0;
1778 synchronized (bookmarkedPosts) {
1779 for (String bookmarkedPostId : bookmarkedPosts) {
1780 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1783 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1786 configuration.save();
1788 } catch (ConfigurationException ce1) {
1789 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1790 } catch (DatabaseException de1) {
1791 logger.log(Level.SEVERE, "Could not save database!", de1);
1793 synchronized (configuration) {
1794 storingConfiguration = false;
1800 * Loads the configuration.
1802 private void loadConfiguration() {
1803 /* create options. */
1804 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1805 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1806 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1807 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1808 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1809 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1810 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1811 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1812 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1813 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1814 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1816 loadConfigurationValue("InsertionDelay");
1817 loadConfigurationValue("PostsPerPage");
1818 loadConfigurationValue("ImagesPerPage");
1819 loadConfigurationValue("CharactersPerPost");
1820 loadConfigurationValue("PostCutOffLength");
1821 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1822 loadConfigurationValue("PositiveTrust");
1823 loadConfigurationValue("NegativeTrust");
1824 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1825 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1826 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1828 /* load known Sones. */
1829 int soneCounter = 0;
1831 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1832 if (knownSoneId == null) {
1835 synchronized (knownSones) {
1836 knownSones.add(knownSoneId);
1840 /* load Sone following times. */
1843 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1844 if (soneId == null) {
1847 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1848 synchronized (soneFollowingTimes) {
1849 soneFollowingTimes.put(soneId, time);
1854 /* load bookmarked posts. */
1855 int bookmarkedPostCounter = 0;
1857 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1858 if (bookmarkedPostId == null) {
1861 synchronized (bookmarkedPosts) {
1862 bookmarkedPosts.add(bookmarkedPostId);
1869 * Loads an {@link Integer} configuration value for the option with the
1870 * given name, logging validation failures.
1873 * The name of the option to load
1875 private void loadConfigurationValue(String optionName) {
1877 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1878 } catch (IllegalArgumentException iae1) {
1879 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1884 * Notifies the core that a new {@link OwnIdentity} was added.
1886 * @param ownIdentityAddedEvent
1890 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1891 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1892 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1893 if (ownIdentity.hasContext("Sone")) {
1894 addLocalSone(ownIdentity);
1899 * Notifies the core that an {@link OwnIdentity} was removed.
1901 * @param ownIdentityRemovedEvent
1905 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1906 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1907 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1908 trustedIdentities.removeAll(ownIdentity);
1912 * Notifies the core that a new {@link Identity} was added.
1914 * @param identityAddedEvent
1918 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1919 Identity identity = identityAddedEvent.identity();
1920 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1921 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1922 addRemoteSone(identity);
1926 * Notifies the core that an {@link Identity} was updated.
1928 * @param identityUpdatedEvent
1932 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1933 Identity identity = identityUpdatedEvent.identity();
1934 final Sone sone = getRemoteSone(identity.getId(), false);
1935 if (sone.isLocal()) {
1938 sone.setIdentity(identity);
1939 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1940 soneDownloader.addSone(sone);
1941 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1945 * Notifies the core that an {@link Identity} was removed.
1947 * @param identityRemovedEvent
1951 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1952 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1953 Identity identity = identityRemovedEvent.identity();
1954 trustedIdentities.remove(ownIdentity, identity);
1955 boolean foundIdentity = false;
1956 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1957 if (trustedIdentity.getKey().equals(ownIdentity)) {
1960 if (trustedIdentity.getValue().contains(identity)) {
1961 foundIdentity = true;
1964 if (foundIdentity) {
1965 /* some local identity still trusts this identity, don’t remove. */
1968 Optional<Sone> sone = getSone(identity.getId());
1969 if (!sone.isPresent()) {
1970 /* TODO - we don’t have the Sone anymore. should this happen? */
1973 database.removePosts(sone.get());
1974 for (Post post : sone.get().getPosts()) {
1975 eventBus.post(new PostRemovedEvent(post));
1977 database.removePostReplies(sone.get());
1978 for (PostReply reply : sone.get().getReplies()) {
1979 eventBus.post(new PostReplyRemovedEvent(reply));
1981 synchronized (sones) {
1982 sones.remove(identity.getId());
1984 eventBus.post(new SoneRemovedEvent(sone.get()));
1988 * Deletes the temporary image.
1990 * @param imageInsertFinishedEvent
1994 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1995 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1996 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1997 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1998 touchConfiguration();
2002 class MarkPostKnown implements Runnable {
2004 private final Post post;
2006 public MarkPostKnown(Post post) {
2012 markPostKnown(post);
2018 class MarkReplyKnown implements Runnable {
2020 private final PostReply postReply;
2022 public MarkReplyKnown(PostReply postReply) {
2023 this.postReply = postReply;
2028 markReplyKnown(postReply);