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.ConfigurationSoneParser.InvalidPostFound;
42 import net.pterodactylus.sone.core.ConfigurationSoneParser.InvalidPostReplyFound;
43 import net.pterodactylus.sone.core.Options.DefaultOption;
44 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
45 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
46 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
48 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
49 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
50 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
51 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
52 import net.pterodactylus.sone.core.event.PostRemovedEvent;
53 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneLockedEvent;
55 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
56 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
57 import net.pterodactylus.sone.data.Album;
58 import net.pterodactylus.sone.data.Client;
59 import net.pterodactylus.sone.data.Image;
60 import net.pterodactylus.sone.data.Post;
61 import net.pterodactylus.sone.data.PostReply;
62 import net.pterodactylus.sone.data.Profile;
63 import net.pterodactylus.sone.data.Profile.Field;
64 import net.pterodactylus.sone.data.Reply;
65 import net.pterodactylus.sone.data.Sone;
66 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
67 import net.pterodactylus.sone.data.Sone.SoneStatus;
68 import net.pterodactylus.sone.data.SoneImpl;
69 import net.pterodactylus.sone.data.TemporaryImage;
70 import net.pterodactylus.sone.database.Database;
71 import net.pterodactylus.sone.database.DatabaseException;
72 import net.pterodactylus.sone.database.PostBuilder;
73 import net.pterodactylus.sone.database.PostProvider;
74 import net.pterodactylus.sone.database.PostReplyBuilder;
75 import net.pterodactylus.sone.database.PostReplyProvider;
76 import net.pterodactylus.sone.database.SoneProvider;
77 import net.pterodactylus.sone.fcp.FcpInterface;
78 import net.pterodactylus.sone.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.annotations.VisibleForTesting;
96 import com.google.common.base.Optional;
97 import com.google.common.base.Predicates;
98 import com.google.common.collect.FluentIterable;
99 import com.google.common.collect.HashMultimap;
100 import com.google.common.collect.ImmutableSet;
101 import com.google.common.collect.Multimap;
102 import com.google.common.collect.Multimaps;
103 import com.google.common.eventbus.EventBus;
104 import com.google.common.eventbus.Subscribe;
105 import com.google.inject.Inject;
106 import com.google.inject.Singleton;
108 import freenet.keys.FreenetURI;
113 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
116 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
119 private static final Logger logger = Logging.getLogger(Core.class);
121 /** The start time. */
122 private final long startupTime = System.currentTimeMillis();
125 private final Options options = new Options();
127 /** The preferences. */
128 private final Preferences preferences = new Preferences(options);
130 /** The event bus. */
131 private final EventBus eventBus;
133 /** The configuration. */
134 private final Configuration configuration;
136 /** Whether we’re currently saving the configuration. */
137 private boolean storingConfiguration = false;
139 /** The identity manager. */
140 private final IdentityManager identityManager;
142 /** Interface to freenet. */
143 private final FreenetInterface freenetInterface;
145 /** The Sone downloader. */
146 private final SoneDownloader soneDownloader;
148 /** The image inserter. */
149 private final ImageInserter imageInserter;
151 /** Sone downloader thread-pool. */
152 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
154 /** The update checker. */
155 private final UpdateChecker updateChecker;
157 /** The trust updater. */
158 private final WebOfTrustUpdater webOfTrustUpdater;
160 /** The FCP interface. */
161 private volatile FcpInterface fcpInterface;
163 /** The times Sones were followed. */
164 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
166 /** Locked local Sones. */
167 /* synchronize on itself. */
168 private final Set<Sone> lockedSones = new HashSet<Sone>();
170 /** Sone inserters. */
171 /* synchronize access on this on sones. */
172 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
174 /** Sone rescuers. */
175 /* synchronize access on this on sones. */
176 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
179 /* synchronize access on this on itself. */
180 private final Map<String, Sone> sones = new HashMap<String, Sone>();
182 /** All known Sones. */
183 private final Set<String> knownSones = new HashSet<String>();
185 /** The post database. */
186 private final Database database;
188 /** All bookmarked posts. */
189 /* synchronize access on itself. */
190 private final Set<String> bookmarkedPosts = new HashSet<String>();
192 /** Trusted identities, sorted by own identities. */
193 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
195 /** All temporary images. */
196 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
198 /** Ticker for threads that mark own elements as known. */
199 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
201 /** The time the configuration was last touched. */
202 private volatile long lastConfigurationUpdate;
205 * Creates a new core.
207 * @param configuration
208 * The configuration of the core
209 * @param freenetInterface
210 * The freenet interface
211 * @param identityManager
212 * The identity manager
213 * @param webOfTrustUpdater
214 * The WebOfTrust updater
221 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
227 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
228 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
229 this.webOfTrustUpdater = webOfTrustUpdater;
230 this.eventBus = eventBus;
231 this.database = database;
235 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
237 this.configuration = configuration;
238 this.freenetInterface = freenetInterface;
239 this.identityManager = identityManager;
240 this.soneDownloader = soneDownloader;
241 this.imageInserter = imageInserter;
242 this.updateChecker = updateChecker;
243 this.webOfTrustUpdater = webOfTrustUpdater;
244 this.eventBus = eventBus;
245 this.database = database;
253 * Returns the time Sone was started.
255 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
257 public long getStartupTime() {
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 ImmutableSet.copyOf(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 FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
369 * Returns the local Sone with the given ID, optionally creating a new Sone.
374 * {@code true} to create a new Sone if none exists,
375 * {@code false} to return null if none exists
376 * @return The Sone with the given ID, or {@code null}
378 public Sone getLocalSone(String id, boolean create) {
379 synchronized (sones) {
380 Sone sone = sones.get(id);
381 if ((sone == null) && create) {
382 sone = new SoneImpl(id, true);
385 if ((sone != null) && !sone.isLocal()) {
386 sone = new SoneImpl(id, true);
397 public Collection<Sone> getRemoteSones() {
398 synchronized (sones) {
399 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
404 * Returns the remote Sone with the given ID.
407 * The ID of the remote Sone to get
409 * {@code true} to always create a Sone, {@code false} to return
410 * {@code null} if no Sone with the given ID exists
411 * @return The Sone with the given ID
413 public Sone getRemoteSone(String id, boolean create) {
414 synchronized (sones) {
415 Sone sone = sones.get(id);
416 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
417 sone = new SoneImpl(id, false);
425 * Returns whether the given Sone has been modified.
428 * The Sone to check for modifications
429 * @return {@code true} if a modification has been detected in the Sone,
430 * {@code false} otherwise
432 public boolean isModifiedSone(Sone sone) {
433 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
437 * Returns the time when the given was first followed by any local Sone.
440 * The Sone to get the time for
441 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
442 * been followed, or {@link Long#MAX_VALUE}
444 public long getSoneFollowingTime(Sone sone) {
445 synchronized (soneFollowingTimes) {
446 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
451 * Returns a post builder.
453 * @return A new post builder
455 public PostBuilder postBuilder() {
456 return database.newPostBuilder();
463 public Optional<Post> getPost(String postId) {
464 return database.getPost(postId);
471 public Collection<Post> getPosts(String soneId) {
472 return database.getPosts(soneId);
479 public Collection<Post> getDirectedPosts(final String recipientId) {
480 checkNotNull(recipientId, "recipient must not be null");
481 return database.getDirectedPosts(recipientId);
485 * Returns a post reply builder.
487 * @return A new post reply builder
489 public PostReplyBuilder postReplyBuilder() {
490 return database.newPostReplyBuilder();
497 public Optional<PostReply> getPostReply(String replyId) {
498 return database.getPostReply(replyId);
505 public List<PostReply> getReplies(final String postId) {
506 return database.getReplies(postId);
510 * Returns all Sones that have liked the given post.
513 * The post to get the liking Sones for
514 * @return The Sones that like the given post
516 public Set<Sone> getLikes(Post post) {
517 Set<Sone> sones = new HashSet<Sone>();
518 for (Sone sone : getSones()) {
519 if (sone.getLikedPostIds().contains(post.getId())) {
527 * Returns all Sones that have liked the given reply.
530 * The reply to get the liking Sones for
531 * @return The Sones that like the given reply
533 public Set<Sone> getLikes(PostReply reply) {
534 Set<Sone> sones = new HashSet<Sone>();
535 for (Sone sone : getSones()) {
536 if (sone.getLikedReplyIds().contains(reply.getId())) {
544 * Returns whether the given post is bookmarked.
548 * @return {@code true} if the given post is bookmarked, {@code false}
551 public boolean isBookmarked(Post post) {
552 return isPostBookmarked(post.getId());
556 * Returns whether the post with the given ID is bookmarked.
559 * The ID of the post to check
560 * @return {@code true} if the post with the given ID is bookmarked,
561 * {@code false} otherwise
563 public boolean isPostBookmarked(String id) {
564 synchronized (bookmarkedPosts) {
565 return bookmarkedPosts.contains(id);
570 * Returns all currently known bookmarked posts.
572 * @return All bookmarked posts
574 public Set<Post> getBookmarkedPosts() {
575 Set<Post> posts = new HashSet<Post>();
576 synchronized (bookmarkedPosts) {
577 for (String bookmarkedPostId : bookmarkedPosts) {
578 Optional<Post> post = getPost(bookmarkedPostId);
579 if (post.isPresent()) {
580 posts.add(post.get());
588 * Returns the album with the given ID, creating a new album if no album
589 * with the given ID can be found.
592 * The ID of the album
593 * @return The album with the given ID
595 public Album getOrCreateAlbum(String albumId) {
596 return getAlbum(albumId, true);
600 * Returns the album with the given ID, optionally creating a new album if
601 * an album with the given ID can not be found.
604 * The ID of the album
606 * {@code true} to create a new album if none exists for the
608 * @return The album with the given ID, or {@code null} if no album with the
609 * given ID exists and {@code create} is {@code false}
611 public Album getAlbum(String albumId, boolean create) {
612 Optional<Album> album = database.getAlbum(albumId);
613 if (album.isPresent()) {
619 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
620 database.storeAlbum(newAlbum);
625 * Returns the image with the given ID, creating it if necessary.
628 * The ID of the image
629 * @return The image with the given ID
631 public Image getImage(String imageId) {
632 return getImage(imageId, true);
636 * Returns the image with the given ID, optionally creating it if it does
640 * The ID of the image
642 * {@code true} to create an image if none exists with the given
644 * @return The image with the given ID, or {@code null} if none exists and
647 public Image getImage(String imageId, boolean create) {
648 Optional<Image> image = database.getImage(imageId);
649 if (image.isPresent()) {
655 Image newImage = database.newImageBuilder().withId(imageId).build();
656 database.storeImage(newImage);
661 * Returns the temporary image with the given ID.
664 * The ID of the temporary image
665 * @return The temporary image, or {@code null} if there is no temporary
666 * image with the given ID
668 public TemporaryImage getTemporaryImage(String imageId) {
669 synchronized (temporaryImages) {
670 return temporaryImages.get(imageId);
679 * Locks the given Sone. A locked Sone will not be inserted by
680 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
686 public void lockSone(Sone sone) {
687 synchronized (lockedSones) {
688 if (lockedSones.add(sone)) {
689 eventBus.post(new SoneLockedEvent(sone));
695 * Unlocks the given Sone.
697 * @see #lockSone(Sone)
701 public void unlockSone(Sone sone) {
702 synchronized (lockedSones) {
703 if (lockedSones.remove(sone)) {
704 eventBus.post(new SoneUnlockedEvent(sone));
710 * Adds a local Sone from the given own identity.
713 * The own identity to create a Sone from
714 * @return The added (or already existing) Sone
716 public Sone addLocalSone(OwnIdentity ownIdentity) {
717 if (ownIdentity == null) {
718 logger.log(Level.WARNING, "Given OwnIdentity is null!");
721 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
722 synchronized (sones) {
725 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
726 } catch (MalformedURLException mue1) {
727 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
730 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
731 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
733 /* TODO - load posts ’n stuff */
734 sones.put(ownIdentity.getId(), sone);
735 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
736 soneInserters.put(sone, soneInserter);
737 sone.setStatus(SoneStatus.idle);
739 soneInserter.start();
745 * Creates a new Sone for the given own identity.
748 * The own identity to create a Sone for
749 * @return The created Sone
751 public Sone createSone(OwnIdentity ownIdentity) {
752 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
753 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
756 Sone sone = addLocalSone(ownIdentity);
758 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
759 touchConfiguration();
764 * Adds the Sone of the given identity.
767 * The identity whose Sone to add
768 * @return The added or already existing Sone
770 public Sone addRemoteSone(Identity identity) {
771 if (identity == null) {
772 logger.log(Level.WARNING, "Given Identity is null!");
775 synchronized (sones) {
776 final Sone sone = getRemoteSone(identity.getId(), true);
777 if (sone.isLocal()) {
780 sone.setIdentity(identity);
781 boolean newSone = sone.getRequestUri() == null;
782 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
783 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
785 synchronized (knownSones) {
786 newSone = !knownSones.contains(sone.getId());
788 sone.setKnown(!newSone);
790 eventBus.post(new NewSoneFoundEvent(sone));
791 for (Sone localSone : getLocalSones()) {
792 if (localSone.getOptions().isAutoFollow()) {
793 followSone(localSone, sone.getId());
798 soneDownloader.addSone(sone);
799 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
805 * Lets the given local Sone follow the Sone with the given ID.
808 * The local Sone that should follow another Sone
810 * The ID of the Sone to follow
812 public void followSone(Sone sone, String soneId) {
813 checkNotNull(sone, "sone must not be null");
814 checkNotNull(soneId, "soneId must not be null");
815 sone.addFriend(soneId);
816 synchronized (soneFollowingTimes) {
817 if (!soneFollowingTimes.containsKey(soneId)) {
818 long now = System.currentTimeMillis();
819 soneFollowingTimes.put(soneId, now);
820 Optional<Sone> followedSone = getSone(soneId);
821 if (!followedSone.isPresent()) {
824 for (Post post : followedSone.get().getPosts()) {
825 if (post.getTime() < now) {
829 for (PostReply reply : followedSone.get().getReplies()) {
830 if (reply.getTime() < now) {
831 markReplyKnown(reply);
836 touchConfiguration();
840 * Lets the given local Sone unfollow the Sone with the given ID.
843 * The local Sone that should unfollow another Sone
845 * The ID of the Sone being unfollowed
847 public void unfollowSone(Sone sone, String soneId) {
848 checkNotNull(sone, "sone must not be null");
849 checkNotNull(soneId, "soneId must not be null");
850 sone.removeFriend(soneId);
851 boolean unfollowedSoneStillFollowed = false;
852 for (Sone localSone : getLocalSones()) {
853 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
855 if (!unfollowedSoneStillFollowed) {
856 synchronized (soneFollowingTimes) {
857 soneFollowingTimes.remove(soneId);
860 touchConfiguration();
864 * Sets the trust value of the given origin Sone for the target Sone.
871 * The trust value (from {@code -100} to {@code 100})
873 public void setTrust(Sone origin, Sone target, int trustValue) {
874 checkNotNull(origin, "origin must not be null");
875 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
876 checkNotNull(target, "target must not be null");
877 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
878 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
882 * Removes any trust assignment for the given target Sone.
889 public void removeTrust(Sone origin, Sone target) {
890 checkNotNull(origin, "origin must not be null");
891 checkNotNull(target, "target must not be null");
892 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
893 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
897 * Assigns the configured positive trust value for the given target.
904 public void trustSone(Sone origin, Sone target) {
905 setTrust(origin, target, preferences.getPositiveTrust());
909 * Assigns the configured negative trust value for the given target.
916 public void distrustSone(Sone origin, Sone target) {
917 setTrust(origin, target, preferences.getNegativeTrust());
921 * Removes the trust assignment for the given target.
928 public void untrustSone(Sone origin, Sone target) {
929 removeTrust(origin, target);
933 * Updates the stored Sone with the given Sone.
938 public void updateSone(Sone sone) {
939 updateSone(sone, false);
943 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
944 * {@code true}, an older Sone than the current Sone can be given to restore
949 * @param soneRescueMode
950 * {@code true} if the stored Sone should be updated regardless
951 * of the age of the given Sone
953 public void updateSone(Sone sone, boolean soneRescueMode) {
954 Optional<Sone> storedSone = getSone(sone.getId());
955 if (storedSone.isPresent()) {
956 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
957 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
960 /* find removed posts. */
961 Collection<Post> removedPosts = new ArrayList<Post>();
962 Collection<Post> newPosts = new ArrayList<Post>();
963 Collection<Post> existingPosts = database.getPosts(sone.getId());
964 for (Post oldPost : existingPosts) {
965 if (!sone.getPosts().contains(oldPost)) {
966 removedPosts.add(oldPost);
969 /* find new posts. */
970 for (Post newPost : sone.getPosts()) {
971 if (existingPosts.contains(newPost)) {
974 if (newPost.getTime() < getSoneFollowingTime(sone)) {
975 newPost.setKnown(true);
976 } else if (!newPost.isKnown()) {
977 newPosts.add(newPost);
981 database.storePosts(sone, sone.getPosts());
982 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
983 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
984 if (!soneRescueMode) {
985 for (PostReply reply : storedSone.get().getReplies()) {
986 if (!sone.getReplies().contains(reply)) {
987 removedPostReplies.add(reply);
991 Set<PostReply> storedReplies = storedSone.get().getReplies();
992 for (PostReply reply : sone.getReplies()) {
993 if (storedReplies.contains(reply)) {
996 if (reply.getTime() < getSoneFollowingTime(sone)) {
997 reply.setKnown(true);
998 } else if (!reply.isKnown()) {
999 newPostReplies.add(reply);
1002 database.storePostReplies(sone, sone.getReplies());
1003 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1004 database.removeAlbum(album);
1005 for (Image image : album.getImages()) {
1006 database.removeImage(image);
1009 for (Post removedPost : removedPosts) {
1010 eventBus.post(new PostRemovedEvent(removedPost));
1012 for (Post newPost : newPosts) {
1013 eventBus.post(new NewPostFoundEvent(newPost));
1015 for (PostReply removedPostReply : removedPostReplies) {
1016 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1018 for (PostReply newPostReply : newPostReplies) {
1019 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1021 for (Album album : sone.getRootAlbum().getAlbums()) {
1022 database.storeAlbum(album);
1023 for (Image image : album.getImages()) {
1024 database.storeImage(image);
1027 synchronized (sones) {
1028 sone.setOptions(storedSone.get().getOptions());
1029 sone.setKnown(storedSone.get().isKnown());
1030 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1031 if (sone.isLocal()) {
1032 soneInserters.get(storedSone.get()).setSone(sone);
1033 touchConfiguration();
1035 sones.put(sone.getId(), sone);
1041 * Deletes the given Sone. This will remove the Sone from the
1042 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1043 * remove the context from its identity.
1046 * The Sone to delete
1048 public void deleteSone(Sone sone) {
1049 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1050 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1053 synchronized (sones) {
1054 if (!getLocalSones().contains(sone)) {
1055 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1058 sones.remove(sone.getId());
1059 SoneInserter soneInserter = soneInserters.remove(sone);
1060 soneInserter.stop();
1062 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1063 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1065 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1066 } catch (ConfigurationException ce1) {
1067 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1072 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1073 * known} before, a {@link MarkSoneKnownEvent} is fired.
1076 * The Sone to mark as known
1078 public void markSoneKnown(Sone sone) {
1079 if (!sone.isKnown()) {
1080 sone.setKnown(true);
1081 synchronized (knownSones) {
1082 knownSones.add(sone.getId());
1084 eventBus.post(new MarkSoneKnownEvent(sone));
1085 touchConfiguration();
1090 * Loads and updates the given Sone from the configuration. If any error is
1091 * encountered, loading is aborted and the given Sone is not changed.
1094 * The Sone to load and update
1096 public void loadSone(Sone sone) {
1097 if (!sone.isLocal()) {
1098 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1101 logger.info(String.format("Loading local Sone: %s", sone));
1104 String sonePrefix = "Sone/" + sone.getId();
1105 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1106 if (soneTime == null) {
1107 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1110 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1113 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1114 Profile profile = configurationSoneParser.parseProfile();
1117 Collection<Post> posts;
1119 posts = configurationSoneParser.parsePosts(database);
1120 } catch (InvalidPostFound ipf) {
1121 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1126 Collection<PostReply> replies;
1128 replies = configurationSoneParser.parsePostReplies(database);
1129 } catch (InvalidPostReplyFound iprf) {
1130 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1134 /* load post likes. */
1135 Set<String> likedPostIds = new HashSet<String>();
1137 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1138 if (likedPostId == null) {
1141 likedPostIds.add(likedPostId);
1144 /* load reply likes. */
1145 Set<String> likedReplyIds = new HashSet<String>();
1147 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1148 if (likedReplyId == null) {
1151 likedReplyIds.add(likedReplyId);
1155 Set<String> friends = new HashSet<String>();
1157 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1158 if (friendId == null) {
1161 friends.add(friendId);
1165 List<Album> topLevelAlbums = new ArrayList<Album>();
1166 int albumCounter = 0;
1168 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1169 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1170 if (albumId == null) {
1173 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1174 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1175 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1176 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1177 if ((albumTitle == null) || (albumDescription == null)) {
1178 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1181 Album album = getOrCreateAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1182 if (albumParentId != null) {
1183 Album parentAlbum = getAlbum(albumParentId, false);
1184 if (parentAlbum == null) {
1185 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1188 parentAlbum.addAlbum(album);
1190 if (!topLevelAlbums.contains(album)) {
1191 topLevelAlbums.add(album);
1197 int imageCounter = 0;
1199 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1200 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1201 if (imageId == null) {
1204 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1205 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1206 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1207 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1208 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1209 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1210 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1211 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1212 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1215 Album album = getAlbum(albumId, false);
1216 if (album == null) {
1217 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1220 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1221 album.addImage(image);
1225 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1226 if (avatarId != null) {
1227 profile.setAvatar(getImage(avatarId, false));
1231 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1232 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1233 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1234 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1235 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1236 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1238 /* if we’re still here, Sone was loaded successfully. */
1239 synchronized (sone) {
1240 sone.setTime(soneTime);
1241 sone.setProfile(profile);
1242 sone.setPosts(posts);
1243 sone.setReplies(replies);
1244 sone.setLikePostIds(likedPostIds);
1245 sone.setLikeReplyIds(likedReplyIds);
1246 for (String friendId : friends) {
1247 followSone(sone, friendId);
1249 for (Album album : sone.getRootAlbum().getAlbums()) {
1250 sone.getRootAlbum().removeAlbum(album);
1252 for (Album album : topLevelAlbums) {
1253 sone.getRootAlbum().addAlbum(album);
1255 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1257 synchronized (knownSones) {
1258 for (String friend : friends) {
1259 knownSones.add(friend);
1262 database.storePosts(sone, posts);
1263 for (Post post : posts) {
1264 post.setKnown(true);
1266 database.storePostReplies(sone, replies);
1267 for (PostReply reply : replies) {
1268 reply.setKnown(true);
1271 logger.info(String.format("Sone loaded successfully: %s", sone));
1275 * Creates a new post.
1278 * The Sone that creates the post
1280 * The recipient Sone, or {@code null} if this post does not have
1283 * The text of the post
1284 * @return The created post
1286 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1287 return createPost(sone, recipient, System.currentTimeMillis(), text);
1291 * Creates a new post.
1294 * The Sone that creates the post
1296 * The recipient Sone, or {@code null} if this post does not have
1299 * The time of the post
1301 * The text of the post
1302 * @return The created post
1304 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1305 checkNotNull(text, "text must not be null");
1306 checkArgument(text.trim().length() > 0, "text must not be empty");
1307 if (!sone.isLocal()) {
1308 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1311 PostBuilder postBuilder = database.newPostBuilder();
1312 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1313 if (recipient.isPresent()) {
1314 postBuilder.to(recipient.get().getId());
1316 final Post post = postBuilder.build();
1317 database.storePost(post);
1318 eventBus.post(new NewPostFoundEvent(post));
1320 touchConfiguration();
1321 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1326 * Deletes the given post.
1329 * The post to delete
1331 public void deletePost(Post post) {
1332 if (!post.getSone().isLocal()) {
1333 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1336 database.removePost(post);
1337 eventBus.post(new PostRemovedEvent(post));
1338 markPostKnown(post);
1339 touchConfiguration();
1343 * Marks the given post as known, if it is currently not a known post
1344 * (according to {@link Post#isKnown()}).
1347 * The post to mark as known
1349 public void markPostKnown(Post post) {
1350 post.setKnown(true);
1351 eventBus.post(new MarkPostKnownEvent(post));
1352 touchConfiguration();
1353 for (PostReply reply : getReplies(post.getId())) {
1354 markReplyKnown(reply);
1359 * Bookmarks the post with the given ID.
1362 * The ID of the post to bookmark
1364 public void bookmarkPost(String id) {
1365 synchronized (bookmarkedPosts) {
1366 bookmarkedPosts.add(id);
1371 * Removes the given post from the bookmarks.
1374 * The post to unbookmark
1376 public void unbookmark(Post post) {
1377 unbookmarkPost(post.getId());
1381 * Removes the post with the given ID from the bookmarks.
1384 * The ID of the post to unbookmark
1386 public void unbookmarkPost(String id) {
1387 synchronized (bookmarkedPosts) {
1388 bookmarkedPosts.remove(id);
1393 * Creates a new reply.
1396 * The Sone that creates the reply
1398 * The post that this reply refers to
1400 * The text of the reply
1401 * @return The created reply
1403 public PostReply createReply(Sone sone, Post post, String text) {
1404 checkNotNull(text, "text must not be null");
1405 checkArgument(text.trim().length() > 0, "text must not be empty");
1406 if (!sone.isLocal()) {
1407 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1410 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1411 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1412 final PostReply reply = postReplyBuilder.build();
1413 database.storePostReply(reply);
1414 eventBus.post(new NewPostReplyFoundEvent(reply));
1415 sone.addReply(reply);
1416 touchConfiguration();
1417 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1422 * Deletes the given reply.
1425 * The reply to delete
1427 public void deleteReply(PostReply reply) {
1428 Sone sone = reply.getSone();
1429 if (!sone.isLocal()) {
1430 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1433 database.removePostReply(reply);
1434 markReplyKnown(reply);
1435 sone.removeReply(reply);
1436 touchConfiguration();
1440 * Marks the given reply as known, if it is currently not a known reply
1441 * (according to {@link Reply#isKnown()}).
1444 * The reply to mark as known
1446 public void markReplyKnown(PostReply reply) {
1447 boolean previouslyKnown = reply.isKnown();
1448 reply.setKnown(true);
1449 eventBus.post(new MarkPostReplyKnownEvent(reply));
1450 if (!previouslyKnown) {
1451 touchConfiguration();
1456 * Creates a new album for the given Sone.
1459 * The Sone to create the album for
1461 * The parent of the album (may be {@code null} to create a
1463 * @return The new album
1465 public Album createAlbum(Sone sone, Album parent) {
1466 Album album = database.newAlbumBuilder().randomId().build();
1467 database.storeAlbum(album);
1468 album.setSone(sone);
1469 parent.addAlbum(album);
1474 * Deletes the given album. The owner of the album has to be a local Sone,
1475 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1478 * The album to remove
1480 public void deleteAlbum(Album album) {
1481 checkNotNull(album, "album must not be null");
1482 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1483 if (!album.isEmpty()) {
1486 album.getParent().removeAlbum(album);
1487 database.removeAlbum(album);
1488 touchConfiguration();
1492 * Creates a new image.
1495 * The Sone creating the image
1497 * The album the image will be inserted into
1498 * @param temporaryImage
1499 * The temporary image to create the image from
1500 * @return The newly created image
1502 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1503 checkNotNull(sone, "sone must not be null");
1504 checkNotNull(album, "album must not be null");
1505 checkNotNull(temporaryImage, "temporaryImage must not be null");
1506 checkArgument(sone.isLocal(), "sone must be a local Sone");
1507 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1508 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1509 album.addImage(image);
1510 database.storeImage(image);
1511 imageInserter.insertImage(temporaryImage, image);
1516 * Deletes the given image. This method will also delete a matching
1519 * @see #deleteTemporaryImage(String)
1521 * The image to delete
1523 public void deleteImage(Image image) {
1524 checkNotNull(image, "image must not be null");
1525 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1526 deleteTemporaryImage(image.getId());
1527 image.getAlbum().removeImage(image);
1528 database.removeImage(image);
1529 touchConfiguration();
1533 * Creates a new temporary image.
1536 * The MIME type of the temporary image
1538 * The encoded data of the image
1539 * @return The temporary image
1541 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1542 TemporaryImage temporaryImage = new TemporaryImage();
1543 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1544 synchronized (temporaryImages) {
1545 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1547 return temporaryImage;
1551 * Deletes the temporary image with the given ID.
1554 * The ID of the temporary image to delete
1556 public void deleteTemporaryImage(String imageId) {
1557 checkNotNull(imageId, "imageId must not be null");
1558 synchronized (temporaryImages) {
1559 temporaryImages.remove(imageId);
1561 Image image = getImage(imageId, false);
1562 if (image != null) {
1563 imageInserter.cancelImageInsert(image);
1568 * Notifies the core that the configuration, either of the core or of a
1569 * single local Sone, has changed, and that the configuration should be
1572 public void touchConfiguration() {
1573 lastConfigurationUpdate = System.currentTimeMillis();
1584 public void serviceStart() {
1585 loadConfiguration();
1586 updateChecker.start();
1587 identityManager.start();
1588 webOfTrustUpdater.init();
1589 webOfTrustUpdater.start();
1597 public void serviceRun() {
1598 long lastSaved = System.currentTimeMillis();
1599 while (!shouldStop()) {
1601 long now = System.currentTimeMillis();
1602 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1603 for (Sone localSone : getLocalSones()) {
1604 saveSone(localSone);
1606 saveConfiguration();
1616 public void serviceStop() {
1617 localElementTicker.shutdownNow();
1618 synchronized (sones) {
1619 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1620 soneInserter.getValue().stop();
1621 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1624 saveConfiguration();
1626 webOfTrustUpdater.stop();
1627 updateChecker.stop();
1628 soneDownloader.stop();
1629 soneDownloaders.shutdown();
1630 identityManager.stop();
1638 * Saves the given Sone. This will persist all local settings for the given
1639 * Sone, such as the friends list and similar, private options.
1644 private synchronized void saveSone(Sone sone) {
1645 if (!sone.isLocal()) {
1646 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1649 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1650 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1654 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1656 /* save Sone into configuration. */
1657 String sonePrefix = "Sone/" + sone.getId();
1658 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1659 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1662 Profile profile = sone.getProfile();
1663 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1664 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1665 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1666 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1667 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1668 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1669 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1671 /* save profile fields. */
1672 int fieldCounter = 0;
1673 for (Field profileField : profile.getFields()) {
1674 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1675 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1676 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1678 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1681 int postCounter = 0;
1682 for (Post post : sone.getPosts()) {
1683 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1684 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1685 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1686 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1687 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1689 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1692 int replyCounter = 0;
1693 for (PostReply reply : sone.getReplies()) {
1694 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1695 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1696 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1697 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1698 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1700 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1702 /* save post likes. */
1703 int postLikeCounter = 0;
1704 for (String postId : sone.getLikedPostIds()) {
1705 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1707 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1709 /* save reply likes. */
1710 int replyLikeCounter = 0;
1711 for (String replyId : sone.getLikedReplyIds()) {
1712 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1714 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1717 int friendCounter = 0;
1718 for (String friendId : sone.getFriends()) {
1719 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1721 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1723 /* save albums. first, collect in a flat structure, top-level first. */
1724 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1726 int albumCounter = 0;
1727 for (Album album : albums) {
1728 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1729 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1730 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1731 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1732 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1733 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1735 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1738 int imageCounter = 0;
1739 for (Album album : albums) {
1740 for (Image image : album.getImages()) {
1741 if (!image.isInserted()) {
1744 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1745 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1746 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1747 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1748 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1749 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1750 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1751 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1752 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1755 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1758 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1759 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1760 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1761 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1762 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1763 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1765 configuration.save();
1767 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1769 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1770 } catch (ConfigurationException ce1) {
1771 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1776 * Saves the current options.
1778 private void saveConfiguration() {
1779 synchronized (configuration) {
1780 if (storingConfiguration) {
1781 logger.log(Level.FINE, "Already storing configuration…");
1784 storingConfiguration = true;
1787 /* store the options first. */
1789 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1790 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1791 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1792 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1793 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1794 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1795 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1796 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1797 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1798 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1799 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1800 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1802 /* save known Sones. */
1803 int soneCounter = 0;
1804 synchronized (knownSones) {
1805 for (String knownSoneId : knownSones) {
1806 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1808 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1811 /* save Sone following times. */
1813 synchronized (soneFollowingTimes) {
1814 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1815 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1816 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1819 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1822 /* save known posts. */
1825 /* save bookmarked posts. */
1826 int bookmarkedPostCounter = 0;
1827 synchronized (bookmarkedPosts) {
1828 for (String bookmarkedPostId : bookmarkedPosts) {
1829 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1832 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1835 configuration.save();
1837 } catch (ConfigurationException ce1) {
1838 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1839 } catch (DatabaseException de1) {
1840 logger.log(Level.SEVERE, "Could not save database!", de1);
1842 synchronized (configuration) {
1843 storingConfiguration = false;
1849 * Loads the configuration.
1851 private void loadConfiguration() {
1852 /* create options. */
1853 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1854 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1855 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1856 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1857 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1858 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1859 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1860 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1861 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1862 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1863 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1865 loadConfigurationValue("InsertionDelay");
1866 loadConfigurationValue("PostsPerPage");
1867 loadConfigurationValue("ImagesPerPage");
1868 loadConfigurationValue("CharactersPerPost");
1869 loadConfigurationValue("PostCutOffLength");
1870 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1871 loadConfigurationValue("PositiveTrust");
1872 loadConfigurationValue("NegativeTrust");
1873 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1874 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1875 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1877 /* load known Sones. */
1878 int soneCounter = 0;
1880 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1881 if (knownSoneId == null) {
1884 synchronized (knownSones) {
1885 knownSones.add(knownSoneId);
1889 /* load Sone following times. */
1892 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1893 if (soneId == null) {
1896 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1897 synchronized (soneFollowingTimes) {
1898 soneFollowingTimes.put(soneId, time);
1903 /* load bookmarked posts. */
1904 int bookmarkedPostCounter = 0;
1906 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1907 if (bookmarkedPostId == null) {
1910 synchronized (bookmarkedPosts) {
1911 bookmarkedPosts.add(bookmarkedPostId);
1918 * Loads an {@link Integer} configuration value for the option with the
1919 * given name, logging validation failures.
1922 * The name of the option to load
1924 private void loadConfigurationValue(String optionName) {
1926 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1927 } catch (IllegalArgumentException iae1) {
1928 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1933 * Notifies the core that a new {@link OwnIdentity} was added.
1935 * @param ownIdentityAddedEvent
1939 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1940 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1941 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1942 if (ownIdentity.hasContext("Sone")) {
1943 addLocalSone(ownIdentity);
1948 * Notifies the core that an {@link OwnIdentity} was removed.
1950 * @param ownIdentityRemovedEvent
1954 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1955 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1956 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1957 trustedIdentities.removeAll(ownIdentity);
1961 * Notifies the core that a new {@link Identity} was added.
1963 * @param identityAddedEvent
1967 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1968 Identity identity = identityAddedEvent.identity();
1969 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1970 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1971 addRemoteSone(identity);
1975 * Notifies the core that an {@link Identity} was updated.
1977 * @param identityUpdatedEvent
1981 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1982 Identity identity = identityUpdatedEvent.identity();
1983 final Sone sone = getRemoteSone(identity.getId(), false);
1984 if (sone.isLocal()) {
1987 sone.setIdentity(identity);
1988 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1989 soneDownloader.addSone(sone);
1990 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1994 * Notifies the core that an {@link Identity} was removed.
1996 * @param identityRemovedEvent
2000 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2001 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2002 Identity identity = identityRemovedEvent.identity();
2003 trustedIdentities.remove(ownIdentity, identity);
2004 boolean foundIdentity = false;
2005 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2006 if (trustedIdentity.getKey().equals(ownIdentity)) {
2009 if (trustedIdentity.getValue().contains(identity)) {
2010 foundIdentity = true;
2013 if (foundIdentity) {
2014 /* some local identity still trusts this identity, don’t remove. */
2017 Optional<Sone> sone = getSone(identity.getId());
2018 if (!sone.isPresent()) {
2019 /* TODO - we don’t have the Sone anymore. should this happen? */
2022 database.removePosts(sone.get());
2023 for (Post post : sone.get().getPosts()) {
2024 eventBus.post(new PostRemovedEvent(post));
2026 database.removePostReplies(sone.get());
2027 for (PostReply reply : sone.get().getReplies()) {
2028 eventBus.post(new PostReplyRemovedEvent(reply));
2030 synchronized (sones) {
2031 sones.remove(identity.getId());
2033 eventBus.post(new SoneRemovedEvent(sone.get()));
2037 * Deletes the temporary image.
2039 * @param imageInsertFinishedEvent
2043 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2044 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2045 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2046 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2047 touchConfiguration();
2051 class MarkPostKnown implements Runnable {
2053 private final Post post;
2055 public MarkPostKnown(Post post) {
2061 markPostKnown(post);
2067 class MarkReplyKnown implements Runnable {
2069 private final PostReply postReply;
2071 public MarkReplyKnown(PostReply postReply) {
2072 this.postReply = postReply;
2077 markReplyKnown(postReply);