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.Options.DefaultOption;
43 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
44 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
45 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
47 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
48 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
49 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
50 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
51 import net.pterodactylus.sone.core.event.PostRemovedEvent;
52 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneLockedEvent;
54 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
55 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
56 import net.pterodactylus.sone.data.Album;
57 import net.pterodactylus.sone.data.Client;
58 import net.pterodactylus.sone.data.Image;
59 import net.pterodactylus.sone.data.Post;
60 import net.pterodactylus.sone.data.PostReply;
61 import net.pterodactylus.sone.data.Profile;
62 import net.pterodactylus.sone.data.Profile.Field;
63 import net.pterodactylus.sone.data.Reply;
64 import net.pterodactylus.sone.data.Sone;
65 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
66 import net.pterodactylus.sone.data.Sone.SoneStatus;
67 import net.pterodactylus.sone.data.SoneImpl;
68 import net.pterodactylus.sone.data.TemporaryImage;
69 import net.pterodactylus.sone.database.Database;
70 import net.pterodactylus.sone.database.DatabaseException;
71 import net.pterodactylus.sone.database.PostBuilder;
72 import net.pterodactylus.sone.database.PostProvider;
73 import net.pterodactylus.sone.database.PostReplyBuilder;
74 import net.pterodactylus.sone.database.PostReplyProvider;
75 import net.pterodactylus.sone.database.SoneProvider;
76 import net.pterodactylus.sone.fcp.FcpInterface;
77 import net.pterodactylus.sone.freenet.wot.Identity;
78 import net.pterodactylus.sone.freenet.wot.IdentityManager;
79 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
84 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
85 import net.pterodactylus.sone.main.SonePlugin;
86 import net.pterodactylus.sone.utils.IntegerRangePredicate;
87 import net.pterodactylus.util.config.Configuration;
88 import net.pterodactylus.util.config.ConfigurationException;
89 import net.pterodactylus.util.logging.Logging;
90 import net.pterodactylus.util.number.Numbers;
91 import net.pterodactylus.util.service.AbstractService;
92 import net.pterodactylus.util.thread.NamedThreadFactory;
94 import com.google.common.annotations.VisibleForTesting;
95 import com.google.common.base.Optional;
96 import com.google.common.base.Predicates;
97 import com.google.common.collect.FluentIterable;
98 import com.google.common.collect.HashMultimap;
99 import com.google.common.collect.ImmutableSet;
100 import com.google.common.collect.Multimap;
101 import com.google.common.collect.Multimaps;
102 import com.google.common.eventbus.EventBus;
103 import com.google.common.eventbus.Subscribe;
104 import com.google.inject.Inject;
105 import com.google.inject.Singleton;
107 import freenet.keys.FreenetURI;
112 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
115 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
118 private static final Logger logger = Logging.getLogger(Core.class);
120 /** The start time. */
121 private final long startupTime = System.currentTimeMillis();
124 private final Options options = new Options();
126 /** The preferences. */
127 private final Preferences preferences = new Preferences(options);
129 /** The event bus. */
130 private final EventBus eventBus;
132 /** The configuration. */
133 private final Configuration configuration;
135 /** Whether we’re currently saving the configuration. */
136 private boolean storingConfiguration = false;
138 /** The identity manager. */
139 private final IdentityManager identityManager;
141 /** Interface to freenet. */
142 private final FreenetInterface freenetInterface;
144 /** The Sone downloader. */
145 private final SoneDownloader soneDownloader;
147 /** The image inserter. */
148 private final ImageInserter imageInserter;
150 /** Sone downloader thread-pool. */
151 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
153 /** The update checker. */
154 private final UpdateChecker updateChecker;
156 /** The trust updater. */
157 private final WebOfTrustUpdater webOfTrustUpdater;
159 /** The FCP interface. */
160 private volatile FcpInterface fcpInterface;
162 /** The times Sones were followed. */
163 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
165 /** Locked local Sones. */
166 /* synchronize on itself. */
167 private final Set<Sone> lockedSones = new HashSet<Sone>();
169 /** Sone inserters. */
170 /* synchronize access on this on sones. */
171 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
173 /** Sone rescuers. */
174 /* synchronize access on this on sones. */
175 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
178 /* synchronize access on this on itself. */
179 private final Map<String, Sone> sones = new HashMap<String, Sone>();
181 /** All known Sones. */
182 private final Set<String> knownSones = new HashSet<String>();
184 /** The post database. */
185 private final Database database;
187 /** All bookmarked posts. */
188 /* synchronize access on itself. */
189 private final Set<String> bookmarkedPosts = new HashSet<String>();
191 /** Trusted identities, sorted by own identities. */
192 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
194 /** All temporary images. */
195 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
197 /** Ticker for threads that mark own elements as known. */
198 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
200 /** The time the configuration was last touched. */
201 private volatile long lastConfigurationUpdate;
204 * Creates a new core.
206 * @param configuration
207 * The configuration of the core
208 * @param freenetInterface
209 * The freenet interface
210 * @param identityManager
211 * The identity manager
212 * @param webOfTrustUpdater
213 * The WebOfTrust updater
220 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
222 this.configuration = configuration;
223 this.freenetInterface = freenetInterface;
224 this.identityManager = identityManager;
225 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
226 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
227 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
228 this.webOfTrustUpdater = webOfTrustUpdater;
229 this.eventBus = eventBus;
230 this.database = database;
234 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
236 this.configuration = configuration;
237 this.freenetInterface = freenetInterface;
238 this.identityManager = identityManager;
239 this.soneDownloader = soneDownloader;
240 this.imageInserter = imageInserter;
241 this.updateChecker = updateChecker;
242 this.webOfTrustUpdater = webOfTrustUpdater;
243 this.eventBus = eventBus;
244 this.database = database;
252 * Returns the time Sone was started.
254 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
256 public long getStartupTime() {
261 * Returns the options used by the core.
263 * @return The options of the core
265 public Preferences getPreferences() {
270 * Returns the identity manager used by the core.
272 * @return The identity manager
274 public IdentityManager getIdentityManager() {
275 return identityManager;
279 * Returns the update checker.
281 * @return The update checker
283 public UpdateChecker getUpdateChecker() {
284 return updateChecker;
288 * Sets the FCP interface to use.
290 * @param fcpInterface
291 * The FCP interface to use
293 public void setFcpInterface(FcpInterface fcpInterface) {
294 this.fcpInterface = fcpInterface;
298 * Returns the Sone rescuer for the given local Sone.
301 * The local Sone to get the rescuer for
302 * @return The Sone rescuer for the given Sone
304 public SoneRescuer getSoneRescuer(Sone sone) {
305 checkNotNull(sone, "sone must not be null");
306 checkArgument(sone.isLocal(), "sone must be local");
307 synchronized (sones) {
308 SoneRescuer soneRescuer = soneRescuers.get(sone);
309 if (soneRescuer == null) {
310 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
311 soneRescuers.put(sone, soneRescuer);
319 * Returns whether the given Sone is currently locked.
323 * @return {@code true} if the Sone is locked, {@code false} if it is not
325 public boolean isLocked(Sone sone) {
326 synchronized (lockedSones) {
327 return lockedSones.contains(sone);
335 public Collection<Sone> getSones() {
336 synchronized (sones) {
337 return ImmutableSet.copyOf(sones.values());
342 * Returns the Sone with the given ID, regardless whether it’s local or
346 * The ID of the Sone to get
347 * @return The Sone with the given ID, or {@code null} if there is no such
351 public Optional<Sone> getSone(String id) {
352 synchronized (sones) {
353 return Optional.fromNullable(sones.get(id));
361 public Collection<Sone> getLocalSones() {
362 synchronized (sones) {
363 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
368 * Returns the local Sone with the given ID, optionally creating a new Sone.
373 * {@code true} to create a new Sone if none exists,
374 * {@code false} to return null if none exists
375 * @return The Sone with the given ID, or {@code null}
377 public Sone getLocalSone(String id, boolean create) {
378 synchronized (sones) {
379 Sone sone = sones.get(id);
380 if ((sone == null) && create) {
381 sone = new SoneImpl(id, true);
384 if ((sone != null) && !sone.isLocal()) {
385 sone = new SoneImpl(id, true);
396 public Collection<Sone> getRemoteSones() {
397 synchronized (sones) {
398 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
403 * Returns the remote Sone with the given ID.
406 * The ID of the remote Sone to get
408 * {@code true} to always create a Sone, {@code false} to return
409 * {@code null} if no Sone with the given ID exists
410 * @return The Sone with the given ID
412 public Sone getRemoteSone(String id, boolean create) {
413 synchronized (sones) {
414 Sone sone = sones.get(id);
415 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
416 sone = new SoneImpl(id, false);
424 * Returns whether the given Sone has been modified.
427 * The Sone to check for modifications
428 * @return {@code true} if a modification has been detected in the Sone,
429 * {@code false} otherwise
431 public boolean isModifiedSone(Sone sone) {
432 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
436 * Returns the time when the given was first followed by any local Sone.
439 * The Sone to get the time for
440 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
441 * been followed, or {@link Long#MAX_VALUE}
443 public long getSoneFollowingTime(Sone sone) {
444 synchronized (soneFollowingTimes) {
445 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
450 * Returns a post builder.
452 * @return A new post builder
454 public PostBuilder postBuilder() {
455 return database.newPostBuilder();
462 public Optional<Post> getPost(String postId) {
463 return database.getPost(postId);
470 public Collection<Post> getPosts(String soneId) {
471 return database.getPosts(soneId);
478 public Collection<Post> getDirectedPosts(final String recipientId) {
479 checkNotNull(recipientId, "recipient must not be null");
480 return database.getDirectedPosts(recipientId);
484 * Returns a post reply builder.
486 * @return A new post reply builder
488 public PostReplyBuilder postReplyBuilder() {
489 return database.newPostReplyBuilder();
496 public Optional<PostReply> getPostReply(String replyId) {
497 return database.getPostReply(replyId);
504 public List<PostReply> getReplies(final String postId) {
505 return database.getReplies(postId);
509 * Returns all Sones that have liked the given post.
512 * The post to get the liking Sones for
513 * @return The Sones that like the given post
515 public Set<Sone> getLikes(Post post) {
516 Set<Sone> sones = new HashSet<Sone>();
517 for (Sone sone : getSones()) {
518 if (sone.getLikedPostIds().contains(post.getId())) {
526 * Returns all Sones that have liked the given reply.
529 * The reply to get the liking Sones for
530 * @return The Sones that like the given reply
532 public Set<Sone> getLikes(PostReply reply) {
533 Set<Sone> sones = new HashSet<Sone>();
534 for (Sone sone : getSones()) {
535 if (sone.getLikedReplyIds().contains(reply.getId())) {
543 * Returns whether the given post is bookmarked.
547 * @return {@code true} if the given post is bookmarked, {@code false}
550 public boolean isBookmarked(Post post) {
551 return isPostBookmarked(post.getId());
555 * Returns whether the post with the given ID is bookmarked.
558 * The ID of the post to check
559 * @return {@code true} if the post with the given ID is bookmarked,
560 * {@code false} otherwise
562 public boolean isPostBookmarked(String id) {
563 synchronized (bookmarkedPosts) {
564 return bookmarkedPosts.contains(id);
569 * Returns all currently known bookmarked posts.
571 * @return All bookmarked posts
573 public Set<Post> getBookmarkedPosts() {
574 Set<Post> posts = new HashSet<Post>();
575 synchronized (bookmarkedPosts) {
576 for (String bookmarkedPostId : bookmarkedPosts) {
577 Optional<Post> post = getPost(bookmarkedPostId);
578 if (post.isPresent()) {
579 posts.add(post.get());
587 * Returns the album with the given ID, creating a new album if no album
588 * with the given ID can be found.
591 * The ID of the album
592 * @return The album with the given ID
594 public Album getOrCreateAlbum(String albumId) {
595 return getAlbum(albumId, true);
599 * Returns the album with the given ID, optionally creating a new album if
600 * an album with the given ID can not be found.
603 * The ID of the album
605 * {@code true} to create a new album if none exists for the
607 * @return The album with the given ID, or {@code null} if no album with the
608 * given ID exists and {@code create} is {@code false}
610 public Album getAlbum(String albumId, boolean create) {
611 Optional<Album> album = database.getAlbum(albumId);
612 if (album.isPresent()) {
618 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
619 database.storeAlbum(newAlbum);
624 * Returns the image with the given ID, creating it if necessary.
627 * The ID of the image
628 * @return The image with the given ID
630 public Image getImage(String imageId) {
631 return getImage(imageId, true);
635 * Returns the image with the given ID, optionally creating it if it does
639 * The ID of the image
641 * {@code true} to create an image if none exists with the given
643 * @return The image with the given ID, or {@code null} if none exists and
646 public Image getImage(String imageId, boolean create) {
647 Optional<Image> image = database.getImage(imageId);
648 if (image.isPresent()) {
654 Image newImage = database.newImageBuilder().withId(imageId).build();
655 database.storeImage(newImage);
660 * Returns the temporary image with the given ID.
663 * The ID of the temporary image
664 * @return The temporary image, or {@code null} if there is no temporary
665 * image with the given ID
667 public TemporaryImage getTemporaryImage(String imageId) {
668 synchronized (temporaryImages) {
669 return temporaryImages.get(imageId);
678 * Locks the given Sone. A locked Sone will not be inserted by
679 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
685 public void lockSone(Sone sone) {
686 synchronized (lockedSones) {
687 if (lockedSones.add(sone)) {
688 eventBus.post(new SoneLockedEvent(sone));
694 * Unlocks the given Sone.
696 * @see #lockSone(Sone)
700 public void unlockSone(Sone sone) {
701 synchronized (lockedSones) {
702 if (lockedSones.remove(sone)) {
703 eventBus.post(new SoneUnlockedEvent(sone));
709 * Adds a local Sone from the given own identity.
712 * The own identity to create a Sone from
713 * @return The added (or already existing) Sone
715 public Sone addLocalSone(OwnIdentity ownIdentity) {
716 if (ownIdentity == null) {
717 logger.log(Level.WARNING, "Given OwnIdentity is null!");
720 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
721 synchronized (sones) {
724 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
725 } catch (MalformedURLException mue1) {
726 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
729 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
730 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
732 /* TODO - load posts ’n stuff */
733 sones.put(ownIdentity.getId(), sone);
734 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
735 soneInserters.put(sone, soneInserter);
736 sone.setStatus(SoneStatus.idle);
738 soneInserter.start();
744 * Creates a new Sone for the given own identity.
747 * The own identity to create a Sone for
748 * @return The created Sone
750 public Sone createSone(OwnIdentity ownIdentity) {
751 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
752 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
755 Sone sone = addLocalSone(ownIdentity);
757 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
758 touchConfiguration();
763 * Adds the Sone of the given identity.
766 * The identity whose Sone to add
767 * @return The added or already existing Sone
769 public Sone addRemoteSone(Identity identity) {
770 if (identity == null) {
771 logger.log(Level.WARNING, "Given Identity is null!");
774 synchronized (sones) {
775 final Sone sone = getRemoteSone(identity.getId(), true);
776 if (sone.isLocal()) {
779 sone.setIdentity(identity);
780 boolean newSone = sone.getRequestUri() == null;
781 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
782 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
784 synchronized (knownSones) {
785 newSone = !knownSones.contains(sone.getId());
787 sone.setKnown(!newSone);
789 eventBus.post(new NewSoneFoundEvent(sone));
790 for (Sone localSone : getLocalSones()) {
791 if (localSone.getOptions().isAutoFollow()) {
792 followSone(localSone, sone.getId());
797 soneDownloader.addSone(sone);
798 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
804 * Lets the given local Sone follow the Sone with the given ID.
807 * The local Sone that should follow another Sone
809 * The ID of the Sone to follow
811 public void followSone(Sone sone, String soneId) {
812 checkNotNull(sone, "sone must not be null");
813 checkNotNull(soneId, "soneId must not be null");
814 sone.addFriend(soneId);
815 synchronized (soneFollowingTimes) {
816 if (!soneFollowingTimes.containsKey(soneId)) {
817 long now = System.currentTimeMillis();
818 soneFollowingTimes.put(soneId, now);
819 Optional<Sone> followedSone = getSone(soneId);
820 if (!followedSone.isPresent()) {
823 for (Post post : followedSone.get().getPosts()) {
824 if (post.getTime() < now) {
828 for (PostReply reply : followedSone.get().getReplies()) {
829 if (reply.getTime() < now) {
830 markReplyKnown(reply);
835 touchConfiguration();
839 * Lets the given local Sone unfollow the Sone with the given ID.
842 * The local Sone that should unfollow another Sone
844 * The ID of the Sone being unfollowed
846 public void unfollowSone(Sone sone, String soneId) {
847 checkNotNull(sone, "sone must not be null");
848 checkNotNull(soneId, "soneId must not be null");
849 sone.removeFriend(soneId);
850 boolean unfollowedSoneStillFollowed = false;
851 for (Sone localSone : getLocalSones()) {
852 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
854 if (!unfollowedSoneStillFollowed) {
855 synchronized (soneFollowingTimes) {
856 soneFollowingTimes.remove(soneId);
859 touchConfiguration();
863 * Sets the trust value of the given origin Sone for the target Sone.
870 * The trust value (from {@code -100} to {@code 100})
872 public void setTrust(Sone origin, Sone target, int trustValue) {
873 checkNotNull(origin, "origin must not be null");
874 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
875 checkNotNull(target, "target must not be null");
876 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
877 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
881 * Removes any trust assignment for the given target Sone.
888 public void removeTrust(Sone origin, Sone target) {
889 checkNotNull(origin, "origin must not be null");
890 checkNotNull(target, "target must not be null");
891 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
892 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
896 * Assigns the configured positive trust value for the given target.
903 public void trustSone(Sone origin, Sone target) {
904 setTrust(origin, target, preferences.getPositiveTrust());
908 * Assigns the configured negative trust value for the given target.
915 public void distrustSone(Sone origin, Sone target) {
916 setTrust(origin, target, preferences.getNegativeTrust());
920 * Removes the trust assignment for the given target.
927 public void untrustSone(Sone origin, Sone target) {
928 removeTrust(origin, target);
932 * Updates the stored Sone with the given Sone.
937 public void updateSone(Sone sone) {
938 updateSone(sone, false);
942 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
943 * {@code true}, an older Sone than the current Sone can be given to restore
948 * @param soneRescueMode
949 * {@code true} if the stored Sone should be updated regardless
950 * of the age of the given Sone
952 public void updateSone(Sone sone, boolean soneRescueMode) {
953 Optional<Sone> storedSone = getSone(sone.getId());
954 if (storedSone.isPresent()) {
955 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
956 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
959 /* find removed posts. */
960 Collection<Post> removedPosts = new ArrayList<Post>();
961 Collection<Post> newPosts = new ArrayList<Post>();
962 Collection<Post> existingPosts = database.getPosts(sone.getId());
963 for (Post oldPost : existingPosts) {
964 if (!sone.getPosts().contains(oldPost)) {
965 removedPosts.add(oldPost);
968 /* find new posts. */
969 for (Post newPost : sone.getPosts()) {
970 if (existingPosts.contains(newPost)) {
973 if (newPost.getTime() < getSoneFollowingTime(sone)) {
974 newPost.setKnown(true);
975 } else if (!newPost.isKnown()) {
976 newPosts.add(newPost);
980 database.storePosts(sone, sone.getPosts());
981 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
982 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
983 if (!soneRescueMode) {
984 for (PostReply reply : storedSone.get().getReplies()) {
985 if (!sone.getReplies().contains(reply)) {
986 removedPostReplies.add(reply);
990 Set<PostReply> storedReplies = storedSone.get().getReplies();
991 for (PostReply reply : sone.getReplies()) {
992 if (storedReplies.contains(reply)) {
995 if (reply.getTime() < getSoneFollowingTime(sone)) {
996 reply.setKnown(true);
997 } else if (!reply.isKnown()) {
998 newPostReplies.add(reply);
1001 database.storePostReplies(sone, sone.getReplies());
1002 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1003 database.removeAlbum(album);
1004 for (Image image : album.getImages()) {
1005 database.removeImage(image);
1008 for (Post removedPost : removedPosts) {
1009 eventBus.post(new PostRemovedEvent(removedPost));
1011 for (Post newPost : newPosts) {
1012 eventBus.post(new NewPostFoundEvent(newPost));
1014 for (PostReply removedPostReply : removedPostReplies) {
1015 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1017 for (PostReply newPostReply : newPostReplies) {
1018 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1020 for (Album album : sone.getRootAlbum().getAlbums()) {
1021 database.storeAlbum(album);
1022 for (Image image : album.getImages()) {
1023 database.storeImage(image);
1026 synchronized (sones) {
1027 sone.setOptions(storedSone.get().getOptions());
1028 sone.setKnown(storedSone.get().isKnown());
1029 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1030 if (sone.isLocal()) {
1031 soneInserters.get(storedSone.get()).setSone(sone);
1032 touchConfiguration();
1034 sones.put(sone.getId(), sone);
1040 * Deletes the given Sone. This will remove the Sone from the
1041 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1042 * remove the context from its identity.
1045 * The Sone to delete
1047 public void deleteSone(Sone sone) {
1048 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1049 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1052 synchronized (sones) {
1053 if (!getLocalSones().contains(sone)) {
1054 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1057 sones.remove(sone.getId());
1058 SoneInserter soneInserter = soneInserters.remove(sone);
1059 soneInserter.stop();
1061 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1062 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1064 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1065 } catch (ConfigurationException ce1) {
1066 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1071 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1072 * known} before, a {@link MarkSoneKnownEvent} is fired.
1075 * The Sone to mark as known
1077 public void markSoneKnown(Sone sone) {
1078 if (!sone.isKnown()) {
1079 sone.setKnown(true);
1080 synchronized (knownSones) {
1081 knownSones.add(sone.getId());
1083 eventBus.post(new MarkSoneKnownEvent(sone));
1084 touchConfiguration();
1089 * Loads and updates the given Sone from the configuration. If any error is
1090 * encountered, loading is aborted and the given Sone is not changed.
1093 * The Sone to load and update
1095 public void loadSone(Sone sone) {
1096 if (!sone.isLocal()) {
1097 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1100 logger.info(String.format("Loading local Sone: %s", sone));
1103 String sonePrefix = "Sone/" + sone.getId();
1104 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1105 if (soneTime == null) {
1106 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1109 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1112 ConfigurationSoneParser configurationSoneParser = new ConfigurationSoneParser(configuration, sone);
1113 Profile profile = configurationSoneParser.parseProfile();
1116 Collection<Post> posts;
1118 posts = configurationSoneParser.parsePosts(database);
1119 } catch (InvalidPostFound ipf) {
1120 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1125 Set<PostReply> replies = new HashSet<PostReply>();
1127 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1128 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1129 if (replyId == null) {
1132 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1133 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1134 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1135 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1136 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1139 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1140 replies.add(postReplyBuilder.build());
1143 /* load post likes. */
1144 Set<String> likedPostIds = new HashSet<String>();
1146 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1147 if (likedPostId == null) {
1150 likedPostIds.add(likedPostId);
1153 /* load reply likes. */
1154 Set<String> likedReplyIds = new HashSet<String>();
1156 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1157 if (likedReplyId == null) {
1160 likedReplyIds.add(likedReplyId);
1164 Set<String> friends = new HashSet<String>();
1166 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1167 if (friendId == null) {
1170 friends.add(friendId);
1174 List<Album> topLevelAlbums = new ArrayList<Album>();
1175 int albumCounter = 0;
1177 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1178 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1179 if (albumId == null) {
1182 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1183 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1184 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1185 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1186 if ((albumTitle == null) || (albumDescription == null)) {
1187 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1190 Album album = getOrCreateAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1191 if (albumParentId != null) {
1192 Album parentAlbum = getAlbum(albumParentId, false);
1193 if (parentAlbum == null) {
1194 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1197 parentAlbum.addAlbum(album);
1199 if (!topLevelAlbums.contains(album)) {
1200 topLevelAlbums.add(album);
1206 int imageCounter = 0;
1208 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1209 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1210 if (imageId == null) {
1213 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1214 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1215 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1216 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1217 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1218 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1219 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1220 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1221 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1224 Album album = getAlbum(albumId, false);
1225 if (album == null) {
1226 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1229 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1230 album.addImage(image);
1234 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1235 if (avatarId != null) {
1236 profile.setAvatar(getImage(avatarId, false));
1240 sone.getOptions().setAutoFollow(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1241 sone.getOptions().setSoneInsertNotificationEnabled(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1242 sone.getOptions().setShowNewSoneNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1243 sone.getOptions().setShowNewPostNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1244 sone.getOptions().setShowNewReplyNotifications(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1245 sone.getOptions().setShowCustomAvatars(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1247 /* if we’re still here, Sone was loaded successfully. */
1248 synchronized (sone) {
1249 sone.setTime(soneTime);
1250 sone.setProfile(profile);
1251 sone.setPosts(posts);
1252 sone.setReplies(replies);
1253 sone.setLikePostIds(likedPostIds);
1254 sone.setLikeReplyIds(likedReplyIds);
1255 for (String friendId : friends) {
1256 followSone(sone, friendId);
1258 for (Album album : sone.getRootAlbum().getAlbums()) {
1259 sone.getRootAlbum().removeAlbum(album);
1261 for (Album album : topLevelAlbums) {
1262 sone.getRootAlbum().addAlbum(album);
1264 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1266 synchronized (knownSones) {
1267 for (String friend : friends) {
1268 knownSones.add(friend);
1271 database.storePosts(sone, posts);
1272 for (Post post : posts) {
1273 post.setKnown(true);
1275 database.storePostReplies(sone, replies);
1276 for (PostReply reply : replies) {
1277 reply.setKnown(true);
1280 logger.info(String.format("Sone loaded successfully: %s", sone));
1284 * Creates a new post.
1287 * The Sone that creates the post
1289 * The recipient Sone, or {@code null} if this post does not have
1292 * The text of the post
1293 * @return The created post
1295 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1296 return createPost(sone, recipient, System.currentTimeMillis(), text);
1300 * Creates a new post.
1303 * The Sone that creates the post
1305 * The recipient Sone, or {@code null} if this post does not have
1308 * The time of the post
1310 * The text of the post
1311 * @return The created post
1313 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1314 checkNotNull(text, "text must not be null");
1315 checkArgument(text.trim().length() > 0, "text must not be empty");
1316 if (!sone.isLocal()) {
1317 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1320 PostBuilder postBuilder = database.newPostBuilder();
1321 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1322 if (recipient.isPresent()) {
1323 postBuilder.to(recipient.get().getId());
1325 final Post post = postBuilder.build();
1326 database.storePost(post);
1327 eventBus.post(new NewPostFoundEvent(post));
1329 touchConfiguration();
1330 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
1335 * Deletes the given post.
1338 * The post to delete
1340 public void deletePost(Post post) {
1341 if (!post.getSone().isLocal()) {
1342 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1345 database.removePost(post);
1346 eventBus.post(new PostRemovedEvent(post));
1347 markPostKnown(post);
1348 touchConfiguration();
1352 * Marks the given post as known, if it is currently not a known post
1353 * (according to {@link Post#isKnown()}).
1356 * The post to mark as known
1358 public void markPostKnown(Post post) {
1359 post.setKnown(true);
1360 eventBus.post(new MarkPostKnownEvent(post));
1361 touchConfiguration();
1362 for (PostReply reply : getReplies(post.getId())) {
1363 markReplyKnown(reply);
1368 * Bookmarks the post with the given ID.
1371 * The ID of the post to bookmark
1373 public void bookmarkPost(String id) {
1374 synchronized (bookmarkedPosts) {
1375 bookmarkedPosts.add(id);
1380 * Removes the given post from the bookmarks.
1383 * The post to unbookmark
1385 public void unbookmark(Post post) {
1386 unbookmarkPost(post.getId());
1390 * Removes the post with the given ID from the bookmarks.
1393 * The ID of the post to unbookmark
1395 public void unbookmarkPost(String id) {
1396 synchronized (bookmarkedPosts) {
1397 bookmarkedPosts.remove(id);
1402 * Creates a new reply.
1405 * The Sone that creates the reply
1407 * The post that this reply refers to
1409 * The text of the reply
1410 * @return The created reply
1412 public PostReply createReply(Sone sone, Post post, String text) {
1413 checkNotNull(text, "text must not be null");
1414 checkArgument(text.trim().length() > 0, "text must not be empty");
1415 if (!sone.isLocal()) {
1416 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1419 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1420 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1421 final PostReply reply = postReplyBuilder.build();
1422 database.storePostReply(reply);
1423 eventBus.post(new NewPostReplyFoundEvent(reply));
1424 sone.addReply(reply);
1425 touchConfiguration();
1426 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1431 * Deletes the given reply.
1434 * The reply to delete
1436 public void deleteReply(PostReply reply) {
1437 Sone sone = reply.getSone();
1438 if (!sone.isLocal()) {
1439 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1442 database.removePostReply(reply);
1443 markReplyKnown(reply);
1444 sone.removeReply(reply);
1445 touchConfiguration();
1449 * Marks the given reply as known, if it is currently not a known reply
1450 * (according to {@link Reply#isKnown()}).
1453 * The reply to mark as known
1455 public void markReplyKnown(PostReply reply) {
1456 boolean previouslyKnown = reply.isKnown();
1457 reply.setKnown(true);
1458 eventBus.post(new MarkPostReplyKnownEvent(reply));
1459 if (!previouslyKnown) {
1460 touchConfiguration();
1465 * Creates a new album for the given Sone.
1468 * The Sone to create the album for
1470 * The parent of the album (may be {@code null} to create a
1472 * @return The new album
1474 public Album createAlbum(Sone sone, Album parent) {
1475 Album album = database.newAlbumBuilder().randomId().build();
1476 database.storeAlbum(album);
1477 album.setSone(sone);
1478 parent.addAlbum(album);
1483 * Deletes the given album. The owner of the album has to be a local Sone,
1484 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1487 * The album to remove
1489 public void deleteAlbum(Album album) {
1490 checkNotNull(album, "album must not be null");
1491 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1492 if (!album.isEmpty()) {
1495 album.getParent().removeAlbum(album);
1496 database.removeAlbum(album);
1497 touchConfiguration();
1501 * Creates a new image.
1504 * The Sone creating the image
1506 * The album the image will be inserted into
1507 * @param temporaryImage
1508 * The temporary image to create the image from
1509 * @return The newly created image
1511 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1512 checkNotNull(sone, "sone must not be null");
1513 checkNotNull(album, "album must not be null");
1514 checkNotNull(temporaryImage, "temporaryImage must not be null");
1515 checkArgument(sone.isLocal(), "sone must be a local Sone");
1516 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1517 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1518 album.addImage(image);
1519 database.storeImage(image);
1520 imageInserter.insertImage(temporaryImage, image);
1525 * Deletes the given image. This method will also delete a matching
1528 * @see #deleteTemporaryImage(String)
1530 * The image to delete
1532 public void deleteImage(Image image) {
1533 checkNotNull(image, "image must not be null");
1534 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1535 deleteTemporaryImage(image.getId());
1536 image.getAlbum().removeImage(image);
1537 database.removeImage(image);
1538 touchConfiguration();
1542 * Creates a new temporary image.
1545 * The MIME type of the temporary image
1547 * The encoded data of the image
1548 * @return The temporary image
1550 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1551 TemporaryImage temporaryImage = new TemporaryImage();
1552 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1553 synchronized (temporaryImages) {
1554 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1556 return temporaryImage;
1560 * Deletes the temporary image with the given ID.
1563 * The ID of the temporary image to delete
1565 public void deleteTemporaryImage(String imageId) {
1566 checkNotNull(imageId, "imageId must not be null");
1567 synchronized (temporaryImages) {
1568 temporaryImages.remove(imageId);
1570 Image image = getImage(imageId, false);
1571 if (image != null) {
1572 imageInserter.cancelImageInsert(image);
1577 * Notifies the core that the configuration, either of the core or of a
1578 * single local Sone, has changed, and that the configuration should be
1581 public void touchConfiguration() {
1582 lastConfigurationUpdate = System.currentTimeMillis();
1593 public void serviceStart() {
1594 loadConfiguration();
1595 updateChecker.start();
1596 identityManager.start();
1597 webOfTrustUpdater.init();
1598 webOfTrustUpdater.start();
1606 public void serviceRun() {
1607 long lastSaved = System.currentTimeMillis();
1608 while (!shouldStop()) {
1610 long now = System.currentTimeMillis();
1611 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1612 for (Sone localSone : getLocalSones()) {
1613 saveSone(localSone);
1615 saveConfiguration();
1625 public void serviceStop() {
1626 localElementTicker.shutdownNow();
1627 synchronized (sones) {
1628 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1629 soneInserter.getValue().stop();
1630 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1633 saveConfiguration();
1635 webOfTrustUpdater.stop();
1636 updateChecker.stop();
1637 soneDownloader.stop();
1638 soneDownloaders.shutdown();
1639 identityManager.stop();
1647 * Saves the given Sone. This will persist all local settings for the given
1648 * Sone, such as the friends list and similar, private options.
1653 private synchronized void saveSone(Sone sone) {
1654 if (!sone.isLocal()) {
1655 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1658 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1659 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1663 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1665 /* save Sone into configuration. */
1666 String sonePrefix = "Sone/" + sone.getId();
1667 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1668 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1671 Profile profile = sone.getProfile();
1672 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1673 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1674 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1675 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1676 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1677 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1678 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1680 /* save profile fields. */
1681 int fieldCounter = 0;
1682 for (Field profileField : profile.getFields()) {
1683 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1684 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1685 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1687 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1690 int postCounter = 0;
1691 for (Post post : sone.getPosts()) {
1692 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1693 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1694 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1695 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1696 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1698 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1701 int replyCounter = 0;
1702 for (PostReply reply : sone.getReplies()) {
1703 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1704 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1705 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1706 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1707 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1709 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1711 /* save post likes. */
1712 int postLikeCounter = 0;
1713 for (String postId : sone.getLikedPostIds()) {
1714 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1716 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1718 /* save reply likes. */
1719 int replyLikeCounter = 0;
1720 for (String replyId : sone.getLikedReplyIds()) {
1721 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1723 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1726 int friendCounter = 0;
1727 for (String friendId : sone.getFriends()) {
1728 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1730 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1732 /* save albums. first, collect in a flat structure, top-level first. */
1733 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1735 int albumCounter = 0;
1736 for (Album album : albums) {
1737 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1738 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1739 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1740 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1741 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1742 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1744 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1747 int imageCounter = 0;
1748 for (Album album : albums) {
1749 for (Image image : album.getImages()) {
1750 if (!image.isInserted()) {
1753 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1754 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1755 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1756 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1757 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1758 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1759 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1760 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1761 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1764 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1767 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().isAutoFollow());
1768 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().isSoneInsertNotificationEnabled());
1769 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().isShowNewSoneNotifications());
1770 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().isShowNewPostNotifications());
1771 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().isShowNewReplyNotifications());
1772 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().getShowCustomAvatars().name());
1774 configuration.save();
1776 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1778 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1779 } catch (ConfigurationException ce1) {
1780 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1785 * Saves the current options.
1787 private void saveConfiguration() {
1788 synchronized (configuration) {
1789 if (storingConfiguration) {
1790 logger.log(Level.FINE, "Already storing configuration…");
1793 storingConfiguration = true;
1796 /* store the options first. */
1798 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1799 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1800 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1801 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1802 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1803 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1804 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1805 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1806 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1807 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1808 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1809 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1811 /* save known Sones. */
1812 int soneCounter = 0;
1813 synchronized (knownSones) {
1814 for (String knownSoneId : knownSones) {
1815 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1817 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1820 /* save Sone following times. */
1822 synchronized (soneFollowingTimes) {
1823 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1824 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1825 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1828 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1831 /* save known posts. */
1834 /* save bookmarked posts. */
1835 int bookmarkedPostCounter = 0;
1836 synchronized (bookmarkedPosts) {
1837 for (String bookmarkedPostId : bookmarkedPosts) {
1838 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1841 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1844 configuration.save();
1846 } catch (ConfigurationException ce1) {
1847 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1848 } catch (DatabaseException de1) {
1849 logger.log(Level.SEVERE, "Could not save database!", de1);
1851 synchronized (configuration) {
1852 storingConfiguration = false;
1858 * Loads the configuration.
1860 private void loadConfiguration() {
1861 /* create options. */
1862 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1863 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1864 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1865 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1866 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1867 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1868 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1869 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1870 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1871 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1872 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1874 loadConfigurationValue("InsertionDelay");
1875 loadConfigurationValue("PostsPerPage");
1876 loadConfigurationValue("ImagesPerPage");
1877 loadConfigurationValue("CharactersPerPost");
1878 loadConfigurationValue("PostCutOffLength");
1879 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1880 loadConfigurationValue("PositiveTrust");
1881 loadConfigurationValue("NegativeTrust");
1882 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
1883 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
1884 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
1886 /* load known Sones. */
1887 int soneCounter = 0;
1889 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1890 if (knownSoneId == null) {
1893 synchronized (knownSones) {
1894 knownSones.add(knownSoneId);
1898 /* load Sone following times. */
1901 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1902 if (soneId == null) {
1905 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1906 synchronized (soneFollowingTimes) {
1907 soneFollowingTimes.put(soneId, time);
1912 /* load bookmarked posts. */
1913 int bookmarkedPostCounter = 0;
1915 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
1916 if (bookmarkedPostId == null) {
1919 synchronized (bookmarkedPosts) {
1920 bookmarkedPosts.add(bookmarkedPostId);
1927 * Loads an {@link Integer} configuration value for the option with the
1928 * given name, logging validation failures.
1931 * The name of the option to load
1933 private void loadConfigurationValue(String optionName) {
1935 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
1936 } catch (IllegalArgumentException iae1) {
1937 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
1942 * Notifies the core that a new {@link OwnIdentity} was added.
1944 * @param ownIdentityAddedEvent
1948 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1949 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1950 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1951 if (ownIdentity.hasContext("Sone")) {
1952 addLocalSone(ownIdentity);
1957 * Notifies the core that an {@link OwnIdentity} was removed.
1959 * @param ownIdentityRemovedEvent
1963 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1964 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1965 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1966 trustedIdentities.removeAll(ownIdentity);
1970 * Notifies the core that a new {@link Identity} was added.
1972 * @param identityAddedEvent
1976 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1977 Identity identity = identityAddedEvent.identity();
1978 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1979 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1980 addRemoteSone(identity);
1984 * Notifies the core that an {@link Identity} was updated.
1986 * @param identityUpdatedEvent
1990 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1991 Identity identity = identityUpdatedEvent.identity();
1992 final Sone sone = getRemoteSone(identity.getId(), false);
1993 if (sone.isLocal()) {
1996 sone.setIdentity(identity);
1997 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
1998 soneDownloader.addSone(sone);
1999 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
2003 * Notifies the core that an {@link Identity} was removed.
2005 * @param identityRemovedEvent
2009 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2010 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2011 Identity identity = identityRemovedEvent.identity();
2012 trustedIdentities.remove(ownIdentity, identity);
2013 boolean foundIdentity = false;
2014 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2015 if (trustedIdentity.getKey().equals(ownIdentity)) {
2018 if (trustedIdentity.getValue().contains(identity)) {
2019 foundIdentity = true;
2022 if (foundIdentity) {
2023 /* some local identity still trusts this identity, don’t remove. */
2026 Optional<Sone> sone = getSone(identity.getId());
2027 if (!sone.isPresent()) {
2028 /* TODO - we don’t have the Sone anymore. should this happen? */
2031 database.removePosts(sone.get());
2032 for (Post post : sone.get().getPosts()) {
2033 eventBus.post(new PostRemovedEvent(post));
2035 database.removePostReplies(sone.get());
2036 for (PostReply reply : sone.get().getReplies()) {
2037 eventBus.post(new PostReplyRemovedEvent(reply));
2039 synchronized (sones) {
2040 sones.remove(identity.getId());
2042 eventBus.post(new SoneRemovedEvent(sone.get()));
2046 * Deletes the temporary image.
2048 * @param imageInsertFinishedEvent
2052 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2053 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2054 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2055 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2056 touchConfiguration();
2060 class MarkPostKnown implements Runnable {
2062 private final Post post;
2064 public MarkPostKnown(Post post) {
2070 markPostKnown(post);
2076 class MarkReplyKnown implements Runnable {
2078 private final PostReply postReply;
2080 public MarkReplyKnown(PostReply postReply) {
2081 this.postReply = postReply;
2086 markReplyKnown(postReply);