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.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.TimeUnit;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.sone.core.Options.DefaultOption;
42 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
57 import net.pterodactylus.sone.data.Image;
58 import net.pterodactylus.sone.data.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.data.SoneImpl;
67 import net.pterodactylus.sone.data.TemporaryImage;
68 import net.pterodactylus.sone.database.Database;
69 import net.pterodactylus.sone.database.DatabaseException;
70 import net.pterodactylus.sone.database.PostBuilder;
71 import net.pterodactylus.sone.database.PostProvider;
72 import net.pterodactylus.sone.database.PostReplyBuilder;
73 import net.pterodactylus.sone.database.PostReplyProvider;
74 import net.pterodactylus.sone.database.SoneProvider;
75 import net.pterodactylus.sone.fcp.FcpInterface;
76 import net.pterodactylus.sone.freenet.wot.Identity;
77 import net.pterodactylus.sone.freenet.wot.IdentityManager;
78 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
84 import net.pterodactylus.sone.main.SonePlugin;
85 import net.pterodactylus.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
93 import com.google.common.annotations.VisibleForTesting;
94 import com.google.common.base.Optional;
95 import com.google.common.base.Predicates;
96 import com.google.common.collect.FluentIterable;
97 import com.google.common.collect.HashMultimap;
98 import com.google.common.collect.ImmutableSet;
99 import com.google.common.collect.Multimap;
100 import com.google.common.collect.Multimaps;
101 import com.google.common.eventbus.EventBus;
102 import com.google.common.eventbus.Subscribe;
103 import com.google.inject.Inject;
105 import freenet.keys.FreenetURI;
110 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
112 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
115 private static final Logger logger = Logging.getLogger(Core.class);
117 /** The start time. */
118 private final long startupTime = System.currentTimeMillis();
121 private final Options options = new Options();
123 /** The preferences. */
124 private final Preferences preferences = new Preferences(options);
126 /** The event bus. */
127 private final EventBus eventBus;
129 /** The configuration. */
130 private final Configuration configuration;
132 /** Whether we’re currently saving the configuration. */
133 private boolean storingConfiguration = false;
135 /** The identity manager. */
136 private final IdentityManager identityManager;
138 /** Interface to freenet. */
139 private final FreenetInterface freenetInterface;
141 /** The Sone downloader. */
142 private final SoneDownloader soneDownloader;
144 /** The image inserter. */
145 private final ImageInserter imageInserter;
147 /** Sone downloader thread-pool. */
148 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
150 /** The update checker. */
151 private final UpdateChecker updateChecker;
153 /** The trust updater. */
154 private final WebOfTrustUpdater webOfTrustUpdater;
156 /** The FCP interface. */
157 private volatile FcpInterface fcpInterface;
159 /** The times Sones were followed. */
160 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
162 /** Locked local Sones. */
163 /* synchronize on itself. */
164 private final Set<Sone> lockedSones = new HashSet<Sone>();
166 /** Sone inserters. */
167 /* synchronize access on this on sones. */
168 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
170 /** Sone rescuers. */
171 /* synchronize access on this on sones. */
172 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175 /* synchronize access on this on itself. */
176 private final Map<String, Sone> sones = new HashMap<String, Sone>();
178 /** All known Sones. */
179 private final Set<String> knownSones = new HashSet<String>();
181 /** The post database. */
182 private final Database database;
184 /** All bookmarked posts. */
185 /* synchronize access on itself. */
186 private final Set<String> bookmarkedPosts = new HashSet<String>();
188 /** Trusted identities, sorted by own identities. */
189 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
191 /** All temporary images. */
192 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
194 /** Ticker for threads that mark own elements as known. */
195 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
197 /** The time the configuration was last touched. */
198 private volatile long lastConfigurationUpdate;
201 * Creates a new core.
203 * @param configuration
204 * The configuration of the core
205 * @param freenetInterface
206 * The freenet interface
207 * @param identityManager
208 * The identity manager
209 * @param webOfTrustUpdater
210 * The WebOfTrust updater
217 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
219 this.configuration = configuration;
220 this.freenetInterface = freenetInterface;
221 this.identityManager = identityManager;
222 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
223 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
224 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
225 this.webOfTrustUpdater = webOfTrustUpdater;
226 this.eventBus = eventBus;
227 this.database = database;
235 * Returns the time Sone was started.
237 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
239 public long getStartupTime() {
244 * Returns the options used by the core.
246 * @return The options of the core
248 public Preferences getPreferences() {
253 * Returns the identity manager used by the core.
255 * @return The identity manager
257 public IdentityManager getIdentityManager() {
258 return identityManager;
262 * Returns the update checker.
264 * @return The update checker
266 public UpdateChecker getUpdateChecker() {
267 return updateChecker;
271 * Sets the FCP interface to use.
273 * @param fcpInterface
274 * The FCP interface to use
276 public void setFcpInterface(FcpInterface fcpInterface) {
277 this.fcpInterface = fcpInterface;
281 * Returns the Sone rescuer for the given local Sone.
284 * The local Sone to get the rescuer for
285 * @return The Sone rescuer for the given Sone
287 public SoneRescuer getSoneRescuer(Sone sone) {
288 checkNotNull(sone, "sone must not be null");
289 checkArgument(sone.isLocal(), "sone must be local");
290 synchronized (sones) {
291 SoneRescuer soneRescuer = soneRescuers.get(sone);
292 if (soneRescuer == null) {
293 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
294 soneRescuers.put(sone, soneRescuer);
302 * Returns whether the given Sone is currently locked.
306 * @return {@code true} if the Sone is locked, {@code false} if it is not
308 public boolean isLocked(Sone sone) {
309 synchronized (lockedSones) {
310 return lockedSones.contains(sone);
318 public Collection<Sone> getSones() {
319 synchronized (sones) {
320 return ImmutableSet.copyOf(sones.values());
325 * Returns the Sone with the given ID, regardless whether it’s local or
329 * The ID of the Sone to get
330 * @return The Sone with the given ID, or {@code null} if there is no such
334 public Optional<Sone> getSone(String id) {
335 synchronized (sones) {
336 return Optional.fromNullable(sones.get(id));
344 public Collection<Sone> getLocalSones() {
345 synchronized (sones) {
346 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
351 * Returns the local Sone with the given ID, optionally creating a new Sone.
356 * {@code true} to create a new Sone if none exists,
357 * {@code false} to return null if none exists
358 * @return The Sone with the given ID, or {@code null}
360 public Sone getLocalSone(String id, boolean create) {
361 synchronized (sones) {
362 Sone sone = sones.get(id);
363 if ((sone == null) && create) {
364 sone = new SoneImpl(id, true);
367 if ((sone != null) && !sone.isLocal()) {
368 sone = new SoneImpl(id, true);
379 public Collection<Sone> getRemoteSones() {
380 synchronized (sones) {
381 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
386 * Returns the remote Sone with the given ID.
389 * The ID of the remote Sone to get
391 * {@code true} to always create a Sone, {@code false} to return
392 * {@code null} if no Sone with the given ID exists
393 * @return The Sone with the given ID
395 public Sone getRemoteSone(String id, boolean create) {
396 synchronized (sones) {
397 Sone sone = sones.get(id);
398 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
399 sone = new SoneImpl(id, false);
407 * Returns whether the given Sone has been modified.
410 * The Sone to check for modifications
411 * @return {@code true} if a modification has been detected in the Sone,
412 * {@code false} otherwise
414 public boolean isModifiedSone(Sone sone) {
415 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
419 * Returns the time when the given was first followed by any local Sone.
422 * The Sone to get the time for
423 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
424 * been followed, or {@link Long#MAX_VALUE}
426 public long getSoneFollowingTime(Sone sone) {
427 synchronized (soneFollowingTimes) {
428 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
433 * Returns whether the target Sone is trusted by the origin Sone.
439 * @return {@code true} if the target Sone is trusted by the origin Sone
441 public boolean isSoneTrusted(Sone origin, Sone target) {
442 checkNotNull(origin, "origin must not be null");
443 checkNotNull(target, "target must not be null");
444 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
445 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
449 * Returns a post builder.
451 * @return A new post builder
453 public PostBuilder postBuilder() {
454 return database.newPostBuilder();
461 public Optional<Post> getPost(String postId) {
462 return database.getPost(postId);
469 public Collection<Post> getPosts(String soneId) {
470 return database.getPosts(soneId);
477 public Collection<Post> getDirectedPosts(final String recipientId) {
478 checkNotNull(recipientId, "recipient must not be null");
479 return database.getDirectedPosts(recipientId);
483 * Returns a post reply builder.
485 * @return A new post reply builder
487 public PostReplyBuilder postReplyBuilder() {
488 return database.newPostReplyBuilder();
495 public Optional<PostReply> getPostReply(String replyId) {
496 return database.getPostReply(replyId);
503 public List<PostReply> getReplies(final String postId) {
504 return database.getReplies(postId);
508 * Returns all Sones that have liked the given post.
511 * The post to get the liking Sones for
512 * @return The Sones that like the given post
514 public Set<Sone> getLikes(Post post) {
515 Set<Sone> sones = new HashSet<Sone>();
516 for (Sone sone : getSones()) {
517 if (sone.getLikedPostIds().contains(post.getId())) {
525 * Returns all Sones that have liked the given reply.
528 * The reply to get the liking Sones for
529 * @return The Sones that like the given reply
531 public Set<Sone> getLikes(PostReply reply) {
532 Set<Sone> sones = new HashSet<Sone>();
533 for (Sone sone : getSones()) {
534 if (sone.getLikedReplyIds().contains(reply.getId())) {
542 * Returns whether the given post is bookmarked.
546 * @return {@code true} if the given post is bookmarked, {@code false}
549 public boolean isBookmarked(Post post) {
550 return isPostBookmarked(post.getId());
554 * Returns whether the post with the given ID is bookmarked.
557 * The ID of the post to check
558 * @return {@code true} if the post with the given ID is bookmarked,
559 * {@code false} otherwise
561 public boolean isPostBookmarked(String id) {
562 synchronized (bookmarkedPosts) {
563 return bookmarkedPosts.contains(id);
568 * Returns all currently known bookmarked posts.
570 * @return All bookmarked posts
572 public Set<Post> getBookmarkedPosts() {
573 Set<Post> posts = new HashSet<Post>();
574 synchronized (bookmarkedPosts) {
575 for (String bookmarkedPostId : bookmarkedPosts) {
576 Optional<Post> post = getPost(bookmarkedPostId);
577 if (post.isPresent()) {
578 posts.add(post.get());
586 * Returns the album with the given ID, creating a new album if no album
587 * with the given ID can be found.
590 * The ID of the album
591 * @return The album with the given ID
593 public Album getAlbum(String albumId) {
594 return getAlbum(albumId, true);
598 * Returns the album with the given ID, optionally creating a new album if
599 * an album with the given ID can not be found.
602 * The ID of the album
604 * {@code true} to create a new album if none exists for the
606 * @return The album with the given ID, or {@code null} if no album with the
607 * given ID exists and {@code create} is {@code false}
609 public Album getAlbum(String albumId, boolean create) {
610 Optional<Album> album = database.getAlbum(albumId);
611 if (album.isPresent()) {
617 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
618 database.storeAlbum(newAlbum);
623 * Returns the image with the given ID, creating it if necessary.
626 * The ID of the image
627 * @return The image with the given ID
629 public Image getImage(String imageId) {
630 return getImage(imageId, true);
634 * Returns the image with the given ID, optionally creating it if it does
638 * The ID of the image
640 * {@code true} to create an image if none exists with the given
642 * @return The image with the given ID, or {@code null} if none exists and
645 public Image getImage(String imageId, boolean create) {
646 Optional<Image> image = database.getImage(imageId);
647 if (image.isPresent()) {
653 Image newImage = database.newImageBuilder().withId(imageId).build();
654 database.storeImage(newImage);
659 * Returns the temporary image with the given ID.
662 * The ID of the temporary image
663 * @return The temporary image, or {@code null} if there is no temporary
664 * image with the given ID
666 public TemporaryImage getTemporaryImage(String imageId) {
667 synchronized (temporaryImages) {
668 return temporaryImages.get(imageId);
677 * Locks the given Sone. A locked Sone will not be inserted by
678 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
684 public void lockSone(Sone sone) {
685 synchronized (lockedSones) {
686 if (lockedSones.add(sone)) {
687 eventBus.post(new SoneLockedEvent(sone));
693 * Unlocks the given Sone.
695 * @see #lockSone(Sone)
699 public void unlockSone(Sone sone) {
700 synchronized (lockedSones) {
701 if (lockedSones.remove(sone)) {
702 eventBus.post(new SoneUnlockedEvent(sone));
708 * Adds a local Sone from the given own identity.
711 * The own identity to create a Sone from
712 * @return The added (or already existing) Sone
714 public Sone addLocalSone(OwnIdentity ownIdentity) {
715 if (ownIdentity == null) {
716 logger.log(Level.WARNING, "Given OwnIdentity is null!");
719 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
720 synchronized (sones) {
723 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
724 } catch (MalformedURLException mue1) {
725 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
728 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
729 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
731 /* TODO - load posts ’n stuff */
732 sones.put(ownIdentity.getId(), sone);
733 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
734 soneInserters.put(sone, soneInserter);
735 sone.setStatus(SoneStatus.idle);
737 soneInserter.start();
743 * Creates a new Sone for the given own identity.
746 * The own identity to create a Sone for
747 * @return The created Sone
749 public Sone createSone(OwnIdentity ownIdentity) {
750 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
751 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
754 Sone sone = addLocalSone(ownIdentity);
756 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
757 touchConfiguration();
762 * Adds the Sone of the given identity.
765 * The identity whose Sone to add
766 * @return The added or already existing Sone
768 public Sone addRemoteSone(Identity identity) {
769 if (identity == null) {
770 logger.log(Level.WARNING, "Given Identity is null!");
773 synchronized (sones) {
774 final Sone sone = getRemoteSone(identity.getId(), true);
775 if (sone.isLocal()) {
778 sone.setIdentity(identity);
779 boolean newSone = sone.getRequestUri() == null;
780 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
781 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
783 synchronized (knownSones) {
784 newSone = !knownSones.contains(sone.getId());
786 sone.setKnown(!newSone);
788 eventBus.post(new NewSoneFoundEvent(sone));
789 for (Sone localSone : getLocalSones()) {
790 if (localSone.getOptions().isAutoFollow()) {
791 followSone(localSone, sone.getId());
796 soneDownloader.addSone(sone);
797 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
803 * Lets the given local Sone follow the Sone with the given ID.
806 * The local Sone that should follow another Sone
808 * The ID of the Sone to follow
810 public void followSone(Sone sone, String soneId) {
811 checkNotNull(sone, "sone must not be null");
812 checkNotNull(soneId, "soneId must not be null");
813 sone.addFriend(soneId);
814 synchronized (soneFollowingTimes) {
815 if (!soneFollowingTimes.containsKey(soneId)) {
816 long now = System.currentTimeMillis();
817 soneFollowingTimes.put(soneId, now);
818 Optional<Sone> followedSone = getSone(soneId);
819 if (!followedSone.isPresent()) {
822 for (Post post : followedSone.get().getPosts()) {
823 if (post.getTime() < now) {
827 for (PostReply reply : followedSone.get().getReplies()) {
828 if (reply.getTime() < now) {
829 markReplyKnown(reply);
834 touchConfiguration();
838 * Lets the given local Sone unfollow the Sone with the given ID.
841 * The local Sone that should unfollow another Sone
843 * The ID of the Sone being unfollowed
845 public void unfollowSone(Sone sone, String soneId) {
846 checkNotNull(sone, "sone must not be null");
847 checkNotNull(soneId, "soneId must not be null");
848 sone.removeFriend(soneId);
849 boolean unfollowedSoneStillFollowed = false;
850 for (Sone localSone : getLocalSones()) {
851 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
853 if (!unfollowedSoneStillFollowed) {
854 synchronized (soneFollowingTimes) {
855 soneFollowingTimes.remove(soneId);
858 touchConfiguration();
862 * Sets the trust value of the given origin Sone for the target Sone.
869 * The trust value (from {@code -100} to {@code 100})
871 public void setTrust(Sone origin, Sone target, int trustValue) {
872 checkNotNull(origin, "origin must not be null");
873 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
874 checkNotNull(target, "target must not be null");
875 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
876 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
880 * Removes any trust assignment for the given target Sone.
887 public void removeTrust(Sone origin, Sone target) {
888 checkNotNull(origin, "origin must not be null");
889 checkNotNull(target, "target must not be null");
890 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
891 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
895 * Assigns the configured positive trust value for the given target.
902 public void trustSone(Sone origin, Sone target) {
903 setTrust(origin, target, preferences.getPositiveTrust());
907 * Assigns the configured negative trust value for the given target.
914 public void distrustSone(Sone origin, Sone target) {
915 setTrust(origin, target, preferences.getNegativeTrust());
919 * Removes the trust assignment for the given target.
926 public void untrustSone(Sone origin, Sone target) {
927 removeTrust(origin, target);
931 * Updates the stored Sone with the given Sone.
936 public void updateSone(Sone sone) {
937 updateSone(sone, false);
941 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
942 * {@code true}, an older Sone than the current Sone can be given to restore
947 * @param soneRescueMode
948 * {@code true} if the stored Sone should be updated regardless
949 * of the age of the given Sone
951 public void updateSone(Sone sone, boolean soneRescueMode) {
952 Optional<Sone> storedSone = getSone(sone.getId());
953 if (storedSone.isPresent()) {
954 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
955 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
958 /* find removed posts. */
959 Collection<Post> removedPosts = new ArrayList<Post>();
960 Collection<Post> newPosts = new ArrayList<Post>();
961 Collection<Post> existingPosts = database.getPosts(sone.getId());
962 for (Post oldPost : existingPosts) {
963 if (!sone.getPosts().contains(oldPost)) {
964 removedPosts.add(oldPost);
967 /* find new posts. */
968 for (Post newPost : sone.getPosts()) {
969 if (existingPosts.contains(newPost)) {
972 if (newPost.getTime() < getSoneFollowingTime(sone)) {
973 newPost.setKnown(true);
974 } else if (!newPost.isKnown()) {
975 newPosts.add(newPost);
979 database.storePosts(sone, sone.getPosts());
980 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
981 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
982 if (!soneRescueMode) {
983 for (PostReply reply : storedSone.get().getReplies()) {
984 if (!sone.getReplies().contains(reply)) {
985 removedPostReplies.add(reply);
989 Set<PostReply> storedReplies = storedSone.get().getReplies();
990 for (PostReply reply : sone.getReplies()) {
991 if (storedReplies.contains(reply)) {
994 if (reply.getTime() < getSoneFollowingTime(sone)) {
995 reply.setKnown(true);
996 } else if (!reply.isKnown()) {
997 newPostReplies.add(reply);
1000 database.storePostReplies(sone, sone.getReplies());
1001 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1002 database.removeAlbum(album);
1003 for (Image image : album.getImages()) {
1004 database.removeImage(image);
1007 for (Post removedPost : removedPosts) {
1008 eventBus.post(new PostRemovedEvent(removedPost));
1010 for (Post newPost : newPosts) {
1011 eventBus.post(new NewPostFoundEvent(newPost));
1013 for (PostReply removedPostReply : removedPostReplies) {
1014 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1016 for (PostReply newPostReply : newPostReplies) {
1017 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1019 for (Album album : sone.getRootAlbum().getAlbums()) {
1020 database.storeAlbum(album);
1021 for (Image image : album.getImages()) {
1022 database.storeImage(image);
1025 synchronized (sones) {
1026 sone.setOptions(storedSone.get().getOptions());
1027 sone.setKnown(storedSone.get().isKnown());
1028 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1029 if (sone.isLocal()) {
1030 soneInserters.get(storedSone.get()).setSone(sone);
1031 touchConfiguration();
1033 sones.put(sone.getId(), sone);
1039 * Deletes the given Sone. This will remove the Sone from the
1040 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1041 * remove the context from its identity.
1044 * The Sone to delete
1046 public void deleteSone(Sone sone) {
1047 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1048 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1051 synchronized (sones) {
1052 if (!getLocalSones().contains(sone)) {
1053 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1056 sones.remove(sone.getId());
1057 SoneInserter soneInserter = soneInserters.remove(sone);
1058 soneInserter.stop();
1060 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1061 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1063 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1064 } catch (ConfigurationException ce1) {
1065 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1070 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1071 * known} before, a {@link MarkSoneKnownEvent} is fired.
1074 * The Sone to mark as known
1076 public void markSoneKnown(Sone sone) {
1077 if (!sone.isKnown()) {
1078 sone.setKnown(true);
1079 synchronized (knownSones) {
1080 knownSones.add(sone.getId());
1082 eventBus.post(new MarkSoneKnownEvent(sone));
1083 touchConfiguration();
1088 * Loads and updates the given Sone from the configuration. If any error is
1089 * encountered, loading is aborted and the given Sone is not changed.
1092 * The Sone to load and update
1094 public void loadSone(Sone sone) {
1095 if (!sone.isLocal()) {
1096 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1099 logger.info(String.format("Loading local Sone: %s", sone));
1102 String sonePrefix = "Sone/" + sone.getId();
1103 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1104 if (soneTime == null) {
1105 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1108 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1111 Profile profile = new Profile(sone);
1112 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1113 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1114 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1115 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1116 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1117 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1119 /* load profile fields. */
1121 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1122 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1123 if (fieldName == null) {
1126 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1127 profile.addField(fieldName).setValue(fieldValue);
1131 Set<Post> posts = new HashSet<Post>();
1133 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1134 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1135 if (postId == null) {
1138 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1139 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1140 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1141 if ((postTime == 0) || (postText == null)) {
1142 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1145 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1146 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1147 postBuilder.to(postRecipientId);
1149 posts.add(postBuilder.build());
1153 Set<PostReply> replies = new HashSet<PostReply>();
1155 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1156 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1157 if (replyId == null) {
1160 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1161 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1162 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1163 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1164 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1167 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1168 replies.add(postReplyBuilder.build());
1171 /* load post likes. */
1172 Set<String> likedPostIds = new HashSet<String>();
1174 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1175 if (likedPostId == null) {
1178 likedPostIds.add(likedPostId);
1181 /* load reply likes. */
1182 Set<String> likedReplyIds = new HashSet<String>();
1184 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1185 if (likedReplyId == null) {
1188 likedReplyIds.add(likedReplyId);
1192 Set<String> friends = new HashSet<String>();
1194 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1195 if (friendId == null) {
1198 friends.add(friendId);
1202 List<Album> topLevelAlbums = new ArrayList<Album>();
1203 int albumCounter = 0;
1205 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1206 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1207 if (albumId == null) {
1210 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1211 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1212 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1213 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1214 if ((albumTitle == null) || (albumDescription == null)) {
1215 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1218 Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1219 if (albumParentId != null) {
1220 Album parentAlbum = getAlbum(albumParentId, false);
1221 if (parentAlbum == null) {
1222 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1225 parentAlbum.addAlbum(album);
1227 if (!topLevelAlbums.contains(album)) {
1228 topLevelAlbums.add(album);
1234 int imageCounter = 0;
1236 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1237 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1238 if (imageId == null) {
1241 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1242 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1243 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1244 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1245 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1246 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1247 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1248 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1249 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1252 Album album = getAlbum(albumId, false);
1253 if (album == null) {
1254 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1257 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1258 album.addImage(image);
1262 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1263 if (avatarId != null) {
1264 profile.setAvatar(getImage(avatarId, false));
1268 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1269 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1270 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1271 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1272 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1273 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1275 /* if we’re still here, Sone was loaded successfully. */
1276 synchronized (sone) {
1277 sone.setTime(soneTime);
1278 sone.setProfile(profile);
1279 sone.setPosts(posts);
1280 sone.setReplies(replies);
1281 sone.setLikePostIds(likedPostIds);
1282 sone.setLikeReplyIds(likedReplyIds);
1283 for (String friendId : friends) {
1284 followSone(sone, friendId);
1286 for (Album album : sone.getRootAlbum().getAlbums()) {
1287 sone.getRootAlbum().removeAlbum(album);
1289 for (Album album : topLevelAlbums) {
1290 sone.getRootAlbum().addAlbum(album);
1292 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1294 synchronized (knownSones) {
1295 for (String friend : friends) {
1296 knownSones.add(friend);
1299 database.storePosts(sone, posts);
1300 for (Post post : posts) {
1301 post.setKnown(true);
1303 database.storePostReplies(sone, replies);
1304 for (PostReply reply : replies) {
1305 reply.setKnown(true);
1308 logger.info(String.format("Sone loaded successfully: %s", sone));
1312 * Creates a new post.
1315 * The Sone that creates the post
1317 * The text of the post
1318 * @return The created post
1320 public Post createPost(Sone sone, String text) {
1321 return createPost(sone, System.currentTimeMillis(), text);
1325 * Creates a new post.
1328 * The Sone that creates the post
1330 * The time of the post
1332 * The text of the post
1333 * @return The created post
1335 public Post createPost(Sone sone, long time, String text) {
1336 return createPost(sone, null, time, text);
1340 * Creates a new post.
1343 * The Sone that creates the post
1345 * The recipient Sone, or {@code null} if this post does not have
1348 * The text of the post
1349 * @return The created post
1351 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1352 return createPost(sone, recipient, System.currentTimeMillis(), text);
1356 * Creates a new post.
1359 * The Sone that creates the post
1361 * The recipient Sone, or {@code null} if this post does not have
1364 * The time of the post
1366 * The text of the post
1367 * @return The created post
1369 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1370 checkNotNull(text, "text must not be null");
1371 checkArgument(text.trim().length() > 0, "text must not be empty");
1372 if (!sone.isLocal()) {
1373 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1376 PostBuilder postBuilder = database.newPostBuilder();
1377 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1378 if (recipient.isPresent()) {
1379 postBuilder.to(recipient.get().getId());
1381 final Post post = postBuilder.build();
1382 database.storePost(post);
1383 eventBus.post(new NewPostFoundEvent(post));
1385 touchConfiguration();
1386 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1391 * Deletes the given post.
1394 * The post to delete
1396 public void deletePost(Post post) {
1397 if (!post.getSone().isLocal()) {
1398 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1401 database.removePost(post);
1402 eventBus.post(new PostRemovedEvent(post));
1403 markPostKnown(post);
1404 touchConfiguration();
1408 * Marks the given post as known, if it is currently not a known post
1409 * (according to {@link Post#isKnown()}).
1412 * The post to mark as known
1414 public void markPostKnown(Post post) {
1415 post.setKnown(true);
1416 eventBus.post(new MarkPostKnownEvent(post));
1417 touchConfiguration();
1418 for (PostReply reply : getReplies(post.getId())) {
1419 markReplyKnown(reply);
1424 * Bookmarks the given post.
1427 * The post to bookmark
1429 public void bookmark(Post post) {
1430 bookmarkPost(post.getId());
1434 * Bookmarks the post with the given ID.
1437 * The ID of the post to bookmark
1439 public void bookmarkPost(String id) {
1440 synchronized (bookmarkedPosts) {
1441 bookmarkedPosts.add(id);
1446 * Removes the given post from the bookmarks.
1449 * The post to unbookmark
1451 public void unbookmark(Post post) {
1452 unbookmarkPost(post.getId());
1456 * Removes the post with the given ID from the bookmarks.
1459 * The ID of the post to unbookmark
1461 public void unbookmarkPost(String id) {
1462 synchronized (bookmarkedPosts) {
1463 bookmarkedPosts.remove(id);
1468 * Creates a new reply.
1471 * The Sone that creates the reply
1473 * The post that this reply refers to
1475 * The text of the reply
1476 * @return The created reply
1478 public PostReply createReply(Sone sone, Post post, String text) {
1479 checkNotNull(text, "text must not be null");
1480 checkArgument(text.trim().length() > 0, "text must not be empty");
1481 if (!sone.isLocal()) {
1482 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1485 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1486 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1487 final PostReply reply = postReplyBuilder.build();
1488 database.storePostReply(reply);
1489 eventBus.post(new NewPostReplyFoundEvent(reply));
1490 sone.addReply(reply);
1491 touchConfiguration();
1492 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1497 * Deletes the given reply.
1500 * The reply to delete
1502 public void deleteReply(PostReply reply) {
1503 Sone sone = reply.getSone();
1504 if (!sone.isLocal()) {
1505 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1508 database.removePostReply(reply);
1509 markReplyKnown(reply);
1510 sone.removeReply(reply);
1511 touchConfiguration();
1515 * Marks the given reply as known, if it is currently not a known reply
1516 * (according to {@link Reply#isKnown()}).
1519 * The reply to mark as known
1521 public void markReplyKnown(PostReply reply) {
1522 boolean previouslyKnown = reply.isKnown();
1523 reply.setKnown(true);
1524 eventBus.post(new MarkPostReplyKnownEvent(reply));
1525 if (!previouslyKnown) {
1526 touchConfiguration();
1531 * Creates a new top-level album for the given Sone.
1534 * The Sone to create the album for
1535 * @return The new album
1537 public Album createAlbum(Sone sone) {
1538 return createAlbum(sone, sone.getRootAlbum());
1542 * Creates a new album for the given Sone.
1545 * The Sone to create the album for
1547 * The parent of the album (may be {@code null} to create a
1549 * @return The new album
1551 public Album createAlbum(Sone sone, Album parent) {
1552 Album album = database.newAlbumBuilder().randomId().build();
1553 database.storeAlbum(album);
1554 album.setSone(sone);
1555 parent.addAlbum(album);
1560 * Deletes the given album. The owner of the album has to be a local Sone,
1561 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1564 * The album to remove
1566 public void deleteAlbum(Album album) {
1567 checkNotNull(album, "album must not be null");
1568 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1569 if (!album.isEmpty()) {
1572 album.getParent().removeAlbum(album);
1573 database.removeAlbum(album);
1574 touchConfiguration();
1578 * Creates a new image.
1581 * The Sone creating the image
1583 * The album the image will be inserted into
1584 * @param temporaryImage
1585 * The temporary image to create the image from
1586 * @return The newly created image
1588 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1589 checkNotNull(sone, "sone must not be null");
1590 checkNotNull(album, "album must not be null");
1591 checkNotNull(temporaryImage, "temporaryImage must not be null");
1592 checkArgument(sone.isLocal(), "sone must be a local Sone");
1593 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1594 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1595 album.addImage(image);
1596 database.storeImage(image);
1597 imageInserter.insertImage(temporaryImage, image);
1602 * Deletes the given image. This method will also delete a matching
1605 * @see #deleteTemporaryImage(TemporaryImage)
1607 * The image to delete
1609 public void deleteImage(Image image) {
1610 checkNotNull(image, "image must not be null");
1611 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1612 deleteTemporaryImage(image.getId());
1613 image.getAlbum().removeImage(image);
1614 database.removeImage(image);
1615 touchConfiguration();
1619 * Creates a new temporary image.
1622 * The MIME type of the temporary image
1624 * The encoded data of the image
1625 * @return The temporary image
1627 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1628 TemporaryImage temporaryImage = new TemporaryImage();
1629 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1630 synchronized (temporaryImages) {
1631 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1633 return temporaryImage;
1637 * Deletes the given temporary image.
1639 * @param temporaryImage
1640 * The temporary image to delete
1642 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1643 checkNotNull(temporaryImage, "temporaryImage must not be null");
1644 deleteTemporaryImage(temporaryImage.getId());
1648 * Deletes the temporary image with the given ID.
1651 * The ID of the temporary image to delete
1653 public void deleteTemporaryImage(String imageId) {
1654 checkNotNull(imageId, "imageId must not be null");
1655 synchronized (temporaryImages) {
1656 temporaryImages.remove(imageId);
1658 Image image = getImage(imageId, false);
1659 if (image != null) {
1660 imageInserter.cancelImageInsert(image);
1665 * Notifies the core that the configuration, either of the core or of a
1666 * single local Sone, has changed, and that the configuration should be
1669 public void touchConfiguration() {
1670 lastConfigurationUpdate = System.currentTimeMillis();
1681 public void serviceStart() {
1682 loadConfiguration();
1683 updateChecker.start();
1684 identityManager.start();
1685 webOfTrustUpdater.init();
1686 webOfTrustUpdater.start();
1694 public void serviceRun() {
1695 long lastSaved = System.currentTimeMillis();
1696 while (!shouldStop()) {
1698 long now = System.currentTimeMillis();
1699 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1700 for (Sone localSone : getLocalSones()) {
1701 saveSone(localSone);
1703 saveConfiguration();
1713 public void serviceStop() {
1714 localElementTicker.shutdownNow();
1715 synchronized (sones) {
1716 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1717 soneInserter.getValue().stop();
1718 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1721 saveConfiguration();
1723 webOfTrustUpdater.stop();
1724 updateChecker.stop();
1725 soneDownloader.stop();
1726 soneDownloaders.shutdown();
1727 identityManager.stop();
1735 * Saves the given Sone. This will persist all local settings for the given
1736 * Sone, such as the friends list and similar, private options.
1741 private synchronized void saveSone(Sone sone) {
1742 if (!sone.isLocal()) {
1743 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1746 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1747 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1751 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1753 /* save Sone into configuration. */
1754 String sonePrefix = "Sone/" + sone.getId();
1755 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1756 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1759 Profile profile = sone.getProfile();
1760 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1761 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1762 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1763 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1764 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1765 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1766 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1768 /* save profile fields. */
1769 int fieldCounter = 0;
1770 for (Field profileField : profile.getFields()) {
1771 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1772 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1773 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1775 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1778 int postCounter = 0;
1779 for (Post post : sone.getPosts()) {
1780 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1781 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1782 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1783 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1784 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1786 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1789 int replyCounter = 0;
1790 for (PostReply reply : sone.getReplies()) {
1791 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1792 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1793 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1794 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1795 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1797 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1799 /* save post likes. */
1800 int postLikeCounter = 0;
1801 for (String postId : sone.getLikedPostIds()) {
1802 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1804 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1806 /* save reply likes. */
1807 int replyLikeCounter = 0;
1808 for (String replyId : sone.getLikedReplyIds()) {
1809 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1811 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1814 int friendCounter = 0;
1815 for (String friendId : sone.getFriends()) {
1816 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1818 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1820 /* save albums. first, collect in a flat structure, top-level first. */
1821 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1823 int albumCounter = 0;
1824 for (Album album : albums) {
1825 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1826 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1827 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1828 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1829 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1830 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1832 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1835 int imageCounter = 0;
1836 for (Album album : albums) {
1837 for (Image image : album.getImages()) {
1838 if (!image.isInserted()) {
1841 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1842 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1843 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1844 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1845 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1846 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1847 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1848 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1849 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1852 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1855 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1856 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1857 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1858 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1859 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1860 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1862 configuration.save();
1864 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1866 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1867 } catch (ConfigurationException ce1) {
1868 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1873 * Saves the current options.
1875 private void saveConfiguration() {
1876 synchronized (configuration) {
1877 if (storingConfiguration) {
1878 logger.log(Level.FINE, "Already storing configuration…");
1881 storingConfiguration = true;
1884 /* store the options first. */
1886 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1887 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1888 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1889 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1890 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1891 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1892 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1893 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1894 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1895 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1896 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1897 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1899 /* save known Sones. */
1900 int soneCounter = 0;
1901 synchronized (knownSones) {
1902 for (String knownSoneId : knownSones) {
1903 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1905 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1908 /* save Sone following times. */
1910 synchronized (soneFollowingTimes) {
1911 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1912 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1913 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1916 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1919 /* save known posts. */
1922 /* save bookmarked posts. */
1923 int bookmarkedPostCounter = 0;
1924 synchronized (bookmarkedPosts) {
1925 for (String bookmarkedPostId : bookmarkedPosts) {
1926 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1929 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1932 configuration.save();
1934 } catch (ConfigurationException ce1) {
1935 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1936 } catch (DatabaseException de1) {
1937 logger.log(Level.SEVERE, "Could not save database!", de1);
1939 synchronized (configuration) {
1940 storingConfiguration = false;
1946 * Loads the configuration.
1948 private void loadConfiguration() {
1949 /* create options. */
1950 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1951 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1952 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1953 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1954 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1955 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1956 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1957 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1958 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1959 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1960 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1962 loadConfigurationValue("InsertionDelay");
1963 loadConfigurationValue("PostsPerPage");
1964 loadConfigurationValue("ImagesPerPage");
1965 loadConfigurationValue("CharactersPerPost");
1966 loadConfigurationValue("PostCutOffLength");
1967 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1968 loadConfigurationValue("PositiveTrust");
1969 loadConfigurationValue("NegativeTrust");
1970 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1971 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1972 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1974 /* load known Sones. */
1975 int soneCounter = 0;
1977 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1978 if (knownSoneId == null) {
1981 synchronized (knownSones) {
1982 knownSones.add(knownSoneId);
1986 /* load Sone following times. */
1989 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1990 if (soneId == null) {
1993 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1994 synchronized (soneFollowingTimes) {
1995 soneFollowingTimes.put(soneId, time);
2000 /* load bookmarked posts. */
2001 int bookmarkedPostCounter = 0;
2003 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2004 if (bookmarkedPostId == null) {
2007 synchronized (bookmarkedPosts) {
2008 bookmarkedPosts.add(bookmarkedPostId);
2015 * Loads an {@link Integer} configuration value for the option with the
2016 * given name, logging validation failures.
2019 * The name of the option to load
2021 private void loadConfigurationValue(String optionName) {
2023 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2024 } catch (IllegalArgumentException iae1) {
2025 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2030 * Notifies the core that a new {@link OwnIdentity} was added.
2032 * @param ownIdentityAddedEvent
2036 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2037 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2038 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2039 if (ownIdentity.hasContext("Sone")) {
2040 addLocalSone(ownIdentity);
2045 * Notifies the core that an {@link OwnIdentity} was removed.
2047 * @param ownIdentityRemovedEvent
2051 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2052 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2053 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2054 trustedIdentities.removeAll(ownIdentity);
2058 * Notifies the core that a new {@link Identity} was added.
2060 * @param identityAddedEvent
2064 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2065 Identity identity = identityAddedEvent.identity();
2066 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2067 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2068 addRemoteSone(identity);
2072 * Notifies the core that an {@link Identity} was updated.
2074 * @param identityUpdatedEvent
2078 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2079 Identity identity = identityUpdatedEvent.identity();
2080 final Sone sone = getRemoteSone(identity.getId(), false);
2081 if (sone.isLocal()) {
2084 sone.setIdentity(identity);
2085 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2086 soneDownloader.addSone(sone);
2087 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
2091 * Notifies the core that an {@link Identity} was removed.
2093 * @param identityRemovedEvent
2097 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2098 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2099 Identity identity = identityRemovedEvent.identity();
2100 trustedIdentities.remove(ownIdentity, identity);
2101 boolean foundIdentity = false;
2102 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2103 if (trustedIdentity.getKey().equals(ownIdentity)) {
2106 if (trustedIdentity.getValue().contains(identity)) {
2107 foundIdentity = true;
2110 if (foundIdentity) {
2111 /* some local identity still trusts this identity, don’t remove. */
2114 Optional<Sone> sone = getSone(identity.getId());
2115 if (!sone.isPresent()) {
2116 /* TODO - we don’t have the Sone anymore. should this happen? */
2119 database.removePosts(sone.get());
2120 for (Post post : sone.get().getPosts()) {
2121 eventBus.post(new PostRemovedEvent(post));
2123 database.removePostReplies(sone.get());
2124 for (PostReply reply : sone.get().getReplies()) {
2125 eventBus.post(new PostReplyRemovedEvent(reply));
2127 synchronized (sones) {
2128 sones.remove(identity.getId());
2130 eventBus.post(new SoneRemovedEvent(sone.get()));
2134 * Deletes the temporary image.
2136 * @param imageInsertFinishedEvent
2140 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2141 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2142 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2143 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2144 touchConfiguration();
2148 class MarkPostKnown implements Runnable {
2150 private final Post post;
2152 public MarkPostKnown(Post post) {
2158 markPostKnown(post);
2164 class MarkReplyKnown implements Runnable {
2166 private final PostReply postReply;
2168 public MarkReplyKnown(PostReply postReply) {
2169 this.postReply = postReply;
2174 markReplyKnown(postReply);