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<Sone> lockedSones = new HashSet<Sone>();
153 /** Sone inserters. */
154 /* synchronize access on this on sones. */
155 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
157 /** Sone rescuers. */
158 /* synchronize access on this on sones. */
159 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
161 /** All known Sones. */
162 private final Set<String> knownSones = new HashSet<String>();
164 /** The post database. */
165 private final Database database;
167 /** Trusted identities, sorted by own identities. */
168 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
170 /** All temporary images. */
171 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
173 /** Ticker for threads that mark own elements as known. */
174 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
176 /** The time the configuration was last touched. */
177 private volatile long lastConfigurationUpdate;
180 * Creates a new core.
182 * @param configuration
183 * The configuration of the core
184 * @param freenetInterface
185 * The freenet interface
186 * @param identityManager
187 * The identity manager
188 * @param webOfTrustUpdater
189 * The WebOfTrust updater
196 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
198 this.configuration = configuration;
199 this.freenetInterface = freenetInterface;
200 this.identityManager = identityManager;
201 this.soneDownloader = new SoneDownloaderImpl(this, freenetInterface);
202 this.imageInserter = new ImageInserter(freenetInterface, freenetInterface.new InsertTokenSupplier());
203 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
204 this.webOfTrustUpdater = webOfTrustUpdater;
205 this.eventBus = eventBus;
206 this.database = database;
207 preferences = new Preferences(eventBus);
211 protected Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, SoneDownloader soneDownloader, ImageInserter imageInserter, UpdateChecker updateChecker, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
213 this.configuration = configuration;
214 this.freenetInterface = freenetInterface;
215 this.identityManager = identityManager;
216 this.soneDownloader = soneDownloader;
217 this.imageInserter = imageInserter;
218 this.updateChecker = updateChecker;
219 this.webOfTrustUpdater = webOfTrustUpdater;
220 this.eventBus = eventBus;
221 this.database = database;
222 preferences = new Preferences(eventBus);
230 * Returns the time Sone was started.
232 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
234 public long getStartupTime() {
239 * Returns the options used by the core.
241 * @return The options of the core
243 public Preferences getPreferences() {
248 * Returns the identity manager used by the core.
250 * @return The identity manager
252 public IdentityManager getIdentityManager() {
253 return identityManager;
257 * Returns the update checker.
259 * @return The update checker
261 public UpdateChecker getUpdateChecker() {
262 return updateChecker;
266 * Returns the Sone rescuer for the given local Sone.
269 * The local Sone to get the rescuer for
270 * @return The Sone rescuer for the given Sone
272 public SoneRescuer getSoneRescuer(Sone sone) {
273 checkNotNull(sone, "sone must not be null");
274 checkArgument(sone.isLocal(), "sone must be local");
275 synchronized (soneRescuers) {
276 SoneRescuer soneRescuer = soneRescuers.get(sone);
277 if (soneRescuer == null) {
278 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
279 soneRescuers.put(sone, soneRescuer);
287 * Returns whether the given Sone is currently locked.
291 * @return {@code true} if the Sone is locked, {@code false} if it is not
293 public boolean isLocked(Sone sone) {
294 synchronized (lockedSones) {
295 return lockedSones.contains(sone);
299 public SoneBuilder soneBuilder() {
300 return database.newSoneBuilder();
307 public Collection<Sone> getSones() {
308 return database.getSones();
312 public Function<String, Optional<Sone>> soneLoader() {
313 return database.soneLoader();
317 * Returns the Sone with the given ID, regardless whether it’s local or
321 * The ID of the Sone to get
322 * @return The Sone with the given ID, or {@code null} if there is no such
326 public Optional<Sone> getSone(String id) {
327 return database.getSone(id);
331 public Collection<LocalSone> getLocalSones() {
332 return database.getLocalSones();
335 public Optional<LocalSone> getLocalSone(String id) {
336 return database.getLocalSone(id);
343 public Collection<Sone> getRemoteSones() {
344 return database.getRemoteSones();
348 * Returns the remote Sone with the given ID.
352 * The ID of the remote Sone to get
353 * @return The Sone with the given ID
355 public Sone getRemoteSone(String id) {
356 return database.getSone(id).orNull();
360 * Returns whether the given Sone has been modified.
363 * The Sone to check for modifications
364 * @return {@code true} if a modification has been detected in the Sone,
365 * {@code false} otherwise
367 public boolean isModifiedSone(Sone sone) {
368 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
372 * Returns the time when the given was first followed by any local Sone.
375 * The Sone to get the time for
376 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
377 * been followed, or {@link Long#MAX_VALUE}
379 public long getSoneFollowingTime(Sone sone) {
380 synchronized (soneFollowingTimes) {
381 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
386 * Returns a post builder.
388 * @return A new post builder
390 public PostBuilder postBuilder() {
391 return database.newPostBuilder();
398 public Optional<Post> getPost(String postId) {
399 return database.getPost(postId);
406 public Collection<Post> getPosts(String soneId) {
407 return database.getPosts(soneId);
414 public Collection<Post> getDirectedPosts(final String recipientId) {
415 checkNotNull(recipientId, "recipient must not be null");
416 return database.getDirectedPosts(recipientId);
420 * Returns a post reply builder.
422 * @return A new post reply builder
424 public PostReplyBuilder postReplyBuilder() {
425 return database.newPostReplyBuilder();
432 public Optional<PostReply> getPostReply(String replyId) {
433 return database.getPostReply(replyId);
440 public List<PostReply> getReplies(final String postId) {
441 return database.getReplies(postId);
445 * Returns all Sones that have liked the given post.
448 * The post to get the liking Sones for
449 * @return The Sones that like the given post
451 public Set<Sone> getLikes(Post post) {
452 Set<Sone> sones = new HashSet<Sone>();
453 for (Sone sone : getSones()) {
454 if (sone.getLikedPostIds().contains(post.getId())) {
462 * Returns all Sones that have liked the given reply.
465 * The reply to get the liking Sones for
466 * @return The Sones that like the given reply
468 public Set<Sone> getLikes(PostReply reply) {
469 Set<Sone> sones = new HashSet<Sone>();
470 for (Sone sone : getSones()) {
471 if (sone.getLikedReplyIds().contains(reply.getId())) {
479 * Returns whether the given post is bookmarked.
483 * @return {@code true} if the given post is bookmarked, {@code false}
486 public boolean isBookmarked(Post post) {
487 return database.isPostBookmarked(post);
491 * Returns all currently known bookmarked posts.
493 * @return All bookmarked posts
495 public Set<Post> getBookmarkedPosts() {
496 return database.getBookmarkedPosts();
499 public AlbumBuilder albumBuilder() {
500 return database.newAlbumBuilder();
504 * Returns the album with the given ID, optionally creating a new album if
505 * an album with the given ID can not be found.
508 * The ID of the album
509 * @return The album with the given ID, or {@code null} if no album with the
512 public Album getAlbum(String albumId) {
513 return database.getAlbum(albumId).orNull();
516 public ImageBuilder imageBuilder() {
517 return database.newImageBuilder();
521 * Returns the image with the given ID, creating it if necessary.
524 * The ID of the image
525 * @return The image with the given ID
527 public Image getImage(String imageId) {
528 return getImage(imageId, true);
532 * Returns the image with the given ID, optionally creating it if it does
536 * The ID of the image
538 * {@code true} to create an image if none exists with the given
540 * @return The image with the given ID, or {@code null} if none exists and
543 public Image getImage(String imageId, boolean create) {
544 Optional<Image> image = database.getImage(imageId);
545 if (image.isPresent()) {
551 Image newImage = database.newImageBuilder().withId(imageId).build();
552 database.storeImage(newImage);
557 * Returns the temporary image with the given ID.
560 * The ID of the temporary image
561 * @return The temporary image, or {@code null} if there is no temporary
562 * image with the given ID
564 public TemporaryImage getTemporaryImage(String imageId) {
565 synchronized (temporaryImages) {
566 return temporaryImages.get(imageId);
575 * Locks the given Sone. A locked Sone will not be inserted by
576 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
582 public void lockSone(Sone sone) {
583 synchronized (lockedSones) {
584 if (lockedSones.add(sone)) {
585 eventBus.post(new SoneLockedEvent(sone));
591 * Unlocks the given Sone.
593 * @see #lockSone(Sone)
597 public void unlockSone(Sone sone) {
598 synchronized (lockedSones) {
599 if (lockedSones.remove(sone)) {
600 eventBus.post(new SoneUnlockedEvent(sone));
606 * Adds a local Sone from the given own identity.
609 * The own identity to create a Sone from
610 * @return The added (or already existing) Sone
612 public Sone addLocalSone(OwnIdentity ownIdentity) {
613 if (ownIdentity == null) {
614 logger.log(Level.WARNING, "Given OwnIdentity is null!");
617 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
618 Sone sone = database.registerLocalSone(ownIdentity);
619 SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, ownIdentity.getId());
620 eventBus.register(soneInserter);
621 synchronized (soneInserters) {
622 soneInserters.put(sone, soneInserter);
624 synchronized (soneInserters) {
625 soneInserters.get(sone).setLastInsertFingerprint(database.getLastInsertFingerprint(sone));
627 sone.setStatus(SoneStatus.idle);
628 soneInserter.start();
633 * Creates a new Sone for the given own identity.
636 * The own identity to create a Sone for
637 * @return The created Sone
639 public Sone createSone(OwnIdentity ownIdentity) {
640 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
641 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
644 Sone sone = addLocalSone(ownIdentity);
646 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
647 touchConfiguration();
652 * Adds the Sone of the given identity.
655 * The identity whose Sone to add
656 * @return The added or already existing Sone
658 public Sone addRemoteSone(Identity identity) {
659 if (identity == null) {
660 logger.log(Level.WARNING, "Given Identity is null!");
663 final Long latestEdition = tryParse(fromNullable(
664 identity.getProperty("Sone.LatestEdition")).or("0"));
665 Optional<Sone> existingSone = getSone(identity.getId());
666 if (existingSone.isPresent() && existingSone.get().isLocal()) {
667 return existingSone.get();
669 boolean newSone = !existingSone.isPresent();
670 Sone sone = !newSone ? existingSone.get() : database.newSoneBuilder().from(identity).build();
671 sone.setLatestEdition(latestEdition);
673 synchronized (knownSones) {
674 newSone = !knownSones.contains(sone.getId());
676 sone.setKnown(!newSone);
678 eventBus.post(new NewSoneFoundEvent(sone));
679 for (Sone localSone : getLocalSones()) {
680 if (localSone.getOptions().isAutoFollow()) {
681 followSone(localSone, sone.getId());
686 database.storeSone(sone);
687 soneDownloader.addSone(sone);
688 soneDownloaders.execute(soneDownloader.fetchSoneWithUriAction(sone));
693 * Lets the given local Sone follow the Sone with the given ID.
696 * The local Sone that should follow another Sone
698 * The ID of the Sone to follow
700 public void followSone(Sone sone, String soneId) {
701 checkNotNull(sone, "sone must not be null");
702 checkNotNull(soneId, "soneId must not be null");
703 database.addFriend(sone, soneId);
704 synchronized (soneFollowingTimes) {
705 if (!soneFollowingTimes.containsKey(soneId)) {
706 long now = System.currentTimeMillis();
707 soneFollowingTimes.put(soneId, now);
708 Optional<Sone> followedSone = getSone(soneId);
709 if (!followedSone.isPresent()) {
712 for (Post post : followedSone.get().getPosts()) {
713 if (post.getTime() < now) {
717 for (PostReply reply : followedSone.get().getReplies()) {
718 if (reply.getTime() < now) {
719 markReplyKnown(reply);
724 touchConfiguration();
728 * Lets the given local Sone unfollow the Sone with the given ID.
731 * The local Sone that should unfollow another Sone
733 * The ID of the Sone being unfollowed
735 public void unfollowSone(Sone sone, String soneId) {
736 checkNotNull(sone, "sone must not be null");
737 checkNotNull(soneId, "soneId must not be null");
738 database.removeFriend(sone, soneId);
739 boolean unfollowedSoneStillFollowed = false;
740 for (Sone localSone : getLocalSones()) {
741 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
743 if (!unfollowedSoneStillFollowed) {
744 synchronized (soneFollowingTimes) {
745 soneFollowingTimes.remove(soneId);
748 touchConfiguration();
752 * Sets the trust value of the given origin Sone for the target Sone.
759 * The trust value (from {@code -100} to {@code 100})
761 public void setTrust(Sone origin, Sone target, int trustValue) {
762 checkNotNull(origin, "origin must not be null");
763 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
764 checkNotNull(target, "target must not be null");
765 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
766 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
770 * Removes any trust assignment for the given target Sone.
777 public void removeTrust(Sone origin, Sone target) {
778 checkNotNull(origin, "origin must not be null");
779 checkNotNull(target, "target must not be null");
780 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
781 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
785 * Assigns the configured positive trust value for the given target.
792 public void trustSone(Sone origin, Sone target) {
793 setTrust(origin, target, preferences.getPositiveTrust());
797 * Assigns the configured negative trust value for the given target.
804 public void distrustSone(Sone origin, Sone target) {
805 setTrust(origin, target, preferences.getNegativeTrust());
809 * Removes the trust assignment for the given target.
816 public void untrustSone(Sone origin, Sone target) {
817 removeTrust(origin, target);
821 * Updates the stored Sone with the given Sone.
826 public void updateSone(Sone sone) {
827 updateSone(sone, false);
831 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
832 * {@code true}, an older Sone than the current Sone can be given to restore
837 * @param soneRescueMode
838 * {@code true} if the stored Sone should be updated regardless
839 * of the age of the given Sone
841 public void updateSone(final Sone sone, boolean soneRescueMode) {
842 Optional<Sone> storedSone = getSone(sone.getId());
843 if (storedSone.isPresent()) {
844 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
845 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
848 List<Object> events =
849 collectEventsForChangesInSone(storedSone.get(), sone);
850 database.storeSone(sone);
851 for (Object event : events) {
852 eventBus.post(event);
854 sone.setOptions(storedSone.get().getOptions());
855 sone.setKnown(storedSone.get().isKnown());
856 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
857 if (sone.isLocal()) {
858 touchConfiguration();
863 private List<Object> collectEventsForChangesInSone(Sone oldSone,
864 final Sone newSone) {
865 final List<Object> events = new ArrayList<Object>();
866 SoneChangeDetector soneChangeDetector = new SoneChangeDetector(
868 soneChangeDetector.onNewPosts(new PostProcessor() {
870 public void processPost(Post post) {
871 if (post.getTime() < getSoneFollowingTime(newSone)) {
873 } else if (!post.isKnown()) {
874 events.add(new NewPostFoundEvent(post));
878 soneChangeDetector.onRemovedPosts(new PostProcessor() {
880 public void processPost(Post post) {
881 events.add(new PostRemovedEvent(post));
884 soneChangeDetector.onNewPostReplies(new PostReplyProcessor() {
886 public void processPostReply(PostReply postReply) {
887 if (postReply.getTime() < getSoneFollowingTime(newSone)) {
888 postReply.setKnown(true);
889 } else if (!postReply.isKnown()) {
890 events.add(new NewPostReplyFoundEvent(postReply));
894 soneChangeDetector.onRemovedPostReplies(new PostReplyProcessor() {
896 public void processPostReply(PostReply postReply) {
897 events.add(new PostReplyRemovedEvent(postReply));
900 soneChangeDetector.detectChanges(newSone);
905 * Deletes the given Sone. This will remove the Sone from the
906 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
907 * remove the context from its identity.
912 public void deleteSone(Sone sone) {
913 if (!(sone.getIdentity() instanceof OwnIdentity)) {
914 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
917 if (!getLocalSones().contains(sone)) {
918 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
921 SoneInserter soneInserter = soneInserters.remove(sone);
923 database.removeSone(sone);
924 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
925 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
927 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
928 } catch (ConfigurationException ce1) {
929 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
934 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
935 * known} before, a {@link MarkSoneKnownEvent} is fired.
938 * The Sone to mark as known
940 public void markSoneKnown(Sone sone) {
941 if (!sone.isKnown()) {
943 synchronized (knownSones) {
944 knownSones.add(sone.getId());
946 eventBus.post(new MarkSoneKnownEvent(sone));
947 touchConfiguration();
952 * Creates a new post.
955 * The Sone that creates the post
957 * The recipient Sone, or {@code null} if this post does not have
960 * The text of the post
961 * @return The created post
963 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
964 checkNotNull(text, "text must not be null");
965 checkArgument(text.trim().length() > 0, "text must not be empty");
966 if (!sone.isLocal()) {
967 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
970 PostBuilder postBuilder = database.newPostBuilder();
971 postBuilder.from(sone.getId()).randomId().currentTime().withText(text.trim());
972 if (recipient.isPresent()) {
973 postBuilder.to(recipient.get().getId());
975 final Post post = postBuilder.build();
976 database.storePost(post);
977 eventBus.post(new NewPostFoundEvent(post));
979 touchConfiguration();
980 localElementTicker.schedule(new MarkPostKnown(post), 10, TimeUnit.SECONDS);
985 * Deletes the given post.
990 public void deletePost(Post post) {
991 if (!post.getSone().isLocal()) {
992 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
995 database.removePost(post);
996 eventBus.post(new PostRemovedEvent(post));
998 touchConfiguration();
1002 * Marks the given post as known, if it is currently not a known post
1003 * (according to {@link Post#isKnown()}).
1006 * The post to mark as known
1008 public void markPostKnown(Post post) {
1009 post.setKnown(true);
1010 eventBus.post(new MarkPostKnownEvent(post));
1011 touchConfiguration();
1012 for (PostReply reply : getReplies(post.getId())) {
1013 markReplyKnown(reply);
1017 public void bookmarkPost(Post post) {
1018 database.bookmarkPost(post);
1022 * Removes the given post from the bookmarks.
1025 * The post to unbookmark
1027 public void unbookmarkPost(Post post) {
1028 database.unbookmarkPost(post);
1032 * Creates a new reply.
1035 * The Sone that creates the reply
1037 * The post that this reply refers to
1039 * The text of the reply
1040 * @return The created reply
1042 public PostReply createReply(Sone sone, Post post, String text) {
1043 checkNotNull(text, "text must not be null");
1044 checkArgument(text.trim().length() > 0, "text must not be empty");
1045 if (!sone.isLocal()) {
1046 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1049 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1050 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1051 final PostReply reply = postReplyBuilder.build();
1052 database.storePostReply(reply);
1053 eventBus.post(new NewPostReplyFoundEvent(reply));
1054 sone.addReply(reply);
1055 touchConfiguration();
1056 localElementTicker.schedule(new MarkReplyKnown(reply), 10, TimeUnit.SECONDS);
1061 * Deletes the given reply.
1064 * The reply to delete
1066 public void deleteReply(PostReply reply) {
1067 Sone sone = reply.getSone();
1068 if (!sone.isLocal()) {
1069 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1072 database.removePostReply(reply);
1073 markReplyKnown(reply);
1074 sone.removeReply(reply);
1075 touchConfiguration();
1079 * Marks the given reply as known, if it is currently not a known reply
1080 * (according to {@link Reply#isKnown()}).
1083 * The reply to mark as known
1085 public void markReplyKnown(PostReply reply) {
1086 boolean previouslyKnown = reply.isKnown();
1087 reply.setKnown(true);
1088 eventBus.post(new MarkPostReplyKnownEvent(reply));
1089 if (!previouslyKnown) {
1090 touchConfiguration();
1095 * Creates a new album for the given Sone.
1098 * The Sone to create the album for
1100 * The parent of the album (may be {@code null} to create a
1102 * @return The new album
1104 public Album createAlbum(Sone sone, Album parent) {
1105 Album album = database.newAlbumBuilder().randomId().by(sone).build();
1106 database.storeAlbum(album);
1107 parent.addAlbum(album);
1112 * Deletes the given album. The owner of the album has to be a local Sone,
1113 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1116 * The album to remove
1118 public void deleteAlbum(Album album) {
1119 checkNotNull(album, "album must not be null");
1120 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1121 if (!album.isEmpty()) {
1124 album.getParent().removeAlbum(album);
1125 database.removeAlbum(album);
1126 touchConfiguration();
1130 * Creates a new image.
1133 * The Sone creating the image
1135 * The album the image will be inserted into
1136 * @param temporaryImage
1137 * The temporary image to create the image from
1138 * @return The newly created image
1140 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1141 checkNotNull(sone, "sone must not be null");
1142 checkNotNull(album, "album must not be null");
1143 checkNotNull(temporaryImage, "temporaryImage must not be null");
1144 checkArgument(sone.isLocal(), "sone must be a local Sone");
1145 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1146 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1147 album.addImage(image);
1148 database.storeImage(image);
1149 imageInserter.insertImage(temporaryImage, image);
1154 * Deletes the given image. This method will also delete a matching
1157 * @see #deleteTemporaryImage(String)
1159 * The image to delete
1161 public void deleteImage(Image image) {
1162 checkNotNull(image, "image must not be null");
1163 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1164 deleteTemporaryImage(image.getId());
1165 image.getAlbum().removeImage(image);
1166 database.removeImage(image);
1167 touchConfiguration();
1171 * Creates a new temporary image.
1174 * The MIME type of the temporary image
1176 * The encoded data of the image
1177 * @return The temporary image
1179 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1180 TemporaryImage temporaryImage = new TemporaryImage();
1181 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1182 synchronized (temporaryImages) {
1183 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1185 return temporaryImage;
1189 * Deletes the temporary image with the given ID.
1192 * The ID of the temporary image to delete
1194 public void deleteTemporaryImage(String imageId) {
1195 checkNotNull(imageId, "imageId must not be null");
1196 synchronized (temporaryImages) {
1197 temporaryImages.remove(imageId);
1199 Image image = getImage(imageId, false);
1200 if (image != null) {
1201 imageInserter.cancelImageInsert(image);
1206 * Notifies the core that the configuration, either of the core or of a
1207 * single local Sone, has changed, and that the configuration should be
1210 public void touchConfiguration() {
1211 lastConfigurationUpdate = System.currentTimeMillis();
1222 public void serviceStart() {
1223 loadConfiguration();
1224 updateChecker.start();
1225 identityManager.start();
1226 webOfTrustUpdater.init();
1227 webOfTrustUpdater.start();
1235 public void serviceRun() {
1236 long lastSaved = System.currentTimeMillis();
1237 while (!shouldStop()) {
1239 long now = System.currentTimeMillis();
1240 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1241 saveConfiguration();
1251 public void serviceStop() {
1252 localElementTicker.shutdownNow();
1253 synchronized (soneInserters) {
1254 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1255 soneInserter.getValue().stop();
1259 saveConfiguration();
1260 webOfTrustUpdater.stop();
1261 updateChecker.stop();
1262 soneDownloader.stop();
1263 soneDownloaders.shutdown();
1264 identityManager.stop();
1272 * Saves the current options.
1274 private void saveConfiguration() {
1275 synchronized (configuration) {
1276 if (storingConfiguration) {
1277 logger.log(Level.FINE, "Already storing configuration…");
1280 storingConfiguration = true;
1283 /* store the options first. */
1285 preferences.saveTo(configuration);
1287 /* save known Sones. */
1288 int soneCounter = 0;
1289 synchronized (knownSones) {
1290 for (String knownSoneId : knownSones) {
1291 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1293 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1296 /* save Sone following times. */
1298 synchronized (soneFollowingTimes) {
1299 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1300 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1301 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1304 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1307 /* save known posts. */
1311 configuration.save();
1313 } catch (ConfigurationException ce1) {
1314 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1315 } catch (DatabaseException de1) {
1316 logger.log(Level.SEVERE, "Could not save database!", de1);
1318 synchronized (configuration) {
1319 storingConfiguration = false;
1325 * Loads the configuration.
1327 private void loadConfiguration() {
1328 new PreferencesLoader(preferences).loadFrom(configuration);
1330 /* load known Sones. */
1331 int soneCounter = 0;
1333 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
1334 if (knownSoneId == null) {
1337 synchronized (knownSones) {
1338 knownSones.add(knownSoneId);
1342 /* load Sone following times. */
1345 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
1346 if (soneId == null) {
1349 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
1350 synchronized (soneFollowingTimes) {
1351 soneFollowingTimes.put(soneId, time);
1358 * Notifies the core that a new {@link OwnIdentity} was added.
1360 * @param ownIdentityAddedEvent
1364 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
1365 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
1366 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
1367 if (ownIdentity.hasContext("Sone")) {
1368 addLocalSone(ownIdentity);
1373 * Notifies the core that an {@link OwnIdentity} was removed.
1375 * @param ownIdentityRemovedEvent
1379 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
1380 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
1381 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
1382 trustedIdentities.removeAll(ownIdentity);
1386 * Notifies the core that a new {@link Identity} was added.
1388 * @param identityAddedEvent
1392 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
1393 Identity identity = identityAddedEvent.identity();
1394 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
1395 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
1396 addRemoteSone(identity);
1400 * Notifies the core that an {@link Identity} was updated.
1402 * @param identityUpdatedEvent
1406 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
1407 Identity identity = identityUpdatedEvent.identity();
1408 final Sone sone = getRemoteSone(identity.getId());
1409 if (sone.isLocal()) {
1412 sone.setLatestEdition(fromNullable(tryParse(identity.getProperty("Sone.LatestEdition"))).or(sone.getLatestEdition()));
1413 soneDownloader.addSone(sone);
1414 soneDownloaders.execute(soneDownloader.fetchSoneAction(sone));
1418 * Notifies the core that an {@link Identity} was removed.
1420 * @param identityRemovedEvent
1424 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
1425 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
1426 Identity identity = identityRemovedEvent.identity();
1427 trustedIdentities.remove(ownIdentity, identity);
1428 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
1429 if (trustedIdentity.getKey().equals(ownIdentity)) {
1432 if (trustedIdentity.getValue().contains(identity)) {
1436 Optional<Sone> sone = getSone(identity.getId());
1437 if (!sone.isPresent()) {
1438 /* TODO - we don’t have the Sone anymore. should this happen? */
1441 database.removeSone(sone.get());
1442 eventBus.post(new SoneRemovedEvent(sone.get()));
1446 public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1447 Sone sone = soneInsertedEvent.sone();
1448 database.setLastInsertFingerprint(sone, soneInsertedEvent.insertFingerprint());
1449 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(
1450 sone.getLatestEdition()));
1454 * Deletes the temporary image.
1456 * @param imageInsertFinishedEvent
1460 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1461 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
1462 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
1463 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
1464 touchConfiguration();
1468 class MarkPostKnown implements Runnable {
1470 private final Post post;
1472 public MarkPostKnown(Post post) {
1478 markPostKnown(post);
1484 class MarkReplyKnown implements Runnable {
1486 private final PostReply postReply;
1488 public MarkReplyKnown(PostReply postReply) {
1489 this.postReply = postReply;
1494 markReplyKnown(postReply);