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<LocalSone, SoneInserter> soneInserters = new HashMap<LocalSone, SoneInserter>();
157 /** Sone rescuers. */
158 /* synchronize access on this on sones. */
159 private final Map<LocalSone, SoneRescuer> soneRescuers = new HashMap<LocalSone, SoneRescuer>();
161 /** The post database. */
162 private final Database database;
164 /** Trusted identities, sorted by own identities. */
165 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
167 /** All temporary images. */
168 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
170 /** Ticker for threads that mark own elements as known. */
171 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
173 /** The time the configuration was last touched. */
174 private volatile long lastConfigurationUpdate;
177 * Creates a new core.
179 * @param configuration
180 * The configuration of the core
181 * @param freenetInterface
182 * The freenet interface
183 * @param identityManager
184 * The identity manager
185 * @param webOfTrustUpdater
186 * The WebOfTrust updater
193 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
195 this.configuration = configuration;
196 this.freenetInterface = freenetInterface;
197 this.identityManager = identityManager;
198 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
199 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
200 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
201 this.webOfTrustUpdater = webOfTrustUpdater;
202 this.eventBus = eventBus;
203 this.database = database;
204 preferences = new Preferences(eventBus);
208 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
210 this.configuration = configuration;
211 this.freenetInterface = freenetInterface;
212 this.identityManager = identityManager;
213 this.soneDownloader = soneDownloader;
214 this.imageInserter = imageInserter;
215 this.updateChecker = updateChecker;
216 this.webOfTrustUpdater = webOfTrustUpdater;
217 this.eventBus = eventBus;
218 this.database = database;
219 preferences = new Preferences(eventBus);
227 * Returns the time Sone was started.
229 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
231 public long getStartupTime() {
236 * Returns the options used by the core.
238 * @return The options of the core
240 public Preferences getPreferences() {
245 * Returns the identity manager used by the core.
247 * @return The identity manager
249 public IdentityManager getIdentityManager() {
250 return identityManager;
254 * Returns the update checker.
256 * @return The update checker
258 public UpdateChecker getUpdateChecker() {
259 return updateChecker;
263 * Returns the Sone rescuer for the given local Sone.
266 * The local Sone to get the rescuer for
267 * @return The Sone rescuer for the given Sone
269 public SoneRescuer getSoneRescuer(LocalSone sone) {
270 checkNotNull(sone, "sone must not be null");
271 synchronized (soneRescuers) {
272 SoneRescuer soneRescuer = soneRescuers.get(sone);
273 if (soneRescuer == null) {
274 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
275 soneRescuers.put(sone, soneRescuer);
283 * Returns whether the given Sone is currently locked.
287 * @return {@code true} if the Sone is locked, {@code false} if it is not
289 public boolean isLocked(LocalSone sone) {
290 synchronized (lockedSones) {
291 return lockedSones.contains(sone);
295 public SoneBuilder soneBuilder() {
296 return database.newSoneBuilder();
303 public Collection<Sone> getSones() {
304 return database.getSones();
308 public Function<String, Optional<Sone>> soneLoader() {
309 return database.soneLoader();
313 * Returns the Sone with the given ID, regardless whether it’s local or
317 * The ID of the Sone to get
318 * @return The Sone with the given ID, or {@code null} if there is no such
322 public Optional<Sone> getSone(String id) {
323 return database.getSone(id);
327 public Collection<LocalSone> getLocalSones() {
328 return database.getLocalSones();
331 public Optional<LocalSone> getLocalSone(String id) {
332 return database.getLocalSone(id);
339 public Collection<Sone> getRemoteSones() {
340 return database.getRemoteSones();
344 * Returns the remote Sone with the given ID.
348 * The ID of the remote Sone to get
349 * @return The Sone with the given ID
351 public Sone getRemoteSone(String id) {
352 return database.getSone(id).orNull();
356 * Returns whether the given Sone has been modified.
359 * The Sone to check for modifications
360 * @return {@code true} if a modification has been detected in the Sone,
361 * {@code false} otherwise
363 public boolean isModifiedSone(LocalSone sone) {
364 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
368 * Returns the time when the given was first followed by any local Sone.
371 * The Sone to get the time for
372 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
373 * been followed, or {@link Long#MAX_VALUE}
375 public long getSoneFollowingTime(Sone sone) {
376 synchronized (soneFollowingTimes) {
377 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
382 * Returns a post builder.
384 * @return A new post builder
386 public PostBuilder postBuilder() {
387 return database.newPostBuilder();
394 public Optional<Post> getPost(String postId) {
395 return database.getPost(postId);
402 public Collection<Post> getPosts(String soneId) {
403 return database.getPosts(soneId);
410 public Collection<Post> getDirectedPosts(final String recipientId) {
411 checkNotNull(recipientId, "recipient must not be null");
412 return database.getDirectedPosts(recipientId);
416 * Returns a post reply builder.
418 * @return A new post reply builder
420 public PostReplyBuilder postReplyBuilder() {
421 return database.newPostReplyBuilder();
428 public Optional<PostReply> getPostReply(String replyId) {
429 return database.getPostReply(replyId);
436 public List<PostReply> getReplies(final String postId) {
437 return database.getReplies(postId);
441 * Returns all Sones that have liked the given post.
444 * The post to get the liking Sones for
445 * @return The Sones that like the given post
447 public Set<Sone> getLikes(Post post) {
448 Set<Sone> sones = new HashSet<Sone>();
449 for (Sone sone : getSones()) {
450 if (sone.getLikedPostIds().contains(post.getId())) {
458 * Returns all Sones that have liked the given reply.
461 * The reply to get the liking Sones for
462 * @return The Sones that like the given reply
464 public Set<Sone> getLikes(PostReply reply) {
465 Set<Sone> sones = new HashSet<Sone>();
466 for (Sone sone : getSones()) {
467 if (sone.getLikedReplyIds().contains(reply.getId())) {
475 * Returns whether the given post is bookmarked.
479 * @return {@code true} if the given post is bookmarked, {@code false}
482 public boolean isBookmarked(Post post) {
483 return database.isPostBookmarked(post);
487 * Returns all currently known bookmarked posts.
489 * @return All bookmarked posts
491 public Set<Post> getBookmarkedPosts() {
492 return database.getBookmarkedPosts();
495 public AlbumBuilder albumBuilder() {
496 return database.newAlbumBuilder();
500 * Returns the album with the given ID, optionally creating a new album if
501 * an album with the given ID can not be found.
504 * The ID of the album
505 * @return The album with the given ID, or {@code null} if no album with the
508 public Album getAlbum(String albumId) {
509 return database.getAlbum(albumId).orNull();
512 public ImageBuilder imageBuilder() {
513 return database.newImageBuilder();
517 * Returns the image with the given ID, creating it if necessary.
520 * The ID of the image
521 * @return The image with the given ID
523 public Image getImage(String imageId) {
524 return getImage(imageId, true);
528 * Returns the image with the given ID, optionally creating it if it does
532 * The ID of the image
534 * {@code true} to create an image if none exists with the given
536 * @return The image with the given ID, or {@code null} if none exists and
539 public Image getImage(String imageId, boolean create) {
540 Optional<Image> image = database.getImage(imageId);
541 if (image.isPresent()) {
547 Image newImage = database.newImageBuilder().withId(imageId).build();
548 database.storeImage(newImage);
553 * Returns the temporary image with the given ID.
556 * The ID of the temporary image
557 * @return The temporary image, or {@code null} if there is no temporary
558 * image with the given ID
560 public TemporaryImage getTemporaryImage(String imageId) {
561 synchronized (temporaryImages) {
562 return temporaryImages.get(imageId);
571 * Locks the given Sone. A locked Sone will not be inserted by
572 * {@link SoneInserter} until it is {@link #unlockSone(LocalSone) unlocked}
578 public void lockSone(LocalSone sone) {
579 synchronized (lockedSones) {
580 if (lockedSones.add(sone)) {
581 eventBus.post(new SoneLockedEvent(sone));
587 * Unlocks the given Sone.
589 * @see #lockSone(LocalSone)
593 public void unlockSone(LocalSone sone) {
594 synchronized (lockedSones) {
595 if (lockedSones.remove(sone)) {
596 eventBus.post(new SoneUnlockedEvent(sone));
602 * Adds a local Sone from the given own identity.
605 * The own identity to create a Sone from
606 * @return The added (or already existing) Sone
608 public LocalSone addLocalSone(OwnIdentity ownIdentity) {
609 if (ownIdentity == null) {
610 logger.log(Level.WARNING, "Given OwnIdentity is null!");
613 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
614 LocalSone sone = database.registerLocalSone(ownIdentity);
615 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
616 eventBus.register(soneInserter);
617 synchronized (soneInserters) {
618 soneInserters.put(sone, soneInserter);
620 synchronized (soneInserters) {
621 soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
623 sone.setStatus(SoneStatus.idle);
624 soneInserter.start();
629 * Creates a new Sone for the given own identity.
632 * The own identity to create a Sone for
633 * @return The created Sone
635 public Sone createSone(OwnIdentity ownIdentity) {
636 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
637 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
640 LocalSone sone = addLocalSone(ownIdentity);
642 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
643 touchConfiguration();
648 * Adds the Sone of the given identity.
651 * The identity whose Sone to add
652 * @return The added or already existing Sone
654 public Sone addRemoteSone(Identity identity) {
655 if (identity == null) {
656 logger.log(Level.WARNING, "Given Identity is null!");
659 final Long latestEdition = tryParse(fromNullable(
660 identity.getProperty("Sone.LatestEdition")).or("0"));
661 Optional<Sone> existingSone = getSone(identity.getId());
662 if (existingSone.isPresent() && existingSone.get().isLocal()) {
663 return existingSone.get();
665 boolean newSone = !existingSone.isPresent();
666 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
667 sone.setLatestEdition(latestEdition);
669 newSone = !database.isSoneKnown(sone);
670 sone.setKnown(!newSone);
672 eventBus.post(new NewSoneFoundEvent(sone));
673 for (LocalSone localSone : getLocalSones()) {
674 if (localSone.getOptions().isAutoFollow()) {
675 followSone(localSone, sone.getId());
680 database.storeSone(sone);
681 soneDownloader.addSone(sone);
682 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
687 * Lets the given local Sone follow the Sone with the given ID.
690 * The local Sone that should follow another Sone
692 * The ID of the Sone to follow
694 public void followSone(LocalSone sone, String soneId) {
695 checkNotNull(sone, "sone must not be null");
696 checkNotNull(soneId, "soneId must not be null");
697 database.addFriend(sone, soneId);
698 synchronized (soneFollowingTimes) {
699 if (!soneFollowingTimes.containsKey(soneId)) {
700 long now = System.currentTimeMillis();
701 soneFollowingTimes.put(soneId, now);
702 Optional<Sone> followedSone = getSone(soneId);
703 if (!followedSone.isPresent()) {
706 for (Post post : followedSone.get().getPosts()) {
707 if (post.getTime() < now) {
711 for (PostReply reply : followedSone.get().getReplies()) {
712 if (reply.getTime() < now) {
713 markReplyKnown(reply);
718 touchConfiguration();
722 * Lets the given local Sone unfollow the Sone with the given ID.
725 * The local Sone that should unfollow another Sone
727 * The ID of the Sone being unfollowed
729 public void unfollowSone(LocalSone sone, String soneId) {
730 checkNotNull(sone, "sone must not be null");
731 checkNotNull(soneId, "soneId must not be null");
732 database.removeFriend(sone, soneId);
733 boolean unfollowedSoneStillFollowed = false;
734 for (Sone localSone : getLocalSones()) {
735 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
737 if (!unfollowedSoneStillFollowed) {
738 synchronized (soneFollowingTimes) {
739 soneFollowingTimes.remove(soneId);
742 touchConfiguration();
746 * Sets the trust value of the given origin Sone for the target Sone.
753 * The trust value (from {@code -100} to {@code 100})
755 public void setTrust(Sone origin, Sone target, int trustValue) {
756 checkNotNull(origin, "origin must not be null");
757 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
758 checkNotNull(target, "target must not be null");
759 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
760 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
764 * Removes any trust assignment for the given target Sone.
771 public void removeTrust(Sone origin, Sone target) {
772 checkNotNull(origin, "origin must not be null");
773 checkNotNull(target, "target must not be null");
774 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
775 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
779 * Assigns the configured positive trust value for the given target.
786 public void trustSone(Sone origin, Sone target) {
787 setTrust(origin, target, preferences.getPositiveTrust());
791 * Assigns the configured negative trust value for the given target.
798 public void distrustSone(Sone origin, Sone target) {
799 setTrust(origin, target, preferences.getNegativeTrust());
803 * Removes the trust assignment for the given target.
810 public void untrustSone(Sone origin, Sone target) {
811 removeTrust(origin, target);
815 * Updates the stored Sone with the given Sone.
820 public void updateSone(Sone sone) {
821 updateSone(sone, false);
825 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
826 * {@code true}, an older Sone than the current Sone can be given to restore
831 * @param soneRescueMode
832 * {@code true} if the stored Sone should be updated regardless
833 * of the age of the given Sone
835 public void updateSone(final Sone sone, boolean soneRescueMode) {
836 Optional<Sone> storedSone = getSone(sone.getId());
837 if (storedSone.isPresent()) {
838 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
839 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
842 List<Object> events =
843 collectEventsForChangesInSone(storedSone.get(), sone);
844 database.storeSone(sone);
845 for (Object event : events) {
846 eventBus.post(event);
848 sone.setOptions(storedSone.get().getOptions());
849 sone.setKnown(storedSone.get().isKnown());
850 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
851 if (sone.isLocal()) {
852 touchConfiguration();
857 private List<Object> collectEventsForChangesInSone(Sone oldSone,
858 final Sone newSone) {
859 final List<Object> events = new ArrayList<Object>();
860 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
862 soneChangeDetector.onNewPosts(new PostProcessor() {
864 public void processPost(Post post) {
865 if (post.getTime() < getSoneFollowingTime(newSone)) {
867 } else if (!post.isKnown()) {
868 events.add(new NewPostFoundEvent(post));
872 soneChangeDetector.onRemovedPosts(new PostProcessor() {
874 public void processPost(Post post) {
875 events.add(new PostRemovedEvent(post));
878 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
880 public void processPostReply(PostReply postReply) {
881 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
882 postReply.setKnown(true);
883 } else if (!postReply.isKnown()) {
884 events.add(new NewPostReplyFoundEvent(postReply));
888 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
890 public void processPostReply(PostReply postReply) {
891 events.add(new PostReplyRemovedEvent(postReply));
894 soneChangeDetector.detectChanges(newSone);
899 * Deletes the given Sone. This will remove the Sone from the
900 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
901 * remove the context from its identity.
906 public void deleteSone(Sone sone) {
907 if (!(sone.getIdentity() instanceof OwnIdentity)) {
908 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
911 if (!getLocalSones().contains(sone)) {
912 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
915 SoneInserter soneInserter = soneInserters.remove(sone);
917 database.removeSone(sone);
918 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
919 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
921 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
922 } catch (ConfigurationException ce1) {
923 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
928 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
929 * known} before, a {@link MarkSoneKnownEvent} is fired.
932 * The Sone to mark as known
934 public void markSoneKnown(Sone sone) {
935 if (!sone.isKnown()) {
937 database.setSoneKnown(sone);
938 eventBus.post(new MarkSoneKnownEvent(sone));
939 touchConfiguration();
944 * Creates a new post.
947 * The Sone that creates the post
949 * The recipient Sone, or {@code null} if this post does not have
952 * The text of the post
953 * @return The created post
955 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
956 checkNotNull(text, "text must not be null");
957 checkArgument(text.trim().length() > 0, "text must not be empty");
958 if (!sone.isLocal()) {
959 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
962 PostBuilder postBuilder = database.newPostBuilder();
963 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
964 if (recipient.isPresent()) {
965 postBuilder.to(recipient.get().getId());
967 final Post post = postBuilder.build();
968 database.storePost(post);
969 eventBus.post(new NewPostFoundEvent(post));
971 touchConfiguration();
972 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
977 * Deletes the given post.
982 public void deletePost(Post post) {
983 if (!post.getSone().isLocal()) {
984 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
987 database.removePost(post);
988 eventBus.post(new PostRemovedEvent(post));
990 touchConfiguration();
994 * Marks the given post as known, if it is currently not a known post
995 * (according to {@link Post#isKnown()}).
998 * The post to mark as known
1000 public void markPostKnown(Post post) {
1001 post.setKnown(true);
1002 eventBus.post(new MarkPostKnownEvent(post));
1003 touchConfiguration();
1004 for (PostReply reply : getReplies(post.getId())) {
1005 markReplyKnown(reply);
1009 public void bookmarkPost(Post post) {
1010 database.bookmarkPost(post);
1014 * Removes the given post from the bookmarks.
1017 * The post to unbookmark
1019 public void unbookmarkPost(Post post) {
1020 database.unbookmarkPost(post);
1024 * Creates a new reply.
1027 * The Sone that creates the reply
1029 * The post that this reply refers to
1031 * The text of the reply
1032 * @return The created reply
1034 public PostReply createReply(Sone sone, Post post, String text) {
1035 checkNotNull(text, "text must not be null");
1036 checkArgument(text.trim().length() > 0, "text must not be empty");
1037 if (!sone.isLocal()) {
1038 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1041 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1042 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1043 final PostReply reply = postReplyBuilder.build();
1044 database.storePostReply(reply);
1045 eventBus.post(new NewPostReplyFoundEvent(reply));
1046 sone.addReply(reply);
1047 touchConfiguration();
1048 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1053 * Deletes the given reply.
1056 * The reply to delete
1058 public void deleteReply(PostReply reply) {
1059 Sone sone = reply.getSone();
1060 if (!sone.isLocal()) {
1061 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1064 database.removePostReply(reply);
1065 markReplyKnown(reply);
1066 sone.removeReply(reply);
1067 touchConfiguration();
1071 * Marks the given reply as known, if it is currently not a known reply
1072 * (according to {@link Reply#isKnown()}).
1075 * The reply to mark as known
1077 public void markReplyKnown(PostReply reply) {
1078 boolean previouslyKnown = reply.isKnown();
1079 reply.setKnown(true);
1080 eventBus.post(new MarkPostReplyKnownEvent(reply));
1081 if (!previouslyKnown) {
1082 touchConfiguration();
1087 * Creates a new album for the given Sone.
1090 * The Sone to create the album for
1092 * The parent of the album (may be {@code null} to create a
1094 * @return The new album
1096 public Album createAlbum(Sone sone, Album parent) {
1097 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1098 database.storeAlbum(album);
1099 parent.addAlbum(album);
1104 * Deletes the given album. The owner of the album has to be a local Sone,
1105 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1108 * The album to remove
1110 public void deleteAlbum(Album album) {
1111 checkNotNull(album, "album must not be null");
1112 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1113 if (!album.isEmpty()) {
1116 album.getParent().removeAlbum(album);
1117 database.removeAlbum(album);
1118 touchConfiguration();
1122 * Creates a new image.
1125 * The Sone creating the image
1127 * The album the image will be inserted into
1128 * @param temporaryImage
1129 * The temporary image to create the image from
1130 * @return The newly created image
1132 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1133 checkNotNull(sone, "sone must not be null");
1134 checkNotNull(album, "album must not be null");
1135 checkNotNull(temporaryImage, "temporaryImage must not be null");
1136 checkArgument(sone.isLocal(), "sone must be a local Sone");
1137 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1138 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1139 album.addImage(image);
1140 database.storeImage(image);
1141 imageInserter.insertImage(temporaryImage, image);
1146 * Deletes the given image. This method will also delete a matching
1149 * @see #deleteTemporaryImage(String)
1151 * The image to delete
1153 public void deleteImage(Image image) {
1154 checkNotNull(image, "image must not be null");
1155 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1156 deleteTemporaryImage(image.getId());
1157 image.getAlbum().removeImage(image);
1158 database.removeImage(image);
1159 touchConfiguration();
1163 * Creates a new temporary image.
1166 * The MIME type of the temporary image
1168 * The encoded data of the image
1169 * @return The temporary image
1171 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1172 TemporaryImage temporaryImage = new TemporaryImage();
1173 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1174 synchronized (temporaryImages) {
1175 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1177 return temporaryImage;
1181 * Deletes the temporary image with the given ID.
1184 * The ID of the temporary image to delete
1186 public void deleteTemporaryImage(String imageId) {
1187 checkNotNull(imageId, "imageId must not be null");
1188 synchronized (temporaryImages) {
1189 temporaryImages.remove(imageId);
1191 Image image = getImage(imageId, false);
1192 if (image != null) {
1193 imageInserter.cancelImageInsert(image);
1198 * Notifies the core that the configuration, either of the core or of a
1199 * single local Sone, has changed, and that the configuration should be
1202 public void touchConfiguration() {
1203 lastConfigurationUpdate = System.currentTimeMillis();
1214 public void serviceStart() {
1215 loadConfiguration();
1216 updateChecker.start();
1217 identityManager.start();
1218 webOfTrustUpdater.init();
1219 webOfTrustUpdater.start();
1227 public void serviceRun() {
1228 long lastSaved = System.currentTimeMillis();
1229 while (!shouldStop()) {
1231 long now = System.currentTimeMillis();
1232 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1233 saveConfiguration();
1243 public void serviceStop() {
1244 localElementTicker.shutdownNow();
1245 synchronized (soneInserters) {
1246 for (Entry<LocalSone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1247 soneInserter.getValue().stop();
1251 saveConfiguration();
1252 webOfTrustUpdater.stop();
1253 updateChecker.stop();
1254 soneDownloader.stop();
1255 soneDownloaders.shutdown();
1256 identityManager.stop();
1264 * Saves the current options.
1266 private void saveConfiguration() {
1267 synchronized (configuration) {
1268 if (storingConfiguration) {
1269 logger.log(Level.FINE, "Already storing configuration…");
1272 storingConfiguration = true;
1275 /* store the options first. */
1277 preferences.saveTo(configuration);
1279 /* save Sone following times. */
1280 int soneCounter = 0;
1281 synchronized (soneFollowingTimes) {
1282 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1283 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1284 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1287 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1290 /* save known posts. */
1294 configuration.save();
1296 } catch (ConfigurationException ce1) {
1297 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1298 } catch (DatabaseException de1) {
1299 logger.log(Level.SEVERE, "Could not save database!", de1);
1301 synchronized (configuration) {
1302 storingConfiguration = false;
1308 * Loads the configuration.
1310 private void loadConfiguration() {
1311 new PreferencesLoader(preferences).loadFrom(configuration);
1313 /* load Sone following times. */
1314 int soneCounter = 0;
1316 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1317 if (soneId == null) {
1320 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1321 synchronized (soneFollowingTimes) {
1322 soneFollowingTimes.put(soneId, time);
1329 * Notifies the core that a new {@link OwnIdentity} was added.
1331 * @param ownIdentityAddedEvent
1335 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1336 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1337 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1338 if (ownIdentity.hasContext("Sone")) {
1339 addLocalSone(ownIdentity);
1344 * Notifies the core that an {@link OwnIdentity} was removed.
1346 * @param ownIdentityRemovedEvent
1350 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1351 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1352 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1353 trustedIdentities.removeAll(ownIdentity);
1357 * Notifies the core that a new {@link Identity} was added.
1359 * @param identityAddedEvent
1363 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1364 Identity identity = identityAddedEvent.identity();
1365 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1366 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1367 addRemoteSone(identity);
1371 * Notifies the core that an {@link Identity} was updated.
1373 * @param identityUpdatedEvent
1377 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1378 Identity identity = identityUpdatedEvent.identity();
1379 final Sone sone = getRemoteSone(identity.getId());
1380 if (sone.isLocal()) {
1383 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1384 soneDownloader.addSone(sone);
1385 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1389 * Notifies the core that an {@link Identity} was removed.
1391 * @param identityRemovedEvent
1395 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1396 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1397 Identity identity = identityRemovedEvent.identity();
1398 trustedIdentities.remove(ownIdentity, identity);
1399 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1400 if (trustedIdentity.getKey().equals(ownIdentity)) {
1403 if (trustedIdentity.getValue().contains(identity)) {
1407 Optional<Sone> sone = getSone(identity.getId());
1408 if (!sone.isPresent()) {
1409 /* TODO - we don’t have the Sone anymore. should this happen? */
1412 database.removeSone(sone.get());
1413 eventBus.post(new SoneRemovedEvent(sone.get()));
1417 public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1418 Sone sone = soneInsertedEvent.sone();
1419 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1420 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1421 sone.getLatestEdition()));
1425 * Deletes the temporary image.
1427 * @param imageInsertFinishedEvent
1431 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1432 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1433 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1434 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1435 touchConfiguration();
1439 class MarkPostKnown implements Runnable {
1441 private final Post post;
1443 public MarkPostKnown(Post post) {
1449 markPostKnown(post);
1455 class MarkReplyKnown implements Runnable {
1457 private final PostReply postReply;
1459 public MarkReplyKnown(PostReply postReply) {
1460 this.postReply = postReply;
1465 markReplyKnown(postReply);