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.Post;
59 import net.pterodactylus.sone.data.PostReply;
60 import net.pterodactylus.sone.data.Reply;
61 import net.pterodactylus.sone.data.Sone;
62 import net.pterodactylus.sone.data.Sone.SoneStatus;
63 import net.pterodactylus.sone.data.TemporaryImage;
64 import net.pterodactylus.sone.database.AlbumBuilder;
65 import net.pterodactylus.sone.database.Database;
66 import net.pterodactylus.sone.database.DatabaseException;
67 import net.pterodactylus.sone.database.ImageBuilder;
68 import net.pterodactylus.sone.database.PostBuilder;
69 import net.pterodactylus.sone.database.PostProvider;
70 import net.pterodactylus.sone.database.PostReplyBuilder;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneBuilder;
73 import net.pterodactylus.sone.database.SoneProvider;
74 import net.pterodactylus.sone.freenet.wot.Identity;
75 import net.pterodactylus.sone.freenet.wot.IdentityManager;
76 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
77 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
78 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
82 import net.pterodactylus.util.config.Configuration;
83 import net.pterodactylus.util.config.ConfigurationException;
84 import net.pterodactylus.util.service.AbstractService;
85 import net.pterodactylus.util.thread.NamedThreadFactory;
87 import com.google.common.annotations.VisibleForTesting;
88 import com.google.common.base.Function;
89 import com.google.common.base.Optional;
90 import com.google.common.collect.HashMultimap;
91 import com.google.common.collect.Multimap;
92 import com.google.common.collect.Multimaps;
93 import com.google.common.eventbus.EventBus;
94 import com.google.common.eventbus.Subscribe;
95 import com.google.inject.Inject;
96 import com.google.inject.Singleton;
101 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
104 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
107 private static final Logger logger = getLogger("Sone.Core");
109 /** The start time. */
110 private final long startupTime = System.currentTimeMillis();
112 /** The preferences. */
113 private final Preferences preferences;
115 /** The event bus. */
116 private final EventBus eventBus;
118 /** The configuration. */
119 private final Configuration configuration;
121 /** Whether we’re currently saving the configuration. */
122 private boolean storingConfiguration = false;
124 /** The identity manager. */
125 private final IdentityManager identityManager;
127 /** Interface to freenet. */
128 private final FreenetInterface freenetInterface;
130 /** The Sone downloader. */
131 private final SoneDownloader soneDownloader;
133 /** The image inserter. */
134 private final ImageInserter imageInserter;
136 /** Sone downloader thread-pool. */
137 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
139 /** The update checker. */
140 private final UpdateChecker updateChecker;
142 /** The trust updater. */
143 private final WebOfTrustUpdater webOfTrustUpdater;
145 /** The times Sones were followed. */
146 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
148 /** Locked local Sones. */
149 /* synchronize on itself. */
150 private final Set<Sone> lockedSones = new HashSet<Sone>();
152 /** Sone inserters. */
153 /* synchronize access on this on sones. */
154 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
156 /** Sone rescuers. */
157 /* synchronize access on this on sones. */
158 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
160 /** All known Sones. */
161 private final Set<String> knownSones = new HashSet<String>();
163 /** The post database. */
164 private final Database database;
166 /** Trusted identities, sorted by own identities. */
167 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
169 /** All temporary images. */
170 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
172 /** Ticker for threads that mark own elements as known. */
173 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
175 /** The time the configuration was last touched. */
176 private volatile long lastConfigurationUpdate;
179 * Creates a new core.
181 * @param configuration
182 * The configuration of the core
183 * @param freenetInterface
184 * The freenet interface
185 * @param identityManager
186 * The identity manager
187 * @param webOfTrustUpdater
188 * The WebOfTrust updater
195 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
197 this.configuration = configuration;
198 this.freenetInterface = freenetInterface;
199 this.identityManager = identityManager;
200 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
201 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
202 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
203 this.webOfTrustUpdater = webOfTrustUpdater;
204 this.eventBus = eventBus;
205 this.database = database;
206 preferences = new Preferences(eventBus);
210 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
212 this.configuration = configuration;
213 this.freenetInterface = freenetInterface;
214 this.identityManager = identityManager;
215 this.soneDownloader = soneDownloader;
216 this.imageInserter = imageInserter;
217 this.updateChecker = updateChecker;
218 this.webOfTrustUpdater = webOfTrustUpdater;
219 this.eventBus = eventBus;
220 this.database = database;
221 preferences = new Preferences(eventBus);
229 * Returns the time Sone was started.
231 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
233 public long getStartupTime() {
238 * Returns the options used by the core.
240 * @return The options of the core
242 public Preferences getPreferences() {
247 * Returns the identity manager used by the core.
249 * @return The identity manager
251 public IdentityManager getIdentityManager() {
252 return identityManager;
256 * Returns the update checker.
258 * @return The update checker
260 public UpdateChecker getUpdateChecker() {
261 return updateChecker;
265 * Returns the Sone rescuer for the given local Sone.
268 * The local Sone to get the rescuer for
269 * @return The Sone rescuer for the given Sone
271 public SoneRescuer getSoneRescuer(Sone sone) {
272 checkNotNull(sone, "sone must not be null");
273 checkArgument(sone.isLocal(), "sone must be local");
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(Sone 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);
333 public Collection<Sone> getLocalSones() {
334 return database.getLocalSones();
338 * Returns the local Sone with the given ID, optionally creating a new Sone.
342 * @return The Sone with the given ID, or {@code null}
344 public Sone getLocalSone(String id) {
345 Optional<Sone> sone = database.getSone(id);
346 if (sone.isPresent() && sone.get().isLocal()) {
356 public Collection<Sone> getRemoteSones() {
357 return database.getRemoteSones();
361 * Returns the remote Sone with the given ID.
365 * The ID of the remote Sone to get
366 * @return The Sone with the given ID
368 public Sone getRemoteSone(String id) {
369 return database.getSone(id).orNull();
373 * Returns whether the given Sone has been modified.
376 * The Sone to check for modifications
377 * @return {@code true} if a modification has been detected in the Sone,
378 * {@code false} otherwise
380 public boolean isModifiedSone(Sone sone) {
381 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
385 * Returns the time when the given was first followed by any local Sone.
388 * The Sone to get the time for
389 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
390 * been followed, or {@link Long#MAX_VALUE}
392 public long getSoneFollowingTime(Sone sone) {
393 synchronized (soneFollowingTimes) {
394 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
399 * Returns a post builder.
401 * @return A new post builder
403 public PostBuilder postBuilder() {
404 return database.newPostBuilder();
411 public Optional<Post> getPost(String postId) {
412 return database.getPost(postId);
419 public Collection<Post> getPosts(String soneId) {
420 return database.getPosts(soneId);
427 public Collection<Post> getDirectedPosts(final String recipientId) {
428 checkNotNull(recipientId, "recipient must not be null");
429 return database.getDirectedPosts(recipientId);
433 * Returns a post reply builder.
435 * @return A new post reply builder
437 public PostReplyBuilder postReplyBuilder() {
438 return database.newPostReplyBuilder();
445 public Optional<PostReply> getPostReply(String replyId) {
446 return database.getPostReply(replyId);
453 public List<PostReply> getReplies(final String postId) {
454 return database.getReplies(postId);
458 * Returns all Sones that have liked the given post.
461 * The post to get the liking Sones for
462 * @return The Sones that like the given post
464 public Set<Sone> getLikes(Post post) {
465 Set<Sone> sones = new HashSet<Sone>();
466 for (Sone sone : getSones()) {
467 if (sone.getLikedPostIds().contains(post.getId())) {
475 * Returns all Sones that have liked the given reply.
478 * The reply to get the liking Sones for
479 * @return The Sones that like the given reply
481 public Set<Sone> getLikes(PostReply reply) {
482 Set<Sone> sones = new HashSet<Sone>();
483 for (Sone sone : getSones()) {
484 if (sone.getLikedReplyIds().contains(reply.getId())) {
492 * Returns whether the given post is bookmarked.
496 * @return {@code true} if the given post is bookmarked, {@code false}
499 public boolean isBookmarked(Post post) {
500 return database.isPostBookmarked(post);
504 * Returns all currently known bookmarked posts.
506 * @return All bookmarked posts
508 public Set<Post> getBookmarkedPosts() {
509 return database.getBookmarkedPosts();
512 public AlbumBuilder albumBuilder() {
513 return database.newAlbumBuilder();
517 * Returns the album with the given ID, optionally creating a new album if
518 * an album with the given ID can not be found.
521 * The ID of the album
522 * @return The album with the given ID, or {@code null} if no album with the
525 public Album getAlbum(String albumId) {
526 return database.getAlbum(albumId).orNull();
529 public ImageBuilder imageBuilder() {
530 return database.newImageBuilder();
534 * Returns the image with the given ID, creating it if necessary.
537 * The ID of the image
538 * @return The image with the given ID
540 public Image getImage(String imageId) {
541 return getImage(imageId, true);
545 * Returns the image with the given ID, optionally creating it if it does
549 * The ID of the image
551 * {@code true} to create an image if none exists with the given
553 * @return The image with the given ID, or {@code null} if none exists and
556 public Image getImage(String imageId, boolean create) {
557 Optional<Image> image = database.getImage(imageId);
558 if (image.isPresent()) {
564 Image newImage = database.newImageBuilder().withId(imageId).build();
565 database.storeImage(newImage);
570 * Returns the temporary image with the given ID.
573 * The ID of the temporary image
574 * @return The temporary image, or {@code null} if there is no temporary
575 * image with the given ID
577 public TemporaryImage getTemporaryImage(String imageId) {
578 synchronized (temporaryImages) {
579 return temporaryImages.get(imageId);
588 * Locks the given Sone. A locked Sone will not be inserted by
589 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
595 public void lockSone(Sone sone) {
596 synchronized (lockedSones) {
597 if (lockedSones.add(sone)) {
598 eventBus.post(new SoneLockedEvent(sone));
604 * Unlocks the given Sone.
606 * @see #lockSone(Sone)
610 public void unlockSone(Sone sone) {
611 synchronized (lockedSones) {
612 if (lockedSones.remove(sone)) {
613 eventBus.post(new SoneUnlockedEvent(sone));
619 * Adds a local Sone from the given own identity.
622 * The own identity to create a Sone from
623 * @return The added (or already existing) Sone
625 public Sone addLocalSone(OwnIdentity ownIdentity) {
626 if (ownIdentity == null) {
627 logger.log(Level.WARNING, "Given OwnIdentity is null!");
630 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
631 Sone sone = database.registerLocalSone(ownIdentity);
632 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
633 eventBus.register(soneInserter);
634 synchronized (soneInserters) {
635 soneInserters.put(sone, soneInserter);
637 synchronized (soneInserters) {
638 soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
640 sone.setStatus(SoneStatus.idle);
641 soneInserter.start();
646 * Creates a new Sone for the given own identity.
649 * The own identity to create a Sone for
650 * @return The created Sone
652 public Sone createSone(OwnIdentity ownIdentity) {
653 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
654 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
657 Sone sone = addLocalSone(ownIdentity);
659 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
660 touchConfiguration();
665 * Adds the Sone of the given identity.
668 * The identity whose Sone to add
669 * @return The added or already existing Sone
671 public Sone addRemoteSone(Identity identity) {
672 if (identity == null) {
673 logger.log(Level.WARNING, "Given Identity is null!");
676 final Long latestEdition = tryParse(fromNullable(
677 identity.getProperty("Sone.LatestEdition")).or("0"));
678 Optional<Sone> existingSone = getSone(identity.getId());
679 if (existingSone.isPresent() && existingSone.get().isLocal()) {
680 return existingSone.get();
682 boolean newSone = !existingSone.isPresent();
683 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
684 sone.setLatestEdition(latestEdition);
686 synchronized (knownSones) {
687 newSone = !knownSones.contains(sone.getId());
689 sone.setKnown(!newSone);
691 eventBus.post(new NewSoneFoundEvent(sone));
692 for (Sone localSone : getLocalSones()) {
693 if (localSone.getOptions().isAutoFollow()) {
694 followSone(localSone, sone.getId());
699 database.storeSone(sone);
700 soneDownloader.addSone(sone);
701 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
706 * Lets the given local Sone follow the Sone with the given ID.
709 * The local Sone that should follow another Sone
711 * The ID of the Sone to follow
713 public void followSone(Sone sone, String soneId) {
714 checkNotNull(sone, "sone must not be null");
715 checkNotNull(soneId, "soneId must not be null");
716 database.addFriend(sone, soneId);
717 synchronized (soneFollowingTimes) {
718 if (!soneFollowingTimes.containsKey(soneId)) {
719 long now = System.currentTimeMillis();
720 soneFollowingTimes.put(soneId, now);
721 Optional<Sone> followedSone = getSone(soneId);
722 if (!followedSone.isPresent()) {
725 for (Post post : followedSone.get().getPosts()) {
726 if (post.getTime() < now) {
730 for (PostReply reply : followedSone.get().getReplies()) {
731 if (reply.getTime() < now) {
732 markReplyKnown(reply);
737 touchConfiguration();
741 * Lets the given local Sone unfollow the Sone with the given ID.
744 * The local Sone that should unfollow another Sone
746 * The ID of the Sone being unfollowed
748 public void unfollowSone(Sone sone, String soneId) {
749 checkNotNull(sone, "sone must not be null");
750 checkNotNull(soneId, "soneId must not be null");
751 database.removeFriend(sone, soneId);
752 boolean unfollowedSoneStillFollowed = false;
753 for (Sone localSone : getLocalSones()) {
754 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
756 if (!unfollowedSoneStillFollowed) {
757 synchronized (soneFollowingTimes) {
758 soneFollowingTimes.remove(soneId);
761 touchConfiguration();
765 * Sets the trust value of the given origin Sone for the target Sone.
772 * The trust value (from {@code -100} to {@code 100})
774 public void setTrust(Sone origin, Sone target, int trustValue) {
775 checkNotNull(origin, "origin must not be null");
776 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
777 checkNotNull(target, "target must not be null");
778 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
779 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
783 * Removes any trust assignment for the given target Sone.
790 public void removeTrust(Sone origin, Sone target) {
791 checkNotNull(origin, "origin must not be null");
792 checkNotNull(target, "target must not be null");
793 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
794 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
798 * Assigns the configured positive trust value for the given target.
805 public void trustSone(Sone origin, Sone target) {
806 setTrust(origin, target, preferences.getPositiveTrust());
810 * Assigns the configured negative trust value for the given target.
817 public void distrustSone(Sone origin, Sone target) {
818 setTrust(origin, target, preferences.getNegativeTrust());
822 * Removes the trust assignment for the given target.
829 public void untrustSone(Sone origin, Sone target) {
830 removeTrust(origin, target);
834 * Updates the stored Sone with the given Sone.
839 public void updateSone(Sone sone) {
840 updateSone(sone, false);
844 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
845 * {@code true}, an older Sone than the current Sone can be given to restore
850 * @param soneRescueMode
851 * {@code true} if the stored Sone should be updated regardless
852 * of the age of the given Sone
854 public void updateSone(final Sone sone, boolean soneRescueMode) {
855 Optional<Sone> storedSone = getSone(sone.getId());
856 if (storedSone.isPresent()) {
857 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
858 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
861 List<Object> events =
862 collectEventsForChangesInSone(storedSone.get(), sone);
863 database.storeSone(sone);
864 for (Object event : events) {
865 eventBus.post(event);
867 sone.setOptions(storedSone.get().getOptions());
868 sone.setKnown(storedSone.get().isKnown());
869 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
870 if (sone.isLocal()) {
871 touchConfiguration();
876 private List<Object> collectEventsForChangesInSone(Sone oldSone,
877 final Sone newSone) {
878 final List<Object> events = new ArrayList<Object>();
879 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
881 soneChangeDetector.onNewPosts(new PostProcessor() {
883 public void processPost(Post post) {
884 if (post.getTime() < getSoneFollowingTime(newSone)) {
886 } else if (!post.isKnown()) {
887 events.add(new NewPostFoundEvent(post));
891 soneChangeDetector.onRemovedPosts(new PostProcessor() {
893 public void processPost(Post post) {
894 events.add(new PostRemovedEvent(post));
897 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
899 public void processPostReply(PostReply postReply) {
900 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
901 postReply.setKnown(true);
902 } else if (!postReply.isKnown()) {
903 events.add(new NewPostReplyFoundEvent(postReply));
907 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
909 public void processPostReply(PostReply postReply) {
910 events.add(new PostReplyRemovedEvent(postReply));
913 soneChangeDetector.detectChanges(newSone);
918 * Deletes the given Sone. This will remove the Sone from the
919 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
920 * remove the context from its identity.
925 public void deleteSone(Sone sone) {
926 if (!(sone.getIdentity() instanceof OwnIdentity)) {
927 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
930 if (!getLocalSones().contains(sone)) {
931 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
934 SoneInserter soneInserter = soneInserters.remove(sone);
936 database.removeSone(sone);
937 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
938 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
940 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
941 } catch (ConfigurationException ce1) {
942 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
947 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
948 * known} before, a {@link MarkSoneKnownEvent} is fired.
951 * The Sone to mark as known
953 public void markSoneKnown(Sone sone) {
954 if (!sone.isKnown()) {
956 synchronized (knownSones) {
957 knownSones.add(sone.getId());
959 eventBus.post(new MarkSoneKnownEvent(sone));
960 touchConfiguration();
965 * Creates a new post.
968 * The Sone that creates the post
970 * The recipient Sone, or {@code null} if this post does not have
973 * The text of the post
974 * @return The created post
976 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
977 checkNotNull(text, "text must not be null");
978 checkArgument(text.trim().length() > 0, "text must not be empty");
979 if (!sone.isLocal()) {
980 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
983 PostBuilder postBuilder = database.newPostBuilder();
984 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
985 if (recipient.isPresent()) {
986 postBuilder.to(recipient.get().getId());
988 final Post post = postBuilder.build();
989 database.storePost(post);
990 eventBus.post(new NewPostFoundEvent(post));
992 touchConfiguration();
993 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
998 * Deletes the given post.
1001 * The post to delete
1003 public void deletePost(Post post) {
1004 if (!post.getSone().isLocal()) {
1005 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1008 database.removePost(post);
1009 eventBus.post(new PostRemovedEvent(post));
1010 markPostKnown(post);
1011 touchConfiguration();
1015 * Marks the given post as known, if it is currently not a known post
1016 * (according to {@link Post#isKnown()}).
1019 * The post to mark as known
1021 public void markPostKnown(Post post) {
1022 post.setKnown(true);
1023 eventBus.post(new MarkPostKnownEvent(post));
1024 touchConfiguration();
1025 for (PostReply reply : getReplies(post.getId())) {
1026 markReplyKnown(reply);
1030 public void bookmarkPost(Post post) {
1031 database.bookmarkPost(post);
1035 * Removes the given post from the bookmarks.
1038 * The post to unbookmark
1040 public void unbookmarkPost(Post post) {
1041 database.unbookmarkPost(post);
1045 * Creates a new reply.
1048 * The Sone that creates the reply
1050 * The post that this reply refers to
1052 * The text of the reply
1053 * @return The created reply
1055 public PostReply createReply(Sone sone, Post post, String text) {
1056 checkNotNull(text, "text must not be null");
1057 checkArgument(text.trim().length() > 0, "text must not be empty");
1058 if (!sone.isLocal()) {
1059 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1062 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1063 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1064 final PostReply reply = postReplyBuilder.build();
1065 database.storePostReply(reply);
1066 eventBus.post(new NewPostReplyFoundEvent(reply));
1067 sone.addReply(reply);
1068 touchConfiguration();
1069 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1074 * Deletes the given reply.
1077 * The reply to delete
1079 public void deleteReply(PostReply reply) {
1080 Sone sone = reply.getSone();
1081 if (!sone.isLocal()) {
1082 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1085 database.removePostReply(reply);
1086 markReplyKnown(reply);
1087 sone.removeReply(reply);
1088 touchConfiguration();
1092 * Marks the given reply as known, if it is currently not a known reply
1093 * (according to {@link Reply#isKnown()}).
1096 * The reply to mark as known
1098 public void markReplyKnown(PostReply reply) {
1099 boolean previouslyKnown = reply.isKnown();
1100 reply.setKnown(true);
1101 eventBus.post(new MarkPostReplyKnownEvent(reply));
1102 if (!previouslyKnown) {
1103 touchConfiguration();
1108 * Creates a new album for the given Sone.
1111 * The Sone to create the album for
1113 * The parent of the album (may be {@code null} to create a
1115 * @return The new album
1117 public Album createAlbum(Sone sone, Album parent) {
1118 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1119 database.storeAlbum(album);
1120 parent.addAlbum(album);
1125 * Deletes the given album. The owner of the album has to be a local Sone,
1126 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1129 * The album to remove
1131 public void deleteAlbum(Album album) {
1132 checkNotNull(album, "album must not be null");
1133 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1134 if (!album.isEmpty()) {
1137 album.getParent().removeAlbum(album);
1138 database.removeAlbum(album);
1139 touchConfiguration();
1143 * Creates a new image.
1146 * The Sone creating the image
1148 * The album the image will be inserted into
1149 * @param temporaryImage
1150 * The temporary image to create the image from
1151 * @return The newly created image
1153 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1154 checkNotNull(sone, "sone must not be null");
1155 checkNotNull(album, "album must not be null");
1156 checkNotNull(temporaryImage, "temporaryImage must not be null");
1157 checkArgument(sone.isLocal(), "sone must be a local Sone");
1158 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1159 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1160 album.addImage(image);
1161 database.storeImage(image);
1162 imageInserter.insertImage(temporaryImage, image);
1167 * Deletes the given image. This method will also delete a matching
1170 * @see #deleteTemporaryImage(String)
1172 * The image to delete
1174 public void deleteImage(Image image) {
1175 checkNotNull(image, "image must not be null");
1176 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1177 deleteTemporaryImage(image.getId());
1178 image.getAlbum().removeImage(image);
1179 database.removeImage(image);
1180 touchConfiguration();
1184 * Creates a new temporary image.
1187 * The MIME type of the temporary image
1189 * The encoded data of the image
1190 * @return The temporary image
1192 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1193 TemporaryImage temporaryImage = new TemporaryImage();
1194 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1195 synchronized (temporaryImages) {
1196 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1198 return temporaryImage;
1202 * Deletes the temporary image with the given ID.
1205 * The ID of the temporary image to delete
1207 public void deleteTemporaryImage(String imageId) {
1208 checkNotNull(imageId, "imageId must not be null");
1209 synchronized (temporaryImages) {
1210 temporaryImages.remove(imageId);
1212 Image image = getImage(imageId, false);
1213 if (image != null) {
1214 imageInserter.cancelImageInsert(image);
1219 * Notifies the core that the configuration, either of the core or of a
1220 * single local Sone, has changed, and that the configuration should be
1223 public void touchConfiguration() {
1224 lastConfigurationUpdate = System.currentTimeMillis();
1235 public void serviceStart() {
1236 loadConfiguration();
1237 updateChecker.start();
1238 identityManager.start();
1239 webOfTrustUpdater.init();
1240 webOfTrustUpdater.start();
1248 public void serviceRun() {
1249 long lastSaved = System.currentTimeMillis();
1250 while (!shouldStop()) {
1252 long now = System.currentTimeMillis();
1253 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1254 saveConfiguration();
1264 public void serviceStop() {
1265 localElementTicker.shutdownNow();
1266 synchronized (soneInserters) {
1267 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1268 soneInserter.getValue().stop();
1272 saveConfiguration();
1273 webOfTrustUpdater.stop();
1274 updateChecker.stop();
1275 soneDownloader.stop();
1276 soneDownloaders.shutdown();
1277 identityManager.stop();
1285 * Saves the current options.
1287 private void saveConfiguration() {
1288 synchronized (configuration) {
1289 if (storingConfiguration) {
1290 logger.log(Level.FINE, "Already storing configuration…");
1293 storingConfiguration = true;
1296 /* store the options first. */
1298 preferences.saveTo(configuration);
1300 /* save known Sones. */
1301 int soneCounter = 0;
1302 synchronized (knownSones) {
1303 for (String knownSoneId : knownSones) {
1304 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1306 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1309 /* save Sone following times. */
1311 synchronized (soneFollowingTimes) {
1312 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1313 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1314 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1317 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1320 /* save known posts. */
1324 configuration.save();
1326 } catch (ConfigurationException ce1) {
1327 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1328 } catch (DatabaseException de1) {
1329 logger.log(Level.SEVERE, "Could not save database!", de1);
1331 synchronized (configuration) {
1332 storingConfiguration = false;
1338 * Loads the configuration.
1340 private void loadConfiguration() {
1341 new PreferencesLoader(preferences).loadFrom(configuration);
1343 /* load known Sones. */
1344 int soneCounter = 0;
1346 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1347 if (knownSoneId == null) {
1350 synchronized (knownSones) {
1351 knownSones.add(knownSoneId);
1355 /* load Sone following times. */
1358 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1359 if (soneId == null) {
1362 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1363 synchronized (soneFollowingTimes) {
1364 soneFollowingTimes.put(soneId, time);
1371 * Notifies the core that a new {@link OwnIdentity} was added.
1373 * @param ownIdentityAddedEvent
1377 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1378 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1379 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1380 if (ownIdentity.hasContext("Sone")) {
1381 addLocalSone(ownIdentity);
1386 * Notifies the core that an {@link OwnIdentity} was removed.
1388 * @param ownIdentityRemovedEvent
1392 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1393 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1394 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1395 trustedIdentities.removeAll(ownIdentity);
1399 * Notifies the core that a new {@link Identity} was added.
1401 * @param identityAddedEvent
1405 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1406 Identity identity = identityAddedEvent.identity();
1407 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1408 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1409 addRemoteSone(identity);
1413 * Notifies the core that an {@link Identity} was updated.
1415 * @param identityUpdatedEvent
1419 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1420 Identity identity = identityUpdatedEvent.identity();
1421 final Sone sone = getRemoteSone(identity.getId());
1422 if (sone.isLocal()) {
1425 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1426 soneDownloader.addSone(sone);
1427 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1431 * Notifies the core that an {@link Identity} was removed.
1433 * @param identityRemovedEvent
1437 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1438 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1439 Identity identity = identityRemovedEvent.identity();
1440 trustedIdentities.remove(ownIdentity, identity);
1441 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1442 if (trustedIdentity.getKey().equals(ownIdentity)) {
1445 if (trustedIdentity.getValue().contains(identity)) {
1449 Optional<Sone> sone = getSone(identity.getId());
1450 if (!sone.isPresent()) {
1451 /* TODO - we don’t have the Sone anymore. should this happen? */
1454 database.removeSone(sone.get());
1455 eventBus.post(new SoneRemovedEvent(sone.get()));
1459 public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1460 Sone sone = soneInsertedEvent.sone();
1461 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1462 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1463 sone.getLatestEdition()));
1467 * Deletes the temporary image.
1469 * @param imageInsertFinishedEvent
1473 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1474 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1475 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1476 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1477 touchConfiguration();
1481 class MarkPostKnown implements Runnable {
1483 private final Post post;
1485 public MarkPostKnown(Post post) {
1491 markPostKnown(post);
1497 class MarkReplyKnown implements Runnable {
1499 private final PostReply postReply;
1501 public MarkReplyKnown(PostReply postReply) {
1502 this.postReply = postReply;
1507 markReplyKnown(postReply);