2 * Sone - Core.java - Copyright © 2010–2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.core;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
39 import net.pterodactylus.sone.core.Options.DefaultOption;
40 import net.pterodactylus.sone.core.Options.Option;
41 import net.pterodactylus.sone.core.Options.OptionWatcher;
42 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
43 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
46 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
47 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
48 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
49 import net.pterodactylus.sone.core.event.PostRemovedEvent;
50 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneLockedEvent;
52 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.PostBuilder;
69 import net.pterodactylus.sone.database.PostProvider;
70 import net.pterodactylus.sone.database.PostReplyBuilder;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneProvider;
73 import net.pterodactylus.sone.fcp.FcpInterface;
74 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
75 import net.pterodactylus.sone.freenet.wot.Identity;
76 import net.pterodactylus.sone.freenet.wot.IdentityManager;
77 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
83 import net.pterodactylus.sone.main.SonePlugin;
84 import net.pterodactylus.sone.utils.IntegerRangePredicate;
85 import net.pterodactylus.util.config.Configuration;
86 import net.pterodactylus.util.config.ConfigurationException;
87 import net.pterodactylus.util.logging.Logging;
88 import net.pterodactylus.util.number.Numbers;
89 import net.pterodactylus.util.service.AbstractService;
90 import net.pterodactylus.util.thread.NamedThreadFactory;
92 import com.google.common.base.Optional;
93 import com.google.common.base.Predicate;
94 import com.google.common.base.Predicates;
95 import com.google.common.collect.Collections2;
96 import com.google.common.collect.FluentIterable;
97 import com.google.common.collect.HashMultimap;
98 import com.google.common.collect.ImmutableSet;
99 import com.google.common.collect.Multimap;
100 import com.google.common.collect.Multimaps;
101 import com.google.common.eventbus.EventBus;
102 import com.google.common.eventbus.Subscribe;
103 import com.google.inject.Inject;
105 import freenet.keys.FreenetURI;
110 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
112 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
115 private static final Logger logger = Logging.getLogger(Core.class);
117 /** The start time. */
118 private final long startupTime = System.currentTimeMillis();
121 private final Options options = new Options();
123 /** The preferences. */
124 private final Preferences preferences = new Preferences(options);
126 /** The event bus. */
127 private final EventBus eventBus;
129 /** The configuration. */
130 private Configuration configuration;
132 /** Whether we’re currently saving the configuration. */
133 private boolean storingConfiguration = false;
135 /** The identity manager. */
136 private final IdentityManager identityManager;
138 /** Interface to freenet. */
139 private final FreenetInterface freenetInterface;
141 /** The Sone downloader. */
142 private final SoneDownloader soneDownloader;
144 /** The image inserter. */
145 private final ImageInserter imageInserter;
147 /** Sone downloader thread-pool. */
148 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
150 /** The update checker. */
151 private final UpdateChecker updateChecker;
153 /** The trust updater. */
154 private final WebOfTrustUpdater webOfTrustUpdater;
156 /** The FCP interface. */
157 private volatile FcpInterface fcpInterface;
159 /** The times Sones were followed. */
160 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
162 /** Locked local Sones. */
163 /* synchronize on itself. */
164 private final Set<Sone> lockedSones = new HashSet<Sone>();
166 /** Sone inserters. */
167 /* synchronize access on this on sones. */
168 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
170 /** Sone rescuers. */
171 /* synchronize access on this on sones. */
172 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
175 /* synchronize access on this on itself. */
176 private final Map<String, Sone> sones = new HashMap<String, Sone>();
178 /** All known Sones. */
179 private final Set<String> knownSones = new HashSet<String>();
181 /** The post database. */
182 private final Database database;
184 /** All bookmarked posts. */
185 /* synchronize access on itself. */
186 private final Set<String> bookmarkedPosts = new HashSet<String>();
188 /** Trusted identities, sorted by own identities. */
189 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
191 /** All known albums. */
192 private final Map<String, Album> albums = new HashMap<String, Album>();
194 /** All known images. */
195 private final Map<String, Image> images = new HashMap<String, Image>();
197 /** All temporary images. */
198 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
200 /** Ticker for threads that mark own elements as known. */
201 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
203 /** The time the configuration was last touched. */
204 private volatile long lastConfigurationUpdate;
207 * Creates a new core.
209 * @param configuration
210 * The configuration of the core
211 * @param freenetInterface
212 * The freenet interface
213 * @param identityManager
214 * The identity manager
215 * @param webOfTrustUpdater
216 * The WebOfTrust updater
223 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
225 this.configuration = configuration;
226 this.freenetInterface = freenetInterface;
227 this.identityManager = identityManager;
228 this.soneDownloader = new SoneDownloader(this, freenetInterface);
229 this.imageInserter = new ImageInserter(freenetInterface);
230 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
231 this.webOfTrustUpdater = webOfTrustUpdater;
232 this.eventBus = eventBus;
233 this.database = database;
241 * Returns the time Sone was started.
243 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
245 public long getStartupTime() {
250 * Sets the configuration to use. This will automatically save the current
251 * configuration to the given configuration.
253 * @param configuration
254 * The new configuration to use
256 public void setConfiguration(Configuration configuration) {
257 this.configuration = configuration;
258 touchConfiguration();
262 * Returns the options used by the core.
264 * @return The options of the core
266 public Preferences getPreferences() {
271 * Returns the identity manager used by the core.
273 * @return The identity manager
275 public IdentityManager getIdentityManager() {
276 return identityManager;
280 * Returns the update checker.
282 * @return The update checker
284 public UpdateChecker getUpdateChecker() {
285 return updateChecker;
289 * Sets the FCP interface to use.
291 * @param fcpInterface
292 * The FCP interface to use
294 public void setFcpInterface(FcpInterface fcpInterface) {
295 this.fcpInterface = fcpInterface;
299 * Returns the Sone rescuer for the given local Sone.
302 * The local Sone to get the rescuer for
303 * @return The Sone rescuer for the given Sone
305 public SoneRescuer getSoneRescuer(Sone sone) {
306 checkNotNull(sone, "sone must not be null");
307 checkArgument(sone.isLocal(), "sone must be local");
308 synchronized (sones) {
309 SoneRescuer soneRescuer = soneRescuers.get(sone);
310 if (soneRescuer == null) {
311 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
312 soneRescuers.put(sone, soneRescuer);
320 * Returns whether the given Sone is currently locked.
324 * @return {@code true} if the Sone is locked, {@code false} if it is not
326 public boolean isLocked(Sone sone) {
327 synchronized (lockedSones) {
328 return lockedSones.contains(sone);
336 public Collection<Sone> getSones() {
337 synchronized (sones) {
338 return Collections.unmodifiableCollection(sones.values());
343 * Returns the Sone with the given ID, regardless whether it’s local or
347 * The ID of the Sone to get
348 * @return The Sone with the given ID, or {@code null} if there is no such
352 public Optional<Sone> getSone(String id) {
353 synchronized (sones) {
354 return Optional.fromNullable(sones.get(id));
362 public Collection<Sone> getLocalSones() {
363 synchronized (sones) {
364 return Collections2.filter(sones.values(), new Predicate<Sone>() {
367 public boolean apply(Sone sone) {
368 return sone.isLocal();
375 * Returns the local Sone with the given ID, optionally creating a new Sone.
380 * {@code true} to create a new Sone if none exists,
381 * {@code false} to return null if none exists
382 * @return The Sone with the given ID, or {@code null}
384 public Sone getLocalSone(String id, boolean create) {
385 synchronized (sones) {
386 Sone sone = sones.get(id);
387 if ((sone == null) && create) {
388 sone = new Sone(id, true);
391 if ((sone != null) && !sone.isLocal()) {
392 sone = new Sone(id, true);
403 public Collection<Sone> getRemoteSones() {
404 synchronized (sones) {
405 return Collections2.filter(sones.values(), new Predicate<Sone>() {
408 public boolean apply(Sone sone) {
409 return !sone.isLocal();
416 * Returns the remote Sone with the given ID.
419 * The ID of the remote Sone to get
421 * {@code true} to always create a Sone, {@code false} to return
422 * {@code null} if no Sone with the given ID exists
423 * @return The Sone with the given ID
425 public Sone getRemoteSone(String id, boolean create) {
426 synchronized (sones) {
427 Sone sone = sones.get(id);
428 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
429 sone = new Sone(id, false);
437 * Returns whether the given Sone has been modified.
440 * The Sone to check for modifications
441 * @return {@code true} if a modification has been detected in the Sone,
442 * {@code false} otherwise
444 public boolean isModifiedSone(Sone sone) {
445 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
449 * Returns the time when the given was first followed by any local Sone.
452 * The Sone to get the time for
453 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
454 * been followed, or {@link Long#MAX_VALUE}
456 public long getSoneFollowingTime(Sone sone) {
457 synchronized (soneFollowingTimes) {
458 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
463 * Returns whether the target Sone is trusted by the origin Sone.
469 * @return {@code true} if the target Sone is trusted by the origin Sone
471 public boolean isSoneTrusted(Sone origin, Sone target) {
472 checkNotNull(origin, "origin must not be null");
473 checkNotNull(target, "target must not be null");
474 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
475 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
479 * Returns a post builder.
481 * @return A new post builder
483 public PostBuilder postBuilder() {
484 return database.newPostBuilder();
491 public Optional<Post> getPost(String postId) {
492 return database.getPost(postId);
499 public Collection<Post> getPosts(String soneId) {
500 return database.getPosts(soneId);
507 public Collection<Post> getDirectedPosts(final String recipientId) {
508 checkNotNull(recipientId, "recipient must not be null");
509 return database.getDirectedPosts(recipientId);
513 * Returns a post reply builder.
515 * @return A new post reply builder
517 public PostReplyBuilder postReplyBuilder() {
518 return database.newPostReplyBuilder();
525 public Optional<PostReply> getPostReply(String replyId) {
526 return database.getPostReply(replyId);
533 public List<PostReply> getReplies(final String postId) {
534 return database.getReplies(postId);
538 * Returns all Sones that have liked the given post.
541 * The post to get the liking Sones for
542 * @return The Sones that like the given post
544 public Set<Sone> getLikes(Post post) {
545 Set<Sone> sones = new HashSet<Sone>();
546 for (Sone sone : getSones()) {
547 if (sone.getLikedPostIds().contains(post.getId())) {
555 * Returns all Sones that have liked the given reply.
558 * The reply to get the liking Sones for
559 * @return The Sones that like the given reply
561 public Set<Sone> getLikes(PostReply reply) {
562 Set<Sone> sones = new HashSet<Sone>();
563 for (Sone sone : getSones()) {
564 if (sone.getLikedReplyIds().contains(reply.getId())) {
572 * Returns whether the given post is bookmarked.
576 * @return {@code true} if the given post is bookmarked, {@code false}
579 public boolean isBookmarked(Post post) {
580 return isPostBookmarked(post.getId());
584 * Returns whether the post with the given ID is bookmarked.
587 * The ID of the post to check
588 * @return {@code true} if the post with the given ID is bookmarked,
589 * {@code false} otherwise
591 public boolean isPostBookmarked(String id) {
592 synchronized (bookmarkedPosts) {
593 return bookmarkedPosts.contains(id);
598 * Returns all currently known bookmarked posts.
600 * @return All bookmarked posts
602 public Set<Post> getBookmarkedPosts() {
603 Set<Post> posts = new HashSet<Post>();
604 synchronized (bookmarkedPosts) {
605 for (String bookmarkedPostId : bookmarkedPosts) {
606 Optional<Post> post = getPost(bookmarkedPostId);
607 if (!post.isPresent()) {
608 posts.add(post.get());
616 * Returns the album with the given ID, creating a new album if no album
617 * with the given ID can be found.
620 * The ID of the album
621 * @return The album with the given ID
623 public Album getAlbum(String albumId) {
624 return getAlbum(albumId, true);
628 * Returns the album with the given ID, optionally creating a new album if
629 * an album with the given ID can not be found.
632 * The ID of the album
634 * {@code true} to create a new album if none exists for the
636 * @return The album with the given ID, or {@code null} if no album with the
637 * given ID exists and {@code create} is {@code false}
639 public Album getAlbum(String albumId, boolean create) {
640 synchronized (albums) {
641 Album album = albums.get(albumId);
642 if (create && (album == null)) {
643 album = new Album(albumId);
644 albums.put(albumId, album);
651 * Returns the image with the given ID, creating it if necessary.
654 * The ID of the image
655 * @return The image with the given ID
657 public Image getImage(String imageId) {
658 return getImage(imageId, true);
662 * Returns the image with the given ID, optionally creating it if it does
666 * The ID of the image
668 * {@code true} to create an image if none exists with the given
670 * @return The image with the given ID, or {@code null} if none exists and
673 public Image getImage(String imageId, boolean create) {
674 synchronized (images) {
675 Image image = images.get(imageId);
676 if (create && (image == null)) {
677 image = new Image(imageId);
678 images.put(imageId, image);
685 * Returns the temporary image with the given ID.
688 * The ID of the temporary image
689 * @return The temporary image, or {@code null} if there is no temporary
690 * image with the given ID
692 public TemporaryImage getTemporaryImage(String imageId) {
693 synchronized (temporaryImages) {
694 return temporaryImages.get(imageId);
703 * Locks the given Sone. A locked Sone will not be inserted by
704 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
710 public void lockSone(Sone sone) {
711 synchronized (lockedSones) {
712 if (lockedSones.add(sone)) {
713 eventBus.post(new SoneLockedEvent(sone));
719 * Unlocks the given Sone.
721 * @see #lockSone(Sone)
725 public void unlockSone(Sone sone) {
726 synchronized (lockedSones) {
727 if (lockedSones.remove(sone)) {
728 eventBus.post(new SoneUnlockedEvent(sone));
734 * Adds a local Sone from the given own identity.
737 * The own identity to create a Sone from
738 * @return The added (or already existing) Sone
740 public Sone addLocalSone(OwnIdentity ownIdentity) {
741 if (ownIdentity == null) {
742 logger.log(Level.WARNING, "Given OwnIdentity is null!");
745 synchronized (sones) {
748 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
749 } catch (MalformedURLException mue1) {
750 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
753 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
754 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
756 /* TODO - load posts ’n stuff */
757 sones.put(ownIdentity.getId(), sone);
758 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
759 soneInserters.put(sone, soneInserter);
760 sone.setStatus(SoneStatus.idle);
762 soneInserter.start();
768 * Creates a new Sone for the given own identity.
771 * The own identity to create a Sone for
772 * @return The created Sone
774 public Sone createSone(OwnIdentity ownIdentity) {
775 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
776 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
779 Sone sone = addLocalSone(ownIdentity);
780 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
781 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
782 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
783 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
784 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
785 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
787 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
788 touchConfiguration();
793 * Adds the Sone of the given identity.
796 * The identity whose Sone to add
797 * @return The added or already existing Sone
799 public Sone addRemoteSone(Identity identity) {
800 if (identity == null) {
801 logger.log(Level.WARNING, "Given Identity is null!");
804 synchronized (sones) {
805 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
806 boolean newSone = sone.getRequestUri() == null;
807 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
808 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
810 synchronized (knownSones) {
811 newSone = !knownSones.contains(sone.getId());
813 sone.setKnown(!newSone);
815 eventBus.post(new NewSoneFoundEvent(sone));
816 for (Sone localSone : getLocalSones()) {
817 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
818 followSone(localSone, sone.getId());
823 soneDownloader.addSone(sone);
824 soneDownloaders.execute(new Runnable() {
827 @SuppressWarnings("synthetic-access")
829 soneDownloader.fetchSone(sone, sone.getRequestUri());
838 * Lets the given local Sone follow the Sone with the given ID.
841 * The local Sone that should follow another Sone
843 * The ID of the Sone to follow
845 public void followSone(Sone sone, String soneId) {
846 checkNotNull(sone, "sone must not be null");
847 checkNotNull(soneId, "soneId must not be null");
848 sone.addFriend(soneId);
849 synchronized (soneFollowingTimes) {
850 if (!soneFollowingTimes.containsKey(soneId)) {
851 long now = System.currentTimeMillis();
852 soneFollowingTimes.put(soneId, now);
853 Optional<Sone> followedSone = getSone(soneId);
854 if (!followedSone.isPresent()) {
857 for (Post post : followedSone.get().getPosts()) {
858 if (post.getTime() < now) {
862 for (PostReply reply : followedSone.get().getReplies()) {
863 if (reply.getTime() < now) {
864 markReplyKnown(reply);
869 touchConfiguration();
873 * Lets the given local Sone unfollow the Sone with the given ID.
876 * The local Sone that should unfollow another Sone
878 * The ID of the Sone being unfollowed
880 public void unfollowSone(Sone sone, String soneId) {
881 checkNotNull(sone, "sone must not be null");
882 checkNotNull(soneId, "soneId must not be null");
883 sone.removeFriend(soneId);
884 boolean unfollowedSoneStillFollowed = false;
885 for (Sone localSone : getLocalSones()) {
886 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
888 if (!unfollowedSoneStillFollowed) {
889 synchronized (soneFollowingTimes) {
890 soneFollowingTimes.remove(soneId);
893 touchConfiguration();
897 * Sets the trust value of the given origin Sone for the target Sone.
904 * The trust value (from {@code -100} to {@code 100})
906 public void setTrust(Sone origin, Sone target, int trustValue) {
907 checkNotNull(origin, "origin must not be null");
908 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
909 checkNotNull(target, "target must not be null");
910 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
911 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
915 * Removes any trust assignment for the given target Sone.
922 public void removeTrust(Sone origin, Sone target) {
923 checkNotNull(origin, "origin must not be null");
924 checkNotNull(target, "target must not be null");
925 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
926 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
930 * Assigns the configured positive trust value for the given target.
937 public void trustSone(Sone origin, Sone target) {
938 setTrust(origin, target, preferences.getPositiveTrust());
942 * Assigns the configured negative trust value for the given target.
949 public void distrustSone(Sone origin, Sone target) {
950 setTrust(origin, target, preferences.getNegativeTrust());
954 * Removes the trust assignment for the given target.
961 public void untrustSone(Sone origin, Sone target) {
962 removeTrust(origin, target);
966 * Updates the stored Sone with the given Sone.
971 public void updateSone(Sone sone) {
972 updateSone(sone, false);
976 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
977 * {@code true}, an older Sone than the current Sone can be given to restore
982 * @param soneRescueMode
983 * {@code true} if the stored Sone should be updated regardless
984 * of the age of the given Sone
986 public void updateSone(Sone sone, boolean soneRescueMode) {
987 Optional<Sone> storedSone = getSone(sone.getId());
988 if (storedSone.isPresent()) {
989 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
990 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
993 /* find removed posts. */
994 Collection<Post> existingPosts = database.getPosts(sone.getId());
995 for (Post oldPost : existingPosts) {
996 if (!sone.getPosts().contains(oldPost)) {
997 eventBus.post(new PostRemovedEvent(oldPost));
1000 /* find new posts. */
1001 for (Post newPost : sone.getPosts()) {
1002 if (existingPosts.contains(newPost)) {
1005 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1006 newPost.setKnown(true);
1007 } else if (!newPost.isKnown()) {
1008 eventBus.post(new NewPostFoundEvent(newPost));
1012 database.storePosts(sone, sone.getPosts());
1013 if (!soneRescueMode) {
1014 for (PostReply reply : storedSone.get().getReplies()) {
1015 if (!sone.getReplies().contains(reply)) {
1016 eventBus.post(new PostReplyRemovedEvent(reply));
1020 Set<PostReply> storedReplies = storedSone.get().getReplies();
1021 for (PostReply reply : sone.getReplies()) {
1022 if (storedReplies.contains(reply)) {
1025 if (reply.getTime() < getSoneFollowingTime(sone)) {
1026 reply.setKnown(true);
1027 } else if (!reply.isKnown()) {
1028 eventBus.post(new NewPostReplyFoundEvent(reply));
1031 database.storePostReplies(sone, sone.getReplies());
1032 synchronized (albums) {
1033 synchronized (images) {
1034 for (Album album : storedSone.get().getAlbums()) {
1035 albums.remove(album.getId());
1036 for (Image image : album.getImages()) {
1037 images.remove(image.getId());
1040 for (Album album : sone.getAlbums()) {
1041 albums.put(album.getId(), album);
1042 for (Image image : album.getImages()) {
1043 images.put(image.getId(), image);
1048 synchronized (sones) {
1049 sone.setOptions(storedSone.get().getOptions());
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));
1117 /* initialize options. */
1118 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1119 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1120 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1121 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1122 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1123 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1126 String sonePrefix = "Sone/" + sone.getId();
1127 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1128 if (soneTime == null) {
1129 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1132 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1135 Profile profile = new Profile(sone);
1136 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1137 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1138 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1139 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1140 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1141 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1143 /* load profile fields. */
1145 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1146 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1147 if (fieldName == null) {
1150 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1151 profile.addField(fieldName).setValue(fieldValue);
1155 Set<Post> posts = new HashSet<Post>();
1157 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1158 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1159 if (postId == null) {
1162 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1163 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1164 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1165 if ((postTime == 0) || (postText == null)) {
1166 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1169 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1170 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1171 postBuilder.to(postRecipientId);
1173 posts.add(postBuilder.build());
1177 Set<PostReply> replies = new HashSet<PostReply>();
1179 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1180 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1181 if (replyId == null) {
1184 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1185 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1186 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1187 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1188 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1191 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1192 replies.add(postReplyBuilder.build());
1195 /* load post likes. */
1196 Set<String> likedPostIds = new HashSet<String>();
1198 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1199 if (likedPostId == null) {
1202 likedPostIds.add(likedPostId);
1205 /* load reply likes. */
1206 Set<String> likedReplyIds = new HashSet<String>();
1208 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1209 if (likedReplyId == null) {
1212 likedReplyIds.add(likedReplyId);
1216 Set<String> friends = new HashSet<String>();
1218 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1219 if (friendId == null) {
1222 friends.add(friendId);
1226 List<Album> topLevelAlbums = new ArrayList<Album>();
1227 int albumCounter = 0;
1229 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1230 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1231 if (albumId == null) {
1234 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1235 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1236 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1237 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1238 if ((albumTitle == null) || (albumDescription == null)) {
1239 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1242 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1243 if (albumParentId != null) {
1244 Album parentAlbum = getAlbum(albumParentId, false);
1245 if (parentAlbum == null) {
1246 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1249 parentAlbum.addAlbum(album);
1251 if (!topLevelAlbums.contains(album)) {
1252 topLevelAlbums.add(album);
1258 int imageCounter = 0;
1260 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1261 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1262 if (imageId == null) {
1265 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1266 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1267 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1268 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1269 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1270 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1271 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1272 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1273 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1276 Album album = getAlbum(albumId, false);
1277 if (album == null) {
1278 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1281 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1282 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
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 sone.setAlbums(topLevelAlbums);
1312 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1314 synchronized (knownSones) {
1315 for (String friend : friends) {
1316 knownSones.add(friend);
1319 database.storePosts(sone, posts);
1320 for (Post post : posts) {
1321 post.setKnown(true);
1323 database.storePostReplies(sone, replies);
1324 for (PostReply reply : replies) {
1325 reply.setKnown(true);
1330 * Creates a new post.
1333 * The Sone that creates the post
1335 * The text of the post
1336 * @return The created post
1338 public Post createPost(Sone sone, String text) {
1339 return createPost(sone, System.currentTimeMillis(), text);
1343 * Creates a new post.
1346 * The Sone that creates the post
1348 * The time of the post
1350 * The text of the post
1351 * @return The created post
1353 public Post createPost(Sone sone, long time, String text) {
1354 return createPost(sone, null, time, text);
1358 * Creates a new post.
1361 * The Sone that creates the post
1363 * The recipient Sone, or {@code null} if this post does not have
1366 * The text of the post
1367 * @return The created post
1369 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1370 return createPost(sone, recipient, System.currentTimeMillis(), text);
1374 * Creates a new post.
1377 * The Sone that creates the post
1379 * The recipient Sone, or {@code null} if this post does not have
1382 * The time of the post
1384 * The text of the post
1385 * @return The created post
1387 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1388 checkNotNull(text, "text must not be null");
1389 checkArgument(text.trim().length() > 0, "text must not be empty");
1390 if (!sone.isLocal()) {
1391 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1394 PostBuilder postBuilder = database.newPostBuilder();
1395 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1396 if (recipient.isPresent()) {
1397 postBuilder.to(recipient.get().getId());
1399 final Post post = postBuilder.build();
1400 database.storePost(post);
1401 eventBus.post(new NewPostFoundEvent(post));
1403 touchConfiguration();
1404 localElementTicker.schedule(new Runnable() {
1411 markPostKnown(post);
1413 }, 10, TimeUnit.SECONDS);
1418 * Deletes the given post.
1421 * The post to delete
1423 public void deletePost(Post post) {
1424 if (!post.getSone().isLocal()) {
1425 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1428 database.removePost(post);
1429 eventBus.post(new PostRemovedEvent(post));
1430 markPostKnown(post);
1431 touchConfiguration();
1435 * Marks the given post as known, if it is currently not a known post
1436 * (according to {@link Post#isKnown()}).
1439 * The post to mark as known
1441 public void markPostKnown(Post post) {
1442 post.setKnown(true);
1443 eventBus.post(new MarkPostKnownEvent(post));
1444 touchConfiguration();
1445 for (PostReply reply : getReplies(post.getId())) {
1446 markReplyKnown(reply);
1451 * Bookmarks the given post.
1454 * The post to bookmark
1456 public void bookmark(Post post) {
1457 bookmarkPost(post.getId());
1461 * Bookmarks the post with the given ID.
1464 * The ID of the post to bookmark
1466 public void bookmarkPost(String id) {
1467 synchronized (bookmarkedPosts) {
1468 bookmarkedPosts.add(id);
1473 * Removes the given post from the bookmarks.
1476 * The post to unbookmark
1478 public void unbookmark(Post post) {
1479 unbookmarkPost(post.getId());
1483 * Removes the post with the given ID from the bookmarks.
1486 * The ID of the post to unbookmark
1488 public void unbookmarkPost(String id) {
1489 synchronized (bookmarkedPosts) {
1490 bookmarkedPosts.remove(id);
1495 * Creates a new reply.
1498 * The Sone that creates the reply
1500 * The post that this reply refers to
1502 * The text of the reply
1503 * @return The created reply
1505 public PostReply createReply(Sone sone, Post post, String text) {
1506 checkNotNull(text, "text must not be null");
1507 checkArgument(text.trim().length() > 0, "text must not be empty");
1508 if (!sone.isLocal()) {
1509 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1512 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1513 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1514 final PostReply reply = postReplyBuilder.build();
1515 database.storePostReply(reply);
1516 eventBus.post(new NewPostReplyFoundEvent(reply));
1517 sone.addReply(reply);
1518 touchConfiguration();
1519 localElementTicker.schedule(new Runnable() {
1526 markReplyKnown(reply);
1528 }, 10, TimeUnit.SECONDS);
1533 * Deletes the given reply.
1536 * The reply to delete
1538 public void deleteReply(PostReply reply) {
1539 Sone sone = reply.getSone();
1540 if (!sone.isLocal()) {
1541 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1544 database.removePostReply(reply);
1545 markReplyKnown(reply);
1546 sone.removeReply(reply);
1547 touchConfiguration();
1551 * Marks the given reply as known, if it is currently not a known reply
1552 * (according to {@link Reply#isKnown()}).
1555 * The reply to mark as known
1557 public void markReplyKnown(PostReply reply) {
1558 boolean previouslyKnown = reply.isKnown();
1559 reply.setKnown(true);
1560 eventBus.post(new MarkPostReplyKnownEvent(reply));
1561 if (!previouslyKnown) {
1562 touchConfiguration();
1567 * Creates a new top-level album for the given Sone.
1570 * The Sone to create the album for
1571 * @return The new album
1573 public Album createAlbum(Sone sone) {
1574 return createAlbum(sone, null);
1578 * Creates a new album for the given Sone.
1581 * The Sone to create the album for
1583 * The parent of the album (may be {@code null} to create a
1585 * @return The new album
1587 public Album createAlbum(Sone sone, Album parent) {
1588 Album album = new Album();
1589 synchronized (albums) {
1590 albums.put(album.getId(), album);
1592 album.setSone(sone);
1593 if (parent != null) {
1594 parent.addAlbum(album);
1596 sone.addAlbum(album);
1602 * Deletes the given album. The owner of the album has to be a local Sone,
1603 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1606 * The album to remove
1608 public void deleteAlbum(Album album) {
1609 checkNotNull(album, "album must not be null");
1610 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1611 if (!album.isEmpty()) {
1614 if (album.getParent() == null) {
1615 album.getSone().removeAlbum(album);
1617 album.getParent().removeAlbum(album);
1619 synchronized (albums) {
1620 albums.remove(album.getId());
1622 touchConfiguration();
1626 * Creates a new image.
1629 * The Sone creating the image
1631 * The album the image will be inserted into
1632 * @param temporaryImage
1633 * The temporary image to create the image from
1634 * @return The newly created image
1636 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1637 checkNotNull(sone, "sone must not be null");
1638 checkNotNull(album, "album must not be null");
1639 checkNotNull(temporaryImage, "temporaryImage must not be null");
1640 checkArgument(sone.isLocal(), "sone must be a local Sone");
1641 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1642 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1643 album.addImage(image);
1644 synchronized (images) {
1645 images.put(image.getId(), image);
1647 imageInserter.insertImage(temporaryImage, image);
1652 * Deletes the given image. This method will also delete a matching
1655 * @see #deleteTemporaryImage(TemporaryImage)
1657 * The image to delete
1659 public void deleteImage(Image image) {
1660 checkNotNull(image, "image must not be null");
1661 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1662 deleteTemporaryImage(image.getId());
1663 image.getAlbum().removeImage(image);
1664 synchronized (images) {
1665 images.remove(image.getId());
1667 touchConfiguration();
1671 * Creates a new temporary image.
1674 * The MIME type of the temporary image
1676 * The encoded data of the image
1677 * @return The temporary image
1679 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1680 TemporaryImage temporaryImage = new TemporaryImage();
1681 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1682 synchronized (temporaryImages) {
1683 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1685 return temporaryImage;
1689 * Deletes the given temporary image.
1691 * @param temporaryImage
1692 * The temporary image to delete
1694 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1695 checkNotNull(temporaryImage, "temporaryImage must not be null");
1696 deleteTemporaryImage(temporaryImage.getId());
1700 * Deletes the temporary image with the given ID.
1703 * The ID of the temporary image to delete
1705 public void deleteTemporaryImage(String imageId) {
1706 checkNotNull(imageId, "imageId must not be null");
1707 synchronized (temporaryImages) {
1708 temporaryImages.remove(imageId);
1710 Image image = getImage(imageId, false);
1711 if (image != null) {
1712 imageInserter.cancelImageInsert(image);
1717 * Notifies the core that the configuration, either of the core or of a
1718 * single local Sone, has changed, and that the configuration should be
1721 public void touchConfiguration() {
1722 lastConfigurationUpdate = System.currentTimeMillis();
1733 public void serviceStart() {
1734 loadConfiguration();
1735 updateChecker.start();
1736 identityManager.start();
1737 webOfTrustUpdater.init();
1738 webOfTrustUpdater.start();
1746 public void serviceRun() {
1747 long lastSaved = System.currentTimeMillis();
1748 while (!shouldStop()) {
1750 long now = System.currentTimeMillis();
1751 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1752 for (Sone localSone : getLocalSones()) {
1753 saveSone(localSone);
1755 saveConfiguration();
1765 public void serviceStop() {
1766 localElementTicker.shutdownNow();
1767 synchronized (sones) {
1768 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1769 soneInserter.getValue().stop();
1770 saveSone(soneInserter.getKey());
1773 saveConfiguration();
1775 webOfTrustUpdater.stop();
1776 updateChecker.stop();
1777 soneDownloader.stop();
1778 soneDownloaders.shutdown();
1779 identityManager.stop();
1787 * Saves the given Sone. This will persist all local settings for the given
1788 * Sone, such as the friends list and similar, private options.
1793 private synchronized void saveSone(Sone sone) {
1794 if (!sone.isLocal()) {
1795 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1798 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1799 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1803 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1805 /* save Sone into configuration. */
1806 String sonePrefix = "Sone/" + sone.getId();
1807 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1808 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1811 Profile profile = sone.getProfile();
1812 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1813 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1814 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1815 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1816 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1817 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1818 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1820 /* save profile fields. */
1821 int fieldCounter = 0;
1822 for (Field profileField : profile.getFields()) {
1823 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1824 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1825 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1827 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1830 int postCounter = 0;
1831 for (Post post : sone.getPosts()) {
1832 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1833 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1834 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1835 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1836 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1838 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1841 int replyCounter = 0;
1842 for (PostReply reply : sone.getReplies()) {
1843 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1844 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1845 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1846 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1847 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1849 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1851 /* save post likes. */
1852 int postLikeCounter = 0;
1853 for (String postId : sone.getLikedPostIds()) {
1854 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1856 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1858 /* save reply likes. */
1859 int replyLikeCounter = 0;
1860 for (String replyId : sone.getLikedReplyIds()) {
1861 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1863 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1866 int friendCounter = 0;
1867 for (String friendId : sone.getFriends()) {
1868 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1870 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1872 /* save albums. first, collect in a flat structure, top-level first. */
1873 List<Album> albums = FluentIterable.from(sone.getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1875 int albumCounter = 0;
1876 for (Album album : albums) {
1877 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1878 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1879 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1880 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1881 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1882 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1884 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1887 int imageCounter = 0;
1888 for (Album album : albums) {
1889 for (Image image : album.getImages()) {
1890 if (!image.isInserted()) {
1893 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1894 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1895 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1896 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1897 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1898 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1899 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1900 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1901 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1904 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1907 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1908 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1909 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1910 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1911 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1912 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1914 configuration.save();
1916 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1918 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1919 } catch (ConfigurationException ce1) {
1920 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1925 * Saves the current options.
1927 private void saveConfiguration() {
1928 synchronized (configuration) {
1929 if (storingConfiguration) {
1930 logger.log(Level.FINE, "Already storing configuration…");
1933 storingConfiguration = true;
1936 /* store the options first. */
1938 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1939 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1940 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1941 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1942 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1943 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1944 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1945 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1946 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1947 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1948 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1949 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1951 /* save known Sones. */
1952 int soneCounter = 0;
1953 synchronized (knownSones) {
1954 for (String knownSoneId : knownSones) {
1955 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1957 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1960 /* save Sone following times. */
1962 synchronized (soneFollowingTimes) {
1963 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1964 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1965 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1968 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1971 /* save known posts. */
1974 /* save bookmarked posts. */
1975 int bookmarkedPostCounter = 0;
1976 synchronized (bookmarkedPosts) {
1977 for (String bookmarkedPostId : bookmarkedPosts) {
1978 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1981 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1984 configuration.save();
1986 } catch (ConfigurationException ce1) {
1987 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1988 } catch (DatabaseException de1) {
1989 logger.log(Level.SEVERE, "Could not save database!", de1);
1991 synchronized (configuration) {
1992 storingConfiguration = false;
1998 * Loads the configuration.
2000 private void loadConfiguration() {
2001 /* create options. */
2002 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2005 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2006 SoneInserter.setInsertionDelay(newValue);
2010 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2011 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2012 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2013 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2014 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2015 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2016 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2017 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2018 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2021 @SuppressWarnings("synthetic-access")
2022 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2023 fcpInterface.setActive(newValue);
2026 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2029 @SuppressWarnings("synthetic-access")
2030 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2031 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2036 loadConfigurationValue("InsertionDelay");
2037 loadConfigurationValue("PostsPerPage");
2038 loadConfigurationValue("ImagesPerPage");
2039 loadConfigurationValue("CharactersPerPost");
2040 loadConfigurationValue("PostCutOffLength");
2041 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2042 loadConfigurationValue("PositiveTrust");
2043 loadConfigurationValue("NegativeTrust");
2044 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2045 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2046 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2048 /* load known Sones. */
2049 int soneCounter = 0;
2051 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2052 if (knownSoneId == null) {
2055 synchronized (knownSones) {
2056 knownSones.add(knownSoneId);
2060 /* load Sone following times. */
2063 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2064 if (soneId == null) {
2067 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2068 synchronized (soneFollowingTimes) {
2069 soneFollowingTimes.put(soneId, time);
2074 /* load bookmarked posts. */
2075 int bookmarkedPostCounter = 0;
2077 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2078 if (bookmarkedPostId == null) {
2081 synchronized (bookmarkedPosts) {
2082 bookmarkedPosts.add(bookmarkedPostId);
2089 * Loads an {@link Integer} configuration value for the option with the
2090 * given name, logging validation failures.
2093 * The name of the option to load
2095 private void loadConfigurationValue(String optionName) {
2097 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2098 } catch (IllegalArgumentException iae1) {
2099 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2104 * Notifies the core that a new {@link OwnIdentity} was added.
2106 * @param ownIdentityAddedEvent
2110 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2111 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2112 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2113 if (ownIdentity.hasContext("Sone")) {
2114 addLocalSone(ownIdentity);
2119 * Notifies the core that an {@link OwnIdentity} was removed.
2121 * @param ownIdentityRemovedEvent
2125 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2126 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2127 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2128 trustedIdentities.removeAll(ownIdentity);
2132 * Notifies the core that a new {@link Identity} was added.
2134 * @param identityAddedEvent
2138 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2139 Identity identity = identityAddedEvent.identity();
2140 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2141 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2142 addRemoteSone(identity);
2146 * Notifies the core that an {@link Identity} was updated.
2148 * @param identityUpdatedEvent
2152 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2153 final Identity identity = identityUpdatedEvent.identity();
2154 soneDownloaders.execute(new Runnable() {
2157 @SuppressWarnings("synthetic-access")
2159 Sone sone = getRemoteSone(identity.getId(), false);
2160 sone.setIdentity(identity);
2161 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2162 soneDownloader.addSone(sone);
2163 soneDownloader.fetchSone(sone);
2169 * Notifies the core that an {@link Identity} was removed.
2171 * @param identityRemovedEvent
2175 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2176 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2177 Identity identity = identityRemovedEvent.identity();
2178 trustedIdentities.remove(ownIdentity, identity);
2179 boolean foundIdentity = false;
2180 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2181 if (trustedIdentity.getKey().equals(ownIdentity)) {
2184 if (trustedIdentity.getValue().contains(identity)) {
2185 foundIdentity = true;
2188 if (foundIdentity) {
2189 /* some local identity still trusts this identity, don’t remove. */
2192 Optional<Sone> sone = getSone(identity.getId());
2193 if (!sone.isPresent()) {
2194 /* TODO - we don’t have the Sone anymore. should this happen? */
2197 database.removePosts(sone.get());
2198 for (Post post : sone.get().getPosts()) {
2199 eventBus.post(new PostRemovedEvent(post));
2201 database.removePostReplies(sone.get());
2202 for (PostReply reply : sone.get().getReplies()) {
2203 eventBus.post(new PostReplyRemovedEvent(reply));
2205 synchronized (sones) {
2206 sones.remove(identity.getId());
2208 eventBus.post(new SoneRemovedEvent(sone.get()));
2212 * Deletes the temporary image.
2214 * @param imageInsertFinishedEvent
2218 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2219 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2220 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2221 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2222 touchConfiguration();