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 /** Locked local Sones. */
147 /* synchronize on itself. */
148 private final Set<LocalSone> lockedSones = new HashSet<LocalSone>();
150 /** Sone inserters. */
151 /* synchronize access on this on sones. */
152 private final Map<LocalSone, SoneInserter> soneInserters = new HashMap<LocalSone, SoneInserter>();
154 /** Sone rescuers. */
155 /* synchronize access on this on sones. */
156 private final Map<LocalSone, SoneRescuer> soneRescuers = new HashMap<LocalSone, SoneRescuer>();
158 /** The post database. */
159 private final Database database;
161 /** Trusted identities, sorted by own identities. */
162 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
164 /** All temporary images. */
165 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
167 /** Ticker for threads that mark own elements as known. */
168 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
170 /** The time the configuration was last touched. */
171 private volatile long lastConfigurationUpdate;
174 * Creates a new core.
176 * @param configuration
177 * The configuration of the core
178 * @param freenetInterface
179 * The freenet interface
180 * @param identityManager
181 * The identity manager
182 * @param webOfTrustUpdater
183 * The WebOfTrust updater
190 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
192 this.configuration = configuration;
193 this.freenetInterface = freenetInterface;
194 this.identityManager = identityManager;
195 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
196 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
197 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
198 this.webOfTrustUpdater = webOfTrustUpdater;
199 this.eventBus = eventBus;
200 this.database = database;
201 preferences = new Preferences(eventBus);
205 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
207 this.configuration = configuration;
208 this.freenetInterface = freenetInterface;
209 this.identityManager = identityManager;
210 this.soneDownloader = soneDownloader;
211 this.imageInserter = imageInserter;
212 this.updateChecker = updateChecker;
213 this.webOfTrustUpdater = webOfTrustUpdater;
214 this.eventBus = eventBus;
215 this.database = database;
216 preferences = new Preferences(eventBus);
224 * Returns the time Sone was started.
226 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
228 public long getStartupTime() {
233 * Returns the options used by the core.
235 * @return The options of the core
237 public Preferences getPreferences() {
242 * Returns the identity manager used by the core.
244 * @return The identity manager
246 public IdentityManager getIdentityManager() {
247 return identityManager;
251 * Returns the update checker.
253 * @return The update checker
255 public UpdateChecker getUpdateChecker() {
256 return updateChecker;
260 * Returns the Sone rescuer for the given local Sone.
263 * The local Sone to get the rescuer for
264 * @return The Sone rescuer for the given Sone
266 public SoneRescuer getSoneRescuer(LocalSone sone) {
267 checkNotNull(sone, "sone must not be null");
268 synchronized (soneRescuers) {
269 SoneRescuer soneRescuer = soneRescuers.get(sone);
270 if (soneRescuer == null) {
271 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
272 soneRescuers.put(sone, soneRescuer);
280 * Returns whether the given Sone is currently locked.
284 * @return {@code true} if the Sone is locked, {@code false} if it is not
286 public boolean isLocked(LocalSone sone) {
287 synchronized (lockedSones) {
288 return lockedSones.contains(sone);
292 public SoneBuilder soneBuilder() {
293 return database.newSoneBuilder();
300 public Collection<Sone> getSones() {
301 return database.getSones();
305 public Function<String, Optional<Sone>> soneLoader() {
306 return database.soneLoader();
310 * Returns the Sone with the given ID, regardless whether it’s local or
314 * The ID of the Sone to get
315 * @return The Sone with the given ID, or {@code null} if there is no such
319 public Optional<Sone> getSone(String id) {
320 return database.getSone(id);
324 public Collection<LocalSone> getLocalSones() {
325 return database.getLocalSones();
328 public Optional<LocalSone> getLocalSone(String id) {
329 return database.getLocalSone(id);
336 public Collection<Sone> getRemoteSones() {
337 return database.getRemoteSones();
341 * Returns the remote Sone with the given ID.
345 * The ID of the remote Sone to get
346 * @return The Sone with the given ID
348 public Sone getRemoteSone(String id) {
349 return database.getSone(id).orNull();
353 * Returns whether the given Sone has been modified.
356 * The Sone to check for modifications
357 * @return {@code true} if a modification has been detected in the Sone,
358 * {@code false} otherwise
360 public boolean isModifiedSone(LocalSone sone) {
361 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
365 * Returns the time when the given was first followed by any local Sone.
368 * The Sone to get the time for
369 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
370 * been followed, or {@link Long#MAX_VALUE}
372 public long getSoneFollowingTime(Sone sone) {
373 return database.getSoneFollowingTime(sone.getId()).or(Long.MAX_VALUE);
377 * Returns a post builder.
379 * @return A new post builder
381 public PostBuilder postBuilder() {
382 return database.newPostBuilder();
389 public Optional<Post> getPost(String postId) {
390 return database.getPost(postId);
397 public Collection<Post> getPosts(String soneId) {
398 return database.getPosts(soneId);
405 public Collection<Post> getDirectedPosts(final String recipientId) {
406 checkNotNull(recipientId, "recipient must not be null");
407 return database.getDirectedPosts(recipientId);
411 * Returns a post reply builder.
413 * @return A new post reply builder
415 public PostReplyBuilder postReplyBuilder() {
416 return database.newPostReplyBuilder();
423 public Optional<PostReply> getPostReply(String replyId) {
424 return database.getPostReply(replyId);
431 public List<PostReply> getReplies(final String postId) {
432 return database.getReplies(postId);
436 * Returns all Sones that have liked the given post.
439 * The post to get the liking Sones for
440 * @return The Sones that like the given post
442 public Set<Sone> getLikes(Post post) {
443 Set<Sone> sones = new HashSet<Sone>();
444 for (Sone sone : getSones()) {
445 if (sone.getLikedPostIds().contains(post.getId())) {
453 * Returns all Sones that have liked the given reply.
456 * The reply to get the liking Sones for
457 * @return The Sones that like the given reply
459 public Set<Sone> getLikes(PostReply reply) {
460 Set<Sone> sones = new HashSet<Sone>();
461 for (Sone sone : getSones()) {
462 if (sone.getLikedReplyIds().contains(reply.getId())) {
470 * Returns whether the given post is bookmarked.
474 * @return {@code true} if the given post is bookmarked, {@code false}
477 public boolean isBookmarked(Post post) {
478 return database.isPostBookmarked(post);
482 * Returns all currently known bookmarked posts.
484 * @return All bookmarked posts
486 public Set<Post> getBookmarkedPosts() {
487 return database.getBookmarkedPosts();
490 public AlbumBuilder albumBuilder() {
491 return database.newAlbumBuilder();
495 * Returns the album with the given ID, optionally creating a new album if
496 * an album with the given ID can not be found.
499 * The ID of the album
500 * @return The album with the given ID, or {@code null} if no album with the
503 public Album getAlbum(String albumId) {
504 return database.getAlbum(albumId).orNull();
507 public ImageBuilder imageBuilder() {
508 return database.newImageBuilder();
512 * Returns the image with the given ID, creating it if necessary.
515 * The ID of the image
516 * @return The image with the given ID
518 public Image getImage(String imageId) {
519 return getImage(imageId, true);
523 * Returns the image with the given ID, optionally creating it if it does
527 * The ID of the image
529 * {@code true} to create an image if none exists with the given
531 * @return The image with the given ID, or {@code null} if none exists and
534 public Image getImage(String imageId, boolean create) {
535 Optional<Image> image = database.getImage(imageId);
536 if (image.isPresent()) {
542 Image newImage = database.newImageBuilder().withId(imageId).build();
543 database.storeImage(newImage);
548 * Returns the temporary image with the given ID.
551 * The ID of the temporary image
552 * @return The temporary image, or {@code null} if there is no temporary
553 * image with the given ID
555 public TemporaryImage getTemporaryImage(String imageId) {
556 synchronized (temporaryImages) {
557 return temporaryImages.get(imageId);
566 * Locks the given Sone. A locked Sone will not be inserted by
567 * {@link SoneInserter} until it is {@link #unlockSone(LocalSone) unlocked}
573 public void lockSone(LocalSone sone) {
574 synchronized (lockedSones) {
575 if (lockedSones.add(sone)) {
576 eventBus.post(new SoneLockedEvent(sone));
582 * Unlocks the given Sone.
584 * @see #lockSone(LocalSone)
588 public void unlockSone(LocalSone sone) {
589 synchronized (lockedSones) {
590 if (lockedSones.remove(sone)) {
591 eventBus.post(new SoneUnlockedEvent(sone));
597 * Adds a local Sone from the given own identity.
600 * The own identity to create a Sone from
601 * @return The added (or already existing) Sone
603 public LocalSone addLocalSone(OwnIdentity ownIdentity) {
604 if (ownIdentity == null) {
605 logger.log(Level.WARNING, "Given OwnIdentity is null!");
608 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
609 LocalSone sone = database.registerLocalSone(ownIdentity);
610 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
611 eventBus.register(soneInserter);
612 synchronized (soneInserters) {
613 soneInserters.put(sone, soneInserter);
615 synchronized (soneInserters) {
616 soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
618 sone.setStatus(SoneStatus.idle);
619 soneInserter.start();
624 * Creates a new Sone for the given own identity.
627 * The own identity to create a Sone for
628 * @return The created Sone
630 public Sone createSone(OwnIdentity ownIdentity) {
631 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
632 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
635 LocalSone sone = addLocalSone(ownIdentity);
637 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
638 touchConfiguration();
643 * Adds the Sone of the given identity.
646 * The identity whose Sone to add
647 * @return The added or already existing Sone
649 public Sone addRemoteSone(Identity identity) {
650 if (identity == null) {
651 logger.log(Level.WARNING, "Given Identity is null!");
654 final Long latestEdition = tryParse(fromNullable(
655 identity.getProperty("Sone.LatestEdition")).or("0"));
656 Optional<Sone> existingSone = getSone(identity.getId());
657 if (existingSone.isPresent() && existingSone.get().isLocal()) {
658 return existingSone.get();
660 boolean newSone = !existingSone.isPresent();
661 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
662 sone.setLatestEdition(latestEdition);
664 newSone = !database.isSoneKnown(sone);
665 sone.setKnown(!newSone);
667 eventBus.post(new NewSoneFoundEvent(sone));
668 for (LocalSone localSone : getLocalSones()) {
669 if (localSone.getOptions().isAutoFollow()) {
670 followSone(localSone, sone.getId());
675 database.storeSone(sone);
676 soneDownloader.addSone(sone);
677 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
682 * Lets the given local Sone follow the Sone with the given ID.
685 * The local Sone that should follow another Sone
687 * The ID of the Sone to follow
689 public void followSone(LocalSone sone, String soneId) {
690 checkNotNull(sone, "sone must not be null");
691 checkNotNull(soneId, "soneId must not be null");
692 boolean newFriend = !database.getSoneFollowingTime(soneId).isPresent();
693 database.addFriend(sone, soneId);
695 long now = System.currentTimeMillis();
696 Optional<Sone> followedSone = getSone(soneId);
697 if (!followedSone.isPresent()) {
700 for (Post post : followedSone.get().getPosts()) {
701 if (post.getTime() < now) {
705 for (PostReply reply : followedSone.get().getReplies()) {
706 if (reply.getTime() < now) {
707 markReplyKnown(reply);
714 * Lets the given local Sone unfollow the Sone with the given ID.
717 * The local Sone that should unfollow another Sone
719 * The ID of the Sone being unfollowed
721 public void unfollowSone(LocalSone sone, String soneId) {
722 checkNotNull(sone, "sone must not be null");
723 checkNotNull(soneId, "soneId must not be null");
724 database.removeFriend(sone, soneId);
728 * Sets the trust value of the given origin Sone for the target Sone.
735 * The trust value (from {@code -100} to {@code 100})
737 public void setTrust(Sone origin, Sone target, int trustValue) {
738 checkNotNull(origin, "origin must not be null");
739 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
740 checkNotNull(target, "target must not be null");
741 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
742 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
746 * Removes any trust assignment for the given target Sone.
753 public void removeTrust(Sone origin, Sone target) {
754 checkNotNull(origin, "origin must not be null");
755 checkNotNull(target, "target must not be null");
756 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
757 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
761 * Assigns the configured positive trust value for the given target.
768 public void trustSone(Sone origin, Sone target) {
769 setTrust(origin, target, preferences.getPositiveTrust());
773 * Assigns the configured negative trust value for the given target.
780 public void distrustSone(Sone origin, Sone target) {
781 setTrust(origin, target, preferences.getNegativeTrust());
785 * Removes the trust assignment for the given target.
792 public void untrustSone(Sone origin, Sone target) {
793 removeTrust(origin, target);
797 * Updates the stored Sone with the given Sone.
802 public void updateSone(Sone sone) {
803 updateSone(sone, false);
807 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
808 * {@code true}, an older Sone than the current Sone can be given to restore
813 * @param soneRescueMode
814 * {@code true} if the stored Sone should be updated regardless
815 * of the age of the given Sone
817 public void updateSone(final Sone sone, boolean soneRescueMode) {
818 Optional<Sone> storedSone = getSone(sone.getId());
819 if (storedSone.isPresent()) {
820 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
821 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
824 List<Object> events =
825 collectEventsForChangesInSone(storedSone.get(), sone);
826 database.storeSone(sone);
827 for (Object event : events) {
828 eventBus.post(event);
830 sone.setOptions(storedSone.get().getOptions());
831 sone.setKnown(storedSone.get().isKnown());
832 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
833 if (sone.isLocal()) {
834 touchConfiguration();
839 private List<Object> collectEventsForChangesInSone(Sone oldSone,
840 final Sone newSone) {
841 final List<Object> events = new ArrayList<Object>();
842 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
844 soneChangeDetector.onNewPosts(new PostProcessor() {
846 public void processPost(Post post) {
847 if (post.getTime() < getSoneFollowingTime(newSone)) {
849 } else if (!post.isKnown()) {
850 events.add(new NewPostFoundEvent(post));
854 soneChangeDetector.onRemovedPosts(new PostProcessor() {
856 public void processPost(Post post) {
857 events.add(new PostRemovedEvent(post));
860 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
862 public void processPostReply(PostReply postReply) {
863 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
864 postReply.setKnown(true);
865 } else if (!postReply.isKnown()) {
866 events.add(new NewPostReplyFoundEvent(postReply));
870 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
872 public void processPostReply(PostReply postReply) {
873 events.add(new PostReplyRemovedEvent(postReply));
876 soneChangeDetector.detectChanges(newSone);
881 * Deletes the given Sone. This will remove the Sone from the
882 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
883 * remove the context from its identity.
888 public void deleteSone(Sone sone) {
889 if (!(sone.getIdentity() instanceof OwnIdentity)) {
890 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
893 if (!getLocalSones().contains(sone)) {
894 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
897 SoneInserter soneInserter = soneInserters.remove(sone);
899 database.removeSone(sone);
900 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
901 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
903 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
904 } catch (ConfigurationException ce1) {
905 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
910 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
911 * known} before, a {@link MarkSoneKnownEvent} is fired.
914 * The Sone to mark as known
916 public void markSoneKnown(Sone sone) {
917 if (!sone.isKnown()) {
919 database.setSoneKnown(sone);
920 eventBus.post(new MarkSoneKnownEvent(sone));
921 touchConfiguration();
926 * Creates a new post.
929 * The Sone that creates the post
931 * The recipient Sone, or {@code null} if this post does not have
934 * The text of the post
935 * @return The created post
937 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
938 checkNotNull(text, "text must not be null");
939 checkArgument(text.trim().length() > 0, "text must not be empty");
940 if (!sone.isLocal()) {
941 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
944 PostBuilder postBuilder = database.newPostBuilder();
945 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
946 if (recipient.isPresent()) {
947 postBuilder.to(recipient.get().getId());
949 final Post post = postBuilder.build();
950 database.storePost(post);
951 eventBus.post(new NewPostFoundEvent(post));
953 touchConfiguration();
954 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
959 * Deletes the given post.
964 public void deletePost(Post post) {
965 if (!post.getSone().isLocal()) {
966 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
969 database.removePost(post);
970 eventBus.post(new PostRemovedEvent(post));
972 touchConfiguration();
976 * Marks the given post as known, if it is currently not a known post
977 * (according to {@link Post#isKnown()}).
980 * The post to mark as known
982 public void markPostKnown(Post post) {
984 eventBus.post(new MarkPostKnownEvent(post));
985 touchConfiguration();
986 for (PostReply reply : getReplies(post.getId())) {
987 markReplyKnown(reply);
991 public void bookmarkPost(Post post) {
992 database.bookmarkPost(post);
996 * Removes the given post from the bookmarks.
999 * The post to unbookmark
1001 public void unbookmarkPost(Post post) {
1002 database.unbookmarkPost(post);
1006 * Creates a new reply.
1009 * The Sone that creates the reply
1011 * The post that this reply refers to
1013 * The text of the reply
1014 * @return The created reply
1016 public PostReply createReply(Sone sone, Post post, String text) {
1017 checkNotNull(text, "text must not be null");
1018 checkArgument(text.trim().length() > 0, "text must not be empty");
1019 if (!sone.isLocal()) {
1020 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1023 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1024 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1025 final PostReply reply = postReplyBuilder.build();
1026 database.storePostReply(reply);
1027 eventBus.post(new NewPostReplyFoundEvent(reply));
1028 sone.addReply(reply);
1029 touchConfiguration();
1030 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1035 * Deletes the given reply.
1038 * The reply to delete
1040 public void deleteReply(PostReply reply) {
1041 Sone sone = reply.getSone();
1042 if (!sone.isLocal()) {
1043 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1046 database.removePostReply(reply);
1047 markReplyKnown(reply);
1048 sone.removeReply(reply);
1049 touchConfiguration();
1053 * Marks the given reply as known, if it is currently not a known reply
1054 * (according to {@link Reply#isKnown()}).
1057 * The reply to mark as known
1059 public void markReplyKnown(PostReply reply) {
1060 boolean previouslyKnown = reply.isKnown();
1061 reply.setKnown(true);
1062 eventBus.post(new MarkPostReplyKnownEvent(reply));
1063 if (!previouslyKnown) {
1064 touchConfiguration();
1069 * Creates a new album for the given Sone.
1072 * The Sone to create the album for
1074 * The parent of the album (may be {@code null} to create a
1076 * @return The new album
1078 public Album createAlbum(Sone sone, Album parent) {
1079 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1080 database.storeAlbum(album);
1081 parent.addAlbum(album);
1086 * Deletes the given album. The owner of the album has to be a local Sone,
1087 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1090 * The album to remove
1092 public void deleteAlbum(Album album) {
1093 checkNotNull(album, "album must not be null");
1094 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1095 if (!album.isEmpty()) {
1098 album.getParent().removeAlbum(album);
1099 database.removeAlbum(album);
1100 touchConfiguration();
1104 * Creates a new image.
1107 * The Sone creating the image
1109 * The album the image will be inserted into
1110 * @param temporaryImage
1111 * The temporary image to create the image from
1112 * @return The newly created image
1114 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1115 checkNotNull(sone, "sone must not be null");
1116 checkNotNull(album, "album must not be null");
1117 checkNotNull(temporaryImage, "temporaryImage must not be null");
1118 checkArgument(sone.isLocal(), "sone must be a local Sone");
1119 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1120 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1121 album.addImage(image);
1122 database.storeImage(image);
1123 imageInserter.insertImage(temporaryImage, image);
1128 * Deletes the given image. This method will also delete a matching
1131 * @see #deleteTemporaryImage(String)
1133 * The image to delete
1135 public void deleteImage(Image image) {
1136 checkNotNull(image, "image must not be null");
1137 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1138 deleteTemporaryImage(image.getId());
1139 image.getAlbum().removeImage(image);
1140 database.removeImage(image);
1141 touchConfiguration();
1145 * Creates a new temporary image.
1148 * The MIME type of the temporary image
1150 * The encoded data of the image
1151 * @return The temporary image
1153 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1154 TemporaryImage temporaryImage = new TemporaryImage();
1155 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1156 synchronized (temporaryImages) {
1157 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1159 return temporaryImage;
1163 * Deletes the temporary image with the given ID.
1166 * The ID of the temporary image to delete
1168 public void deleteTemporaryImage(String imageId) {
1169 checkNotNull(imageId, "imageId must not be null");
1170 synchronized (temporaryImages) {
1171 temporaryImages.remove(imageId);
1173 Image image = getImage(imageId, false);
1174 if (image != null) {
1175 imageInserter.cancelImageInsert(image);
1180 * Notifies the core that the configuration, either of the core or of a
1181 * single local Sone, has changed, and that the configuration should be
1184 public void touchConfiguration() {
1185 lastConfigurationUpdate = System.currentTimeMillis();
1196 public void serviceStart() {
1197 loadConfiguration();
1198 updateChecker.start();
1199 identityManager.start();
1200 webOfTrustUpdater.init();
1201 webOfTrustUpdater.start();
1209 public void serviceRun() {
1210 long lastSaved = System.currentTimeMillis();
1211 while (!shouldStop()) {
1213 long now = System.currentTimeMillis();
1214 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1215 saveConfiguration();
1225 public void serviceStop() {
1226 localElementTicker.shutdownNow();
1227 synchronized (soneInserters) {
1228 for (Entry<LocalSone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1229 soneInserter.getValue().stop();
1233 saveConfiguration();
1234 webOfTrustUpdater.stop();
1235 updateChecker.stop();
1236 soneDownloader.stop();
1237 soneDownloaders.shutdown();
1238 identityManager.stop();
1246 * Saves the current options.
1248 private void saveConfiguration() {
1249 synchronized (configuration) {
1250 if (storingConfiguration) {
1251 logger.log(Level.FINE, "Already storing configuration…");
1254 storingConfiguration = true;
1257 /* store the options first. */
1259 preferences.saveTo(configuration);
1261 /* save known posts. */
1265 configuration.save();
1267 } catch (ConfigurationException ce1) {
1268 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1269 } catch (DatabaseException de1) {
1270 logger.log(Level.SEVERE, "Could not save database!", de1);
1272 synchronized (configuration) {
1273 storingConfiguration = false;
1279 * Loads the configuration.
1281 private void loadConfiguration() {
1282 new PreferencesLoader(preferences).loadFrom(configuration);
1286 * Notifies the core that a new {@link OwnIdentity} was added.
1288 * @param ownIdentityAddedEvent
1292 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1293 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1294 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1295 if (ownIdentity.hasContext("Sone")) {
1296 addLocalSone(ownIdentity);
1301 * Notifies the core that an {@link OwnIdentity} was removed.
1303 * @param ownIdentityRemovedEvent
1307 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1308 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1309 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1310 trustedIdentities.removeAll(ownIdentity);
1314 * Notifies the core that a new {@link Identity} was added.
1316 * @param identityAddedEvent
1320 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1321 Identity identity = identityAddedEvent.identity();
1322 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1323 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1324 addRemoteSone(identity);
1328 * Notifies the core that an {@link Identity} was updated.
1330 * @param identityUpdatedEvent
1334 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1335 Identity identity = identityUpdatedEvent.identity();
1336 final Sone sone = getRemoteSone(identity.getId());
1337 if (sone.isLocal()) {
1340 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1341 soneDownloader.addSone(sone);
1342 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1346 * Notifies the core that an {@link Identity} was removed.
1348 * @param identityRemovedEvent
1352 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1353 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1354 Identity identity = identityRemovedEvent.identity();
1355 trustedIdentities.remove(ownIdentity, identity);
1356 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1357 if (trustedIdentity.getKey().equals(ownIdentity)) {
1360 if (trustedIdentity.getValue().contains(identity)) {
1364 Optional<Sone> sone = getSone(identity.getId());
1365 if (!sone.isPresent()) {
1366 /* TODO - we don’t have the Sone anymore. should this happen? */
1369 database.removeSone(sone.get());
1370 eventBus.post(new SoneRemovedEvent(sone.get()));
1374 public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1375 Sone sone = soneInsertedEvent.sone();
1376 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1377 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1378 sone.getLatestEdition()));
1382 * Deletes the temporary image.
1384 * @param imageInsertFinishedEvent
1388 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1389 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1390 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1391 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1392 touchConfiguration();
1396 class MarkPostKnown implements Runnable {
1398 private final Post post;
1400 public MarkPostKnown(Post post) {
1406 markPostKnown(post);
1412 class MarkReplyKnown implements Runnable {
1414 private final PostReply postReply;
1416 public MarkReplyKnown(PostReply postReply) {
1417 this.postReply = postReply;
1422 markReplyKnown(postReply);