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.Preconditions.checkArgument;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Predicates.not;
23 import static net.pterodactylus.sone.data.Sone.LOCAL_SONE_FILTER;
25 import java.net.MalformedURLException;
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.Options.DefaultOption;
42 import net.pterodactylus.sone.core.SoneInserter.SetInsertionDelay;
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.SoneLockedEvent;
53 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
54 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
55 import net.pterodactylus.sone.data.Album;
56 import net.pterodactylus.sone.data.Client;
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.Profile;
61 import net.pterodactylus.sone.data.Profile.Field;
62 import net.pterodactylus.sone.data.Reply;
63 import net.pterodactylus.sone.data.Sone;
64 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
65 import net.pterodactylus.sone.data.Sone.SoneStatus;
66 import net.pterodactylus.sone.data.SoneImpl;
67 import net.pterodactylus.sone.data.TemporaryImage;
68 import net.pterodactylus.sone.database.Database;
69 import net.pterodactylus.sone.database.DatabaseException;
70 import net.pterodactylus.sone.database.PostBuilder;
71 import net.pterodactylus.sone.database.PostProvider;
72 import net.pterodactylus.sone.database.PostReplyBuilder;
73 import net.pterodactylus.sone.database.PostReplyProvider;
74 import net.pterodactylus.sone.database.SoneProvider;
75 import net.pterodactylus.sone.fcp.FcpInterface;
76 import net.pterodactylus.sone.freenet.wot.Identity;
77 import net.pterodactylus.sone.freenet.wot.IdentityManager;
78 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
79 import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
80 import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
81 import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
82 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
83 import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
84 import net.pterodactylus.sone.main.SonePlugin;
85 import net.pterodactylus.sone.utils.IntegerRangePredicate;
86 import net.pterodactylus.util.config.Configuration;
87 import net.pterodactylus.util.config.ConfigurationException;
88 import net.pterodactylus.util.logging.Logging;
89 import net.pterodactylus.util.number.Numbers;
90 import net.pterodactylus.util.service.AbstractService;
91 import net.pterodactylus.util.thread.NamedThreadFactory;
93 import com.google.common.base.Optional;
94 import com.google.common.base.Predicates;
95 import com.google.common.collect.FluentIterable;
96 import com.google.common.collect.HashMultimap;
97 import com.google.common.collect.ImmutableSet;
98 import com.google.common.collect.Multimap;
99 import com.google.common.collect.Multimaps;
100 import com.google.common.eventbus.EventBus;
101 import com.google.common.eventbus.Subscribe;
102 import com.google.inject.Inject;
104 import freenet.keys.FreenetURI;
109 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
111 public class Core extends AbstractService implements SoneProvider, PostProvider, PostReplyProvider {
114 private static final Logger logger = Logging.getLogger(Core.class);
116 /** The start time. */
117 private final long startupTime = System.currentTimeMillis();
120 private final Options options = new Options();
122 /** The preferences. */
123 private final Preferences preferences = new Preferences(options);
125 /** The event bus. */
126 private final EventBus eventBus;
128 /** The configuration. */
129 private final Configuration configuration;
131 /** Whether we’re currently saving the configuration. */
132 private boolean storingConfiguration = false;
134 /** The identity manager. */
135 private final IdentityManager identityManager;
137 /** Interface to freenet. */
138 private final FreenetInterface freenetInterface;
140 /** The Sone downloader. */
141 private final SoneDownloader soneDownloader;
143 /** The image inserter. */
144 private final ImageInserter imageInserter;
146 /** Sone downloader thread-pool. */
147 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
149 /** The update checker. */
150 private final UpdateChecker updateChecker;
152 /** The trust updater. */
153 private final WebOfTrustUpdater webOfTrustUpdater;
155 /** The FCP interface. */
156 private volatile FcpInterface fcpInterface;
158 /** The times Sones were followed. */
159 private final Map<String, Long> soneFollowingTimes = new HashMap<String, Long>();
161 /** Locked local Sones. */
162 /* synchronize on itself. */
163 private final Set<Sone> lockedSones = new HashSet<Sone>();
165 /** Sone inserters. */
166 /* synchronize access on this on sones. */
167 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
169 /** Sone rescuers. */
170 /* synchronize access on this on sones. */
171 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
174 /* synchronize access on this on itself. */
175 private final Map<String, Sone> sones = new HashMap<String, Sone>();
177 /** All known Sones. */
178 private final Set<String> knownSones = new HashSet<String>();
180 /** The post database. */
181 private final Database database;
183 /** All bookmarked posts. */
184 /* synchronize access on itself. */
185 private final Set<String> bookmarkedPosts = new HashSet<String>();
187 /** Trusted identities, sorted by own identities. */
188 private final Multimap<OwnIdentity, Identity> trustedIdentities = Multimaps.synchronizedSetMultimap(HashMultimap.<OwnIdentity, Identity>create());
190 /** All temporary images. */
191 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
193 /** Ticker for threads that mark own elements as known. */
194 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
196 /** The time the configuration was last touched. */
197 private volatile long lastConfigurationUpdate;
200 * Creates a new core.
202 * @param configuration
203 * The configuration of the core
204 * @param freenetInterface
205 * The freenet interface
206 * @param identityManager
207 * The identity manager
208 * @param webOfTrustUpdater
209 * The WebOfTrust updater
216 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
218 this.configuration = configuration;
219 this.freenetInterface = freenetInterface;
220 this.identityManager = identityManager;
221 this.soneDownloader = new SoneDownloader(this, freenetInterface);
222 this.imageInserter = new ImageInserter(freenetInterface);
223 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
224 this.webOfTrustUpdater = webOfTrustUpdater;
225 this.eventBus = eventBus;
226 this.database = database;
234 * Returns the time Sone was started.
236 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
238 public long getStartupTime() {
243 * Returns the options used by the core.
245 * @return The options of the core
247 public Preferences getPreferences() {
252 * Returns the identity manager used by the core.
254 * @return The identity manager
256 public IdentityManager getIdentityManager() {
257 return identityManager;
261 * Returns the update checker.
263 * @return The update checker
265 public UpdateChecker getUpdateChecker() {
266 return updateChecker;
270 * Sets the FCP interface to use.
272 * @param fcpInterface
273 * The FCP interface to use
275 public void setFcpInterface(FcpInterface fcpInterface) {
276 this.fcpInterface = fcpInterface;
280 * Returns the Sone rescuer for the given local Sone.
283 * The local Sone to get the rescuer for
284 * @return The Sone rescuer for the given Sone
286 public SoneRescuer getSoneRescuer(Sone sone) {
287 checkNotNull(sone, "sone must not be null");
288 checkArgument(sone.isLocal(), "sone must be local");
289 synchronized (sones) {
290 SoneRescuer soneRescuer = soneRescuers.get(sone);
291 if (soneRescuer == null) {
292 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
293 soneRescuers.put(sone, soneRescuer);
301 * Returns whether the given Sone is currently locked.
305 * @return {@code true} if the Sone is locked, {@code false} if it is not
307 public boolean isLocked(Sone sone) {
308 synchronized (lockedSones) {
309 return lockedSones.contains(sone);
317 public Collection<Sone> getSones() {
318 synchronized (sones) {
319 return ImmutableSet.copyOf(sones.values());
324 * Returns the Sone with the given ID, regardless whether it’s local or
328 * The ID of the Sone to get
329 * @return The Sone with the given ID, or {@code null} if there is no such
333 public Optional<Sone> getSone(String id) {
334 synchronized (sones) {
335 return Optional.fromNullable(sones.get(id));
343 public Collection<Sone> getLocalSones() {
344 synchronized (sones) {
345 return FluentIterable.from(sones.values()).filter(LOCAL_SONE_FILTER).toSet();
350 * Returns the local Sone with the given ID, optionally creating a new Sone.
355 * {@code true} to create a new Sone if none exists,
356 * {@code false} to return null if none exists
357 * @return The Sone with the given ID, or {@code null}
359 public Sone getLocalSone(String id, boolean create) {
360 synchronized (sones) {
361 Sone sone = sones.get(id);
362 if ((sone == null) && create) {
363 sone = new SoneImpl(id, true);
366 if ((sone != null) && !sone.isLocal()) {
367 sone = new SoneImpl(id, true);
378 public Collection<Sone> getRemoteSones() {
379 synchronized (sones) {
380 return FluentIterable.from(sones.values()).filter(not(LOCAL_SONE_FILTER)).toSet();
385 * Returns the remote Sone with the given ID.
388 * The ID of the remote Sone to get
390 * {@code true} to always create a Sone, {@code false} to return
391 * {@code null} if no Sone with the given ID exists
392 * @return The Sone with the given ID
394 public Sone getRemoteSone(String id, boolean create) {
395 synchronized (sones) {
396 Sone sone = sones.get(id);
397 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
398 sone = new SoneImpl(id, false);
406 * Returns whether the given Sone has been modified.
409 * The Sone to check for modifications
410 * @return {@code true} if a modification has been detected in the Sone,
411 * {@code false} otherwise
413 public boolean isModifiedSone(Sone sone) {
414 return soneInserters.containsKey(sone) && soneInserters.get(sone).isModified();
418 * Returns the time when the given was first followed by any local Sone.
421 * The Sone to get the time for
422 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
423 * been followed, or {@link Long#MAX_VALUE}
425 public long getSoneFollowingTime(Sone sone) {
426 synchronized (soneFollowingTimes) {
427 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
432 * Returns whether the target Sone is trusted by the origin Sone.
438 * @return {@code true} if the target Sone is trusted by the origin Sone
440 public boolean isSoneTrusted(Sone origin, Sone target) {
441 checkNotNull(origin, "origin must not be null");
442 checkNotNull(target, "target must not be null");
443 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
444 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
448 * Returns a post builder.
450 * @return A new post builder
452 public PostBuilder postBuilder() {
453 return database.newPostBuilder();
460 public Optional<Post> getPost(String postId) {
461 return database.getPost(postId);
468 public Collection<Post> getPosts(String soneId) {
469 return database.getPosts(soneId);
476 public Collection<Post> getDirectedPosts(final String recipientId) {
477 checkNotNull(recipientId, "recipient must not be null");
478 return database.getDirectedPosts(recipientId);
482 * Returns a post reply builder.
484 * @return A new post reply builder
486 public PostReplyBuilder postReplyBuilder() {
487 return database.newPostReplyBuilder();
494 public Optional<PostReply> getPostReply(String replyId) {
495 return database.getPostReply(replyId);
502 public List<PostReply> getReplies(final String postId) {
503 return database.getReplies(postId);
507 * Returns all Sones that have liked the given post.
510 * The post to get the liking Sones for
511 * @return The Sones that like the given post
513 public Set<Sone> getLikes(Post post) {
514 Set<Sone> sones = new HashSet<Sone>();
515 for (Sone sone : getSones()) {
516 if (sone.getLikedPostIds().contains(post.getId())) {
524 * Returns all Sones that have liked the given reply.
527 * The reply to get the liking Sones for
528 * @return The Sones that like the given reply
530 public Set<Sone> getLikes(PostReply reply) {
531 Set<Sone> sones = new HashSet<Sone>();
532 for (Sone sone : getSones()) {
533 if (sone.getLikedReplyIds().contains(reply.getId())) {
541 * Returns whether the given post is bookmarked.
545 * @return {@code true} if the given post is bookmarked, {@code false}
548 public boolean isBookmarked(Post post) {
549 return isPostBookmarked(post.getId());
553 * Returns whether the post with the given ID is bookmarked.
556 * The ID of the post to check
557 * @return {@code true} if the post with the given ID is bookmarked,
558 * {@code false} otherwise
560 public boolean isPostBookmarked(String id) {
561 synchronized (bookmarkedPosts) {
562 return bookmarkedPosts.contains(id);
567 * Returns all currently known bookmarked posts.
569 * @return All bookmarked posts
571 public Set<Post> getBookmarkedPosts() {
572 Set<Post> posts = new HashSet<Post>();
573 synchronized (bookmarkedPosts) {
574 for (String bookmarkedPostId : bookmarkedPosts) {
575 Optional<Post> post = getPost(bookmarkedPostId);
576 if (post.isPresent()) {
577 posts.add(post.get());
585 * Returns the album with the given ID, creating a new album if no album
586 * with the given ID can be found.
589 * The ID of the album
590 * @return The album with the given ID
592 public Album getAlbum(String albumId) {
593 return getAlbum(albumId, true);
597 * Returns the album with the given ID, optionally creating a new album if
598 * an album with the given ID can not be found.
601 * The ID of the album
603 * {@code true} to create a new album if none exists for the
605 * @return The album with the given ID, or {@code null} if no album with the
606 * given ID exists and {@code create} is {@code false}
608 public Album getAlbum(String albumId, boolean create) {
609 Optional<Album> album = database.getAlbum(albumId);
610 if (album.isPresent()) {
616 Album newAlbum = database.newAlbumBuilder().withId(albumId).build();
617 database.storeAlbum(newAlbum);
622 * Returns the image with the given ID, creating it if necessary.
625 * The ID of the image
626 * @return The image with the given ID
628 public Image getImage(String imageId) {
629 return getImage(imageId, true);
633 * Returns the image with the given ID, optionally creating it if it does
637 * The ID of the image
639 * {@code true} to create an image if none exists with the given
641 * @return The image with the given ID, or {@code null} if none exists and
644 public Image getImage(String imageId, boolean create) {
645 Optional<Image> image = database.getImage(imageId);
646 if (image.isPresent()) {
652 Image newImage = database.newImageBuilder().withId(imageId).build();
653 database.storeImage(newImage);
658 * Returns the temporary image with the given ID.
661 * The ID of the temporary image
662 * @return The temporary image, or {@code null} if there is no temporary
663 * image with the given ID
665 public TemporaryImage getTemporaryImage(String imageId) {
666 synchronized (temporaryImages) {
667 return temporaryImages.get(imageId);
676 * Locks the given Sone. A locked Sone will not be inserted by
677 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
683 public void lockSone(Sone sone) {
684 synchronized (lockedSones) {
685 if (lockedSones.add(sone)) {
686 eventBus.post(new SoneLockedEvent(sone));
692 * Unlocks the given Sone.
694 * @see #lockSone(Sone)
698 public void unlockSone(Sone sone) {
699 synchronized (lockedSones) {
700 if (lockedSones.remove(sone)) {
701 eventBus.post(new SoneUnlockedEvent(sone));
707 * Adds a local Sone from the given own identity.
710 * The own identity to create a Sone from
711 * @return The added (or already existing) Sone
713 public Sone addLocalSone(OwnIdentity ownIdentity) {
714 if (ownIdentity == null) {
715 logger.log(Level.WARNING, "Given OwnIdentity is null!");
718 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
719 synchronized (sones) {
722 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
723 } catch (MalformedURLException mue1) {
724 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
727 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
728 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
730 /* TODO - load posts ’n stuff */
731 sones.put(ownIdentity.getId(), sone);
732 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
733 soneInserters.put(sone, soneInserter);
734 sone.setStatus(SoneStatus.idle);
736 soneInserter.start();
742 * Creates a new Sone for the given own identity.
745 * The own identity to create a Sone for
746 * @return The created Sone
748 public Sone createSone(OwnIdentity ownIdentity) {
749 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
750 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
753 Sone sone = addLocalSone(ownIdentity);
754 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
755 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
756 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
757 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
758 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
759 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
761 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
762 touchConfiguration();
767 * Adds the Sone of the given identity.
770 * The identity whose Sone to add
771 * @return The added or already existing Sone
773 public Sone addRemoteSone(Identity identity) {
774 if (identity == null) {
775 logger.log(Level.WARNING, "Given Identity is null!");
778 synchronized (sones) {
779 final Sone sone = getRemoteSone(identity.getId(), true);
780 if (sone.isLocal()) {
783 sone.setIdentity(identity);
784 boolean newSone = sone.getRequestUri() == null;
785 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
786 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
788 synchronized (knownSones) {
789 newSone = !knownSones.contains(sone.getId());
791 sone.setKnown(!newSone);
793 eventBus.post(new NewSoneFoundEvent(sone));
794 for (Sone localSone : getLocalSones()) {
795 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
796 followSone(localSone, sone.getId());
801 soneDownloader.addSone(sone);
802 soneDownloaders.execute(soneDownloader.new FetchSone(sone));
808 * Lets the given local Sone follow the Sone with the given ID.
811 * The local Sone that should follow another Sone
813 * The ID of the Sone to follow
815 public void followSone(Sone sone, String soneId) {
816 checkNotNull(sone, "sone must not be null");
817 checkNotNull(soneId, "soneId must not be null");
818 sone.addFriend(soneId);
819 synchronized (soneFollowingTimes) {
820 if (!soneFollowingTimes.containsKey(soneId)) {
821 long now = System.currentTimeMillis();
822 soneFollowingTimes.put(soneId, now);
823 Optional<Sone> followedSone = getSone(soneId);
824 if (!followedSone.isPresent()) {
827 for (Post post : followedSone.get().getPosts()) {
828 if (post.getTime() < now) {
832 for (PostReply reply : followedSone.get().getReplies()) {
833 if (reply.getTime() < now) {
834 markReplyKnown(reply);
839 touchConfiguration();
843 * Lets the given local Sone unfollow the Sone with the given ID.
846 * The local Sone that should unfollow another Sone
848 * The ID of the Sone being unfollowed
850 public void unfollowSone(Sone sone, String soneId) {
851 checkNotNull(sone, "sone must not be null");
852 checkNotNull(soneId, "soneId must not be null");
853 sone.removeFriend(soneId);
854 boolean unfollowedSoneStillFollowed = false;
855 for (Sone localSone : getLocalSones()) {
856 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
858 if (!unfollowedSoneStillFollowed) {
859 synchronized (soneFollowingTimes) {
860 soneFollowingTimes.remove(soneId);
863 touchConfiguration();
867 * Sets the trust value of the given origin Sone for the target Sone.
874 * The trust value (from {@code -100} to {@code 100})
876 public void setTrust(Sone origin, Sone target, int trustValue) {
877 checkNotNull(origin, "origin must not be null");
878 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
879 checkNotNull(target, "target must not be null");
880 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
881 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
885 * Removes any trust assignment for the given target Sone.
892 public void removeTrust(Sone origin, Sone target) {
893 checkNotNull(origin, "origin must not be null");
894 checkNotNull(target, "target must not be null");
895 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
896 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
900 * Assigns the configured positive trust value for the given target.
907 public void trustSone(Sone origin, Sone target) {
908 setTrust(origin, target, preferences.getPositiveTrust());
912 * Assigns the configured negative trust value for the given target.
919 public void distrustSone(Sone origin, Sone target) {
920 setTrust(origin, target, preferences.getNegativeTrust());
924 * Removes the trust assignment for the given target.
931 public void untrustSone(Sone origin, Sone target) {
932 removeTrust(origin, target);
936 * Updates the stored Sone with the given Sone.
941 public void updateSone(Sone sone) {
942 updateSone(sone, false);
946 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
947 * {@code true}, an older Sone than the current Sone can be given to restore
952 * @param soneRescueMode
953 * {@code true} if the stored Sone should be updated regardless
954 * of the age of the given Sone
956 public void updateSone(Sone sone, boolean soneRescueMode) {
957 Optional<Sone> storedSone = getSone(sone.getId());
958 if (storedSone.isPresent()) {
959 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
960 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
963 /* find removed posts. */
964 Collection<Post> removedPosts = new ArrayList<Post>();
965 Collection<Post> newPosts = new ArrayList<Post>();
966 Collection<Post> existingPosts = database.getPosts(sone.getId());
967 for (Post oldPost : existingPosts) {
968 if (!sone.getPosts().contains(oldPost)) {
969 removedPosts.add(oldPost);
972 /* find new posts. */
973 for (Post newPost : sone.getPosts()) {
974 if (existingPosts.contains(newPost)) {
977 if (newPost.getTime() < getSoneFollowingTime(sone)) {
978 newPost.setKnown(true);
979 } else if (!newPost.isKnown()) {
980 newPosts.add(newPost);
984 database.storePosts(sone, sone.getPosts());
985 Collection<PostReply> newPostReplies = new ArrayList<PostReply>();
986 Collection<PostReply> removedPostReplies = new ArrayList<PostReply>();
987 if (!soneRescueMode) {
988 for (PostReply reply : storedSone.get().getReplies()) {
989 if (!sone.getReplies().contains(reply)) {
990 removedPostReplies.add(reply);
994 Set<PostReply> storedReplies = storedSone.get().getReplies();
995 for (PostReply reply : sone.getReplies()) {
996 if (storedReplies.contains(reply)) {
999 if (reply.getTime() < getSoneFollowingTime(sone)) {
1000 reply.setKnown(true);
1001 } else if (!reply.isKnown()) {
1002 newPostReplies.add(reply);
1005 database.storePostReplies(sone, sone.getReplies());
1006 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1007 database.removeAlbum(album);
1008 for (Image image : album.getImages()) {
1009 database.removeImage(image);
1012 for (Post removedPost : removedPosts) {
1013 eventBus.post(new PostRemovedEvent(removedPost));
1015 for (Post newPost : newPosts) {
1016 eventBus.post(new NewPostFoundEvent(newPost));
1018 for (PostReply removedPostReply : removedPostReplies) {
1019 eventBus.post(new PostReplyRemovedEvent(removedPostReply));
1021 for (PostReply newPostReply : newPostReplies) {
1022 eventBus.post(new NewPostReplyFoundEvent(newPostReply));
1024 for (Album album : sone.getRootAlbum().getAlbums()) {
1025 database.storeAlbum(album);
1026 for (Image image : album.getImages()) {
1027 database.storeImage(image);
1030 synchronized (sones) {
1031 sone.setOptions(storedSone.get().getOptions());
1032 sone.setKnown(storedSone.get().isKnown());
1033 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1034 if (sone.isLocal()) {
1035 soneInserters.get(storedSone.get()).setSone(sone);
1036 touchConfiguration();
1038 sones.put(sone.getId(), sone);
1044 * Deletes the given Sone. This will remove the Sone from the
1045 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1046 * remove the context from its identity.
1049 * The Sone to delete
1051 public void deleteSone(Sone sone) {
1052 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1053 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1056 synchronized (sones) {
1057 if (!getLocalSones().contains(sone)) {
1058 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1061 sones.remove(sone.getId());
1062 SoneInserter soneInserter = soneInserters.remove(sone);
1063 soneInserter.stop();
1065 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1066 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1068 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1069 } catch (ConfigurationException ce1) {
1070 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1075 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1076 * known} before, a {@link MarkSoneKnownEvent} is fired.
1079 * The Sone to mark as known
1081 public void markSoneKnown(Sone sone) {
1082 if (!sone.isKnown()) {
1083 sone.setKnown(true);
1084 synchronized (knownSones) {
1085 knownSones.add(sone.getId());
1087 eventBus.post(new MarkSoneKnownEvent(sone));
1088 touchConfiguration();
1093 * Loads and updates the given Sone from the configuration. If any error is
1094 * encountered, loading is aborted and the given Sone is not changed.
1097 * The Sone to load and update
1099 public void loadSone(Sone sone) {
1100 if (!sone.isLocal()) {
1101 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1104 logger.info(String.format("Loading local Sone: %s", sone));
1106 /* initialize options. */
1107 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1108 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1109 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1110 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1111 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1112 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1115 String sonePrefix = "Sone/" + sone.getId();
1116 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1117 if (soneTime == null) {
1118 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1121 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1124 Profile profile = new Profile(sone);
1125 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1126 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1127 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1128 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1129 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1130 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1132 /* load profile fields. */
1134 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1135 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1136 if (fieldName == null) {
1139 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1140 profile.addField(fieldName).setValue(fieldValue);
1144 Set<Post> posts = new HashSet<Post>();
1146 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1147 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1148 if (postId == null) {
1151 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1152 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1153 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1154 if ((postTime == 0) || (postText == null)) {
1155 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1158 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1159 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1160 postBuilder.to(postRecipientId);
1162 posts.add(postBuilder.build());
1166 Set<PostReply> replies = new HashSet<PostReply>();
1168 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1169 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1170 if (replyId == null) {
1173 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1174 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1175 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1176 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1177 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1180 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1181 replies.add(postReplyBuilder.build());
1184 /* load post likes. */
1185 Set<String> likedPostIds = new HashSet<String>();
1187 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1188 if (likedPostId == null) {
1191 likedPostIds.add(likedPostId);
1194 /* load reply likes. */
1195 Set<String> likedReplyIds = new HashSet<String>();
1197 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1198 if (likedReplyId == null) {
1201 likedReplyIds.add(likedReplyId);
1205 Set<String> friends = new HashSet<String>();
1207 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1208 if (friendId == null) {
1211 friends.add(friendId);
1215 List<Album> topLevelAlbums = new ArrayList<Album>();
1216 int albumCounter = 0;
1218 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1219 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1220 if (albumId == null) {
1223 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1224 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1225 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1226 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1227 if ((albumTitle == null) || (albumDescription == null)) {
1228 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1231 Album album = getAlbum(albumId).setSone(sone).modify().setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId).update();
1232 if (albumParentId != null) {
1233 Album parentAlbum = getAlbum(albumParentId, false);
1234 if (parentAlbum == null) {
1235 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1238 parentAlbum.addAlbum(album);
1240 if (!topLevelAlbums.contains(album)) {
1241 topLevelAlbums.add(album);
1247 int imageCounter = 0;
1249 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1250 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1251 if (imageId == null) {
1254 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1255 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1256 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1257 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1258 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1259 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1260 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1261 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1262 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1265 Album album = getAlbum(albumId, false);
1266 if (album == null) {
1267 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1270 Image image = getImage(imageId).modify().setSone(sone).setCreationTime(creationTime).setKey(key).setTitle(title).setDescription(description).setWidth(width).setHeight(height).update();
1271 album.addImage(image);
1275 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1276 if (avatarId != null) {
1277 profile.setAvatar(getImage(avatarId, false));
1281 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1282 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1283 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1284 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1285 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1286 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1288 /* if we’re still here, Sone was loaded successfully. */
1289 synchronized (sone) {
1290 sone.setTime(soneTime);
1291 sone.setProfile(profile);
1292 sone.setPosts(posts);
1293 sone.setReplies(replies);
1294 sone.setLikePostIds(likedPostIds);
1295 sone.setLikeReplyIds(likedReplyIds);
1296 for (String friendId : friends) {
1297 followSone(sone, friendId);
1299 for (Album album : sone.getRootAlbum().getAlbums()) {
1300 sone.getRootAlbum().removeAlbum(album);
1302 for (Album album : topLevelAlbums) {
1303 sone.getRootAlbum().addAlbum(album);
1305 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1307 synchronized (knownSones) {
1308 for (String friend : friends) {
1309 knownSones.add(friend);
1312 database.storePosts(sone, posts);
1313 for (Post post : posts) {
1314 post.setKnown(true);
1316 database.storePostReplies(sone, replies);
1317 for (PostReply reply : replies) {
1318 reply.setKnown(true);
1321 logger.info(String.format("Sone loaded successfully: %s", sone));
1325 * Creates a new post.
1328 * The Sone that creates the post
1330 * The text of the post
1331 * @return The created post
1333 public Post createPost(Sone sone, String text) {
1334 return createPost(sone, System.currentTimeMillis(), text);
1338 * Creates a new post.
1341 * The Sone that creates the post
1343 * The time of the post
1345 * The text of the post
1346 * @return The created post
1348 public Post createPost(Sone sone, long time, String text) {
1349 return createPost(sone, null, time, text);
1353 * Creates a new post.
1356 * The Sone that creates the post
1358 * The recipient Sone, or {@code null} if this post does not have
1361 * The text of the post
1362 * @return The created post
1364 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1365 return createPost(sone, recipient, System.currentTimeMillis(), text);
1369 * Creates a new post.
1372 * The Sone that creates the post
1374 * The recipient Sone, or {@code null} if this post does not have
1377 * The time of the post
1379 * The text of the post
1380 * @return The created post
1382 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1383 checkNotNull(text, "text must not be null");
1384 checkArgument(text.trim().length() > 0, "text must not be empty");
1385 if (!sone.isLocal()) {
1386 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1389 PostBuilder postBuilder = database.newPostBuilder();
1390 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1391 if (recipient.isPresent()) {
1392 postBuilder.to(recipient.get().getId());
1394 final Post post = postBuilder.build();
1395 database.storePost(post);
1396 eventBus.post(new NewPostFoundEvent(post));
1398 touchConfiguration();
1399 localElementTicker.schedule(new Runnable() {
1406 markPostKnown(post);
1408 }, 10, TimeUnit.SECONDS);
1413 * Deletes the given post.
1416 * The post to delete
1418 public void deletePost(Post post) {
1419 if (!post.getSone().isLocal()) {
1420 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1423 database.removePost(post);
1424 eventBus.post(new PostRemovedEvent(post));
1425 markPostKnown(post);
1426 touchConfiguration();
1430 * Marks the given post as known, if it is currently not a known post
1431 * (according to {@link Post#isKnown()}).
1434 * The post to mark as known
1436 public void markPostKnown(Post post) {
1437 post.setKnown(true);
1438 eventBus.post(new MarkPostKnownEvent(post));
1439 touchConfiguration();
1440 for (PostReply reply : getReplies(post.getId())) {
1441 markReplyKnown(reply);
1446 * Bookmarks the given post.
1449 * The post to bookmark
1451 public void bookmark(Post post) {
1452 bookmarkPost(post.getId());
1456 * Bookmarks the post with the given ID.
1459 * The ID of the post to bookmark
1461 public void bookmarkPost(String id) {
1462 synchronized (bookmarkedPosts) {
1463 bookmarkedPosts.add(id);
1468 * Removes the given post from the bookmarks.
1471 * The post to unbookmark
1473 public void unbookmark(Post post) {
1474 unbookmarkPost(post.getId());
1478 * Removes the post with the given ID from the bookmarks.
1481 * The ID of the post to unbookmark
1483 public void unbookmarkPost(String id) {
1484 synchronized (bookmarkedPosts) {
1485 bookmarkedPosts.remove(id);
1490 * Creates a new reply.
1493 * The Sone that creates the reply
1495 * The post that this reply refers to
1497 * The text of the reply
1498 * @return The created reply
1500 public PostReply createReply(Sone sone, Post post, String text) {
1501 checkNotNull(text, "text must not be null");
1502 checkArgument(text.trim().length() > 0, "text must not be empty");
1503 if (!sone.isLocal()) {
1504 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1507 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1508 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1509 final PostReply reply = postReplyBuilder.build();
1510 database.storePostReply(reply);
1511 eventBus.post(new NewPostReplyFoundEvent(reply));
1512 sone.addReply(reply);
1513 touchConfiguration();
1514 localElementTicker.schedule(new Runnable() {
1521 markReplyKnown(reply);
1523 }, 10, TimeUnit.SECONDS);
1528 * Deletes the given reply.
1531 * The reply to delete
1533 public void deleteReply(PostReply reply) {
1534 Sone sone = reply.getSone();
1535 if (!sone.isLocal()) {
1536 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1539 database.removePostReply(reply);
1540 markReplyKnown(reply);
1541 sone.removeReply(reply);
1542 touchConfiguration();
1546 * Marks the given reply as known, if it is currently not a known reply
1547 * (according to {@link Reply#isKnown()}).
1550 * The reply to mark as known
1552 public void markReplyKnown(PostReply reply) {
1553 boolean previouslyKnown = reply.isKnown();
1554 reply.setKnown(true);
1555 eventBus.post(new MarkPostReplyKnownEvent(reply));
1556 if (!previouslyKnown) {
1557 touchConfiguration();
1562 * Creates a new top-level album for the given Sone.
1565 * The Sone to create the album for
1566 * @return The new album
1568 public Album createAlbum(Sone sone) {
1569 return createAlbum(sone, sone.getRootAlbum());
1573 * Creates a new album for the given Sone.
1576 * The Sone to create the album for
1578 * The parent of the album (may be {@code null} to create a
1580 * @return The new album
1582 public Album createAlbum(Sone sone, Album parent) {
1583 Album album = database.newAlbumBuilder().randomId().build();
1584 database.storeAlbum(album);
1585 album.setSone(sone);
1586 parent.addAlbum(album);
1591 * Deletes the given album. The owner of the album has to be a local Sone,
1592 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1595 * The album to remove
1597 public void deleteAlbum(Album album) {
1598 checkNotNull(album, "album must not be null");
1599 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1600 if (!album.isEmpty()) {
1603 album.getParent().removeAlbum(album);
1604 database.removeAlbum(album);
1605 touchConfiguration();
1609 * Creates a new image.
1612 * The Sone creating the image
1614 * The album the image will be inserted into
1615 * @param temporaryImage
1616 * The temporary image to create the image from
1617 * @return The newly created image
1619 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1620 checkNotNull(sone, "sone must not be null");
1621 checkNotNull(album, "album must not be null");
1622 checkNotNull(temporaryImage, "temporaryImage must not be null");
1623 checkArgument(sone.isLocal(), "sone must be a local Sone");
1624 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1625 Image image = database.newImageBuilder().withId(temporaryImage.getId()).build().modify().setSone(sone).setCreationTime(System.currentTimeMillis()).update();
1626 album.addImage(image);
1627 database.storeImage(image);
1628 imageInserter.insertImage(temporaryImage, image);
1633 * Deletes the given image. This method will also delete a matching
1636 * @see #deleteTemporaryImage(TemporaryImage)
1638 * The image to delete
1640 public void deleteImage(Image image) {
1641 checkNotNull(image, "image must not be null");
1642 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1643 deleteTemporaryImage(image.getId());
1644 image.getAlbum().removeImage(image);
1645 database.removeImage(image);
1646 touchConfiguration();
1650 * Creates a new temporary image.
1653 * The MIME type of the temporary image
1655 * The encoded data of the image
1656 * @return The temporary image
1658 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1659 TemporaryImage temporaryImage = new TemporaryImage();
1660 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1661 synchronized (temporaryImages) {
1662 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1664 return temporaryImage;
1668 * Deletes the given temporary image.
1670 * @param temporaryImage
1671 * The temporary image to delete
1673 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1674 checkNotNull(temporaryImage, "temporaryImage must not be null");
1675 deleteTemporaryImage(temporaryImage.getId());
1679 * Deletes the temporary image with the given ID.
1682 * The ID of the temporary image to delete
1684 public void deleteTemporaryImage(String imageId) {
1685 checkNotNull(imageId, "imageId must not be null");
1686 synchronized (temporaryImages) {
1687 temporaryImages.remove(imageId);
1689 Image image = getImage(imageId, false);
1690 if (image != null) {
1691 imageInserter.cancelImageInsert(image);
1696 * Notifies the core that the configuration, either of the core or of a
1697 * single local Sone, has changed, and that the configuration should be
1700 public void touchConfiguration() {
1701 lastConfigurationUpdate = System.currentTimeMillis();
1712 public void serviceStart() {
1713 loadConfiguration();
1714 updateChecker.start();
1715 identityManager.start();
1716 webOfTrustUpdater.init();
1717 webOfTrustUpdater.start();
1725 public void serviceRun() {
1726 long lastSaved = System.currentTimeMillis();
1727 while (!shouldStop()) {
1729 long now = System.currentTimeMillis();
1730 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1731 for (Sone localSone : getLocalSones()) {
1732 saveSone(localSone);
1734 saveConfiguration();
1744 public void serviceStop() {
1745 localElementTicker.shutdownNow();
1746 synchronized (sones) {
1747 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1748 soneInserter.getValue().stop();
1749 saveSone(getLocalSone(soneInserter.getKey().getId(), false));
1752 saveConfiguration();
1754 webOfTrustUpdater.stop();
1755 updateChecker.stop();
1756 soneDownloader.stop();
1757 soneDownloaders.shutdown();
1758 identityManager.stop();
1766 * Saves the given Sone. This will persist all local settings for the given
1767 * Sone, such as the friends list and similar, private options.
1772 private synchronized void saveSone(Sone sone) {
1773 if (!sone.isLocal()) {
1774 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1777 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1778 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1782 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1784 /* save Sone into configuration. */
1785 String sonePrefix = "Sone/" + sone.getId();
1786 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1787 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1790 Profile profile = sone.getProfile();
1791 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1792 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1793 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1794 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1795 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1796 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1797 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1799 /* save profile fields. */
1800 int fieldCounter = 0;
1801 for (Field profileField : profile.getFields()) {
1802 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1803 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1804 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1806 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1809 int postCounter = 0;
1810 for (Post post : sone.getPosts()) {
1811 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1812 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1813 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1814 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1815 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1817 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1820 int replyCounter = 0;
1821 for (PostReply reply : sone.getReplies()) {
1822 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1823 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1824 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1825 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1826 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1828 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1830 /* save post likes. */
1831 int postLikeCounter = 0;
1832 for (String postId : sone.getLikedPostIds()) {
1833 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1835 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1837 /* save reply likes. */
1838 int replyLikeCounter = 0;
1839 for (String replyId : sone.getLikedReplyIds()) {
1840 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1842 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1845 int friendCounter = 0;
1846 for (String friendId : sone.getFriends()) {
1847 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1849 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1851 /* save albums. first, collect in a flat structure, top-level first. */
1852 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1854 int albumCounter = 0;
1855 for (Album album : albums) {
1856 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1857 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1858 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1859 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1860 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1861 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1863 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1866 int imageCounter = 0;
1867 for (Album album : albums) {
1868 for (Image image : album.getImages()) {
1869 if (!image.isInserted()) {
1872 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1873 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1874 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1875 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1876 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1877 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1878 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1879 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1880 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1883 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1886 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1887 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1888 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1889 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1890 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1891 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1893 configuration.save();
1895 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1897 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1898 } catch (ConfigurationException ce1) {
1899 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1904 * Saves the current options.
1906 private void saveConfiguration() {
1907 synchronized (configuration) {
1908 if (storingConfiguration) {
1909 logger.log(Level.FINE, "Already storing configuration…");
1912 storingConfiguration = true;
1915 /* store the options first. */
1917 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1918 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1919 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1920 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1921 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1922 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1923 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1924 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1925 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1926 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1927 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1928 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1930 /* save known Sones. */
1931 int soneCounter = 0;
1932 synchronized (knownSones) {
1933 for (String knownSoneId : knownSones) {
1934 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1936 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1939 /* save Sone following times. */
1941 synchronized (soneFollowingTimes) {
1942 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1943 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1944 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1947 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1950 /* save known posts. */
1953 /* save bookmarked posts. */
1954 int bookmarkedPostCounter = 0;
1955 synchronized (bookmarkedPosts) {
1956 for (String bookmarkedPostId : bookmarkedPosts) {
1957 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1960 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1963 configuration.save();
1965 } catch (ConfigurationException ce1) {
1966 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1967 } catch (DatabaseException de1) {
1968 logger.log(Level.SEVERE, "Could not save database!", de1);
1970 synchronized (configuration) {
1971 storingConfiguration = false;
1977 * Loads the configuration.
1979 private void loadConfiguration() {
1980 /* create options. */
1981 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new SetInsertionDelay()));
1982 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1983 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
1984 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1985 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
1986 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
1987 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
1988 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
1989 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
1990 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, fcpInterface.new SetActive()));
1991 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, fcpInterface.new SetFullAccessRequired()));
1993 loadConfigurationValue("InsertionDelay");
1994 loadConfigurationValue("PostsPerPage");
1995 loadConfigurationValue("ImagesPerPage");
1996 loadConfigurationValue("CharactersPerPost");
1997 loadConfigurationValue("PostCutOffLength");
1998 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
1999 loadConfigurationValue("PositiveTrust");
2000 loadConfigurationValue("NegativeTrust");
2001 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2002 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2003 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2005 /* load known Sones. */
2006 int soneCounter = 0;
2008 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2009 if (knownSoneId == null) {
2012 synchronized (knownSones) {
2013 knownSones.add(knownSoneId);
2017 /* load Sone following times. */
2020 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2021 if (soneId == null) {
2024 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2025 synchronized (soneFollowingTimes) {
2026 soneFollowingTimes.put(soneId, time);
2031 /* load bookmarked posts. */
2032 int bookmarkedPostCounter = 0;
2034 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2035 if (bookmarkedPostId == null) {
2038 synchronized (bookmarkedPosts) {
2039 bookmarkedPosts.add(bookmarkedPostId);
2046 * Loads an {@link Integer} configuration value for the option with the
2047 * given name, logging validation failures.
2050 * The name of the option to load
2052 private void loadConfigurationValue(String optionName) {
2054 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2055 } catch (IllegalArgumentException iae1) {
2056 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2061 * Notifies the core that a new {@link OwnIdentity} was added.
2063 * @param ownIdentityAddedEvent
2067 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2068 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2069 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2070 if (ownIdentity.hasContext("Sone")) {
2071 addLocalSone(ownIdentity);
2076 * Notifies the core that an {@link OwnIdentity} was removed.
2078 * @param ownIdentityRemovedEvent
2082 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2083 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2084 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2085 trustedIdentities.removeAll(ownIdentity);
2089 * Notifies the core that a new {@link Identity} was added.
2091 * @param identityAddedEvent
2095 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2096 Identity identity = identityAddedEvent.identity();
2097 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2098 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2099 addRemoteSone(identity);
2103 * Notifies the core that an {@link Identity} was updated.
2105 * @param identityUpdatedEvent
2109 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2110 final Identity identity = identityUpdatedEvent.identity();
2111 soneDownloaders.execute(new Runnable() {
2114 @SuppressWarnings("synthetic-access")
2116 Sone sone = getRemoteSone(identity.getId(), false);
2117 if (sone.isLocal()) {
2120 sone.setIdentity(identity);
2121 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2122 soneDownloader.addSone(sone);
2123 soneDownloader.fetchSone(sone);
2129 * Notifies the core that an {@link Identity} was removed.
2131 * @param identityRemovedEvent
2135 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2136 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2137 Identity identity = identityRemovedEvent.identity();
2138 trustedIdentities.remove(ownIdentity, identity);
2139 boolean foundIdentity = false;
2140 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2141 if (trustedIdentity.getKey().equals(ownIdentity)) {
2144 if (trustedIdentity.getValue().contains(identity)) {
2145 foundIdentity = true;
2148 if (foundIdentity) {
2149 /* some local identity still trusts this identity, don’t remove. */
2152 Optional<Sone> sone = getSone(identity.getId());
2153 if (!sone.isPresent()) {
2154 /* TODO - we don’t have the Sone anymore. should this happen? */
2157 database.removePosts(sone.get());
2158 for (Post post : sone.get().getPosts()) {
2159 eventBus.post(new PostRemovedEvent(post));
2161 database.removePostReplies(sone.get());
2162 for (PostReply reply : sone.get().getReplies()) {
2163 eventBus.post(new PostReplyRemovedEvent(reply));
2165 synchronized (sones) {
2166 sones.remove(identity.getId());
2168 eventBus.post(new SoneRemovedEvent(sone.get()));
2172 * Deletes the temporary image.
2174 * @param imageInsertFinishedEvent
2178 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2179 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2180 imageInsertFinishedEvent.image().modify().setKey(imageInsertFinishedEvent.resultingUri().toString()).update();
2181 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2182 touchConfiguration();