2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
25 import java.net.MalformedURLException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.Map.Entry;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.TimeUnit;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.sone.core.Options.DefaultOption;
42 import net.pterodactylus.sone.core.Options.Option;
43 import net.pterodactylus.sone.core.Options.OptionWatcher;
44 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
45 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
46 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
49 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
50 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
51 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
52 import net.pterodactylus.sone.core.event.PostRemovedEvent;
53 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneLockedEvent;
55 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.SoneImpl;
69 import net.pterodactylus.sone.data.TemporaryImage;
70 import net.pterodactylus.sone.database.Database;
71 import net.pterodactylus.sone.database.DatabaseException;
72 import net.pterodactylus.sone.database.PostBuilder;
73 import net.pterodactylus.sone.database.PostProvider;
74 import net.pterodactylus.sone.database.PostReplyBuilder;
75 import net.pterodactylus.sone.database.PostReplyProvider;
76 import net.pterodactylus.sone.database.SoneProvider;
77 import net.pterodactylus.sone.fcp.FcpInterface;
78 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
79 import net.pterodactylus.sone.fcp.FcpInterface.SetActive;
80 import net.pterodactylus.sone.freenet.wot.Identity;
81 import net.pterodactylus.sone.freenet.wot.IdentityManager;
82 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
83 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
86 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
87 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
88 import net.pterodactylus.sone.main.SonePlugin;
89 import net.pterodactylus.sone.utils.IntegerRangePredicate;
90 import net.pterodactylus.util.config.Configuration;
91 import net.pterodactylus.util.config.ConfigurationException;
92 import net.pterodactylus.util.logging.Logging;
93 import net.pterodactylus.util.number.Numbers;
94 import net.pterodactylus.util.service.AbstractService;
95 import net.pterodactylus.util.thread.NamedThreadFactory;
97 import com.google.common.base.Optional;
98 import com.google.common.base.Predicates;
99 import com.google.common.collect.FluentIterable;
100 import com.google.common.collect.HashMultimap;
101 import com.google.common.collect.ImmutableSet;
102 import com.google.common.collect.Multimap;
103 import com.google.common.collect.Multimaps;
104 import com.google.common.eventbus.EventBus;
105 import com.google.common.eventbus.Subscribe;
106 import com.google.inject.Inject;
108 import freenet.keys.FreenetURI;
113 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
115 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
118 private static final Logger logger = Logging.getLogger(Core.class);
120 /** The start time. */
121 private final long startupTime = System.currentTimeMillis();
124 private final Options options = new Options();
126 /** The preferences. */
127 private final Preferences preferences = new Preferences(options);
129 /** The event bus. */
130 private final EventBus eventBus;
132 /** The configuration. */
133 private final Configuration configuration;
135 /** Whether we’re currently saving the configuration. */
136 private boolean storingConfiguration = false;
138 /** The identity manager. */
139 private final IdentityManager identityManager;
141 /** Interface to freenet. */
142 private final FreenetInterface freenetInterface;
144 /** The Sone downloader. */
145 private final SoneDownloader soneDownloader;
147 /** The image inserter. */
148 private final ImageInserter imageInserter;
150 /** Sone downloader thread-pool. */
151 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
153 /** The update checker. */
154 private final UpdateChecker updateChecker;
156 /** The trust updater. */
157 private final WebOfTrustUpdater webOfTrustUpdater;
159 /** The FCP interface. */
160 private volatile FcpInterface fcpInterface;
162 /** The times Sones were followed. */
163 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
165 /** Locked local Sones. */
166 /* synchronize on itself. */
167 private final Set<Sone> lockedSones = new HashSet<Sone>();
169 /** Sone inserters. */
170 /* synchronize access on this on sones. */
171 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
173 /** Sone rescuers. */
174 /* synchronize access on this on sones. */
175 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
178 /* synchronize access on this on itself. */
179 private final Map<String, Sone> sones = new HashMap<String, Sone>();
181 /** All known Sones. */
182 private final Set<String> knownSones = new HashSet<String>();
184 /** The post database. */
185 private final Database database;
187 /** All bookmarked posts. */
188 /* synchronize access on itself. */
189 private final Set<String> bookmarkedPosts = new HashSet<String>();
191 /** Trusted identities, sorted by own identities. */
192 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
194 /** All temporary images. */
195 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
197 /** Ticker for threads that mark own elements as known. */
198 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
200 /** The time the configuration was last touched. */
201 private volatile long lastConfigurationUpdate;
204 * Creates a new core.
206 * @param configuration
207 * The configuration of the core
208 * @param freenetInterface
209 * The freenet interface
210 * @param identityManager
211 * The identity manager
212 * @param webOfTrustUpdater
213 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloader(this, freenetInterface);
226 this.imageInserter = new ImageInserter(freenetInterface);
227 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
230 this.database = database;
238 * Returns the time Sone was started.
240 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
242 public long getStartupTime() {
247 * Returns the options used by the core.
249 * @return The options of the core
251 public Preferences getPreferences() {
256 * Returns the identity manager used by the core.
258 * @return The identity manager
260 public IdentityManager getIdentityManager() {
261 return identityManager;
265 * Returns the update checker.
267 * @return The update checker
269 public UpdateChecker getUpdateChecker() {
270 return updateChecker;
274 * Sets the FCP interface to use.
276 * @param fcpInterface
277 * The FCP interface to use
279 public void setFcpInterface(FcpInterface fcpInterface) {
280 this.fcpInterface = fcpInterface;
284 * Returns the Sone rescuer for the given local Sone.
287 * The local Sone to get the rescuer for
288 * @return The Sone rescuer for the given Sone
290 public SoneRescuer getSoneRescuer(Sone sone) {
291 checkNotNull(sone, "sone must not be null");
292 checkArgument(sone.isLocal(), "sone must be local");
293 synchronized (sones) {
294 SoneRescuer soneRescuer = soneRescuers.get(sone);
295 if (soneRescuer == null) {
296 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
297 soneRescuers.put(sone, soneRescuer);
305 * Returns whether the given Sone is currently locked.
309 * @return {@code true} if the Sone is locked, {@code false} if it is not
311 public boolean isLocked(Sone sone) {
312 synchronized (lockedSones) {
313 return lockedSones.contains(sone);
321 public Collection<Sone> getSones() {
322 synchronized (sones) {
323 return ImmutableSet.copyOf(sones.values());
328 * Returns the Sone with the given ID, regardless whether it’s local or
332 * The ID of the Sone to get
333 * @return The Sone with the given ID, or {@code null} if there is no such
337 public Optional<Sone> getSone(String id) {
338 synchronized (sones) {
339 return Optional.fromNullable(sones.get(id));
347 public Collection<Sone> getLocalSones() {
348 synchronized (sones) {
349 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
354 * Returns the local Sone with the given ID, optionally creating a new Sone.
359 * {@code true} to create a new Sone if none exists,
360 * {@code false} to return null if none exists
361 * @return The Sone with the given ID, or {@code null}
363 public Sone getLocalSone(String id, boolean create) {
364 synchronized (sones) {
365 Sone sone = sones.get(id);
366 if ((sone == null) && create) {
367 sone = new SoneImpl(id, true);
370 if ((sone != null) && !sone.isLocal()) {
371 sone = new SoneImpl(id, true);
382 public Collection<Sone> getRemoteSones() {
383 synchronized (sones) {
384 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
389 * Returns the remote Sone with the given ID.
392 * The ID of the remote Sone to get
394 * {@code true} to always create a Sone, {@code false} to return
395 * {@code null} if no Sone with the given ID exists
396 * @return The Sone with the given ID
398 public Sone getRemoteSone(String id, boolean create) {
399 synchronized (sones) {
400 Sone sone = sones.get(id);
401 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
402 sone = new SoneImpl(id, false);
410 * Returns whether the given Sone has been modified.
413 * The Sone to check for modifications
414 * @return {@code true} if a modification has been detected in the Sone,
415 * {@code false} otherwise
417 public boolean isModifiedSone(Sone sone) {
418 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
422 * Returns the time when the given was first followed by any local Sone.
425 * The Sone to get the time for
426 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
427 * been followed, or {@link Long#MAX_VALUE}
429 public long getSoneFollowingTime(Sone sone) {
430 synchronized (soneFollowingTimes) {
431 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
436 * Returns whether the target Sone is trusted by the origin Sone.
442 * @return {@code true} if the target Sone is trusted by the origin Sone
444 public boolean isSoneTrusted(Sone origin, Sone target) {
445 checkNotNull(origin, "origin must not be null");
446 checkNotNull(target, "target must not be null");
447 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
448 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
452 * Returns a post builder.
454 * @return A new post builder
456 public PostBuilder postBuilder() {
457 return database.newPostBuilder();
464 public Optional<Post> getPost(String postId) {
465 return database.getPost(postId);
472 public Collection<Post> getPosts(String soneId) {
473 return database.getPosts(soneId);
480 public Collection<Post> getDirectedPosts(final String recipientId) {
481 checkNotNull(recipientId, "recipient must not be null");
482 return database.getDirectedPosts(recipientId);
486 * Returns a post reply builder.
488 * @return A new post reply builder
490 public PostReplyBuilder postReplyBuilder() {
491 return database.newPostReplyBuilder();
498 public Optional<PostReply> getPostReply(String replyId) {
499 return database.getPostReply(replyId);
506 public List<PostReply> getReplies(final String postId) {
507 return database.getReplies(postId);
511 * Returns all Sones that have liked the given post.
514 * The post to get the liking Sones for
515 * @return The Sones that like the given post
517 public Set<Sone> getLikes(Post post) {
518 Set<Sone> sones = new HashSet<Sone>();
519 for (Sone sone : getSones()) {
520 if (sone.getLikedPostIds().contains(post.getId())) {
528 * Returns all Sones that have liked the given reply.
531 * The reply to get the liking Sones for
532 * @return The Sones that like the given reply
534 public Set<Sone> getLikes(PostReply reply) {
535 Set<Sone> sones = new HashSet<Sone>();
536 for (Sone sone : getSones()) {
537 if (sone.getLikedReplyIds().contains(reply.getId())) {
545 * Returns whether the given post is bookmarked.
549 * @return {@code true} if the given post is bookmarked, {@code false}
552 public boolean isBookmarked(Post post) {
553 return isPostBookmarked(post.getId());
557 * Returns whether the post with the given ID is bookmarked.
560 * The ID of the post to check
561 * @return {@code true} if the post with the given ID is bookmarked,
562 * {@code false} otherwise
564 public boolean isPostBookmarked(String id) {
565 synchronized (bookmarkedPosts) {
566 return bookmarkedPosts.contains(id);
571 * Returns all currently known bookmarked posts.
573 * @return All bookmarked posts
575 public Set<Post> getBookmarkedPosts() {
576 Set<Post> posts = new HashSet<Post>();
577 synchronized (bookmarkedPosts) {
578 for (String bookmarkedPostId : bookmarkedPosts) {
579 Optional<Post> post = getPost(bookmarkedPostId);
580 if (post.isPresent()) {
581 posts.add(post.get());
589 * Returns the album with the given ID, creating a new album if no album
590 * with the given ID can be found.
593 * The ID of the album
594 * @return The album with the given ID
596 public Album getAlbum(String albumId) {
597 return getAlbum(albumId, true);
601 * Returns the album with the given ID, optionally creating a new album if
602 * an album with the given ID can not be found.
605 * The ID of the album
607 * {@code true} to create a new album if none exists for the
609 * @return The album with the given ID, or {@code null} if no album with the
610 * given ID exists and {@code create} is {@code false}
612 public Album getAlbum(String albumId, boolean create) {
613 Optional<Album> album = database.getAlbum(albumId);
614 if (album.isPresent()) {
620 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
621 database.storeAlbum(newAlbum);
626 * Returns the image with the given ID, creating it if necessary.
629 * The ID of the image
630 * @return The image with the given ID
632 public Image getImage(String imageId) {
633 return getImage(imageId, true);
637 * Returns the image with the given ID, optionally creating it if it does
641 * The ID of the image
643 * {@code true} to create an image if none exists with the given
645 * @return The image with the given ID, or {@code null} if none exists and
648 public Image getImage(String imageId, boolean create) {
649 Optional<Image> image = database.getImage(imageId);
650 if (image.isPresent()) {
656 Image newImage = database.newImageBuilder().withId(imageId).build();
657 database.storeImage(newImage);
662 * Returns the temporary image with the given ID.
665 * The ID of the temporary image
666 * @return The temporary image, or {@code null} if there is no temporary
667 * image with the given ID
669 public TemporaryImage getTemporaryImage(String imageId) {
670 synchronized (temporaryImages) {
671 return temporaryImages.get(imageId);
680 * Locks the given Sone. A locked Sone will not be inserted by
681 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
687 public void lockSone(Sone sone) {
688 synchronized (lockedSones) {
689 if (lockedSones.add(sone)) {
690 eventBus.post(new SoneLockedEvent(sone));
696 * Unlocks the given Sone.
698 * @see #lockSone(Sone)
702 public void unlockSone(Sone sone) {
703 synchronized (lockedSones) {
704 if (lockedSones.remove(sone)) {
705 eventBus.post(new SoneUnlockedEvent(sone));
711 * Adds a local Sone from the given own identity.
714 * The own identity to create a Sone from
715 * @return The added (or already existing) Sone
717 public Sone addLocalSone(OwnIdentity ownIdentity) {
718 if (ownIdentity == null) {
719 logger.log(Level.WARNING, "Given OwnIdentity is null!");
722 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
723 synchronized (sones) {
726 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
727 } catch (MalformedURLException mue1) {
728 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
731 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
732 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
734 /* TODO - load posts ’n stuff */
735 sones.put(ownIdentity.getId(), sone);
736 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
737 soneInserters.put(sone, soneInserter);
738 sone.setStatus(SoneStatus.idle);
740 soneInserter.start();
746 * Creates a new Sone for the given own identity.
749 * The own identity to create a Sone for
750 * @return The created Sone
752 public Sone createSone(OwnIdentity ownIdentity) {
753 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
754 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
757 Sone sone = addLocalSone(ownIdentity);
758 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
759 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
760 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
761 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
762 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
763 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
765 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
766 touchConfiguration();
771 * Adds the Sone of the given identity.
774 * The identity whose Sone to add
775 * @return The added or already existing Sone
777 public Sone addRemoteSone(Identity identity) {
778 if (identity == null) {
779 logger.log(Level.WARNING, "Given Identity is null!");
782 synchronized (sones) {
783 final Sone sone = getRemoteSone(identity.getId(), true);
784 if (sone.isLocal()) {
787 sone.setIdentity(identity);
788 boolean newSone = sone.getRequestUri() == null;
789 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
790 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
792 synchronized (knownSones) {
793 newSone = !knownSones.contains(sone.getId());
795 sone.setKnown(!newSone);
797 eventBus.post(new NewSoneFoundEvent(sone));
798 for (Sone localSone : getLocalSones()) {
799 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
800 followSone(localSone, sone.getId());
805 soneDownloader.addSone(sone);
806 soneDownloaders.execute(new Runnable() {
809 @SuppressWarnings("synthetic-access")
811 soneDownloader.fetchSone(sone, sone.getRequestUri());
820 * Lets the given local Sone follow the Sone with the given ID.
823 * The local Sone that should follow another Sone
825 * The ID of the Sone to follow
827 public void followSone(Sone sone, String soneId) {
828 checkNotNull(sone, "sone must not be null");
829 checkNotNull(soneId, "soneId must not be null");
830 sone.addFriend(soneId);
831 synchronized (soneFollowingTimes) {
832 if (!soneFollowingTimes.containsKey(soneId)) {
833 long now = System.currentTimeMillis();
834 soneFollowingTimes.put(soneId, now);
835 Optional<Sone> followedSone = getSone(soneId);
836 if (!followedSone.isPresent()) {
839 for (Post post : followedSone.get().getPosts()) {
840 if (post.getTime() < now) {
844 for (PostReply reply : followedSone.get().getReplies()) {
845 if (reply.getTime() < now) {
846 markReplyKnown(reply);
851 touchConfiguration();
855 * Lets the given local Sone unfollow the Sone with the given ID.
858 * The local Sone that should unfollow another Sone
860 * The ID of the Sone being unfollowed
862 public void unfollowSone(Sone sone, String soneId) {
863 checkNotNull(sone, "sone must not be null");
864 checkNotNull(soneId, "soneId must not be null");
865 sone.removeFriend(soneId);
866 boolean unfollowedSoneStillFollowed = false;
867 for (Sone localSone : getLocalSones()) {
868 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
870 if (!unfollowedSoneStillFollowed) {
871 synchronized (soneFollowingTimes) {
872 soneFollowingTimes.remove(soneId);
875 touchConfiguration();
879 * Sets the trust value of the given origin Sone for the target Sone.
886 * The trust value (from {@code -100} to {@code 100})
888 public void setTrust(Sone origin, Sone target, int trustValue) {
889 checkNotNull(origin, "origin must not be null");
890 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
891 checkNotNull(target, "target must not be null");
892 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
893 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
897 * Removes any trust assignment for the given target Sone.
904 public void removeTrust(Sone origin, Sone target) {
905 checkNotNull(origin, "origin must not be null");
906 checkNotNull(target, "target must not be null");
907 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
908 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
912 * Assigns the configured positive trust value for the given target.
919 public void trustSone(Sone origin, Sone target) {
920 setTrust(origin, target, preferences.getPositiveTrust());
924 * Assigns the configured negative trust value for the given target.
931 public void distrustSone(Sone origin, Sone target) {
932 setTrust(origin, target, preferences.getNegativeTrust());
936 * Removes the trust assignment for the given target.
943 public void untrustSone(Sone origin, Sone target) {
944 removeTrust(origin, target);
948 * Updates the stored Sone with the given Sone.
953 public void updateSone(Sone sone) {
954 updateSone(sone, false);
958 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
959 * {@code true}, an older Sone than the current Sone can be given to restore
964 * @param soneRescueMode
965 * {@code true} if the stored Sone should be updated regardless
966 * of the age of the given Sone
968 public void updateSone(Sone sone, boolean soneRescueMode) {
969 Optional<Sone> storedSone = getSone(sone.getId());
970 if (storedSone.isPresent()) {
971 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
972 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
975 /* find removed posts. */
976 Collection<Post> removedPosts = new ArrayList<Post>();
977 Collection<Post> newPosts = new ArrayList<Post>();
978 Collection<Post> existingPosts = database.getPosts(sone.getId());
979 for (Post oldPost : existingPosts) {
980 if (!sone.getPosts().contains(oldPost)) {
981 removedPosts.add(oldPost);
984 /* find new posts. */
985 for (Post newPost : sone.getPosts()) {
986 if (existingPosts.contains(newPost)) {
989 if (newPost.getTime() < getSoneFollowingTime(sone)) {
990 newPost.setKnown(true);
991 } else if (!newPost.isKnown()) {
992 newPosts.add(newPost);
996 database.storePosts(sone, sone.getPosts());
997 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
998 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
999 if (!soneRescueMode) {
1000 for (PostReply reply : storedSone.get().getReplies()) {
1001 if (!sone.getReplies().contains(reply)) {
1002 removedPostReplies.add(reply);
1006 Set<PostReply> storedReplies = storedSone.get().getReplies();
1007 for (PostReply reply : sone.getReplies()) {
1008 if (storedReplies.contains(reply)) {
1011 if (reply.getTime() < getSoneFollowingTime(sone)) {
1012 reply.setKnown(true);
1013 } else if (!reply.isKnown()) {
1014 newPostReplies.add(reply);
1017 database.storePostReplies(sone, sone.getReplies());
1018 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1019 database.removeAlbum(album);
1020 for (Image image : album.getImages()) {
1021 database.removeImage(image);
1024 for (Post removedPost : removedPosts) {
1025 eventBus.post(new PostRemovedEvent(removedPost));
1027 for (Post newPost : newPosts) {
1028 eventBus.post(new NewPostFoundEvent(newPost));
1030 for (PostReply removedPostReply : removedPostReplies) {
1031 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1033 for (PostReply newPostReply : newPostReplies) {
1034 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1036 for (Album album : sone.getRootAlbum().getAlbums()) {
1037 database.storeAlbum(album);
1038 for (Image image : album.getImages()) {
1039 database.storeImage(image);
1042 synchronized (sones) {
1043 sone.setOptions(storedSone.get().getOptions());
1044 sone.setKnown(storedSone.get().isKnown());
1045 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1046 if (sone.isLocal()) {
1047 soneInserters.get(storedSone.get()).setSone(sone);
1048 touchConfiguration();
1050 sones.put(sone.getId(), sone);
1056 * Deletes the given Sone. This will remove the Sone from the
1057 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1058 * remove the context from its identity.
1061 * The Sone to delete
1063 public void deleteSone(Sone sone) {
1064 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1065 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1068 synchronized (sones) {
1069 if (!getLocalSones().contains(sone)) {
1070 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1073 sones.remove(sone.getId());
1074 SoneInserter soneInserter = soneInserters.remove(sone);
1075 soneInserter.stop();
1077 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1078 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1080 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1081 } catch (ConfigurationException ce1) {
1082 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1087 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1088 * known} before, a {@link MarkSoneKnownEvent} is fired.
1091 * The Sone to mark as known
1093 public void markSoneKnown(Sone sone) {
1094 if (!sone.isKnown()) {
1095 sone.setKnown(true);
1096 synchronized (knownSones) {
1097 knownSones.add(sone.getId());
1099 eventBus.post(new MarkSoneKnownEvent(sone));
1100 touchConfiguration();
1105 * Loads and updates the given Sone from the configuration. If any error is
1106 * encountered, loading is aborted and the given Sone is not changed.
1109 * The Sone to load and update
1111 public void loadSone(Sone sone) {
1112 if (!sone.isLocal()) {
1113 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1116 logger.info(String.format("Loading local Sone: %s", sone));
1118 /* initialize options. */
1119 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1120 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1121 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1122 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1123 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1124 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1127 String sonePrefix = "Sone/" + sone.getId();
1128 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1129 if (soneTime == null) {
1130 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1133 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1136 Profile profile = new Profile(sone);
1137 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1138 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1139 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1140 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1141 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1142 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1144 /* load profile fields. */
1146 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1147 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1148 if (fieldName == null) {
1151 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1152 profile.addField(fieldName).setValue(fieldValue);
1156 Set<Post> posts = new HashSet<Post>();
1158 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1159 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1160 if (postId == null) {
1163 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1164 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1165 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1166 if ((postTime == 0) || (postText == null)) {
1167 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1170 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1171 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1172 postBuilder.to(postRecipientId);
1174 posts.add(postBuilder.build());
1178 Set<PostReply> replies = new HashSet<PostReply>();
1180 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1181 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1182 if (replyId == null) {
1185 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1186 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1187 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1188 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1189 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1192 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1193 replies.add(postReplyBuilder.build());
1196 /* load post likes. */
1197 Set<String> likedPostIds = new HashSet<String>();
1199 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1200 if (likedPostId == null) {
1203 likedPostIds.add(likedPostId);
1206 /* load reply likes. */
1207 Set<String> likedReplyIds = new HashSet<String>();
1209 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1210 if (likedReplyId == null) {
1213 likedReplyIds.add(likedReplyId);
1217 Set<String> friends = new HashSet<String>();
1219 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1220 if (friendId == null) {
1223 friends.add(friendId);
1227 List<Album> topLevelAlbums = new ArrayList<Album>();
1228 int albumCounter = 0;
1230 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1231 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1232 if (albumId == null) {
1235 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1236 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1237 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1238 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1239 if ((albumTitle == null) || (albumDescription == null)) {
1240 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1243 Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1244 if (albumParentId != null) {
1245 Album parentAlbum = getAlbum(albumParentId, false);
1246 if (parentAlbum == null) {
1247 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1250 parentAlbum.addAlbum(album);
1252 if (!topLevelAlbums.contains(album)) {
1253 topLevelAlbums.add(album);
1259 int imageCounter = 0;
1261 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1262 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1263 if (imageId == null) {
1266 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1267 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1268 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1269 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1270 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1271 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1272 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1273 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1274 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1277 Album album = getAlbum(albumId, false);
1278 if (album == null) {
1279 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1282 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1283 album.addImage(image);
1287 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1288 if (avatarId != null) {
1289 profile.setAvatar(getImage(avatarId, false));
1293 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1294 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1295 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1296 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1297 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1298 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1300 /* if we’re still here, Sone was loaded successfully. */
1301 synchronized (sone) {
1302 sone.setTime(soneTime);
1303 sone.setProfile(profile);
1304 sone.setPosts(posts);
1305 sone.setReplies(replies);
1306 sone.setLikePostIds(likedPostIds);
1307 sone.setLikeReplyIds(likedReplyIds);
1308 for (String friendId : friends) {
1309 followSone(sone, friendId);
1311 for (Album album : sone.getRootAlbum().getAlbums()) {
1312 sone.getRootAlbum().removeAlbum(album);
1314 for (Album album : topLevelAlbums) {
1315 sone.getRootAlbum().addAlbum(album);
1317 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1319 synchronized (knownSones) {
1320 for (String friend : friends) {
1321 knownSones.add(friend);
1324 database.storePosts(sone, posts);
1325 for (Post post : posts) {
1326 post.setKnown(true);
1328 database.storePostReplies(sone, replies);
1329 for (PostReply reply : replies) {
1330 reply.setKnown(true);
1333 logger.info(String.format("Sone loaded successfully: %s", sone));
1337 * Creates a new post.
1340 * The Sone that creates the post
1342 * The text of the post
1343 * @return The created post
1345 public Post createPost(Sone sone, String text) {
1346 return createPost(sone, System.currentTimeMillis(), text);
1350 * Creates a new post.
1353 * The Sone that creates the post
1355 * The time of the post
1357 * The text of the post
1358 * @return The created post
1360 public Post createPost(Sone sone, long time, String text) {
1361 return createPost(sone, null, time, text);
1365 * Creates a new post.
1368 * The Sone that creates the post
1370 * The recipient Sone, or {@code null} if this post does not have
1373 * The text of the post
1374 * @return The created post
1376 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1377 return createPost(sone, recipient, System.currentTimeMillis(), text);
1381 * Creates a new post.
1384 * The Sone that creates the post
1386 * The recipient Sone, or {@code null} if this post does not have
1389 * The time of the post
1391 * The text of the post
1392 * @return The created post
1394 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1395 checkNotNull(text, "text must not be null");
1396 checkArgument(text.trim().length() > 0, "text must not be empty");
1397 if (!sone.isLocal()) {
1398 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1401 PostBuilder postBuilder = database.newPostBuilder();
1402 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1403 if (recipient.isPresent()) {
1404 postBuilder.to(recipient.get().getId());
1406 final Post post = postBuilder.build();
1407 database.storePost(post);
1408 eventBus.post(new NewPostFoundEvent(post));
1410 touchConfiguration();
1411 localElementTicker.schedule(new Runnable() {
1418 markPostKnown(post);
1420 }, 10, TimeUnit.SECONDS);
1425 * Deletes the given post.
1428 * The post to delete
1430 public void deletePost(Post post) {
1431 if (!post.getSone().isLocal()) {
1432 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1435 database.removePost(post);
1436 eventBus.post(new PostRemovedEvent(post));
1437 markPostKnown(post);
1438 touchConfiguration();
1442 * Marks the given post as known, if it is currently not a known post
1443 * (according to {@link Post#isKnown()}).
1446 * The post to mark as known
1448 public void markPostKnown(Post post) {
1449 post.setKnown(true);
1450 eventBus.post(new MarkPostKnownEvent(post));
1451 touchConfiguration();
1452 for (PostReply reply : getReplies(post.getId())) {
1453 markReplyKnown(reply);
1458 * Bookmarks the given post.
1461 * The post to bookmark
1463 public void bookmark(Post post) {
1464 bookmarkPost(post.getId());
1468 * Bookmarks the post with the given ID.
1471 * The ID of the post to bookmark
1473 public void bookmarkPost(String id) {
1474 synchronized (bookmarkedPosts) {
1475 bookmarkedPosts.add(id);
1480 * Removes the given post from the bookmarks.
1483 * The post to unbookmark
1485 public void unbookmark(Post post) {
1486 unbookmarkPost(post.getId());
1490 * Removes the post with the given ID from the bookmarks.
1493 * The ID of the post to unbookmark
1495 public void unbookmarkPost(String id) {
1496 synchronized (bookmarkedPosts) {
1497 bookmarkedPosts.remove(id);
1502 * Creates a new reply.
1505 * The Sone that creates the reply
1507 * The post that this reply refers to
1509 * The text of the reply
1510 * @return The created reply
1512 public PostReply createReply(Sone sone, Post post, String text) {
1513 checkNotNull(text, "text must not be null");
1514 checkArgument(text.trim().length() > 0, "text must not be empty");
1515 if (!sone.isLocal()) {
1516 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1519 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1520 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1521 final PostReply reply = postReplyBuilder.build();
1522 database.storePostReply(reply);
1523 eventBus.post(new NewPostReplyFoundEvent(reply));
1524 sone.addReply(reply);
1525 touchConfiguration();
1526 localElementTicker.schedule(new Runnable() {
1533 markReplyKnown(reply);
1535 }, 10, TimeUnit.SECONDS);
1540 * Deletes the given reply.
1543 * The reply to delete
1545 public void deleteReply(PostReply reply) {
1546 Sone sone = reply.getSone();
1547 if (!sone.isLocal()) {
1548 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1551 database.removePostReply(reply);
1552 markReplyKnown(reply);
1553 sone.removeReply(reply);
1554 touchConfiguration();
1558 * Marks the given reply as known, if it is currently not a known reply
1559 * (according to {@link Reply#isKnown()}).
1562 * The reply to mark as known
1564 public void markReplyKnown(PostReply reply) {
1565 boolean previouslyKnown = reply.isKnown();
1566 reply.setKnown(true);
1567 eventBus.post(new MarkPostReplyKnownEvent(reply));
1568 if (!previouslyKnown) {
1569 touchConfiguration();
1574 * Creates a new top-level album for the given Sone.
1577 * The Sone to create the album for
1578 * @return The new album
1580 public Album createAlbum(Sone sone) {
1581 return createAlbum(sone, sone.getRootAlbum());
1585 * Creates a new album for the given Sone.
1588 * The Sone to create the album for
1590 * The parent of the album (may be {@code null} to create a
1592 * @return The new album
1594 public Album createAlbum(Sone sone, Album parent) {
1595 Album album = database.newAlbumBuilder().randomId().build();
1596 database.storeAlbum(album);
1597 album.setSone(sone);
1598 parent.addAlbum(album);
1603 * Deletes the given album. The owner of the album has to be a local Sone,
1604 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1607 * The album to remove
1609 public void deleteAlbum(Album album) {
1610 checkNotNull(album, "album must not be null");
1611 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1612 if (!album.isEmpty()) {
1615 album.getParent().removeAlbum(album);
1616 database.removeAlbum(album);
1617 touchConfiguration();
1621 * Creates a new image.
1624 * The Sone creating the image
1626 * The album the image will be inserted into
1627 * @param temporaryImage
1628 * The temporary image to create the image from
1629 * @return The newly created image
1631 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1632 checkNotNull(sone, "sone must not be null");
1633 checkNotNull(album, "album must not be null");
1634 checkNotNull(temporaryImage, "temporaryImage must not be null");
1635 checkArgument(sone.isLocal(), "sone must be a local Sone");
1636 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1637 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1638 album.addImage(image);
1639 database.storeImage(image);
1640 imageInserter.insertImage(temporaryImage, image);
1645 * Deletes the given image. This method will also delete a matching
1648 * @see #deleteTemporaryImage(TemporaryImage)
1650 * The image to delete
1652 public void deleteImage(Image image) {
1653 checkNotNull(image, "image must not be null");
1654 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1655 deleteTemporaryImage(image.getId());
1656 image.getAlbum().removeImage(image);
1657 database.removeImage(image);
1658 touchConfiguration();
1662 * Creates a new temporary image.
1665 * The MIME type of the temporary image
1667 * The encoded data of the image
1668 * @return The temporary image
1670 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1671 TemporaryImage temporaryImage = new TemporaryImage();
1672 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1673 synchronized (temporaryImages) {
1674 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1676 return temporaryImage;
1680 * Deletes the given temporary image.
1682 * @param temporaryImage
1683 * The temporary image to delete
1685 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1686 checkNotNull(temporaryImage, "temporaryImage must not be null");
1687 deleteTemporaryImage(temporaryImage.getId());
1691 * Deletes the temporary image with the given ID.
1694 * The ID of the temporary image to delete
1696 public void deleteTemporaryImage(String imageId) {
1697 checkNotNull(imageId, "imageId must not be null");
1698 synchronized (temporaryImages) {
1699 temporaryImages.remove(imageId);
1701 Image image = getImage(imageId, false);
1702 if (image != null) {
1703 imageInserter.cancelImageInsert(image);
1708 * Notifies the core that the configuration, either of the core or of a
1709 * single local Sone, has changed, and that the configuration should be
1712 public void touchConfiguration() {
1713 lastConfigurationUpdate = System.currentTimeMillis();
1724 public void serviceStart() {
1725 loadConfiguration();
1726 updateChecker.start();
1727 identityManager.start();
1728 webOfTrustUpdater.init();
1729 webOfTrustUpdater.start();
1737 public void serviceRun() {
1738 long lastSaved = System.currentTimeMillis();
1739 while (!shouldStop()) {
1741 long now = System.currentTimeMillis();
1742 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1743 for (Sone localSone : getLocalSones()) {
1744 saveSone(localSone);
1746 saveConfiguration();
1756 public void serviceStop() {
1757 localElementTicker.shutdownNow();
1758 synchronized (sones) {
1759 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1760 soneInserter.getValue().stop();
1761 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1764 saveConfiguration();
1766 webOfTrustUpdater.stop();
1767 updateChecker.stop();
1768 soneDownloader.stop();
1769 soneDownloaders.shutdown();
1770 identityManager.stop();
1778 * Saves the given Sone. This will persist all local settings for the given
1779 * Sone, such as the friends list and similar, private options.
1784 private synchronized void saveSone(Sone sone) {
1785 if (!sone.isLocal()) {
1786 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1789 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1790 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1794 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1796 /* save Sone into configuration. */
1797 String sonePrefix = "Sone/" + sone.getId();
1798 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1799 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1802 Profile profile = sone.getProfile();
1803 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1804 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1805 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1806 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1807 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1808 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1809 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1811 /* save profile fields. */
1812 int fieldCounter = 0;
1813 for (Field profileField : profile.getFields()) {
1814 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1815 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1816 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1818 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1821 int postCounter = 0;
1822 for (Post post : sone.getPosts()) {
1823 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1824 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1825 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1826 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1827 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1829 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1832 int replyCounter = 0;
1833 for (PostReply reply : sone.getReplies()) {
1834 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1835 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1836 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1837 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1838 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1840 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1842 /* save post likes. */
1843 int postLikeCounter = 0;
1844 for (String postId : sone.getLikedPostIds()) {
1845 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1847 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1849 /* save reply likes. */
1850 int replyLikeCounter = 0;
1851 for (String replyId : sone.getLikedReplyIds()) {
1852 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1854 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1857 int friendCounter = 0;
1858 for (String friendId : sone.getFriends()) {
1859 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1861 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1863 /* save albums. first, collect in a flat structure, top-level first. */
1864 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1866 int albumCounter = 0;
1867 for (Album album : albums) {
1868 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1869 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1870 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1871 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1872 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1873 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1875 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1878 int imageCounter = 0;
1879 for (Album album : albums) {
1880 for (Image image : album.getImages()) {
1881 if (!image.isInserted()) {
1884 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1885 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1886 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1887 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1888 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1889 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1890 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1891 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1892 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1895 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1898 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1899 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1900 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1901 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1902 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1903 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1905 configuration.save();
1907 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1909 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1910 } catch (ConfigurationException ce1) {
1911 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1916 * Saves the current options.
1918 private void saveConfiguration() {
1919 synchronized (configuration) {
1920 if (storingConfiguration) {
1921 logger.log(Level.FINE, "Already storing configuration…");
1924 storingConfiguration = true;
1927 /* store the options first. */
1929 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1930 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1931 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1932 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1933 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1934 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1935 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1936 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1937 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1938 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1939 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1940 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1942 /* save known Sones. */
1943 int soneCounter = 0;
1944 synchronized (knownSones) {
1945 for (String knownSoneId : knownSones) {
1946 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1948 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1951 /* save Sone following times. */
1953 synchronized (soneFollowingTimes) {
1954 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1955 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1956 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1959 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1962 /* save known posts. */
1965 /* save bookmarked posts. */
1966 int bookmarkedPostCounter = 0;
1967 synchronized (bookmarkedPosts) {
1968 for (String bookmarkedPostId : bookmarkedPosts) {
1969 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1972 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1975 configuration.save();
1977 } catch (ConfigurationException ce1) {
1978 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1979 } catch (DatabaseException de1) {
1980 logger.log(Level.SEVERE, "Could not save database!", de1);
1982 synchronized (configuration) {
1983 storingConfiguration = false;
1989 * Loads the configuration.
1991 private void loadConfiguration() {
1992 /* create options. */
1993 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1994 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1995 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1996 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1997 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1998 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1999 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2000 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2001 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2002 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
2003 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2006 @SuppressWarnings("synthetic-access")
2007 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2008 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2013 loadConfigurationValue("InsertionDelay");
2014 loadConfigurationValue("PostsPerPage");
2015 loadConfigurationValue("ImagesPerPage");
2016 loadConfigurationValue("CharactersPerPost");
2017 loadConfigurationValue("PostCutOffLength");
2018 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2019 loadConfigurationValue("PositiveTrust");
2020 loadConfigurationValue("NegativeTrust");
2021 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2022 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2023 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2025 /* load known Sones. */
2026 int soneCounter = 0;
2028 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2029 if (knownSoneId == null) {
2032 synchronized (knownSones) {
2033 knownSones.add(knownSoneId);
2037 /* load Sone following times. */
2040 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2041 if (soneId == null) {
2044 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2045 synchronized (soneFollowingTimes) {
2046 soneFollowingTimes.put(soneId, time);
2051 /* load bookmarked posts. */
2052 int bookmarkedPostCounter = 0;
2054 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2055 if (bookmarkedPostId == null) {
2058 synchronized (bookmarkedPosts) {
2059 bookmarkedPosts.add(bookmarkedPostId);
2066 * Loads an {@link Integer} configuration value for the option with the
2067 * given name, logging validation failures.
2070 * The name of the option to load
2072 private void loadConfigurationValue(String optionName) {
2074 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2075 } catch (IllegalArgumentException iae1) {
2076 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2081 * Notifies the core that a new {@link OwnIdentity} was added.
2083 * @param ownIdentityAddedEvent
2087 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2088 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2089 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2090 if (ownIdentity.hasContext("Sone")) {
2091 addLocalSone(ownIdentity);
2096 * Notifies the core that an {@link OwnIdentity} was removed.
2098 * @param ownIdentityRemovedEvent
2102 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2103 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2104 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2105 trustedIdentities.removeAll(ownIdentity);
2109 * Notifies the core that a new {@link Identity} was added.
2111 * @param identityAddedEvent
2115 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2116 Identity identity = identityAddedEvent.identity();
2117 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2118 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2119 addRemoteSone(identity);
2123 * Notifies the core that an {@link Identity} was updated.
2125 * @param identityUpdatedEvent
2129 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2130 final Identity identity = identityUpdatedEvent.identity();
2131 soneDownloaders.execute(new Runnable() {
2134 @SuppressWarnings("synthetic-access")
2136 Sone sone = getRemoteSone(identity.getId(), false);
2137 if (sone.isLocal()) {
2140 sone.setIdentity(identity);
2141 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2142 soneDownloader.addSone(sone);
2143 soneDownloader.fetchSone(sone);
2149 * Notifies the core that an {@link Identity} was removed.
2151 * @param identityRemovedEvent
2155 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2156 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2157 Identity identity = identityRemovedEvent.identity();
2158 trustedIdentities.remove(ownIdentity, identity);
2159 boolean foundIdentity = false;
2160 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2161 if (trustedIdentity.getKey().equals(ownIdentity)) {
2164 if (trustedIdentity.getValue().contains(identity)) {
2165 foundIdentity = true;
2168 if (foundIdentity) {
2169 /* some local identity still trusts this identity, don’t remove. */
2172 Optional<Sone> sone = getSone(identity.getId());
2173 if (!sone.isPresent()) {
2174 /* TODO - we don’t have the Sone anymore. should this happen? */
2177 database.removePosts(sone.get());
2178 for (Post post : sone.get().getPosts()) {
2179 eventBus.post(new PostRemovedEvent(post));
2181 database.removePostReplies(sone.get());
2182 for (PostReply reply : sone.get().getReplies()) {
2183 eventBus.post(new PostReplyRemovedEvent(reply));
2185 synchronized (sones) {
2186 sones.remove(identity.getId());
2188 eventBus.post(new SoneRemovedEvent(sone.get()));
2192 * Deletes the temporary image.
2194 * @param imageInsertFinishedEvent
2198 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2199 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2200 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2201 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2202 touchConfiguration();