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);
647 * Returns the image with the given ID, creating it if necessary.
650 * The ID of the image
651 * @return The image with the given ID
653 public Image getImage(String imageId) {
654 return getImage(imageId, true);
658 * Returns the image with the given ID, optionally creating it if it does
662 * The ID of the image
664 * {@code true} to create an image if none exists with the given
666 * @return The image with the given ID, or {@code null} if none exists and
669 public Image getImage(String imageId, boolean create) {
670 Optional<Image> image = database.getImage(imageId);
671 if (image.isPresent()) {
677 Image newImage = database.newImageBuilder().withId(imageId).build();
678 database.storeImage(newImage);
683 * Returns the temporary image with the given ID.
686 * The ID of the temporary image
687 * @return The temporary image, or {@code null} if there is no temporary
688 * image with the given ID
690 public TemporaryImage getTemporaryImage(String imageId) {
691 synchronized (temporaryImages) {
692 return temporaryImages.get(imageId);
701 * Locks the given Sone. A locked Sone will not be inserted by
702 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
708 public void lockSone(Sone sone) {
709 synchronized (lockedSones) {
710 if (lockedSones.add(sone)) {
711 eventBus.post(new SoneLockedEvent(sone));
717 * Unlocks the given Sone.
719 * @see #lockSone(Sone)
723 public void unlockSone(Sone sone) {
724 synchronized (lockedSones) {
725 if (lockedSones.remove(sone)) {
726 eventBus.post(new SoneUnlockedEvent(sone));
732 * Adds a local Sone from the given own identity.
735 * The own identity to create a Sone from
736 * @return The added (or already existing) Sone
738 public Sone addLocalSone(OwnIdentity ownIdentity) {
739 if (ownIdentity == null) {
740 logger.log(Level.WARNING, "Given OwnIdentity is null!");
743 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
744 synchronized (sones) {
747 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
748 } catch (MalformedURLException mue1) {
749 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
752 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
753 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
755 /* TODO - load posts ’n stuff */
756 sones.put(ownIdentity.getId(), sone);
757 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
758 soneInserters.put(sone, soneInserter);
759 sone.setStatus(SoneStatus.idle);
761 soneInserter.start();
767 * Creates a new Sone for the given own identity.
770 * The own identity to create a Sone for
771 * @return The created Sone
773 public Sone createSone(OwnIdentity ownIdentity) {
774 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
775 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
778 Sone sone = addLocalSone(ownIdentity);
779 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
780 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
781 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
782 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
783 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
784 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
786 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
787 touchConfiguration();
792 * Adds the Sone of the given identity.
795 * The identity whose Sone to add
796 * @return The added or already existing Sone
798 public Sone addRemoteSone(Identity identity) {
799 if (identity == null) {
800 logger.log(Level.WARNING, "Given Identity is null!");
803 synchronized (sones) {
804 final Sone sone = getRemoteSone(identity.getId(), true);
805 if (sone.isLocal()) {
808 sone.setIdentity(identity);
809 boolean newSone = sone.getRequestUri() == null;
810 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
811 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
813 synchronized (knownSones) {
814 newSone = !knownSones.contains(sone.getId());
816 sone.setKnown(!newSone);
818 eventBus.post(new NewSoneFoundEvent(sone));
819 for (Sone localSone : getLocalSones()) {
820 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
821 followSone(localSone, sone.getId());
826 soneDownloader.addSone(sone);
827 soneDownloaders.execute(new Runnable() {
830 @SuppressWarnings("synthetic-access")
832 soneDownloader.fetchSone(sone, sone.getRequestUri());
841 * Lets the given local Sone follow the Sone with the given ID.
844 * The local Sone that should follow another Sone
846 * The ID of the Sone to follow
848 public void followSone(Sone sone, String soneId) {
849 checkNotNull(sone, "sone must not be null");
850 checkNotNull(soneId, "soneId must not be null");
851 sone.addFriend(soneId);
852 synchronized (soneFollowingTimes) {
853 if (!soneFollowingTimes.containsKey(soneId)) {
854 long now = System.currentTimeMillis();
855 soneFollowingTimes.put(soneId, now);
856 Optional<Sone> followedSone = getSone(soneId);
857 if (!followedSone.isPresent()) {
860 for (Post post : followedSone.get().getPosts()) {
861 if (post.getTime() < now) {
865 for (PostReply reply : followedSone.get().getReplies()) {
866 if (reply.getTime() < now) {
867 markReplyKnown(reply);
872 touchConfiguration();
876 * Lets the given local Sone unfollow the Sone with the given ID.
879 * The local Sone that should unfollow another Sone
881 * The ID of the Sone being unfollowed
883 public void unfollowSone(Sone sone, String soneId) {
884 checkNotNull(sone, "sone must not be null");
885 checkNotNull(soneId, "soneId must not be null");
886 sone.removeFriend(soneId);
887 boolean unfollowedSoneStillFollowed = false;
888 for (Sone localSone : getLocalSones()) {
889 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
891 if (!unfollowedSoneStillFollowed) {
892 synchronized (soneFollowingTimes) {
893 soneFollowingTimes.remove(soneId);
896 touchConfiguration();
900 * Sets the trust value of the given origin Sone for the target Sone.
907 * The trust value (from {@code -100} to {@code 100})
909 public void setTrust(Sone origin, Sone target, int trustValue) {
910 checkNotNull(origin, "origin must not be null");
911 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
912 checkNotNull(target, "target must not be null");
913 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
914 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
918 * Removes any trust assignment for the given target Sone.
925 public void removeTrust(Sone origin, Sone target) {
926 checkNotNull(origin, "origin must not be null");
927 checkNotNull(target, "target must not be null");
928 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
929 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
933 * Assigns the configured positive trust value for the given target.
940 public void trustSone(Sone origin, Sone target) {
941 setTrust(origin, target, preferences.getPositiveTrust());
945 * Assigns the configured negative trust value for the given target.
952 public void distrustSone(Sone origin, Sone target) {
953 setTrust(origin, target, preferences.getNegativeTrust());
957 * Removes the trust assignment for the given target.
964 public void untrustSone(Sone origin, Sone target) {
965 removeTrust(origin, target);
969 * Updates the stored Sone with the given Sone.
974 public void updateSone(Sone sone) {
975 updateSone(sone, false);
979 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
980 * {@code true}, an older Sone than the current Sone can be given to restore
985 * @param soneRescueMode
986 * {@code true} if the stored Sone should be updated regardless
987 * of the age of the given Sone
989 public void updateSone(Sone sone, boolean soneRescueMode) {
990 Optional<Sone> storedSone = getSone(sone.getId());
991 if (storedSone.isPresent()) {
992 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
993 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
996 /* find removed posts. */
997 Collection<Post> existingPosts = database.getPosts(sone.getId());
998 for (Post oldPost : existingPosts) {
999 if (!sone.getPosts().contains(oldPost)) {
1000 eventBus.post(new PostRemovedEvent(oldPost));
1003 /* find new posts. */
1004 for (Post newPost : sone.getPosts()) {
1005 if (existingPosts.contains(newPost)) {
1008 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1009 newPost.setKnown(true);
1010 } else if (!newPost.isKnown()) {
1011 eventBus.post(new NewPostFoundEvent(newPost));
1015 database.storePosts(sone, sone.getPosts());
1016 if (!soneRescueMode) {
1017 for (PostReply reply : storedSone.get().getReplies()) {
1018 if (!sone.getReplies().contains(reply)) {
1019 eventBus.post(new PostReplyRemovedEvent(reply));
1023 Set<PostReply> storedReplies = storedSone.get().getReplies();
1024 for (PostReply reply : sone.getReplies()) {
1025 if (storedReplies.contains(reply)) {
1028 if (reply.getTime() < getSoneFollowingTime(sone)) {
1029 reply.setKnown(true);
1030 } else if (!reply.isKnown()) {
1031 eventBus.post(new NewPostReplyFoundEvent(reply));
1034 database.storePostReplies(sone, sone.getReplies());
1035 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1036 database.removeAlbum(album);
1037 for (Image image : album.getImages()) {
1038 database.removeImage(image);
1041 for (Album album : sone.getRootAlbum().getAlbums()) {
1042 database.storeAlbum(album);
1043 for (Image image : album.getImages()) {
1044 database.storeImage(image);
1047 synchronized (sones) {
1048 sone.setOptions(storedSone.get().getOptions());
1049 sone.setKnown(storedSone.get().isKnown());
1050 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1051 if (sone.isLocal()) {
1052 soneInserters.get(storedSone.get()).setSone(sone);
1053 touchConfiguration();
1055 sones.put(sone.getId(), sone);
1061 * Deletes the given Sone. This will remove the Sone from the
1062 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1063 * remove the context from its identity.
1066 * The Sone to delete
1068 public void deleteSone(Sone sone) {
1069 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1070 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1073 synchronized (sones) {
1074 if (!getLocalSones().contains(sone)) {
1075 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1078 sones.remove(sone.getId());
1079 SoneInserter soneInserter = soneInserters.remove(sone);
1080 soneInserter.stop();
1082 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1083 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1085 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1086 } catch (ConfigurationException ce1) {
1087 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1092 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1093 * known} before, a {@link MarkSoneKnownEvent} is fired.
1096 * The Sone to mark as known
1098 public void markSoneKnown(Sone sone) {
1099 if (!sone.isKnown()) {
1100 sone.setKnown(true);
1101 synchronized (knownSones) {
1102 knownSones.add(sone.getId());
1104 eventBus.post(new MarkSoneKnownEvent(sone));
1105 touchConfiguration();
1110 * Loads and updates the given Sone from the configuration. If any error is
1111 * encountered, loading is aborted and the given Sone is not changed.
1114 * The Sone to load and update
1116 public void loadSone(Sone sone) {
1117 if (!sone.isLocal()) {
1118 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1121 logger.info(String.format("Loading local Sone: %s", sone));
1123 /* initialize options. */
1124 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1125 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1126 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1127 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1128 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1129 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1132 String sonePrefix = "Sone/" + sone.getId();
1133 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1134 if (soneTime == null) {
1135 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1138 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1141 Profile profile = new Profile(sone);
1142 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1143 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1144 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1145 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1146 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1147 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1149 /* load profile fields. */
1151 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1152 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1153 if (fieldName == null) {
1156 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1157 profile.addField(fieldName).setValue(fieldValue);
1161 Set<Post> posts = new HashSet<Post>();
1163 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1164 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1165 if (postId == null) {
1168 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1169 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1170 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1171 if ((postTime == 0) || (postText == null)) {
1172 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1175 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1176 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1177 postBuilder.to(postRecipientId);
1179 posts.add(postBuilder.build());
1183 Set<PostReply> replies = new HashSet<PostReply>();
1185 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1186 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1187 if (replyId == null) {
1190 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1191 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1192 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1193 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1194 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1197 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1198 replies.add(postReplyBuilder.build());
1201 /* load post likes. */
1202 Set<String> likedPostIds = new HashSet<String>();
1204 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1205 if (likedPostId == null) {
1208 likedPostIds.add(likedPostId);
1211 /* load reply likes. */
1212 Set<String> likedReplyIds = new HashSet<String>();
1214 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1215 if (likedReplyId == null) {
1218 likedReplyIds.add(likedReplyId);
1222 Set<String> friends = new HashSet<String>();
1224 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1225 if (friendId == null) {
1228 friends.add(friendId);
1232 List<Album> topLevelAlbums = new ArrayList<Album>();
1233 int albumCounter = 0;
1235 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1236 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1237 if (albumId == null) {
1240 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1241 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1242 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1243 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1244 if ((albumTitle == null) || (albumDescription == null)) {
1245 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1248 Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1249 if (albumParentId != null) {
1250 Album parentAlbum = getAlbum(albumParentId, false);
1251 if (parentAlbum == null) {
1252 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1255 parentAlbum.addAlbum(album);
1257 if (!topLevelAlbums.contains(album)) {
1258 topLevelAlbums.add(album);
1264 int imageCounter = 0;
1266 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1267 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1268 if (imageId == null) {
1271 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1272 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1273 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1274 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1275 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1276 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1277 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1278 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1279 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1282 Album album = getAlbum(albumId, false);
1283 if (album == null) {
1284 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1287 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1288 album.addImage(image);
1292 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1293 if (avatarId != null) {
1294 profile.setAvatar(getImage(avatarId, false));
1298 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1299 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1300 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1301 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1302 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1303 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1305 /* if we’re still here, Sone was loaded successfully. */
1306 synchronized (sone) {
1307 sone.setTime(soneTime);
1308 sone.setProfile(profile);
1309 sone.setPosts(posts);
1310 sone.setReplies(replies);
1311 sone.setLikePostIds(likedPostIds);
1312 sone.setLikeReplyIds(likedReplyIds);
1313 for (String friendId : friends) {
1314 followSone(sone, friendId);
1316 for (Album album : sone.getRootAlbum().getAlbums()) {
1317 sone.getRootAlbum().removeAlbum(album);
1319 for (Album album : topLevelAlbums) {
1320 sone.getRootAlbum().addAlbum(album);
1322 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1324 synchronized (knownSones) {
1325 for (String friend : friends) {
1326 knownSones.add(friend);
1329 database.storePosts(sone, posts);
1330 for (Post post : posts) {
1331 post.setKnown(true);
1333 database.storePostReplies(sone, replies);
1334 for (PostReply reply : replies) {
1335 reply.setKnown(true);
1338 logger.info(String.format("Sone loaded successfully: %s", sone));
1342 * Creates a new post.
1345 * The Sone that creates the post
1347 * The text of the post
1348 * @return The created post
1350 public Post createPost(Sone sone, String text) {
1351 return createPost(sone, System.currentTimeMillis(), text);
1355 * Creates a new post.
1358 * The Sone that creates the post
1360 * The time of the post
1362 * The text of the post
1363 * @return The created post
1365 public Post createPost(Sone sone, long time, String text) {
1366 return createPost(sone, null, time, text);
1370 * Creates a new post.
1373 * The Sone that creates the post
1375 * The recipient Sone, or {@code null} if this post does not have
1378 * The text of the post
1379 * @return The created post
1381 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1382 return createPost(sone, recipient, System.currentTimeMillis(), text);
1386 * Creates a new post.
1389 * The Sone that creates the post
1391 * The recipient Sone, or {@code null} if this post does not have
1394 * The time of the post
1396 * The text of the post
1397 * @return The created post
1399 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1400 checkNotNull(text, "text must not be null");
1401 checkArgument(text.trim().length() > 0, "text must not be empty");
1402 if (!sone.isLocal()) {
1403 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1406 PostBuilder postBuilder = database.newPostBuilder();
1407 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1408 if (recipient.isPresent()) {
1409 postBuilder.to(recipient.get().getId());
1411 final Post post = postBuilder.build();
1412 database.storePost(post);
1413 eventBus.post(new NewPostFoundEvent(post));
1415 touchConfiguration();
1416 localElementTicker.schedule(new Runnable() {
1423 markPostKnown(post);
1425 }, 10, TimeUnit.SECONDS);
1430 * Deletes the given post.
1433 * The post to delete
1435 public void deletePost(Post post) {
1436 if (!post.getSone().isLocal()) {
1437 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1440 database.removePost(post);
1441 eventBus.post(new PostRemovedEvent(post));
1442 markPostKnown(post);
1443 touchConfiguration();
1447 * Marks the given post as known, if it is currently not a known post
1448 * (according to {@link Post#isKnown()}).
1451 * The post to mark as known
1453 public void markPostKnown(Post post) {
1454 post.setKnown(true);
1455 eventBus.post(new MarkPostKnownEvent(post));
1456 touchConfiguration();
1457 for (PostReply reply : getReplies(post.getId())) {
1458 markReplyKnown(reply);
1463 * Bookmarks the given post.
1466 * The post to bookmark
1468 public void bookmark(Post post) {
1469 bookmarkPost(post.getId());
1473 * Bookmarks the post with the given ID.
1476 * The ID of the post to bookmark
1478 public void bookmarkPost(String id) {
1479 synchronized (bookmarkedPosts) {
1480 bookmarkedPosts.add(id);
1485 * Removes the given post from the bookmarks.
1488 * The post to unbookmark
1490 public void unbookmark(Post post) {
1491 unbookmarkPost(post.getId());
1495 * Removes the post with the given ID from the bookmarks.
1498 * The ID of the post to unbookmark
1500 public void unbookmarkPost(String id) {
1501 synchronized (bookmarkedPosts) {
1502 bookmarkedPosts.remove(id);
1507 * Creates a new reply.
1510 * The Sone that creates the reply
1512 * The post that this reply refers to
1514 * The text of the reply
1515 * @return The created reply
1517 public PostReply createReply(Sone sone, Post post, String text) {
1518 checkNotNull(text, "text must not be null");
1519 checkArgument(text.trim().length() > 0, "text must not be empty");
1520 if (!sone.isLocal()) {
1521 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1524 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1525 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1526 final PostReply reply = postReplyBuilder.build();
1527 database.storePostReply(reply);
1528 eventBus.post(new NewPostReplyFoundEvent(reply));
1529 sone.addReply(reply);
1530 touchConfiguration();
1531 localElementTicker.schedule(new Runnable() {
1538 markReplyKnown(reply);
1540 }, 10, TimeUnit.SECONDS);
1545 * Deletes the given reply.
1548 * The reply to delete
1550 public void deleteReply(PostReply reply) {
1551 Sone sone = reply.getSone();
1552 if (!sone.isLocal()) {
1553 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1556 database.removePostReply(reply);
1557 markReplyKnown(reply);
1558 sone.removeReply(reply);
1559 touchConfiguration();
1563 * Marks the given reply as known, if it is currently not a known reply
1564 * (according to {@link Reply#isKnown()}).
1567 * The reply to mark as known
1569 public void markReplyKnown(PostReply reply) {
1570 boolean previouslyKnown = reply.isKnown();
1571 reply.setKnown(true);
1572 eventBus.post(new MarkPostReplyKnownEvent(reply));
1573 if (!previouslyKnown) {
1574 touchConfiguration();
1579 * Creates a new top-level album for the given Sone.
1582 * The Sone to create the album for
1583 * @return The new album
1585 public Album createAlbum(Sone sone) {
1586 return createAlbum(sone, sone.getRootAlbum());
1590 * Creates a new album for the given Sone.
1593 * The Sone to create the album for
1595 * The parent of the album (may be {@code null} to create a
1597 * @return The new album
1599 public Album createAlbum(Sone sone, Album parent) {
1600 Album album = database.newAlbumBuilder().randomId().build();
1601 database.storeAlbum(album);
1602 album.setSone(sone);
1603 parent.addAlbum(album);
1608 * Deletes the given album. The owner of the album has to be a local Sone,
1609 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1612 * The album to remove
1614 public void deleteAlbum(Album album) {
1615 checkNotNull(album, "album must not be null");
1616 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1617 if (!album.isEmpty()) {
1620 album.getParent().removeAlbum(album);
1621 database.removeAlbum(album);
1622 touchConfiguration();
1626 * Creates a new image.
1629 * The Sone creating the image
1631 * The album the image will be inserted into
1632 * @param temporaryImage
1633 * The temporary image to create the image from
1634 * @return The newly created image
1636 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1637 checkNotNull(sone, "sone must not be null");
1638 checkNotNull(album, "album must not be null");
1639 checkNotNull(temporaryImage, "temporaryImage must not be null");
1640 checkArgument(sone.isLocal(), "sone must be a local Sone");
1641 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1642 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1643 album.addImage(image);
1644 database.storeImage(image);
1645 imageInserter.insertImage(temporaryImage, image);
1650 * Deletes the given image. This method will also delete a matching
1653 * @see #deleteTemporaryImage(TemporaryImage)
1655 * The image to delete
1657 public void deleteImage(Image image) {
1658 checkNotNull(image, "image must not be null");
1659 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1660 deleteTemporaryImage(image.getId());
1661 image.getAlbum().removeImage(image);
1662 database.removeImage(image);
1663 touchConfiguration();
1667 * Creates a new temporary image.
1670 * The MIME type of the temporary image
1672 * The encoded data of the image
1673 * @return The temporary image
1675 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1676 TemporaryImage temporaryImage = new TemporaryImage();
1677 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1678 synchronized (temporaryImages) {
1679 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1681 return temporaryImage;
1685 * Deletes the given temporary image.
1687 * @param temporaryImage
1688 * The temporary image to delete
1690 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1691 checkNotNull(temporaryImage, "temporaryImage must not be null");
1692 deleteTemporaryImage(temporaryImage.getId());
1696 * Deletes the temporary image with the given ID.
1699 * The ID of the temporary image to delete
1701 public void deleteTemporaryImage(String imageId) {
1702 checkNotNull(imageId, "imageId must not be null");
1703 synchronized (temporaryImages) {
1704 temporaryImages.remove(imageId);
1706 Image image = getImage(imageId, false);
1707 if (image != null) {
1708 imageInserter.cancelImageInsert(image);
1713 * Notifies the core that the configuration, either of the core or of a
1714 * single local Sone, has changed, and that the configuration should be
1717 public void touchConfiguration() {
1718 lastConfigurationUpdate = System.currentTimeMillis();
1729 public void serviceStart() {
1730 loadConfiguration();
1731 updateChecker.start();
1732 identityManager.start();
1733 webOfTrustUpdater.init();
1734 webOfTrustUpdater.start();
1742 public void serviceRun() {
1743 long lastSaved = System.currentTimeMillis();
1744 while (!shouldStop()) {
1746 long now = System.currentTimeMillis();
1747 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1748 for (Sone localSone : getLocalSones()) {
1749 saveSone(localSone);
1751 saveConfiguration();
1761 public void serviceStop() {
1762 localElementTicker.shutdownNow();
1763 synchronized (sones) {
1764 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1765 soneInserter.getValue().stop();
1766 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1769 saveConfiguration();
1771 webOfTrustUpdater.stop();
1772 updateChecker.stop();
1773 soneDownloader.stop();
1774 soneDownloaders.shutdown();
1775 identityManager.stop();
1783 * Saves the given Sone. This will persist all local settings for the given
1784 * Sone, such as the friends list and similar, private options.
1789 private synchronized void saveSone(Sone sone) {
1790 if (!sone.isLocal()) {
1791 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1794 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1795 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1799 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1801 /* save Sone into configuration. */
1802 String sonePrefix = "Sone/" + sone.getId();
1803 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1804 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1807 Profile profile = sone.getProfile();
1808 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1809 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1810 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1811 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1812 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1813 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1814 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1816 /* save profile fields. */
1817 int fieldCounter = 0;
1818 for (Field profileField : profile.getFields()) {
1819 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1820 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1821 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1823 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1826 int postCounter = 0;
1827 for (Post post : sone.getPosts()) {
1828 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1829 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1830 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1831 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1832 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1834 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1837 int replyCounter = 0;
1838 for (PostReply reply : sone.getReplies()) {
1839 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1840 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1841 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1842 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1843 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1845 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1847 /* save post likes. */
1848 int postLikeCounter = 0;
1849 for (String postId : sone.getLikedPostIds()) {
1850 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1852 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1854 /* save reply likes. */
1855 int replyLikeCounter = 0;
1856 for (String replyId : sone.getLikedReplyIds()) {
1857 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1859 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1862 int friendCounter = 0;
1863 for (String friendId : sone.getFriends()) {
1864 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1866 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1868 /* save albums. first, collect in a flat structure, top-level first. */
1869 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1871 int albumCounter = 0;
1872 for (Album album : albums) {
1873 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1874 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1875 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1876 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1877 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1878 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1880 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1883 int imageCounter = 0;
1884 for (Album album : albums) {
1885 for (Image image : album.getImages()) {
1886 if (!image.isInserted()) {
1889 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1890 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1891 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1892 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1893 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1894 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1895 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1896 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1897 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1900 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1903 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1904 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1905 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1906 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1907 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1908 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1910 configuration.save();
1912 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1914 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1915 } catch (ConfigurationException ce1) {
1916 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1921 * Saves the current options.
1923 private void saveConfiguration() {
1924 synchronized (configuration) {
1925 if (storingConfiguration) {
1926 logger.log(Level.FINE, "Already storing configuration…");
1929 storingConfiguration = true;
1932 /* store the options first. */
1934 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1935 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1936 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1937 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1938 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1939 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1940 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1941 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1942 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1943 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1944 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1945 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1947 /* save known Sones. */
1948 int soneCounter = 0;
1949 synchronized (knownSones) {
1950 for (String knownSoneId : knownSones) {
1951 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1953 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1956 /* save Sone following times. */
1958 synchronized (soneFollowingTimes) {
1959 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1960 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1961 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1964 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1967 /* save known posts. */
1970 /* save bookmarked posts. */
1971 int bookmarkedPostCounter = 0;
1972 synchronized (bookmarkedPosts) {
1973 for (String bookmarkedPostId : bookmarkedPosts) {
1974 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1977 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1980 configuration.save();
1982 } catch (ConfigurationException ce1) {
1983 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1984 } catch (DatabaseException de1) {
1985 logger.log(Level.SEVERE, "Could not save database!", de1);
1987 synchronized (configuration) {
1988 storingConfiguration = false;
1994 * Loads the configuration.
1996 private void loadConfiguration() {
1997 /* create options. */
1998 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2001 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2002 SoneInserter.setInsertionDelay(newValue);
2006 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2007 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2008 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2009 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2010 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2011 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2012 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2013 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2014 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2017 @SuppressWarnings("synthetic-access")
2018 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2019 fcpInterface.setActive(newValue);
2022 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2025 @SuppressWarnings("synthetic-access")
2026 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2027 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2032 loadConfigurationValue("InsertionDelay");
2033 loadConfigurationValue("PostsPerPage");
2034 loadConfigurationValue("ImagesPerPage");
2035 loadConfigurationValue("CharactersPerPost");
2036 loadConfigurationValue("PostCutOffLength");
2037 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2038 loadConfigurationValue("PositiveTrust");
2039 loadConfigurationValue("NegativeTrust");
2040 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2041 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2042 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2044 /* load known Sones. */
2045 int soneCounter = 0;
2047 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2048 if (knownSoneId == null) {
2051 synchronized (knownSones) {
2052 knownSones.add(knownSoneId);
2056 /* load Sone following times. */
2059 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2060 if (soneId == null) {
2063 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2064 synchronized (soneFollowingTimes) {
2065 soneFollowingTimes.put(soneId, time);
2070 /* load bookmarked posts. */
2071 int bookmarkedPostCounter = 0;
2073 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2074 if (bookmarkedPostId == null) {
2077 synchronized (bookmarkedPosts) {
2078 bookmarkedPosts.add(bookmarkedPostId);
2085 * Loads an {@link Integer} configuration value for the option with the
2086 * given name, logging validation failures.
2089 * The name of the option to load
2091 private void loadConfigurationValue(String optionName) {
2093 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2094 } catch (IllegalArgumentException iae1) {
2095 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2100 * Notifies the core that a new {@link OwnIdentity} was added.
2102 * @param ownIdentityAddedEvent
2106 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2107 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2108 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2109 if (ownIdentity.hasContext("Sone")) {
2110 addLocalSone(ownIdentity);
2115 * Notifies the core that an {@link OwnIdentity} was removed.
2117 * @param ownIdentityRemovedEvent
2121 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2122 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2123 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2124 trustedIdentities.removeAll(ownIdentity);
2128 * Notifies the core that a new {@link Identity} was added.
2130 * @param identityAddedEvent
2134 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2135 Identity identity = identityAddedEvent.identity();
2136 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2137 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2138 addRemoteSone(identity);
2142 * Notifies the core that an {@link Identity} was updated.
2144 * @param identityUpdatedEvent
2148 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2149 final Identity identity = identityUpdatedEvent.identity();
2150 soneDownloaders.execute(new Runnable() {
2153 @SuppressWarnings("synthetic-access")
2155 Sone sone = getRemoteSone(identity.getId(), false);
2156 if (sone.isLocal()) {
2159 sone.setIdentity(identity);
2160 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2161 soneDownloader.addSone(sone);
2162 soneDownloader.fetchSone(sone);
2168 * Notifies the core that an {@link Identity} was removed.
2170 * @param identityRemovedEvent
2174 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2175 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2176 Identity identity = identityRemovedEvent.identity();
2177 trustedIdentities.remove(ownIdentity, identity);
2178 boolean foundIdentity = false;
2179 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2180 if (trustedIdentity.getKey().equals(ownIdentity)) {
2183 if (trustedIdentity.getValue().contains(identity)) {
2184 foundIdentity = true;
2187 if (foundIdentity) {
2188 /* some local identity still trusts this identity, don’t remove. */
2191 Optional<Sone> sone = getSone(identity.getId());
2192 if (!sone.isPresent()) {
2193 /* TODO - we don’t have the Sone anymore. should this happen? */
2196 database.removePosts(sone.get());
2197 for (Post post : sone.get().getPosts()) {
2198 eventBus.post(new PostRemovedEvent(post));
2200 database.removePostReplies(sone.get());
2201 for (PostReply reply : sone.get().getReplies()) {
2202 eventBus.post(new PostReplyRemovedEvent(reply));
2204 synchronized (sones) {
2205 sones.remove(identity.getId());
2207 eventBus.post(new SoneRemovedEvent(sone.get()));
2211 * Deletes the temporary image.
2213 * @param imageInsertFinishedEvent
2217 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2218 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2219 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2220 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2221 touchConfiguration();