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.event.ImageInsertFinishedEvent;
45 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
48 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
49 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
50 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
51 import net.pterodactylus.sone.core.event.PostRemovedEvent;
52 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneLockedEvent;
54 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
56 import net.pterodactylus.sone.data.Album;
57 import net.pterodactylus.sone.data.Client;
58 import net.pterodactylus.sone.data.Image;
59 import net.pterodactylus.sone.data.Post;
60 import net.pterodactylus.sone.data.PostReply;
61 import net.pterodactylus.sone.data.Profile;
62 import net.pterodactylus.sone.data.Profile.Field;
63 import net.pterodactylus.sone.data.Reply;
64 import net.pterodactylus.sone.data.Sone;
65 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
66 import net.pterodactylus.sone.data.Sone.SoneStatus;
67 import net.pterodactylus.sone.data.SoneImpl;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.database.Database;
70 import net.pterodactylus.sone.database.DatabaseException;
71 import net.pterodactylus.sone.database.PostBuilder;
72 import net.pterodactylus.sone.database.PostProvider;
73 import net.pterodactylus.sone.database.PostReplyBuilder;
74 import net.pterodactylus.sone.database.PostReplyProvider;
75 import net.pterodactylus.sone.database.SoneProvider;
76 import net.pterodactylus.sone.fcp.FcpInterface;
77 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
78 import net.pterodactylus.sone.freenet.wot.Identity;
79 import net.pterodactylus.sone.freenet.wot.IdentityManager;
80 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
85 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
86 import net.pterodactylus.sone.main.SonePlugin;
87 import net.pterodactylus.sone.utils.IntegerRangePredicate;
88 import net.pterodactylus.util.config.Configuration;
89 import net.pterodactylus.util.config.ConfigurationException;
90 import net.pterodactylus.util.logging.Logging;
91 import net.pterodactylus.util.number.Numbers;
92 import net.pterodactylus.util.service.AbstractService;
93 import net.pterodactylus.util.thread.NamedThreadFactory;
95 import com.google.common.base.Optional;
96 import com.google.common.base.Predicates;
97 import com.google.common.collect.FluentIterable;
98 import com.google.common.collect.HashMultimap;
99 import com.google.common.collect.ImmutableSet;
100 import com.google.common.collect.Multimap;
101 import com.google.common.collect.Multimaps;
102 import com.google.common.eventbus.EventBus;
103 import com.google.common.eventbus.Subscribe;
104 import com.google.inject.Inject;
106 import freenet.keys.FreenetURI;
111 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
113 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
116 private static final Logger logger = Logging.getLogger(Core.class);
118 /** The start time. */
119 private final long startupTime = System.currentTimeMillis();
122 private final Options options = new Options();
124 /** The preferences. */
125 private final Preferences preferences = new Preferences(options);
127 /** The event bus. */
128 private final EventBus eventBus;
130 /** The configuration. */
131 private final Configuration configuration;
133 /** Whether we’re currently saving the configuration. */
134 private boolean storingConfiguration = false;
136 /** The identity manager. */
137 private final IdentityManager identityManager;
139 /** Interface to freenet. */
140 private final FreenetInterface freenetInterface;
142 /** The Sone downloader. */
143 private final SoneDownloader soneDownloader;
145 /** The image inserter. */
146 private final ImageInserter imageInserter;
148 /** Sone downloader thread-pool. */
149 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
151 /** The update checker. */
152 private final UpdateChecker updateChecker;
154 /** The trust updater. */
155 private final WebOfTrustUpdater webOfTrustUpdater;
157 /** The FCP interface. */
158 private volatile FcpInterface fcpInterface;
160 /** The times Sones were followed. */
161 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
163 /** Locked local Sones. */
164 /* synchronize on itself. */
165 private final Set<Sone> lockedSones = new HashSet<Sone>();
167 /** Sone inserters. */
168 /* synchronize access on this on sones. */
169 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
171 /** Sone rescuers. */
172 /* synchronize access on this on sones. */
173 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
176 /* synchronize access on this on itself. */
177 private final Map<String, Sone> sones = new HashMap<String, Sone>();
179 /** All known Sones. */
180 private final Set<String> knownSones = new HashSet<String>();
182 /** The post database. */
183 private final Database database;
185 /** All bookmarked posts. */
186 /* synchronize access on itself. */
187 private final Set<String> bookmarkedPosts = new HashSet<String>();
189 /** Trusted identities, sorted by own identities. */
190 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
192 /** All temporary images. */
193 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
195 /** Ticker for threads that mark own elements as known. */
196 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
198 /** The time the configuration was last touched. */
199 private volatile long lastConfigurationUpdate;
202 * Creates a new core.
204 * @param configuration
205 * The configuration of the core
206 * @param freenetInterface
207 * The freenet interface
208 * @param identityManager
209 * The identity manager
210 * @param webOfTrustUpdater
211 * The WebOfTrust updater
218 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
220 this.configuration = configuration;
221 this.freenetInterface = freenetInterface;
222 this.identityManager = identityManager;
223 this.soneDownloader = new SoneDownloader(this, freenetInterface);
224 this.imageInserter = new ImageInserter(freenetInterface);
225 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
226 this.webOfTrustUpdater = webOfTrustUpdater;
227 this.eventBus = eventBus;
228 this.database = database;
236 * Returns the time Sone was started.
238 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
240 public long getStartupTime() {
245 * Returns the options used by the core.
247 * @return The options of the core
249 public Preferences getPreferences() {
254 * Returns the identity manager used by the core.
256 * @return The identity manager
258 public IdentityManager getIdentityManager() {
259 return identityManager;
263 * Returns the update checker.
265 * @return The update checker
267 public UpdateChecker getUpdateChecker() {
268 return updateChecker;
272 * Sets the FCP interface to use.
274 * @param fcpInterface
275 * The FCP interface to use
277 public void setFcpInterface(FcpInterface fcpInterface) {
278 this.fcpInterface = fcpInterface;
282 * Returns the Sone rescuer for the given local Sone.
285 * The local Sone to get the rescuer for
286 * @return The Sone rescuer for the given Sone
288 public SoneRescuer getSoneRescuer(Sone sone) {
289 checkNotNull(sone, "sone must not be null");
290 checkArgument(sone.isLocal(), "sone must be local");
291 synchronized (sones) {
292 SoneRescuer soneRescuer = soneRescuers.get(sone);
293 if (soneRescuer == null) {
294 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
295 soneRescuers.put(sone, soneRescuer);
303 * Returns whether the given Sone is currently locked.
307 * @return {@code true} if the Sone is locked, {@code false} if it is not
309 public boolean isLocked(Sone sone) {
310 synchronized (lockedSones) {
311 return lockedSones.contains(sone);
319 public Collection<Sone> getSones() {
320 synchronized (sones) {
321 return ImmutableSet.copyOf(sones.values());
326 * Returns the Sone with the given ID, regardless whether it’s local or
330 * The ID of the Sone to get
331 * @return The Sone with the given ID, or {@code null} if there is no such
335 public Optional<Sone> getSone(String id) {
336 synchronized (sones) {
337 return Optional.fromNullable(sones.get(id));
345 public Collection<Sone> getLocalSones() {
346 synchronized (sones) {
347 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
352 * Returns the local Sone with the given ID, optionally creating a new Sone.
357 * {@code true} to create a new Sone if none exists,
358 * {@code false} to return null if none exists
359 * @return The Sone with the given ID, or {@code null}
361 public Sone getLocalSone(String id, boolean create) {
362 synchronized (sones) {
363 Sone sone = sones.get(id);
364 if ((sone == null) && create) {
365 sone = new SoneImpl(id, true);
368 if ((sone != null) && !sone.isLocal()) {
369 sone = new SoneImpl(id, true);
380 public Collection<Sone> getRemoteSones() {
381 synchronized (sones) {
382 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
387 * Returns the remote Sone with the given ID.
390 * The ID of the remote Sone to get
392 * {@code true} to always create a Sone, {@code false} to return
393 * {@code null} if no Sone with the given ID exists
394 * @return The Sone with the given ID
396 public Sone getRemoteSone(String id, boolean create) {
397 synchronized (sones) {
398 Sone sone = sones.get(id);
399 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
400 sone = new SoneImpl(id, false);
408 * Returns whether the given Sone has been modified.
411 * The Sone to check for modifications
412 * @return {@code true} if a modification has been detected in the Sone,
413 * {@code false} otherwise
415 public boolean isModifiedSone(Sone sone) {
416 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
420 * Returns the time when the given was first followed by any local Sone.
423 * The Sone to get the time for
424 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
425 * been followed, or {@link Long#MAX_VALUE}
427 public long getSoneFollowingTime(Sone sone) {
428 synchronized (soneFollowingTimes) {
429 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
434 * Returns whether the target Sone is trusted by the origin Sone.
440 * @return {@code true} if the target Sone is trusted by the origin Sone
442 public boolean isSoneTrusted(Sone origin, Sone target) {
443 checkNotNull(origin, "origin must not be null");
444 checkNotNull(target, "target must not be null");
445 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
446 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
450 * Returns a post builder.
452 * @return A new post builder
454 public PostBuilder postBuilder() {
455 return database.newPostBuilder();
462 public Optional<Post> getPost(String postId) {
463 return database.getPost(postId);
470 public Collection<Post> getPosts(String soneId) {
471 return database.getPosts(soneId);
478 public Collection<Post> getDirectedPosts(final String recipientId) {
479 checkNotNull(recipientId, "recipient must not be null");
480 return database.getDirectedPosts(recipientId);
484 * Returns a post reply builder.
486 * @return A new post reply builder
488 public PostReplyBuilder postReplyBuilder() {
489 return database.newPostReplyBuilder();
496 public Optional<PostReply> getPostReply(String replyId) {
497 return database.getPostReply(replyId);
504 public List<PostReply> getReplies(final String postId) {
505 return database.getReplies(postId);
509 * Returns all Sones that have liked the given post.
512 * The post to get the liking Sones for
513 * @return The Sones that like the given post
515 public Set<Sone> getLikes(Post post) {
516 Set<Sone> sones = new HashSet<Sone>();
517 for (Sone sone : getSones()) {
518 if (sone.getLikedPostIds().contains(post.getId())) {
526 * Returns all Sones that have liked the given reply.
529 * The reply to get the liking Sones for
530 * @return The Sones that like the given reply
532 public Set<Sone> getLikes(PostReply reply) {
533 Set<Sone> sones = new HashSet<Sone>();
534 for (Sone sone : getSones()) {
535 if (sone.getLikedReplyIds().contains(reply.getId())) {
543 * Returns whether the given post is bookmarked.
547 * @return {@code true} if the given post is bookmarked, {@code false}
550 public boolean isBookmarked(Post post) {
551 return isPostBookmarked(post.getId());
555 * Returns whether the post with the given ID is bookmarked.
558 * The ID of the post to check
559 * @return {@code true} if the post with the given ID is bookmarked,
560 * {@code false} otherwise
562 public boolean isPostBookmarked(String id) {
563 synchronized (bookmarkedPosts) {
564 return bookmarkedPosts.contains(id);
569 * Returns all currently known bookmarked posts.
571 * @return All bookmarked posts
573 public Set<Post> getBookmarkedPosts() {
574 Set<Post> posts = new HashSet<Post>();
575 synchronized (bookmarkedPosts) {
576 for (String bookmarkedPostId : bookmarkedPosts) {
577 Optional<Post> post = getPost(bookmarkedPostId);
578 if (post.isPresent()) {
579 posts.add(post.get());
587 * Returns the album with the given ID, creating a new album if no album
588 * with the given ID can be found.
591 * The ID of the album
592 * @return The album with the given ID
594 public Album getAlbum(String albumId) {
595 return getAlbum(albumId, true);
599 * Returns the album with the given ID, optionally creating a new album if
600 * an album with the given ID can not be found.
603 * The ID of the album
605 * {@code true} to create a new album if none exists for the
607 * @return The album with the given ID, or {@code null} if no album with the
608 * given ID exists and {@code create} is {@code false}
610 public Album getAlbum(String albumId, boolean create) {
611 Optional<Album> album = database.getAlbum(albumId);
612 if (album.isPresent()) {
618 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
619 database.storeAlbum(newAlbum);
624 * Returns the image with the given ID, creating it if necessary.
627 * The ID of the image
628 * @return The image with the given ID
630 public Image getImage(String imageId) {
631 return getImage(imageId, true);
635 * Returns the image with the given ID, optionally creating it if it does
639 * The ID of the image
641 * {@code true} to create an image if none exists with the given
643 * @return The image with the given ID, or {@code null} if none exists and
646 public Image getImage(String imageId, boolean create) {
647 Optional<Image> image = database.getImage(imageId);
648 if (image.isPresent()) {
654 Image newImage = database.newImageBuilder().withId(imageId).build();
655 database.storeImage(newImage);
660 * Returns the temporary image with the given ID.
663 * The ID of the temporary image
664 * @return The temporary image, or {@code null} if there is no temporary
665 * image with the given ID
667 public TemporaryImage getTemporaryImage(String imageId) {
668 synchronized (temporaryImages) {
669 return temporaryImages.get(imageId);
678 * Locks the given Sone. A locked Sone will not be inserted by
679 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
685 public void lockSone(Sone sone) {
686 synchronized (lockedSones) {
687 if (lockedSones.add(sone)) {
688 eventBus.post(new SoneLockedEvent(sone));
694 * Unlocks the given Sone.
696 * @see #lockSone(Sone)
700 public void unlockSone(Sone sone) {
701 synchronized (lockedSones) {
702 if (lockedSones.remove(sone)) {
703 eventBus.post(new SoneUnlockedEvent(sone));
709 * Adds a local Sone from the given own identity.
712 * The own identity to create a Sone from
713 * @return The added (or already existing) Sone
715 public Sone addLocalSone(OwnIdentity ownIdentity) {
716 if (ownIdentity == null) {
717 logger.log(Level.WARNING, "Given OwnIdentity is null!");
720 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
721 synchronized (sones) {
724 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
725 } catch (MalformedURLException mue1) {
726 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
729 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
730 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
732 /* TODO - load posts ’n stuff */
733 sones.put(ownIdentity.getId(), sone);
734 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
735 soneInserters.put(sone, soneInserter);
736 sone.setStatus(SoneStatus.idle);
738 soneInserter.start();
744 * Creates a new Sone for the given own identity.
747 * The own identity to create a Sone for
748 * @return The created Sone
750 public Sone createSone(OwnIdentity ownIdentity) {
751 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
752 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
755 Sone sone = addLocalSone(ownIdentity);
756 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
757 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
758 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
759 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
760 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
761 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
763 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
764 touchConfiguration();
769 * Adds the Sone of the given identity.
772 * The identity whose Sone to add
773 * @return The added or already existing Sone
775 public Sone addRemoteSone(Identity identity) {
776 if (identity == null) {
777 logger.log(Level.WARNING, "Given Identity is null!");
780 synchronized (sones) {
781 final Sone sone = getRemoteSone(identity.getId(), true);
782 if (sone.isLocal()) {
785 sone.setIdentity(identity);
786 boolean newSone = sone.getRequestUri() == null;
787 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
788 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
790 synchronized (knownSones) {
791 newSone = !knownSones.contains(sone.getId());
793 sone.setKnown(!newSone);
795 eventBus.post(new NewSoneFoundEvent(sone));
796 for (Sone localSone : getLocalSones()) {
797 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
798 followSone(localSone, sone.getId());
803 soneDownloader.addSone(sone);
804 soneDownloaders.execute(new Runnable() {
807 @SuppressWarnings("synthetic-access")
809 soneDownloader.fetchSone(sone, sone.getRequestUri());
818 * Lets the given local Sone follow the Sone with the given ID.
821 * The local Sone that should follow another Sone
823 * The ID of the Sone to follow
825 public void followSone(Sone sone, String soneId) {
826 checkNotNull(sone, "sone must not be null");
827 checkNotNull(soneId, "soneId must not be null");
828 sone.addFriend(soneId);
829 synchronized (soneFollowingTimes) {
830 if (!soneFollowingTimes.containsKey(soneId)) {
831 long now = System.currentTimeMillis();
832 soneFollowingTimes.put(soneId, now);
833 Optional<Sone> followedSone = getSone(soneId);
834 if (!followedSone.isPresent()) {
837 for (Post post : followedSone.get().getPosts()) {
838 if (post.getTime() < now) {
842 for (PostReply reply : followedSone.get().getReplies()) {
843 if (reply.getTime() < now) {
844 markReplyKnown(reply);
849 touchConfiguration();
853 * Lets the given local Sone unfollow the Sone with the given ID.
856 * The local Sone that should unfollow another Sone
858 * The ID of the Sone being unfollowed
860 public void unfollowSone(Sone sone, String soneId) {
861 checkNotNull(sone, "sone must not be null");
862 checkNotNull(soneId, "soneId must not be null");
863 sone.removeFriend(soneId);
864 boolean unfollowedSoneStillFollowed = false;
865 for (Sone localSone : getLocalSones()) {
866 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
868 if (!unfollowedSoneStillFollowed) {
869 synchronized (soneFollowingTimes) {
870 soneFollowingTimes.remove(soneId);
873 touchConfiguration();
877 * Sets the trust value of the given origin Sone for the target Sone.
884 * The trust value (from {@code -100} to {@code 100})
886 public void setTrust(Sone origin, Sone target, int trustValue) {
887 checkNotNull(origin, "origin must not be null");
888 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
889 checkNotNull(target, "target must not be null");
890 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
891 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
895 * Removes any trust assignment for the given target Sone.
902 public void removeTrust(Sone origin, Sone target) {
903 checkNotNull(origin, "origin must not be null");
904 checkNotNull(target, "target must not be null");
905 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
906 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
910 * Assigns the configured positive trust value for the given target.
917 public void trustSone(Sone origin, Sone target) {
918 setTrust(origin, target, preferences.getPositiveTrust());
922 * Assigns the configured negative trust value for the given target.
929 public void distrustSone(Sone origin, Sone target) {
930 setTrust(origin, target, preferences.getNegativeTrust());
934 * Removes the trust assignment for the given target.
941 public void untrustSone(Sone origin, Sone target) {
942 removeTrust(origin, target);
946 * Updates the stored Sone with the given Sone.
951 public void updateSone(Sone sone) {
952 updateSone(sone, false);
956 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
957 * {@code true}, an older Sone than the current Sone can be given to restore
962 * @param soneRescueMode
963 * {@code true} if the stored Sone should be updated regardless
964 * of the age of the given Sone
966 public void updateSone(Sone sone, boolean soneRescueMode) {
967 Optional<Sone> storedSone = getSone(sone.getId());
968 if (storedSone.isPresent()) {
969 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
970 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
973 /* find removed posts. */
974 Collection<Post> removedPosts = new ArrayList<Post>();
975 Collection<Post> newPosts = new ArrayList<Post>();
976 Collection<Post> existingPosts = database.getPosts(sone.getId());
977 for (Post oldPost : existingPosts) {
978 if (!sone.getPosts().contains(oldPost)) {
979 removedPosts.add(oldPost);
982 /* find new posts. */
983 for (Post newPost : sone.getPosts()) {
984 if (existingPosts.contains(newPost)) {
987 if (newPost.getTime() < getSoneFollowingTime(sone)) {
988 newPost.setKnown(true);
989 } else if (!newPost.isKnown()) {
990 newPosts.add(newPost);
994 database.storePosts(sone, sone.getPosts());
995 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
996 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
997 if (!soneRescueMode) {
998 for (PostReply reply : storedSone.get().getReplies()) {
999 if (!sone.getReplies().contains(reply)) {
1000 removedPostReplies.add(reply);
1004 Set<PostReply> storedReplies = storedSone.get().getReplies();
1005 for (PostReply reply : sone.getReplies()) {
1006 if (storedReplies.contains(reply)) {
1009 if (reply.getTime() < getSoneFollowingTime(sone)) {
1010 reply.setKnown(true);
1011 } else if (!reply.isKnown()) {
1012 newPostReplies.add(reply);
1015 database.storePostReplies(sone, sone.getReplies());
1016 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1017 database.removeAlbum(album);
1018 for (Image image : album.getImages()) {
1019 database.removeImage(image);
1022 for (Post removedPost : removedPosts) {
1023 eventBus.post(new PostRemovedEvent(removedPost));
1025 for (Post newPost : newPosts) {
1026 eventBus.post(new NewPostFoundEvent(newPost));
1028 for (PostReply removedPostReply : removedPostReplies) {
1029 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1031 for (PostReply newPostReply : newPostReplies) {
1032 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1034 for (Album album : sone.getRootAlbum().getAlbums()) {
1035 database.storeAlbum(album);
1036 for (Image image : album.getImages()) {
1037 database.storeImage(image);
1040 synchronized (sones) {
1041 sone.setOptions(storedSone.get().getOptions());
1042 sone.setKnown(storedSone.get().isKnown());
1043 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1044 if (sone.isLocal()) {
1045 soneInserters.get(storedSone.get()).setSone(sone);
1046 touchConfiguration();
1048 sones.put(sone.getId(), sone);
1054 * Deletes the given Sone. This will remove the Sone from the
1055 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1056 * remove the context from its identity.
1059 * The Sone to delete
1061 public void deleteSone(Sone sone) {
1062 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1063 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1066 synchronized (sones) {
1067 if (!getLocalSones().contains(sone)) {
1068 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1071 sones.remove(sone.getId());
1072 SoneInserter soneInserter = soneInserters.remove(sone);
1073 soneInserter.stop();
1075 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1076 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1078 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1079 } catch (ConfigurationException ce1) {
1080 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1085 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1086 * known} before, a {@link MarkSoneKnownEvent} is fired.
1089 * The Sone to mark as known
1091 public void markSoneKnown(Sone sone) {
1092 if (!sone.isKnown()) {
1093 sone.setKnown(true);
1094 synchronized (knownSones) {
1095 knownSones.add(sone.getId());
1097 eventBus.post(new MarkSoneKnownEvent(sone));
1098 touchConfiguration();
1103 * Loads and updates the given Sone from the configuration. If any error is
1104 * encountered, loading is aborted and the given Sone is not changed.
1107 * The Sone to load and update
1109 public void loadSone(Sone sone) {
1110 if (!sone.isLocal()) {
1111 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1114 logger.info(String.format("Loading local Sone: %s", sone));
1116 /* initialize options. */
1117 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1118 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1119 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1120 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1121 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1122 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1125 String sonePrefix = "Sone/" + sone.getId();
1126 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1127 if (soneTime == null) {
1128 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1131 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1134 Profile profile = new Profile(sone);
1135 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1136 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1137 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1138 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1139 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1140 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1142 /* load profile fields. */
1144 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1145 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1146 if (fieldName == null) {
1149 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1150 profile.addField(fieldName).setValue(fieldValue);
1154 Set<Post> posts = new HashSet<Post>();
1156 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1157 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1158 if (postId == null) {
1161 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1162 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1163 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1164 if ((postTime == 0) || (postText == null)) {
1165 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1168 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1169 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1170 postBuilder.to(postRecipientId);
1172 posts.add(postBuilder.build());
1176 Set<PostReply> replies = new HashSet<PostReply>();
1178 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1179 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1180 if (replyId == null) {
1183 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1184 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1185 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1186 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1187 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1190 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1191 replies.add(postReplyBuilder.build());
1194 /* load post likes. */
1195 Set<String> likedPostIds = new HashSet<String>();
1197 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1198 if (likedPostId == null) {
1201 likedPostIds.add(likedPostId);
1204 /* load reply likes. */
1205 Set<String> likedReplyIds = new HashSet<String>();
1207 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1208 if (likedReplyId == null) {
1211 likedReplyIds.add(likedReplyId);
1215 Set<String> friends = new HashSet<String>();
1217 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1218 if (friendId == null) {
1221 friends.add(friendId);
1225 List<Album> topLevelAlbums = new ArrayList<Album>();
1226 int albumCounter = 0;
1228 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1229 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1230 if (albumId == null) {
1233 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1234 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1235 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1236 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1237 if ((albumTitle == null) || (albumDescription == null)) {
1238 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1241 Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1242 if (albumParentId != null) {
1243 Album parentAlbum = getAlbum(albumParentId, false);
1244 if (parentAlbum == null) {
1245 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1248 parentAlbum.addAlbum(album);
1250 if (!topLevelAlbums.contains(album)) {
1251 topLevelAlbums.add(album);
1257 int imageCounter = 0;
1259 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1260 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1261 if (imageId == null) {
1264 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1265 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1266 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1267 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1268 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1269 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1270 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1271 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1272 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1275 Album album = getAlbum(albumId, false);
1276 if (album == null) {
1277 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1280 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1281 album.addImage(image);
1285 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1286 if (avatarId != null) {
1287 profile.setAvatar(getImage(avatarId, false));
1291 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1292 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1293 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1294 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1295 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1296 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1298 /* if we’re still here, Sone was loaded successfully. */
1299 synchronized (sone) {
1300 sone.setTime(soneTime);
1301 sone.setProfile(profile);
1302 sone.setPosts(posts);
1303 sone.setReplies(replies);
1304 sone.setLikePostIds(likedPostIds);
1305 sone.setLikeReplyIds(likedReplyIds);
1306 for (String friendId : friends) {
1307 followSone(sone, friendId);
1309 for (Album album : sone.getRootAlbum().getAlbums()) {
1310 sone.getRootAlbum().removeAlbum(album);
1312 for (Album album : topLevelAlbums) {
1313 sone.getRootAlbum().addAlbum(album);
1315 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1317 synchronized (knownSones) {
1318 for (String friend : friends) {
1319 knownSones.add(friend);
1322 database.storePosts(sone, posts);
1323 for (Post post : posts) {
1324 post.setKnown(true);
1326 database.storePostReplies(sone, replies);
1327 for (PostReply reply : replies) {
1328 reply.setKnown(true);
1331 logger.info(String.format("Sone loaded successfully: %s", sone));
1335 * Creates a new post.
1338 * The Sone that creates the post
1340 * The text of the post
1341 * @return The created post
1343 public Post createPost(Sone sone, String text) {
1344 return createPost(sone, System.currentTimeMillis(), text);
1348 * Creates a new post.
1351 * The Sone that creates the post
1353 * The time of the post
1355 * The text of the post
1356 * @return The created post
1358 public Post createPost(Sone sone, long time, String text) {
1359 return createPost(sone, null, time, text);
1363 * Creates a new post.
1366 * The Sone that creates the post
1368 * The recipient Sone, or {@code null} if this post does not have
1371 * The text of the post
1372 * @return The created post
1374 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1375 return createPost(sone, recipient, System.currentTimeMillis(), text);
1379 * Creates a new post.
1382 * The Sone that creates the post
1384 * The recipient Sone, or {@code null} if this post does not have
1387 * The time of the post
1389 * The text of the post
1390 * @return The created post
1392 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1393 checkNotNull(text, "text must not be null");
1394 checkArgument(text.trim().length() > 0, "text must not be empty");
1395 if (!sone.isLocal()) {
1396 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1399 PostBuilder postBuilder = database.newPostBuilder();
1400 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1401 if (recipient.isPresent()) {
1402 postBuilder.to(recipient.get().getId());
1404 final Post post = postBuilder.build();
1405 database.storePost(post);
1406 eventBus.post(new NewPostFoundEvent(post));
1408 touchConfiguration();
1409 localElementTicker.schedule(new Runnable() {
1416 markPostKnown(post);
1418 }, 10, TimeUnit.SECONDS);
1423 * Deletes the given post.
1426 * The post to delete
1428 public void deletePost(Post post) {
1429 if (!post.getSone().isLocal()) {
1430 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1433 database.removePost(post);
1434 eventBus.post(new PostRemovedEvent(post));
1435 markPostKnown(post);
1436 touchConfiguration();
1440 * Marks the given post as known, if it is currently not a known post
1441 * (according to {@link Post#isKnown()}).
1444 * The post to mark as known
1446 public void markPostKnown(Post post) {
1447 post.setKnown(true);
1448 eventBus.post(new MarkPostKnownEvent(post));
1449 touchConfiguration();
1450 for (PostReply reply : getReplies(post.getId())) {
1451 markReplyKnown(reply);
1456 * Bookmarks the given post.
1459 * The post to bookmark
1461 public void bookmark(Post post) {
1462 bookmarkPost(post.getId());
1466 * Bookmarks the post with the given ID.
1469 * The ID of the post to bookmark
1471 public void bookmarkPost(String id) {
1472 synchronized (bookmarkedPosts) {
1473 bookmarkedPosts.add(id);
1478 * Removes the given post from the bookmarks.
1481 * The post to unbookmark
1483 public void unbookmark(Post post) {
1484 unbookmarkPost(post.getId());
1488 * Removes the post with the given ID from the bookmarks.
1491 * The ID of the post to unbookmark
1493 public void unbookmarkPost(String id) {
1494 synchronized (bookmarkedPosts) {
1495 bookmarkedPosts.remove(id);
1500 * Creates a new reply.
1503 * The Sone that creates the reply
1505 * The post that this reply refers to
1507 * The text of the reply
1508 * @return The created reply
1510 public PostReply createReply(Sone sone, Post post, String text) {
1511 checkNotNull(text, "text must not be null");
1512 checkArgument(text.trim().length() > 0, "text must not be empty");
1513 if (!sone.isLocal()) {
1514 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1517 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1518 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1519 final PostReply reply = postReplyBuilder.build();
1520 database.storePostReply(reply);
1521 eventBus.post(new NewPostReplyFoundEvent(reply));
1522 sone.addReply(reply);
1523 touchConfiguration();
1524 localElementTicker.schedule(new Runnable() {
1531 markReplyKnown(reply);
1533 }, 10, TimeUnit.SECONDS);
1538 * Deletes the given reply.
1541 * The reply to delete
1543 public void deleteReply(PostReply reply) {
1544 Sone sone = reply.getSone();
1545 if (!sone.isLocal()) {
1546 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1549 database.removePostReply(reply);
1550 markReplyKnown(reply);
1551 sone.removeReply(reply);
1552 touchConfiguration();
1556 * Marks the given reply as known, if it is currently not a known reply
1557 * (according to {@link Reply#isKnown()}).
1560 * The reply to mark as known
1562 public void markReplyKnown(PostReply reply) {
1563 boolean previouslyKnown = reply.isKnown();
1564 reply.setKnown(true);
1565 eventBus.post(new MarkPostReplyKnownEvent(reply));
1566 if (!previouslyKnown) {
1567 touchConfiguration();
1572 * Creates a new top-level album for the given Sone.
1575 * The Sone to create the album for
1576 * @return The new album
1578 public Album createAlbum(Sone sone) {
1579 return createAlbum(sone, sone.getRootAlbum());
1583 * Creates a new album for the given Sone.
1586 * The Sone to create the album for
1588 * The parent of the album (may be {@code null} to create a
1590 * @return The new album
1592 public Album createAlbum(Sone sone, Album parent) {
1593 Album album = database.newAlbumBuilder().randomId().build();
1594 database.storeAlbum(album);
1595 album.setSone(sone);
1596 parent.addAlbum(album);
1601 * Deletes the given album. The owner of the album has to be a local Sone,
1602 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1605 * The album to remove
1607 public void deleteAlbum(Album album) {
1608 checkNotNull(album, "album must not be null");
1609 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1610 if (!album.isEmpty()) {
1613 album.getParent().removeAlbum(album);
1614 database.removeAlbum(album);
1615 touchConfiguration();
1619 * Creates a new image.
1622 * The Sone creating the image
1624 * The album the image will be inserted into
1625 * @param temporaryImage
1626 * The temporary image to create the image from
1627 * @return The newly created image
1629 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1630 checkNotNull(sone, "sone must not be null");
1631 checkNotNull(album, "album must not be null");
1632 checkNotNull(temporaryImage, "temporaryImage must not be null");
1633 checkArgument(sone.isLocal(), "sone must be a local Sone");
1634 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1635 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1636 album.addImage(image);
1637 database.storeImage(image);
1638 imageInserter.insertImage(temporaryImage, image);
1643 * Deletes the given image. This method will also delete a matching
1646 * @see #deleteTemporaryImage(TemporaryImage)
1648 * The image to delete
1650 public void deleteImage(Image image) {
1651 checkNotNull(image, "image must not be null");
1652 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1653 deleteTemporaryImage(image.getId());
1654 image.getAlbum().removeImage(image);
1655 database.removeImage(image);
1656 touchConfiguration();
1660 * Creates a new temporary image.
1663 * The MIME type of the temporary image
1665 * The encoded data of the image
1666 * @return The temporary image
1668 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1669 TemporaryImage temporaryImage = new TemporaryImage();
1670 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1671 synchronized (temporaryImages) {
1672 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1674 return temporaryImage;
1678 * Deletes the given temporary image.
1680 * @param temporaryImage
1681 * The temporary image to delete
1683 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1684 checkNotNull(temporaryImage, "temporaryImage must not be null");
1685 deleteTemporaryImage(temporaryImage.getId());
1689 * Deletes the temporary image with the given ID.
1692 * The ID of the temporary image to delete
1694 public void deleteTemporaryImage(String imageId) {
1695 checkNotNull(imageId, "imageId must not be null");
1696 synchronized (temporaryImages) {
1697 temporaryImages.remove(imageId);
1699 Image image = getImage(imageId, false);
1700 if (image != null) {
1701 imageInserter.cancelImageInsert(image);
1706 * Notifies the core that the configuration, either of the core or of a
1707 * single local Sone, has changed, and that the configuration should be
1710 public void touchConfiguration() {
1711 lastConfigurationUpdate = System.currentTimeMillis();
1722 public void serviceStart() {
1723 loadConfiguration();
1724 updateChecker.start();
1725 identityManager.start();
1726 webOfTrustUpdater.init();
1727 webOfTrustUpdater.start();
1735 public void serviceRun() {
1736 long lastSaved = System.currentTimeMillis();
1737 while (!shouldStop()) {
1739 long now = System.currentTimeMillis();
1740 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1741 for (Sone localSone : getLocalSones()) {
1742 saveSone(localSone);
1744 saveConfiguration();
1754 public void serviceStop() {
1755 localElementTicker.shutdownNow();
1756 synchronized (sones) {
1757 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1758 soneInserter.getValue().stop();
1759 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1762 saveConfiguration();
1764 webOfTrustUpdater.stop();
1765 updateChecker.stop();
1766 soneDownloader.stop();
1767 soneDownloaders.shutdown();
1768 identityManager.stop();
1776 * Saves the given Sone. This will persist all local settings for the given
1777 * Sone, such as the friends list and similar, private options.
1782 private synchronized void saveSone(Sone sone) {
1783 if (!sone.isLocal()) {
1784 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1787 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1788 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1792 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1794 /* save Sone into configuration. */
1795 String sonePrefix = "Sone/" + sone.getId();
1796 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1797 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1800 Profile profile = sone.getProfile();
1801 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1802 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1803 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1804 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1805 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1806 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1807 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1809 /* save profile fields. */
1810 int fieldCounter = 0;
1811 for (Field profileField : profile.getFields()) {
1812 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1813 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1814 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1816 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1819 int postCounter = 0;
1820 for (Post post : sone.getPosts()) {
1821 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1822 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1823 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1824 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1825 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1827 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1830 int replyCounter = 0;
1831 for (PostReply reply : sone.getReplies()) {
1832 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1833 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1834 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1835 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1836 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1838 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1840 /* save post likes. */
1841 int postLikeCounter = 0;
1842 for (String postId : sone.getLikedPostIds()) {
1843 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1845 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1847 /* save reply likes. */
1848 int replyLikeCounter = 0;
1849 for (String replyId : sone.getLikedReplyIds()) {
1850 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1852 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1855 int friendCounter = 0;
1856 for (String friendId : sone.getFriends()) {
1857 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1859 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1861 /* save albums. first, collect in a flat structure, top-level first. */
1862 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1864 int albumCounter = 0;
1865 for (Album album : albums) {
1866 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1867 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1868 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1869 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1870 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1871 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1873 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1876 int imageCounter = 0;
1877 for (Album album : albums) {
1878 for (Image image : album.getImages()) {
1879 if (!image.isInserted()) {
1882 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1883 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1884 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1885 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1886 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1887 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1888 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1889 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1890 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1893 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1896 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1897 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1898 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1899 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1900 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1901 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1903 configuration.save();
1905 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1907 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1908 } catch (ConfigurationException ce1) {
1909 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1914 * Saves the current options.
1916 private void saveConfiguration() {
1917 synchronized (configuration) {
1918 if (storingConfiguration) {
1919 logger.log(Level.FINE, "Already storing configuration…");
1922 storingConfiguration = true;
1925 /* store the options first. */
1927 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1928 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1929 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1930 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1931 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1932 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1933 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1934 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1935 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1936 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1937 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1938 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1940 /* save known Sones. */
1941 int soneCounter = 0;
1942 synchronized (knownSones) {
1943 for (String knownSoneId : knownSones) {
1944 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1946 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1949 /* save Sone following times. */
1951 synchronized (soneFollowingTimes) {
1952 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1953 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1954 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1957 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1960 /* save known posts. */
1963 /* save bookmarked posts. */
1964 int bookmarkedPostCounter = 0;
1965 synchronized (bookmarkedPosts) {
1966 for (String bookmarkedPostId : bookmarkedPosts) {
1967 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1970 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1973 configuration.save();
1975 } catch (ConfigurationException ce1) {
1976 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1977 } catch (DatabaseException de1) {
1978 logger.log(Level.SEVERE, "Could not save database!", de1);
1980 synchronized (configuration) {
1981 storingConfiguration = false;
1987 * Loads the configuration.
1989 private void loadConfiguration() {
1990 /* create options. */
1991 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
1994 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
1995 SoneInserter.setInsertionDelay(newValue);
1999 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2000 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2001 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2002 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2003 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2004 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2005 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2006 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2007 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2010 @SuppressWarnings("synthetic-access")
2011 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2012 fcpInterface.setActive(newValue);
2015 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2018 @SuppressWarnings("synthetic-access")
2019 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2020 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2025 loadConfigurationValue("InsertionDelay");
2026 loadConfigurationValue("PostsPerPage");
2027 loadConfigurationValue("ImagesPerPage");
2028 loadConfigurationValue("CharactersPerPost");
2029 loadConfigurationValue("PostCutOffLength");
2030 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2031 loadConfigurationValue("PositiveTrust");
2032 loadConfigurationValue("NegativeTrust");
2033 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2034 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2035 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2037 /* load known Sones. */
2038 int soneCounter = 0;
2040 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2041 if (knownSoneId == null) {
2044 synchronized (knownSones) {
2045 knownSones.add(knownSoneId);
2049 /* load Sone following times. */
2052 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2053 if (soneId == null) {
2056 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2057 synchronized (soneFollowingTimes) {
2058 soneFollowingTimes.put(soneId, time);
2063 /* load bookmarked posts. */
2064 int bookmarkedPostCounter = 0;
2066 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2067 if (bookmarkedPostId == null) {
2070 synchronized (bookmarkedPosts) {
2071 bookmarkedPosts.add(bookmarkedPostId);
2078 * Loads an {@link Integer} configuration value for the option with the
2079 * given name, logging validation failures.
2082 * The name of the option to load
2084 private void loadConfigurationValue(String optionName) {
2086 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2087 } catch (IllegalArgumentException iae1) {
2088 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2093 * Notifies the core that a new {@link OwnIdentity} was added.
2095 * @param ownIdentityAddedEvent
2099 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2100 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2101 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2102 if (ownIdentity.hasContext("Sone")) {
2103 addLocalSone(ownIdentity);
2108 * Notifies the core that an {@link OwnIdentity} was removed.
2110 * @param ownIdentityRemovedEvent
2114 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2115 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2116 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2117 trustedIdentities.removeAll(ownIdentity);
2121 * Notifies the core that a new {@link Identity} was added.
2123 * @param identityAddedEvent
2127 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2128 Identity identity = identityAddedEvent.identity();
2129 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2130 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2131 addRemoteSone(identity);
2135 * Notifies the core that an {@link Identity} was updated.
2137 * @param identityUpdatedEvent
2141 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2142 final Identity identity = identityUpdatedEvent.identity();
2143 soneDownloaders.execute(new Runnable() {
2146 @SuppressWarnings("synthetic-access")
2148 Sone sone = getRemoteSone(identity.getId(), false);
2149 if (sone.isLocal()) {
2152 sone.setIdentity(identity);
2153 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2154 soneDownloader.addSone(sone);
2155 soneDownloader.fetchSone(sone);
2161 * Notifies the core that an {@link Identity} was removed.
2163 * @param identityRemovedEvent
2167 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2168 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2169 Identity identity = identityRemovedEvent.identity();
2170 trustedIdentities.remove(ownIdentity, identity);
2171 boolean foundIdentity = false;
2172 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2173 if (trustedIdentity.getKey().equals(ownIdentity)) {
2176 if (trustedIdentity.getValue().contains(identity)) {
2177 foundIdentity = true;
2180 if (foundIdentity) {
2181 /* some local identity still trusts this identity, don’t remove. */
2184 Optional<Sone> sone = getSone(identity.getId());
2185 if (!sone.isPresent()) {
2186 /* TODO - we don’t have the Sone anymore. should this happen? */
2189 database.removePosts(sone.get());
2190 for (Post post : sone.get().getPosts()) {
2191 eventBus.post(new PostRemovedEvent(post));
2193 database.removePostReplies(sone.get());
2194 for (PostReply reply : sone.get().getReplies()) {
2195 eventBus.post(new PostReplyRemovedEvent(reply));
2197 synchronized (sones) {
2198 sones.remove(identity.getId());
2200 eventBus.post(new SoneRemovedEvent(sone.get()));
2204 * Deletes the temporary image.
2206 * @param imageInsertFinishedEvent
2210 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2211 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2212 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2213 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2214 touchConfiguration();