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;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
39 import net.pterodactylus.sone.core.Options.DefaultOption;
40 import net.pterodactylus.sone.core.Options.Option;
41 import net.pterodactylus.sone.core.Options.OptionWatcher;
42 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
43 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
46 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
47 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
48 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
49 import net.pterodactylus.sone.core.event.PostRemovedEvent;
50 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneLockedEvent;
52 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.SoneImpl;
66 import net.pterodactylus.sone.data.TemporaryImage;
67 import net.pterodactylus.sone.database.Database;
68 import net.pterodactylus.sone.database.DatabaseException;
69 import net.pterodactylus.sone.database.PostBuilder;
70 import net.pterodactylus.sone.database.PostProvider;
71 import net.pterodactylus.sone.database.PostReplyBuilder;
72 import net.pterodactylus.sone.database.PostReplyProvider;
73 import net.pterodactylus.sone.database.SoneProvider;
74 import net.pterodactylus.sone.fcp.FcpInterface;
75 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
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.base.Optional;
94 import com.google.common.base.Predicate;
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 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 SoneDownloader(this, freenetInterface);
223 this.imageInserter = new ImageInserter(freenetInterface);
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 * Sets the configuration to use. This will automatically save the current
245 * configuration to the given configuration.
247 * @param configuration
248 * The new configuration to use
250 public void setConfiguration(Configuration configuration) {
251 this.configuration = configuration;
252 touchConfiguration();
256 * Returns the options used by the core.
258 * @return The options of the core
260 public Preferences getPreferences() {
265 * Returns the identity manager used by the core.
267 * @return The identity manager
269 public IdentityManager getIdentityManager() {
270 return identityManager;
274 * Returns the update checker.
276 * @return The update checker
278 public UpdateChecker getUpdateChecker() {
279 return updateChecker;
283 * Sets the FCP interface to use.
285 * @param fcpInterface
286 * The FCP interface to use
288 public void setFcpInterface(FcpInterface fcpInterface) {
289 this.fcpInterface = fcpInterface;
293 * Returns the Sone rescuer for the given local Sone.
296 * The local Sone to get the rescuer for
297 * @return The Sone rescuer for the given Sone
299 public SoneRescuer getSoneRescuer(Sone sone) {
300 checkNotNull(sone, "sone must not be null");
301 checkArgument(sone.isLocal(), "sone must be local");
302 synchronized (sones) {
303 SoneRescuer soneRescuer = soneRescuers.get(sone);
304 if (soneRescuer == null) {
305 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
306 soneRescuers.put(sone, soneRescuer);
314 * Returns whether the given Sone is currently locked.
318 * @return {@code true} if the Sone is locked, {@code false} if it is not
320 public boolean isLocked(Sone sone) {
321 synchronized (lockedSones) {
322 return lockedSones.contains(sone);
330 public Collection<Sone> getSones() {
331 synchronized (sones) {
332 return ImmutableSet.copyOf(sones.values());
337 * Returns the Sone with the given ID, regardless whether it’s local or
341 * The ID of the Sone to get
342 * @return The Sone with the given ID, or {@code null} if there is no such
346 public Optional<Sone> getSone(String id) {
347 synchronized (sones) {
348 return Optional.fromNullable(sones.get(id));
356 public Collection<Sone> getLocalSones() {
357 synchronized (sones) {
358 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
361 public boolean apply(Sone sone) {
362 return sone.isLocal();
369 * Returns the local Sone with the given ID, optionally creating a new Sone.
374 * {@code true} to create a new Sone if none exists,
375 * {@code false} to return null if none exists
376 * @return The Sone with the given ID, or {@code null}
378 public Sone getLocalSone(String id, boolean create) {
379 synchronized (sones) {
380 Sone sone = sones.get(id);
381 if ((sone == null) && create) {
382 sone = new SoneImpl(id, true);
385 if ((sone != null) && !sone.isLocal()) {
386 sone = new SoneImpl(id, true);
397 public Collection<Sone> getRemoteSones() {
398 synchronized (sones) {
399 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
402 public boolean apply(Sone sone) {
403 return !sone.isLocal();
410 * Returns the remote Sone with the given ID.
413 * The ID of the remote Sone to get
415 * {@code true} to always create a Sone, {@code false} to return
416 * {@code null} if no Sone with the given ID exists
417 * @return The Sone with the given ID
419 public Sone getRemoteSone(String id, boolean create) {
420 synchronized (sones) {
421 Sone sone = sones.get(id);
422 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
423 sone = new SoneImpl(id, false);
431 * Returns whether the given Sone has been modified.
434 * The Sone to check for modifications
435 * @return {@code true} if a modification has been detected in the Sone,
436 * {@code false} otherwise
438 public boolean isModifiedSone(Sone sone) {
439 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
443 * Returns the time when the given was first followed by any local Sone.
446 * The Sone to get the time for
447 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
448 * been followed, or {@link Long#MAX_VALUE}
450 public long getSoneFollowingTime(Sone sone) {
451 synchronized (soneFollowingTimes) {
452 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
457 * Returns whether the target Sone is trusted by the origin Sone.
463 * @return {@code true} if the target Sone is trusted by the origin Sone
465 public boolean isSoneTrusted(Sone origin, Sone target) {
466 checkNotNull(origin, "origin must not be null");
467 checkNotNull(target, "target must not be null");
468 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
469 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
473 * Returns a post builder.
475 * @return A new post builder
477 public PostBuilder postBuilder() {
478 return database.newPostBuilder();
485 public Optional<Post> getPost(String postId) {
486 return database.getPost(postId);
493 public Collection<Post> getPosts(String soneId) {
494 return database.getPosts(soneId);
501 public Collection<Post> getDirectedPosts(final String recipientId) {
502 checkNotNull(recipientId, "recipient must not be null");
503 return database.getDirectedPosts(recipientId);
507 * Returns a post reply builder.
509 * @return A new post reply builder
511 public PostReplyBuilder postReplyBuilder() {
512 return database.newPostReplyBuilder();
519 public Optional<PostReply> getPostReply(String replyId) {
520 return database.getPostReply(replyId);
527 public List<PostReply> getReplies(final String postId) {
528 return database.getReplies(postId);
532 * Returns all Sones that have liked the given post.
535 * The post to get the liking Sones for
536 * @return The Sones that like the given post
538 public Set<Sone> getLikes(Post post) {
539 Set<Sone> sones = new HashSet<Sone>();
540 for (Sone sone : getSones()) {
541 if (sone.getLikedPostIds().contains(post.getId())) {
549 * Returns all Sones that have liked the given reply.
552 * The reply to get the liking Sones for
553 * @return The Sones that like the given reply
555 public Set<Sone> getLikes(PostReply reply) {
556 Set<Sone> sones = new HashSet<Sone>();
557 for (Sone sone : getSones()) {
558 if (sone.getLikedReplyIds().contains(reply.getId())) {
566 * Returns whether the given post is bookmarked.
570 * @return {@code true} if the given post is bookmarked, {@code false}
573 public boolean isBookmarked(Post post) {
574 return isPostBookmarked(post.getId());
578 * Returns whether the post with the given ID is bookmarked.
581 * The ID of the post to check
582 * @return {@code true} if the post with the given ID is bookmarked,
583 * {@code false} otherwise
585 public boolean isPostBookmarked(String id) {
586 synchronized (bookmarkedPosts) {
587 return bookmarkedPosts.contains(id);
592 * Returns all currently known bookmarked posts.
594 * @return All bookmarked posts
596 public Set<Post> getBookmarkedPosts() {
597 Set<Post> posts = new HashSet<Post>();
598 synchronized (bookmarkedPosts) {
599 for (String bookmarkedPostId : bookmarkedPosts) {
600 Optional<Post> post = getPost(bookmarkedPostId);
601 if (post.isPresent()) {
602 posts.add(post.get());
610 * Returns the album with the given ID, creating a new album if no album
611 * with the given ID can be found.
614 * The ID of the album
615 * @return The album with the given ID
617 public Album getAlbum(String albumId) {
618 return getAlbum(albumId, true);
622 * Returns the album with the given ID, optionally creating a new album if
623 * an album with the given ID can not be found.
626 * The ID of the album
628 * {@code true} to create a new album if none exists for the
630 * @return The album with the given ID, or {@code null} if no album with the
631 * given ID exists and {@code create} is {@code false}
633 public Album getAlbum(String albumId, boolean create) {
634 Optional<Album> album = database.getAlbum(albumId);
635 if (album.isPresent()) {
641 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
642 database.storeAlbum(newAlbum);
646 public Optional<Image> getImage(String imageId) {
647 return database.getImage(imageId);
651 * Returns the temporary image with the given ID.
654 * The ID of the temporary image
655 * @return The temporary image, or {@code null} if there is no temporary
656 * image with the given ID
658 public TemporaryImage getTemporaryImage(String imageId) {
659 synchronized (temporaryImages) {
660 return temporaryImages.get(imageId);
669 * Locks the given Sone. A locked Sone will not be inserted by
670 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
676 public void lockSone(Sone sone) {
677 synchronized (lockedSones) {
678 if (lockedSones.add(sone)) {
679 eventBus.post(new SoneLockedEvent(sone));
685 * Unlocks the given Sone.
687 * @see #lockSone(Sone)
691 public void unlockSone(Sone sone) {
692 synchronized (lockedSones) {
693 if (lockedSones.remove(sone)) {
694 eventBus.post(new SoneUnlockedEvent(sone));
700 * Adds a local Sone from the given own identity.
703 * The own identity to create a Sone from
704 * @return The added (or already existing) Sone
706 public Sone addLocalSone(OwnIdentity ownIdentity) {
707 if (ownIdentity == null) {
708 logger.log(Level.WARNING, "Given OwnIdentity is null!");
711 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
712 synchronized (sones) {
715 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
716 } catch (MalformedURLException mue1) {
717 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
720 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
721 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
723 /* TODO - load posts ’n stuff */
724 sones.put(ownIdentity.getId(), sone);
725 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
726 soneInserters.put(sone, soneInserter);
727 sone.setStatus(SoneStatus.idle);
729 soneInserter.start();
735 * Creates a new Sone for the given own identity.
738 * The own identity to create a Sone for
739 * @return The created Sone
741 public Sone createSone(OwnIdentity ownIdentity) {
742 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
743 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
746 Sone sone = addLocalSone(ownIdentity);
747 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
748 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
749 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
750 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
751 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
752 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
754 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
755 touchConfiguration();
760 * Adds the Sone of the given identity.
763 * The identity whose Sone to add
764 * @return The added or already existing Sone
766 public Sone addRemoteSone(Identity identity) {
767 if (identity == null) {
768 logger.log(Level.WARNING, "Given Identity is null!");
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(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
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().getBooleanOption("AutoFollow").get()) {
789 followSone(localSone, sone.getId());
794 soneDownloader.addSone(sone);
795 soneDownloaders.execute(new Runnable() {
798 @SuppressWarnings("synthetic-access")
800 soneDownloader.fetchSone(sone, sone.getRequestUri());
809 * Lets the given local Sone follow the Sone with the given ID.
812 * The local Sone that should follow another Sone
814 * The ID of the Sone to follow
816 public void followSone(Sone sone, String soneId) {
817 checkNotNull(sone, "sone must not be null");
818 checkNotNull(soneId, "soneId must not be null");
819 sone.addFriend(soneId);
820 synchronized (soneFollowingTimes) {
821 if (!soneFollowingTimes.containsKey(soneId)) {
822 long now = System.currentTimeMillis();
823 soneFollowingTimes.put(soneId, now);
824 Optional<Sone> followedSone = getSone(soneId);
825 if (!followedSone.isPresent()) {
828 for (Post post : followedSone.get().getPosts()) {
829 if (post.getTime() < now) {
833 for (PostReply reply : followedSone.get().getReplies()) {
834 if (reply.getTime() < now) {
835 markReplyKnown(reply);
840 touchConfiguration();
844 * Lets the given local Sone unfollow the Sone with the given ID.
847 * The local Sone that should unfollow another Sone
849 * The ID of the Sone being unfollowed
851 public void unfollowSone(Sone sone, String soneId) {
852 checkNotNull(sone, "sone must not be null");
853 checkNotNull(soneId, "soneId must not be null");
854 sone.removeFriend(soneId);
855 boolean unfollowedSoneStillFollowed = false;
856 for (Sone localSone : getLocalSones()) {
857 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
859 if (!unfollowedSoneStillFollowed) {
860 synchronized (soneFollowingTimes) {
861 soneFollowingTimes.remove(soneId);
864 touchConfiguration();
868 * Sets the trust value of the given origin Sone for the target Sone.
875 * The trust value (from {@code -100} to {@code 100})
877 public void setTrust(Sone origin, Sone target, int trustValue) {
878 checkNotNull(origin, "origin must not be null");
879 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
880 checkNotNull(target, "target must not be null");
881 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
882 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
886 * Removes any trust assignment for the given target Sone.
893 public void removeTrust(Sone origin, Sone target) {
894 checkNotNull(origin, "origin must not be null");
895 checkNotNull(target, "target must not be null");
896 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
897 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
901 * Assigns the configured positive trust value for the given target.
908 public void trustSone(Sone origin, Sone target) {
909 setTrust(origin, target, preferences.getPositiveTrust());
913 * Assigns the configured negative trust value for the given target.
920 public void distrustSone(Sone origin, Sone target) {
921 setTrust(origin, target, preferences.getNegativeTrust());
925 * Removes the trust assignment for the given target.
932 public void untrustSone(Sone origin, Sone target) {
933 removeTrust(origin, target);
937 * Updates the stored Sone with the given Sone.
942 public void updateSone(Sone sone) {
943 updateSone(sone, false);
947 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
948 * {@code true}, an older Sone than the current Sone can be given to restore
953 * @param soneRescueMode
954 * {@code true} if the stored Sone should be updated regardless
955 * of the age of the given Sone
957 public void updateSone(Sone sone, boolean soneRescueMode) {
958 Optional<Sone> storedSone = getSone(sone.getId());
959 if (storedSone.isPresent()) {
960 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
961 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
964 /* find removed posts. */
965 Collection<Post> existingPosts = database.getPosts(sone.getId());
966 for (Post oldPost : existingPosts) {
967 if (!sone.getPosts().contains(oldPost)) {
968 eventBus.post(new PostRemovedEvent(oldPost));
971 /* find new posts. */
972 for (Post newPost : sone.getPosts()) {
973 if (existingPosts.contains(newPost)) {
976 if (newPost.getTime() < getSoneFollowingTime(sone)) {
977 newPost.setKnown(true);
978 } else if (!newPost.isKnown()) {
979 eventBus.post(new NewPostFoundEvent(newPost));
983 database.storePosts(sone, sone.getPosts());
984 if (!soneRescueMode) {
985 for (PostReply reply : storedSone.get().getReplies()) {
986 if (!sone.getReplies().contains(reply)) {
987 eventBus.post(new PostReplyRemovedEvent(reply));
991 Set<PostReply> storedReplies = storedSone.get().getReplies();
992 for (PostReply reply : sone.getReplies()) {
993 if (storedReplies.contains(reply)) {
996 if (reply.getTime() < getSoneFollowingTime(sone)) {
997 reply.setKnown(true);
998 } else if (!reply.isKnown()) {
999 eventBus.post(new NewPostReplyFoundEvent(reply));
1002 database.storePostReplies(sone, sone.getReplies());
1003 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1004 database.removeAlbum(album);
1005 for (Image image : album.getImages()) {
1006 database.removeImage(image);
1009 for (Album album : sone.getRootAlbum().getAlbums()) {
1010 database.storeAlbum(album);
1011 for (Image image : album.getImages()) {
1012 database.storeImage(image);
1015 synchronized (sones) {
1016 sone.setOptions(storedSone.get().getOptions());
1017 sone.setKnown(storedSone.get().isKnown());
1018 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1019 if (sone.isLocal()) {
1020 soneInserters.get(storedSone.get()).setSone(sone);
1021 touchConfiguration();
1023 sones.put(sone.getId(), sone);
1029 * Deletes the given Sone. This will remove the Sone from the
1030 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1031 * remove the context from its identity.
1034 * The Sone to delete
1036 public void deleteSone(Sone sone) {
1037 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1038 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1041 synchronized (sones) {
1042 if (!getLocalSones().contains(sone)) {
1043 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1046 sones.remove(sone.getId());
1047 SoneInserter soneInserter = soneInserters.remove(sone);
1048 soneInserter.stop();
1050 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1051 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1053 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1054 } catch (ConfigurationException ce1) {
1055 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1060 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1061 * known} before, a {@link MarkSoneKnownEvent} is fired.
1064 * The Sone to mark as known
1066 public void markSoneKnown(Sone sone) {
1067 if (!sone.isKnown()) {
1068 sone.setKnown(true);
1069 synchronized (knownSones) {
1070 knownSones.add(sone.getId());
1072 eventBus.post(new MarkSoneKnownEvent(sone));
1073 touchConfiguration();
1078 * Loads and updates the given Sone from the configuration. If any error is
1079 * encountered, loading is aborted and the given Sone is not changed.
1082 * The Sone to load and update
1084 public void loadSone(Sone sone) {
1085 if (!sone.isLocal()) {
1086 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1089 logger.info(String.format("Loading local Sone: %s", sone));
1091 /* initialize options. */
1092 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1093 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1094 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1095 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1096 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1097 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
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 Profile profile = new Profile(sone);
1110 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1111 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1112 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1113 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1114 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1115 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1117 /* load profile fields. */
1119 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1120 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1121 if (fieldName == null) {
1124 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1125 profile.addField(fieldName).setValue(fieldValue);
1129 Set<Post> posts = new HashSet<Post>();
1131 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1132 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1133 if (postId == null) {
1136 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1137 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1138 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1139 if ((postTime == 0) || (postText == null)) {
1140 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1143 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1144 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1145 postBuilder.to(postRecipientId);
1147 posts.add(postBuilder.build());
1151 Set<PostReply> replies = new HashSet<PostReply>();
1153 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1154 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1155 if (replyId == null) {
1158 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1159 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1160 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1161 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1162 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1165 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1166 replies.add(postReplyBuilder.build());
1169 /* load post likes. */
1170 Set<String> likedPostIds = new HashSet<String>();
1172 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1173 if (likedPostId == null) {
1176 likedPostIds.add(likedPostId);
1179 /* load reply likes. */
1180 Set<String> likedReplyIds = new HashSet<String>();
1182 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1183 if (likedReplyId == null) {
1186 likedReplyIds.add(likedReplyId);
1190 Set<String> friends = new HashSet<String>();
1192 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1193 if (friendId == null) {
1196 friends.add(friendId);
1200 List<Album> topLevelAlbums = new ArrayList<Album>();
1201 int albumCounter = 0;
1203 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1204 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1205 if (albumId == null) {
1208 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1209 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1210 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1211 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1212 if ((albumTitle == null) || (albumDescription == null)) {
1213 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1216 Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1217 if (albumParentId != null) {
1218 Album parentAlbum = getAlbum(albumParentId, false);
1219 if (parentAlbum == null) {
1220 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1223 parentAlbum.addAlbum(album);
1225 if (!topLevelAlbums.contains(album)) {
1226 topLevelAlbums.add(album);
1232 int imageCounter = 0;
1234 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1235 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1236 if (imageId == null) {
1239 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1240 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1241 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1242 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1243 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1244 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1245 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1246 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1247 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1250 Album album = getAlbum(albumId, false);
1251 if (album == null) {
1252 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1255 album.newImageBuilder().withId(imageId).by(sone).created(creationTime).at(key).sized(width, height).build().modify().setTitle(title).setDescription(description).update();
1259 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1260 if (avatarId != null) {
1261 profile.setAvatar(getImage(avatarId).orNull());
1265 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1266 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1267 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1268 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1269 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1270 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1272 /* if we’re still here, Sone was loaded successfully. */
1273 synchronized (sone) {
1274 sone.setTime(soneTime);
1275 sone.setProfile(profile);
1276 sone.setPosts(posts);
1277 sone.setReplies(replies);
1278 sone.setLikePostIds(likedPostIds);
1279 sone.setLikeReplyIds(likedReplyIds);
1280 for (String friendId : friends) {
1281 followSone(sone, friendId);
1283 for (Album album : sone.getRootAlbum().getAlbums()) {
1284 sone.getRootAlbum().removeAlbum(album);
1286 for (Album album : topLevelAlbums) {
1287 sone.getRootAlbum().addAlbum(album);
1289 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1291 synchronized (knownSones) {
1292 for (String friend : friends) {
1293 knownSones.add(friend);
1296 database.storePosts(sone, posts);
1297 for (Post post : posts) {
1298 post.setKnown(true);
1300 database.storePostReplies(sone, replies);
1301 for (PostReply reply : replies) {
1302 reply.setKnown(true);
1305 logger.info(String.format("Sone loaded successfully: %s", sone));
1309 * Creates a new post.
1312 * The Sone that creates the post
1314 * The text of the post
1315 * @return The created post
1317 public Post createPost(Sone sone, String text) {
1318 return createPost(sone, System.currentTimeMillis(), text);
1322 * Creates a new post.
1325 * The Sone that creates the post
1327 * The time of the post
1329 * The text of the post
1330 * @return The created post
1332 public Post createPost(Sone sone, long time, String text) {
1333 return createPost(sone, null, time, text);
1337 * Creates a new post.
1340 * The Sone that creates the post
1342 * The recipient Sone, or {@code null} if this post does not have
1345 * The text of the post
1346 * @return The created post
1348 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1349 return createPost(sone, recipient, System.currentTimeMillis(), text);
1353 * Creates a new post.
1356 * The Sone that creates the post
1358 * The recipient Sone, or {@code null} if this post does not have
1361 * The time of the post
1363 * The text of the post
1364 * @return The created post
1366 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1367 checkNotNull(text, "text must not be null");
1368 checkArgument(text.trim().length() > 0, "text must not be empty");
1369 if (!sone.isLocal()) {
1370 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1373 PostBuilder postBuilder = database.newPostBuilder();
1374 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1375 if (recipient.isPresent()) {
1376 postBuilder.to(recipient.get().getId());
1378 final Post post = postBuilder.build();
1379 database.storePost(post);
1380 eventBus.post(new NewPostFoundEvent(post));
1382 touchConfiguration();
1383 localElementTicker.schedule(new Runnable() {
1390 markPostKnown(post);
1392 }, 10, TimeUnit.SECONDS);
1397 * Deletes the given post.
1400 * The post to delete
1402 public void deletePost(Post post) {
1403 if (!post.getSone().isLocal()) {
1404 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1407 database.removePost(post);
1408 eventBus.post(new PostRemovedEvent(post));
1409 markPostKnown(post);
1410 touchConfiguration();
1414 * Marks the given post as known, if it is currently not a known post
1415 * (according to {@link Post#isKnown()}).
1418 * The post to mark as known
1420 public void markPostKnown(Post post) {
1421 post.setKnown(true);
1422 eventBus.post(new MarkPostKnownEvent(post));
1423 touchConfiguration();
1424 for (PostReply reply : getReplies(post.getId())) {
1425 markReplyKnown(reply);
1430 * Bookmarks the given post.
1433 * The post to bookmark
1435 public void bookmark(Post post) {
1436 bookmarkPost(post.getId());
1440 * Bookmarks the post with the given ID.
1443 * The ID of the post to bookmark
1445 public void bookmarkPost(String id) {
1446 synchronized (bookmarkedPosts) {
1447 bookmarkedPosts.add(id);
1452 * Removes the given post from the bookmarks.
1455 * The post to unbookmark
1457 public void unbookmark(Post post) {
1458 unbookmarkPost(post.getId());
1462 * Removes the post with the given ID from the bookmarks.
1465 * The ID of the post to unbookmark
1467 public void unbookmarkPost(String id) {
1468 synchronized (bookmarkedPosts) {
1469 bookmarkedPosts.remove(id);
1474 * Creates a new reply.
1477 * The Sone that creates the reply
1479 * The post that this reply refers to
1481 * The text of the reply
1482 * @return The created reply
1484 public PostReply createReply(Sone sone, Post post, String text) {
1485 checkNotNull(text, "text must not be null");
1486 checkArgument(text.trim().length() > 0, "text must not be empty");
1487 if (!sone.isLocal()) {
1488 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1491 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1492 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1493 final PostReply reply = postReplyBuilder.build();
1494 database.storePostReply(reply);
1495 eventBus.post(new NewPostReplyFoundEvent(reply));
1496 sone.addReply(reply);
1497 touchConfiguration();
1498 localElementTicker.schedule(new Runnable() {
1505 markReplyKnown(reply);
1507 }, 10, TimeUnit.SECONDS);
1512 * Deletes the given reply.
1515 * The reply to delete
1517 public void deleteReply(PostReply reply) {
1518 Sone sone = reply.getSone();
1519 if (!sone.isLocal()) {
1520 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1523 database.removePostReply(reply);
1524 markReplyKnown(reply);
1525 sone.removeReply(reply);
1526 touchConfiguration();
1530 * Marks the given reply as known, if it is currently not a known reply
1531 * (according to {@link Reply#isKnown()}).
1534 * The reply to mark as known
1536 public void markReplyKnown(PostReply reply) {
1537 boolean previouslyKnown = reply.isKnown();
1538 reply.setKnown(true);
1539 eventBus.post(new MarkPostReplyKnownEvent(reply));
1540 if (!previouslyKnown) {
1541 touchConfiguration();
1546 * Creates a new top-level album for the given Sone.
1549 * The Sone to create the album for
1550 * @return The new album
1552 public Album createAlbum(Sone sone) {
1553 return createAlbum(sone, sone.getRootAlbum());
1557 * Creates a new album for the given Sone.
1560 * The Sone to create the album for
1562 * The parent of the album (may be {@code null} to create a
1564 * @return The new album
1566 public Album createAlbum(Sone sone, Album parent) {
1567 Album album = database.newAlbumBuilder().randomId().build();
1568 database.storeAlbum(album);
1569 album.setSone(sone);
1570 parent.addAlbum(album);
1575 * Deletes the given album. The owner of the album has to be a local Sone,
1576 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1579 * The album to remove
1581 public void deleteAlbum(Album album) {
1582 checkNotNull(album, "album must not be null");
1583 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1584 if (!album.isEmpty()) {
1587 album.getParent().removeAlbum(album);
1588 database.removeAlbum(album);
1589 touchConfiguration();
1593 * Creates a new image.
1596 * The Sone creating the image
1598 * The album the image will be inserted into
1599 * @param temporaryImage
1600 * The temporary image to create the image from
1601 * @return The newly created image
1603 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1604 checkNotNull(sone, "sone must not be null");
1605 checkNotNull(album, "album must not be null");
1606 checkNotNull(temporaryImage, "temporaryImage must not be null");
1607 checkArgument(sone.isLocal(), "sone must be a local Sone");
1608 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1609 Image image = album.newImageBuilder().withId(temporaryImage.getId()).by(sone).createdNow().sized(temporaryImage.getWidth(), temporaryImage.getHeight()).build();
1610 database.storeImage(image);
1611 imageInserter.insertImage(temporaryImage, image);
1616 * Deletes the given image. This method will also delete a matching
1619 * @see #deleteTemporaryImage(TemporaryImage)
1621 * The image to delete
1623 public void deleteImage(Image image) {
1624 checkNotNull(image, "image must not be null");
1625 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1626 deleteTemporaryImage(image.getId());
1627 image.getAlbum().removeImage(image);
1628 database.removeImage(image);
1629 touchConfiguration();
1633 * Creates a new temporary image.
1636 * The MIME type of the temporary image
1638 * The encoded data of the image
1639 * @return The temporary image
1641 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData, int width, int height) {
1642 TemporaryImage temporaryImage = new TemporaryImage(mimeType, imageData, width, height);
1643 synchronized (temporaryImages) {
1644 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1646 return temporaryImage;
1650 * Deletes the given temporary image.
1652 * @param temporaryImage
1653 * The temporary image to delete
1655 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1656 checkNotNull(temporaryImage, "temporaryImage must not be null");
1657 deleteTemporaryImage(temporaryImage.getId());
1661 * Deletes the temporary image with the given ID.
1664 * The ID of the temporary image to delete
1666 public void deleteTemporaryImage(String imageId) {
1667 checkNotNull(imageId, "imageId must not be null");
1668 synchronized (temporaryImages) {
1669 temporaryImages.remove(imageId);
1671 Optional<Image> image = getImage(imageId);
1672 if (image.isPresent()) {
1673 imageInserter.cancelImageInsert(image.get());
1678 * Notifies the core that the configuration, either of the core or of a
1679 * single local Sone, has changed, and that the configuration should be
1682 public void touchConfiguration() {
1683 lastConfigurationUpdate = System.currentTimeMillis();
1694 public void serviceStart() {
1695 loadConfiguration();
1696 updateChecker.start();
1697 identityManager.start();
1698 webOfTrustUpdater.init();
1699 webOfTrustUpdater.start();
1707 public void serviceRun() {
1708 long lastSaved = System.currentTimeMillis();
1709 while (!shouldStop()) {
1711 long now = System.currentTimeMillis();
1712 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1713 for (Sone localSone : getLocalSones()) {
1714 saveSone(localSone);
1716 saveConfiguration();
1726 public void serviceStop() {
1727 localElementTicker.shutdownNow();
1728 synchronized (sones) {
1729 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1730 soneInserter.getValue().stop();
1731 saveSone(soneInserter.getKey());
1734 saveConfiguration();
1736 webOfTrustUpdater.stop();
1737 updateChecker.stop();
1738 soneDownloader.stop();
1739 soneDownloaders.shutdown();
1740 identityManager.stop();
1748 * Saves the given Sone. This will persist all local settings for the given
1749 * Sone, such as the friends list and similar, private options.
1754 private synchronized void saveSone(Sone sone) {
1755 if (!sone.isLocal()) {
1756 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1759 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1760 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1764 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1766 /* save Sone into configuration. */
1767 String sonePrefix = "Sone/" + sone.getId();
1768 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1769 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1772 Profile profile = sone.getProfile();
1773 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1774 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1775 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1776 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1777 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1778 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1779 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1781 /* save profile fields. */
1782 int fieldCounter = 0;
1783 for (Field profileField : profile.getFields()) {
1784 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1785 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1786 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1788 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1791 int postCounter = 0;
1792 for (Post post : sone.getPosts()) {
1793 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1794 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1795 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1796 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1797 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1799 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1802 int replyCounter = 0;
1803 for (PostReply reply : sone.getReplies()) {
1804 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1805 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1806 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1807 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1808 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1810 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1812 /* save post likes. */
1813 int postLikeCounter = 0;
1814 for (String postId : sone.getLikedPostIds()) {
1815 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1817 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1819 /* save reply likes. */
1820 int replyLikeCounter = 0;
1821 for (String replyId : sone.getLikedReplyIds()) {
1822 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1824 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1827 int friendCounter = 0;
1828 for (String friendId : sone.getFriends()) {
1829 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1831 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1833 /* save albums. first, collect in a flat structure, top-level first. */
1834 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1836 int albumCounter = 0;
1837 for (Album album : albums) {
1838 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1839 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1840 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1841 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1842 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1843 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1845 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1848 int imageCounter = 0;
1849 for (Album album : albums) {
1850 for (Image image : album.getImages()) {
1851 if (!image.isInserted()) {
1854 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1855 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1856 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1857 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1858 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1859 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1860 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1861 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1862 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1865 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1868 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1869 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1870 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1871 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1872 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1873 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1875 configuration.save();
1877 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1879 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1880 } catch (ConfigurationException ce1) {
1881 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1886 * Saves the current options.
1888 private void saveConfiguration() {
1889 synchronized (configuration) {
1890 if (storingConfiguration) {
1891 logger.log(Level.FINE, "Already storing configuration…");
1894 storingConfiguration = true;
1897 /* store the options first. */
1899 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1900 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1901 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1902 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1903 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1904 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1905 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1906 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1907 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1908 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1909 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1910 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1912 /* save known Sones. */
1913 int soneCounter = 0;
1914 synchronized (knownSones) {
1915 for (String knownSoneId : knownSones) {
1916 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1918 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1921 /* save Sone following times. */
1923 synchronized (soneFollowingTimes) {
1924 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1925 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1926 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1929 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1932 /* save known posts. */
1935 /* save bookmarked posts. */
1936 int bookmarkedPostCounter = 0;
1937 synchronized (bookmarkedPosts) {
1938 for (String bookmarkedPostId : bookmarkedPosts) {
1939 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1942 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1945 configuration.save();
1947 } catch (ConfigurationException ce1) {
1948 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1949 } catch (DatabaseException de1) {
1950 logger.log(Level.SEVERE, "Could not save database!", de1);
1952 synchronized (configuration) {
1953 storingConfiguration = false;
1959 * Loads the configuration.
1961 private void loadConfiguration() {
1962 /* create options. */
1963 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1966 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1967 SoneInserter.setInsertionDelay(newValue);
1971 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1972 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1973 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1974 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1975 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1976 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1977 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1978 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1979 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
1982 @SuppressWarnings("synthetic-access")
1983 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
1984 fcpInterface.setActive(newValue);
1987 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
1990 @SuppressWarnings("synthetic-access")
1991 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1992 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
1997 loadConfigurationValue("InsertionDelay");
1998 loadConfigurationValue("PostsPerPage");
1999 loadConfigurationValue("ImagesPerPage");
2000 loadConfigurationValue("CharactersPerPost");
2001 loadConfigurationValue("PostCutOffLength");
2002 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2003 loadConfigurationValue("PositiveTrust");
2004 loadConfigurationValue("NegativeTrust");
2005 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2006 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2007 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2009 /* load known Sones. */
2010 int soneCounter = 0;
2012 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2013 if (knownSoneId == null) {
2016 synchronized (knownSones) {
2017 knownSones.add(knownSoneId);
2021 /* load Sone following times. */
2024 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2025 if (soneId == null) {
2028 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2029 synchronized (soneFollowingTimes) {
2030 soneFollowingTimes.put(soneId, time);
2035 /* load bookmarked posts. */
2036 int bookmarkedPostCounter = 0;
2038 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2039 if (bookmarkedPostId == null) {
2042 synchronized (bookmarkedPosts) {
2043 bookmarkedPosts.add(bookmarkedPostId);
2050 * Loads an {@link Integer} configuration value for the option with the
2051 * given name, logging validation failures.
2054 * The name of the option to load
2056 private void loadConfigurationValue(String optionName) {
2058 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2059 } catch (IllegalArgumentException iae1) {
2060 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2065 * Notifies the core that a new {@link OwnIdentity} was added.
2067 * @param ownIdentityAddedEvent
2071 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2072 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2073 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2074 if (ownIdentity.hasContext("Sone")) {
2075 addLocalSone(ownIdentity);
2080 * Notifies the core that an {@link OwnIdentity} was removed.
2082 * @param ownIdentityRemovedEvent
2086 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2087 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2088 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2089 trustedIdentities.removeAll(ownIdentity);
2093 * Notifies the core that a new {@link Identity} was added.
2095 * @param identityAddedEvent
2099 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2100 Identity identity = identityAddedEvent.identity();
2101 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2102 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2103 addRemoteSone(identity);
2107 * Notifies the core that an {@link Identity} was updated.
2109 * @param identityUpdatedEvent
2113 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2114 final Identity identity = identityUpdatedEvent.identity();
2115 soneDownloaders.execute(new Runnable() {
2118 @SuppressWarnings("synthetic-access")
2120 Sone sone = getRemoteSone(identity.getId(), false);
2121 if (sone.isLocal()) {
2124 sone.setIdentity(identity);
2125 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2126 soneDownloader.addSone(sone);
2127 soneDownloader.fetchSone(sone);
2133 * Notifies the core that an {@link Identity} was removed.
2135 * @param identityRemovedEvent
2139 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2140 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2141 Identity identity = identityRemovedEvent.identity();
2142 trustedIdentities.remove(ownIdentity, identity);
2143 boolean foundIdentity = false;
2144 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2145 if (trustedIdentity.getKey().equals(ownIdentity)) {
2148 if (trustedIdentity.getValue().contains(identity)) {
2149 foundIdentity = true;
2152 if (foundIdentity) {
2153 /* some local identity still trusts this identity, don’t remove. */
2156 Optional<Sone> sone = getSone(identity.getId());
2157 if (!sone.isPresent()) {
2158 /* TODO - we don’t have the Sone anymore. should this happen? */
2161 database.removePosts(sone.get());
2162 for (Post post : sone.get().getPosts()) {
2163 eventBus.post(new PostRemovedEvent(post));
2165 database.removePostReplies(sone.get());
2166 for (PostReply reply : sone.get().getReplies()) {
2167 eventBus.post(new PostReplyRemovedEvent(reply));
2169 synchronized (sones) {
2170 sones.remove(identity.getId());
2172 eventBus.post(new SoneRemovedEvent(sone.get()));
2176 * Deletes the temporary image.
2178 * @param imageInsertFinishedEvent
2182 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2183 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2184 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2185 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2186 touchConfiguration();