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.Optional.fromNullable;
21 import static com.google.common.base.Preconditions.checkArgument;
22 import static com.google.common.base.Preconditions.checkNotNull;
23 import static com.google.common.primitives.Longs.tryParse;
24 import static java.util.logging.Logger.getLogger;
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.SoneChangeDetector.PostProcessor;
42 import net.pterodactylus.sone.core.SoneChangeDetector.PostReplyProcessor;
43 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
44 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
46 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
47 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
48 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
49 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
50 import net.pterodactylus.sone.core.event.PostRemovedEvent;
51 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
52 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
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.Image;
58 import net.pterodactylus.sone.data.LocalSone;
59 import net.pterodactylus.sone.data.Post;
60 import net.pterodactylus.sone.data.PostReply;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.SoneStatus;
64 import net.pterodactylus.sone.data.TemporaryImage;
65 import net.pterodactylus.sone.database.AlbumBuilder;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.ImageBuilder;
69 import net.pterodactylus.sone.database.PostBuilder;
70 import net.pterodactylus.sone.database.PostProvider;
71 import net.pterodactylus.sone.database.PostReplyBuilder;
72 import net.pterodactylus.sone.database.PostReplyProvider;
73 import net.pterodactylus.sone.database.SoneBuilder;
74 import net.pterodactylus.sone.database.SoneProvider;
75 import net.pterodactylus.sone.freenet.wot.Identity;
76 import net.pterodactylus.sone.freenet.wot.IdentityManager;
77 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
83 import net.pterodactylus.util.config.Configuration;
84 import net.pterodactylus.util.config.ConfigurationException;
85 import net.pterodactylus.util.service.AbstractService;
86 import net.pterodactylus.util.thread.NamedThreadFactory;
88 import com.google.common.annotations.VisibleForTesting;
89 import com.google.common.base.Function;
90 import com.google.common.base.Optional;
91 import com.google.common.collect.HashMultimap;
92 import com.google.common.collect.Multimap;
93 import com.google.common.collect.Multimaps;
94 import com.google.common.eventbus.EventBus;
95 import com.google.common.eventbus.Subscribe;
96 import com.google.inject.Inject;
97 import com.google.inject.Singleton;
102 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
105 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
108 private static final Logger logger = getLogger("Sone.Core");
110 /** The start time. */
111 private final long startupTime = System.currentTimeMillis();
113 /** The preferences. */
114 private final Preferences preferences;
116 /** The event bus. */
117 private final EventBus eventBus;
119 /** The configuration. */
120 private final Configuration configuration;
122 /** Whether we’re currently saving the configuration. */
123 private boolean storingConfiguration = false;
125 /** The identity manager. */
126 private final IdentityManager identityManager;
128 /** Interface to freenet. */
129 private final FreenetInterface freenetInterface;
131 /** The Sone downloader. */
132 private final SoneDownloader soneDownloader;
134 /** The image inserter. */
135 private final ImageInserter imageInserter;
137 /** Sone downloader thread-pool. */
138 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
140 /** The update checker. */
141 private final UpdateChecker updateChecker;
143 /** The trust updater. */
144 private final WebOfTrustUpdater webOfTrustUpdater;
146 /** The times Sones were followed. */
147 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
149 /** Locked local Sones. */
150 /* synchronize on itself. */
151 private final Set<LocalSone> lockedSones = new HashSet<LocalSone>();
153 /** Sone inserters. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
157 /** Sone rescuers. */
158 /* synchronize access on this on sones. */
159 private final Map<LocalSone, SoneRescuer> soneRescuers = new HashMap<LocalSone, SoneRescuer>();
161 /** All known Sones. */
162 private final Set<String> knownSones = new HashSet<String>();
164 /** The post database. */
165 private final Database database;
167 /** Trusted identities, sorted by own identities. */
168 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
170 /** All temporary images. */
171 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
173 /** Ticker for threads that mark own elements as known. */
174 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
176 /** The time the configuration was last touched. */
177 private volatile long lastConfigurationUpdate;
180 * Creates a new core.
182 * @param configuration
183 * The configuration of the core
184 * @param freenetInterface
185 * The freenet interface
186 * @param identityManager
187 * The identity manager
188 * @param webOfTrustUpdater
189 * The WebOfTrust updater
196 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
198 this.configuration = configuration;
199 this.freenetInterface = freenetInterface;
200 this.identityManager = identityManager;
201 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
202 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
203 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
204 this.webOfTrustUpdater = webOfTrustUpdater;
205 this.eventBus = eventBus;
206 this.database = database;
207 preferences = new Preferences(eventBus);
211 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
213 this.configuration = configuration;
214 this.freenetInterface = freenetInterface;
215 this.identityManager = identityManager;
216 this.soneDownloader = soneDownloader;
217 this.imageInserter = imageInserter;
218 this.updateChecker = updateChecker;
219 this.webOfTrustUpdater = webOfTrustUpdater;
220 this.eventBus = eventBus;
221 this.database = database;
222 preferences = new Preferences(eventBus);
230 * Returns the time Sone was started.
232 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
234 public long getStartupTime() {
239 * Returns the options used by the core.
241 * @return The options of the core
243 public Preferences getPreferences() {
248 * Returns the identity manager used by the core.
250 * @return The identity manager
252 public IdentityManager getIdentityManager() {
253 return identityManager;
257 * Returns the update checker.
259 * @return The update checker
261 public UpdateChecker getUpdateChecker() {
262 return updateChecker;
266 * Returns the Sone rescuer for the given local Sone.
269 * The local Sone to get the rescuer for
270 * @return The Sone rescuer for the given Sone
272 public SoneRescuer getSoneRescuer(LocalSone sone) {
273 checkNotNull(sone, "sone must not be null");
274 synchronized (soneRescuers) {
275 SoneRescuer soneRescuer = soneRescuers.get(sone);
276 if (soneRescuer == null) {
277 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
278 soneRescuers.put(sone, soneRescuer);
286 * Returns whether the given Sone is currently locked.
290 * @return {@code true} if the Sone is locked, {@code false} if it is not
292 public boolean isLocked(LocalSone sone) {
293 synchronized (lockedSones) {
294 return lockedSones.contains(sone);
298 public SoneBuilder soneBuilder() {
299 return database.newSoneBuilder();
306 public Collection<Sone> getSones() {
307 return database.getSones();
311 public Function<String, Optional<Sone>> soneLoader() {
312 return database.soneLoader();
316 * Returns the Sone with the given ID, regardless whether it’s local or
320 * The ID of the Sone to get
321 * @return The Sone with the given ID, or {@code null} if there is no such
325 public Optional<Sone> getSone(String id) {
326 return database.getSone(id);
330 public Collection<LocalSone> getLocalSones() {
331 return database.getLocalSones();
334 public Optional<LocalSone> getLocalSone(String id) {
335 return database.getLocalSone(id);
342 public Collection<Sone> getRemoteSones() {
343 return database.getRemoteSones();
347 * Returns the remote Sone with the given ID.
351 * The ID of the remote Sone to get
352 * @return The Sone with the given ID
354 public Sone getRemoteSone(String id) {
355 return database.getSone(id).orNull();
359 * Returns whether the given Sone has been modified.
362 * The Sone to check for modifications
363 * @return {@code true} if a modification has been detected in the Sone,
364 * {@code false} otherwise
366 public boolean isModifiedSone(Sone sone) {
367 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
371 * Returns the time when the given was first followed by any local Sone.
374 * The Sone to get the time for
375 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
376 * been followed, or {@link Long#MAX_VALUE}
378 public long getSoneFollowingTime(Sone sone) {
379 synchronized (soneFollowingTimes) {
380 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
385 * Returns a post builder.
387 * @return A new post builder
389 public PostBuilder postBuilder() {
390 return database.newPostBuilder();
397 public Optional<Post> getPost(String postId) {
398 return database.getPost(postId);
405 public Collection<Post> getPosts(String soneId) {
406 return database.getPosts(soneId);
413 public Collection<Post> getDirectedPosts(final String recipientId) {
414 checkNotNull(recipientId, "recipient must not be null");
415 return database.getDirectedPosts(recipientId);
419 * Returns a post reply builder.
421 * @return A new post reply builder
423 public PostReplyBuilder postReplyBuilder() {
424 return database.newPostReplyBuilder();
431 public Optional<PostReply> getPostReply(String replyId) {
432 return database.getPostReply(replyId);
439 public List<PostReply> getReplies(final String postId) {
440 return database.getReplies(postId);
444 * Returns all Sones that have liked the given post.
447 * The post to get the liking Sones for
448 * @return The Sones that like the given post
450 public Set<Sone> getLikes(Post post) {
451 Set<Sone> sones = new HashSet<Sone>();
452 for (Sone sone : getSones()) {
453 if (sone.getLikedPostIds().contains(post.getId())) {
461 * Returns all Sones that have liked the given reply.
464 * The reply to get the liking Sones for
465 * @return The Sones that like the given reply
467 public Set<Sone> getLikes(PostReply reply) {
468 Set<Sone> sones = new HashSet<Sone>();
469 for (Sone sone : getSones()) {
470 if (sone.getLikedReplyIds().contains(reply.getId())) {
478 * Returns whether the given post is bookmarked.
482 * @return {@code true} if the given post is bookmarked, {@code false}
485 public boolean isBookmarked(Post post) {
486 return database.isPostBookmarked(post);
490 * Returns all currently known bookmarked posts.
492 * @return All bookmarked posts
494 public Set<Post> getBookmarkedPosts() {
495 return database.getBookmarkedPosts();
498 public AlbumBuilder albumBuilder() {
499 return database.newAlbumBuilder();
503 * Returns the album with the given ID, optionally creating a new album if
504 * an album with the given ID can not be found.
507 * The ID of the album
508 * @return The album with the given ID, or {@code null} if no album with the
511 public Album getAlbum(String albumId) {
512 return database.getAlbum(albumId).orNull();
515 public ImageBuilder imageBuilder() {
516 return database.newImageBuilder();
520 * Returns the image with the given ID, creating it if necessary.
523 * The ID of the image
524 * @return The image with the given ID
526 public Image getImage(String imageId) {
527 return getImage(imageId, true);
531 * Returns the image with the given ID, optionally creating it if it does
535 * The ID of the image
537 * {@code true} to create an image if none exists with the given
539 * @return The image with the given ID, or {@code null} if none exists and
542 public Image getImage(String imageId, boolean create) {
543 Optional<Image> image = database.getImage(imageId);
544 if (image.isPresent()) {
550 Image newImage = database.newImageBuilder().withId(imageId).build();
551 database.storeImage(newImage);
556 * Returns the temporary image with the given ID.
559 * The ID of the temporary image
560 * @return The temporary image, or {@code null} if there is no temporary
561 * image with the given ID
563 public TemporaryImage getTemporaryImage(String imageId) {
564 synchronized (temporaryImages) {
565 return temporaryImages.get(imageId);
574 * Locks the given Sone. A locked Sone will not be inserted by
575 * {@link SoneInserter} until it is {@link #unlockSone(LocalSone) unlocked}
581 public void lockSone(LocalSone sone) {
582 synchronized (lockedSones) {
583 if (lockedSones.add(sone)) {
584 eventBus.post(new SoneLockedEvent(sone));
590 * Unlocks the given Sone.
592 * @see #lockSone(LocalSone)
596 public void unlockSone(LocalSone sone) {
597 synchronized (lockedSones) {
598 if (lockedSones.remove(sone)) {
599 eventBus.post(new SoneUnlockedEvent(sone));
605 * Adds a local Sone from the given own identity.
608 * The own identity to create a Sone from
609 * @return The added (or already existing) Sone
611 public Sone addLocalSone(OwnIdentity ownIdentity) {
612 if (ownIdentity == null) {
613 logger.log(Level.WARNING, "Given OwnIdentity is null!");
616 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
617 Sone sone = database.registerLocalSone(ownIdentity);
618 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
619 eventBus.register(soneInserter);
620 synchronized (soneInserters) {
621 soneInserters.put(sone, soneInserter);
623 synchronized (soneInserters) {
624 soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
626 sone.setStatus(SoneStatus.idle);
627 soneInserter.start();
632 * Creates a new Sone for the given own identity.
635 * The own identity to create a Sone for
636 * @return The created Sone
638 public Sone createSone(OwnIdentity ownIdentity) {
639 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
640 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
643 Sone sone = addLocalSone(ownIdentity);
645 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
646 touchConfiguration();
651 * Adds the Sone of the given identity.
654 * The identity whose Sone to add
655 * @return The added or already existing Sone
657 public Sone addRemoteSone(Identity identity) {
658 if (identity == null) {
659 logger.log(Level.WARNING, "Given Identity is null!");
662 final Long latestEdition = tryParse(fromNullable(
663 identity.getProperty("Sone.LatestEdition")).or("0"));
664 Optional<Sone> existingSone = getSone(identity.getId());
665 if (existingSone.isPresent() && existingSone.get().isLocal()) {
666 return existingSone.get();
668 boolean newSone = !existingSone.isPresent();
669 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
670 sone.setLatestEdition(latestEdition);
672 synchronized (knownSones) {
673 newSone = !knownSones.contains(sone.getId());
675 sone.setKnown(!newSone);
677 eventBus.post(new NewSoneFoundEvent(sone));
678 for (Sone localSone : getLocalSones()) {
679 if (localSone.getOptions().isAutoFollow()) {
680 followSone(localSone, sone.getId());
685 database.storeSone(sone);
686 soneDownloader.addSone(sone);
687 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
692 * Lets the given local Sone follow the Sone with the given ID.
695 * The local Sone that should follow another Sone
697 * The ID of the Sone to follow
699 public void followSone(Sone sone, String soneId) {
700 checkNotNull(sone, "sone must not be null");
701 checkNotNull(soneId, "soneId must not be null");
702 database.addFriend(sone, soneId);
703 synchronized (soneFollowingTimes) {
704 if (!soneFollowingTimes.containsKey(soneId)) {
705 long now = System.currentTimeMillis();
706 soneFollowingTimes.put(soneId, now);
707 Optional<Sone> followedSone = getSone(soneId);
708 if (!followedSone.isPresent()) {
711 for (Post post : followedSone.get().getPosts()) {
712 if (post.getTime() < now) {
716 for (PostReply reply : followedSone.get().getReplies()) {
717 if (reply.getTime() < now) {
718 markReplyKnown(reply);
723 touchConfiguration();
727 * Lets the given local Sone unfollow the Sone with the given ID.
730 * The local Sone that should unfollow another Sone
732 * The ID of the Sone being unfollowed
734 public void unfollowSone(Sone sone, String soneId) {
735 checkNotNull(sone, "sone must not be null");
736 checkNotNull(soneId, "soneId must not be null");
737 database.removeFriend(sone, soneId);
738 boolean unfollowedSoneStillFollowed = false;
739 for (Sone localSone : getLocalSones()) {
740 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
742 if (!unfollowedSoneStillFollowed) {
743 synchronized (soneFollowingTimes) {
744 soneFollowingTimes.remove(soneId);
747 touchConfiguration();
751 * Sets the trust value of the given origin Sone for the target Sone.
758 * The trust value (from {@code -100} to {@code 100})
760 public void setTrust(Sone origin, Sone target, int trustValue) {
761 checkNotNull(origin, "origin must not be null");
762 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
763 checkNotNull(target, "target must not be null");
764 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
765 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
769 * Removes any trust assignment for the given target Sone.
776 public void removeTrust(Sone origin, Sone target) {
777 checkNotNull(origin, "origin must not be null");
778 checkNotNull(target, "target must not be null");
779 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
780 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
784 * Assigns the configured positive trust value for the given target.
791 public void trustSone(Sone origin, Sone target) {
792 setTrust(origin, target, preferences.getPositiveTrust());
796 * Assigns the configured negative trust value for the given target.
803 public void distrustSone(Sone origin, Sone target) {
804 setTrust(origin, target, preferences.getNegativeTrust());
808 * Removes the trust assignment for the given target.
815 public void untrustSone(Sone origin, Sone target) {
816 removeTrust(origin, target);
820 * Updates the stored Sone with the given Sone.
825 public void updateSone(Sone sone) {
826 updateSone(sone, false);
830 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
831 * {@code true}, an older Sone than the current Sone can be given to restore
836 * @param soneRescueMode
837 * {@code true} if the stored Sone should be updated regardless
838 * of the age of the given Sone
840 public void updateSone(final Sone sone, boolean soneRescueMode) {
841 Optional<Sone> storedSone = getSone(sone.getId());
842 if (storedSone.isPresent()) {
843 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
844 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
847 List<Object> events =
848 collectEventsForChangesInSone(storedSone.get(), sone);
849 database.storeSone(sone);
850 for (Object event : events) {
851 eventBus.post(event);
853 sone.setOptions(storedSone.get().getOptions());
854 sone.setKnown(storedSone.get().isKnown());
855 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
856 if (sone.isLocal()) {
857 touchConfiguration();
862 private List<Object> collectEventsForChangesInSone(Sone oldSone,
863 final Sone newSone) {
864 final List<Object> events = new ArrayList<Object>();
865 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
867 soneChangeDetector.onNewPosts(new PostProcessor() {
869 public void processPost(Post post) {
870 if (post.getTime() < getSoneFollowingTime(newSone)) {
872 } else if (!post.isKnown()) {
873 events.add(new NewPostFoundEvent(post));
877 soneChangeDetector.onRemovedPosts(new PostProcessor() {
879 public void processPost(Post post) {
880 events.add(new PostRemovedEvent(post));
883 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
885 public void processPostReply(PostReply postReply) {
886 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
887 postReply.setKnown(true);
888 } else if (!postReply.isKnown()) {
889 events.add(new NewPostReplyFoundEvent(postReply));
893 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
895 public void processPostReply(PostReply postReply) {
896 events.add(new PostReplyRemovedEvent(postReply));
899 soneChangeDetector.detectChanges(newSone);
904 * Deletes the given Sone. This will remove the Sone from the
905 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
906 * remove the context from its identity.
911 public void deleteSone(Sone sone) {
912 if (!(sone.getIdentity() instanceof OwnIdentity)) {
913 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
916 if (!getLocalSones().contains(sone)) {
917 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
920 SoneInserter soneInserter = soneInserters.remove(sone);
922 database.removeSone(sone);
923 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
924 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
926 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
927 } catch (ConfigurationException ce1) {
928 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
933 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
934 * known} before, a {@link MarkSoneKnownEvent} is fired.
937 * The Sone to mark as known
939 public void markSoneKnown(Sone sone) {
940 if (!sone.isKnown()) {
942 synchronized (knownSones) {
943 knownSones.add(sone.getId());
945 eventBus.post(new MarkSoneKnownEvent(sone));
946 touchConfiguration();
951 * Creates a new post.
954 * The Sone that creates the post
956 * The recipient Sone, or {@code null} if this post does not have
959 * The text of the post
960 * @return The created post
962 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
963 checkNotNull(text, "text must not be null");
964 checkArgument(text.trim().length() > 0, "text must not be empty");
965 if (!sone.isLocal()) {
966 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
969 PostBuilder postBuilder = database.newPostBuilder();
970 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
971 if (recipient.isPresent()) {
972 postBuilder.to(recipient.get().getId());
974 final Post post = postBuilder.build();
975 database.storePost(post);
976 eventBus.post(new NewPostFoundEvent(post));
978 touchConfiguration();
979 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
984 * Deletes the given post.
989 public void deletePost(Post post) {
990 if (!post.getSone().isLocal()) {
991 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
994 database.removePost(post);
995 eventBus.post(new PostRemovedEvent(post));
997 touchConfiguration();
1001 * Marks the given post as known, if it is currently not a known post
1002 * (according to {@link Post#isKnown()}).
1005 * The post to mark as known
1007 public void markPostKnown(Post post) {
1008 post.setKnown(true);
1009 eventBus.post(new MarkPostKnownEvent(post));
1010 touchConfiguration();
1011 for (PostReply reply : getReplies(post.getId())) {
1012 markReplyKnown(reply);
1016 public void bookmarkPost(Post post) {
1017 database.bookmarkPost(post);
1021 * Removes the given post from the bookmarks.
1024 * The post to unbookmark
1026 public void unbookmarkPost(Post post) {
1027 database.unbookmarkPost(post);
1031 * Creates a new reply.
1034 * The Sone that creates the reply
1036 * The post that this reply refers to
1038 * The text of the reply
1039 * @return The created reply
1041 public PostReply createReply(Sone sone, Post post, String text) {
1042 checkNotNull(text, "text must not be null");
1043 checkArgument(text.trim().length() > 0, "text must not be empty");
1044 if (!sone.isLocal()) {
1045 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1048 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1049 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1050 final PostReply reply = postReplyBuilder.build();
1051 database.storePostReply(reply);
1052 eventBus.post(new NewPostReplyFoundEvent(reply));
1053 sone.addReply(reply);
1054 touchConfiguration();
1055 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1060 * Deletes the given reply.
1063 * The reply to delete
1065 public void deleteReply(PostReply reply) {
1066 Sone sone = reply.getSone();
1067 if (!sone.isLocal()) {
1068 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1071 database.removePostReply(reply);
1072 markReplyKnown(reply);
1073 sone.removeReply(reply);
1074 touchConfiguration();
1078 * Marks the given reply as known, if it is currently not a known reply
1079 * (according to {@link Reply#isKnown()}).
1082 * The reply to mark as known
1084 public void markReplyKnown(PostReply reply) {
1085 boolean previouslyKnown = reply.isKnown();
1086 reply.setKnown(true);
1087 eventBus.post(new MarkPostReplyKnownEvent(reply));
1088 if (!previouslyKnown) {
1089 touchConfiguration();
1094 * Creates a new album for the given Sone.
1097 * The Sone to create the album for
1099 * The parent of the album (may be {@code null} to create a
1101 * @return The new album
1103 public Album createAlbum(Sone sone, Album parent) {
1104 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1105 database.storeAlbum(album);
1106 parent.addAlbum(album);
1111 * Deletes the given album. The owner of the album has to be a local Sone,
1112 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1115 * The album to remove
1117 public void deleteAlbum(Album album) {
1118 checkNotNull(album, "album must not be null");
1119 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1120 if (!album.isEmpty()) {
1123 album.getParent().removeAlbum(album);
1124 database.removeAlbum(album);
1125 touchConfiguration();
1129 * Creates a new image.
1132 * The Sone creating the image
1134 * The album the image will be inserted into
1135 * @param temporaryImage
1136 * The temporary image to create the image from
1137 * @return The newly created image
1139 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1140 checkNotNull(sone, "sone must not be null");
1141 checkNotNull(album, "album must not be null");
1142 checkNotNull(temporaryImage, "temporaryImage must not be null");
1143 checkArgument(sone.isLocal(), "sone must be a local Sone");
1144 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1145 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1146 album.addImage(image);
1147 database.storeImage(image);
1148 imageInserter.insertImage(temporaryImage, image);
1153 * Deletes the given image. This method will also delete a matching
1156 * @see #deleteTemporaryImage(String)
1158 * The image to delete
1160 public void deleteImage(Image image) {
1161 checkNotNull(image, "image must not be null");
1162 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1163 deleteTemporaryImage(image.getId());
1164 image.getAlbum().removeImage(image);
1165 database.removeImage(image);
1166 touchConfiguration();
1170 * Creates a new temporary image.
1173 * The MIME type of the temporary image
1175 * The encoded data of the image
1176 * @return The temporary image
1178 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1179 TemporaryImage temporaryImage = new TemporaryImage();
1180 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1181 synchronized (temporaryImages) {
1182 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1184 return temporaryImage;
1188 * Deletes the temporary image with the given ID.
1191 * The ID of the temporary image to delete
1193 public void deleteTemporaryImage(String imageId) {
1194 checkNotNull(imageId, "imageId must not be null");
1195 synchronized (temporaryImages) {
1196 temporaryImages.remove(imageId);
1198 Image image = getImage(imageId, false);
1199 if (image != null) {
1200 imageInserter.cancelImageInsert(image);
1205 * Notifies the core that the configuration, either of the core or of a
1206 * single local Sone, has changed, and that the configuration should be
1209 public void touchConfiguration() {
1210 lastConfigurationUpdate = System.currentTimeMillis();
1221 public void serviceStart() {
1222 loadConfiguration();
1223 updateChecker.start();
1224 identityManager.start();
1225 webOfTrustUpdater.init();
1226 webOfTrustUpdater.start();
1234 public void serviceRun() {
1235 long lastSaved = System.currentTimeMillis();
1236 while (!shouldStop()) {
1238 long now = System.currentTimeMillis();
1239 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1240 saveConfiguration();
1250 public void serviceStop() {
1251 localElementTicker.shutdownNow();
1252 synchronized (soneInserters) {
1253 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1254 soneInserter.getValue().stop();
1258 saveConfiguration();
1259 webOfTrustUpdater.stop();
1260 updateChecker.stop();
1261 soneDownloader.stop();
1262 soneDownloaders.shutdown();
1263 identityManager.stop();
1271 * Saves the current options.
1273 private void saveConfiguration() {
1274 synchronized (configuration) {
1275 if (storingConfiguration) {
1276 logger.log(Level.FINE, "Already storing configuration…");
1279 storingConfiguration = true;
1282 /* store the options first. */
1284 preferences.saveTo(configuration);
1286 /* save known Sones. */
1287 int soneCounter = 0;
1288 synchronized (knownSones) {
1289 for (String knownSoneId : knownSones) {
1290 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1292 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1295 /* save Sone following times. */
1297 synchronized (soneFollowingTimes) {
1298 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1299 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1300 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1303 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1306 /* save known posts. */
1310 configuration.save();
1312 } catch (ConfigurationException ce1) {
1313 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1314 } catch (DatabaseException de1) {
1315 logger.log(Level.SEVERE, "Could not save database!", de1);
1317 synchronized (configuration) {
1318 storingConfiguration = false;
1324 * Loads the configuration.
1326 private void loadConfiguration() {
1327 new PreferencesLoader(preferences).loadFrom(configuration);
1329 /* load known Sones. */
1330 int soneCounter = 0;
1332 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1333 if (knownSoneId == null) {
1336 synchronized (knownSones) {
1337 knownSones.add(knownSoneId);
1341 /* load Sone following times. */
1344 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1345 if (soneId == null) {
1348 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1349 synchronized (soneFollowingTimes) {
1350 soneFollowingTimes.put(soneId, time);
1357 * Notifies the core that a new {@link OwnIdentity} was added.
1359 * @param ownIdentityAddedEvent
1363 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1364 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1365 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1366 if (ownIdentity.hasContext("Sone")) {
1367 addLocalSone(ownIdentity);
1372 * Notifies the core that an {@link OwnIdentity} was removed.
1374 * @param ownIdentityRemovedEvent
1378 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1379 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1380 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1381 trustedIdentities.removeAll(ownIdentity);
1385 * Notifies the core that a new {@link Identity} was added.
1387 * @param identityAddedEvent
1391 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1392 Identity identity = identityAddedEvent.identity();
1393 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1394 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1395 addRemoteSone(identity);
1399 * Notifies the core that an {@link Identity} was updated.
1401 * @param identityUpdatedEvent
1405 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1406 Identity identity = identityUpdatedEvent.identity();
1407 final Sone sone = getRemoteSone(identity.getId());
1408 if (sone.isLocal()) {
1411 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1412 soneDownloader.addSone(sone);
1413 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1417 * Notifies the core that an {@link Identity} was removed.
1419 * @param identityRemovedEvent
1423 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1424 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1425 Identity identity = identityRemovedEvent.identity();
1426 trustedIdentities.remove(ownIdentity, identity);
1427 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1428 if (trustedIdentity.getKey().equals(ownIdentity)) {
1431 if (trustedIdentity.getValue().contains(identity)) {
1435 Optional<Sone> sone = getSone(identity.getId());
1436 if (!sone.isPresent()) {
1437 /* TODO - we don’t have the Sone anymore. should this happen? */
1440 database.removeSone(sone.get());
1441 eventBus.post(new SoneRemovedEvent(sone.get()));
1445 public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1446 Sone sone = soneInsertedEvent.sone();
1447 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1448 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1449 sone.getLatestEdition()));
1453 * Deletes the temporary image.
1455 * @param imageInsertFinishedEvent
1459 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1460 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1461 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1462 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1463 touchConfiguration();
1467 class MarkPostKnown implements Runnable {
1469 private final Post post;
1471 public MarkPostKnown(Post post) {
1477 markPostKnown(post);
1483 class MarkReplyKnown implements Runnable {
1485 private final PostReply postReply;
1487 public MarkReplyKnown(PostReply postReply) {
1488 this.postReply = postReply;
1493 markReplyKnown(postReply);