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;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
39 import net.pterodactylus.sone.core.Options.DefaultOption;
40 import net.pterodactylus.sone.core.Options.Option;
41 import net.pterodactylus.sone.core.Options.OptionWatcher;
42 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
43 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
44 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
45 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
46 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
47 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
48 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
49 import net.pterodactylus.sone.core.event.PostRemovedEvent;
50 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
51 import net.pterodactylus.sone.core.event.SoneLockedEvent;
52 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
53 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Client;
56 import net.pterodactylus.sone.data.Image;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Profile;
60 import net.pterodactylus.sone.data.Profile.Field;
61 import net.pterodactylus.sone.data.Reply;
62 import net.pterodactylus.sone.data.Sone;
63 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
64 import net.pterodactylus.sone.data.Sone.SoneStatus;
65 import net.pterodactylus.sone.data.TemporaryImage;
66 import net.pterodactylus.sone.database.Database;
67 import net.pterodactylus.sone.database.DatabaseException;
68 import net.pterodactylus.sone.database.PostBuilder;
69 import net.pterodactylus.sone.database.PostProvider;
70 import net.pterodactylus.sone.database.PostReplyBuilder;
71 import net.pterodactylus.sone.database.PostReplyProvider;
72 import net.pterodactylus.sone.database.SoneProvider;
73 import net.pterodactylus.sone.fcp.FcpInterface;
74 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
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.sone.main.SonePlugin;
84 import net.pterodactylus.sone.utils.IntegerRangePredicate;
85 import net.pterodactylus.util.config.Configuration;
86 import net.pterodactylus.util.config.ConfigurationException;
87 import net.pterodactylus.util.logging.Logging;
88 import net.pterodactylus.util.number.Numbers;
89 import net.pterodactylus.util.service.AbstractService;
90 import net.pterodactylus.util.thread.NamedThreadFactory;
92 import com.google.common.base.Optional;
93 import com.google.common.base.Predicate;
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 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 known albums. */
191 private final Map<String, Album> albums = new HashMap<String, Album>();
193 /** All known images. */
194 private final Map<String, Image> images = new HashMap<String, Image>();
196 /** All temporary images. */
197 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
199 /** Ticker for threads that mark own elements as known. */
200 private final ScheduledExecutorService localElementTicker = Executors.newScheduledThreadPool(1);
202 /** The time the configuration was last touched. */
203 private volatile long lastConfigurationUpdate;
206 * Creates a new core.
208 * @param configuration
209 * The configuration of the core
210 * @param freenetInterface
211 * The freenet interface
212 * @param identityManager
213 * The identity manager
214 * @param webOfTrustUpdater
215 * The WebOfTrust updater
222 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus, Database database) {
224 this.configuration = configuration;
225 this.freenetInterface = freenetInterface;
226 this.identityManager = identityManager;
227 this.soneDownloader = new SoneDownloader(this, freenetInterface);
228 this.imageInserter = new ImageInserter(freenetInterface);
229 this.updateChecker = new UpdateChecker(eventBus, freenetInterface);
230 this.webOfTrustUpdater = webOfTrustUpdater;
231 this.eventBus = eventBus;
232 this.database = database;
240 * Returns the time Sone was started.
242 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
244 public long getStartupTime() {
249 * Sets the configuration to use. This will automatically save the current
250 * configuration to the given configuration.
252 * @param configuration
253 * The new configuration to use
255 public void setConfiguration(Configuration configuration) {
256 this.configuration = configuration;
257 touchConfiguration();
261 * Returns the options used by the core.
263 * @return The options of the core
265 public Preferences getPreferences() {
270 * Returns the identity manager used by the core.
272 * @return The identity manager
274 public IdentityManager getIdentityManager() {
275 return identityManager;
279 * Returns the update checker.
281 * @return The update checker
283 public UpdateChecker getUpdateChecker() {
284 return updateChecker;
288 * Sets the FCP interface to use.
290 * @param fcpInterface
291 * The FCP interface to use
293 public void setFcpInterface(FcpInterface fcpInterface) {
294 this.fcpInterface = fcpInterface;
298 * Returns the Sone rescuer for the given local Sone.
301 * The local Sone to get the rescuer for
302 * @return The Sone rescuer for the given Sone
304 public SoneRescuer getSoneRescuer(Sone sone) {
305 checkNotNull(sone, "sone must not be null");
306 checkArgument(sone.isLocal(), "sone must be local");
307 synchronized (sones) {
308 SoneRescuer soneRescuer = soneRescuers.get(sone);
309 if (soneRescuer == null) {
310 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
311 soneRescuers.put(sone, soneRescuer);
319 * Returns whether the given Sone is currently locked.
323 * @return {@code true} if the Sone is locked, {@code false} if it is not
325 public boolean isLocked(Sone sone) {
326 synchronized (lockedSones) {
327 return lockedSones.contains(sone);
335 public Collection<Sone> getSones() {
336 synchronized (sones) {
337 return ImmutableSet.copyOf(sones.values());
342 * Returns the Sone with the given ID, regardless whether it’s local or
346 * The ID of the Sone to get
347 * @return The Sone with the given ID, or {@code null} if there is no such
351 public Optional<Sone> getSone(String id) {
352 synchronized (sones) {
353 return Optional.fromNullable(sones.get(id));
361 public Collection<Sone> getLocalSones() {
362 synchronized (sones) {
363 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
366 public boolean apply(Sone sone) {
367 return sone.isLocal();
374 * Returns the local Sone with the given ID, optionally creating a new Sone.
379 * {@code true} to create a new Sone if none exists,
380 * {@code false} to return null if none exists
381 * @return The Sone with the given ID, or {@code null}
383 public Sone getLocalSone(String id, boolean create) {
384 synchronized (sones) {
385 Sone sone = sones.get(id);
386 if ((sone == null) && create) {
387 sone = new Sone(id, true);
390 if ((sone != null) && !sone.isLocal()) {
391 sone = new Sone(id, true);
402 public Collection<Sone> getRemoteSones() {
403 synchronized (sones) {
404 return FluentIterable.from(sones.values()).filter(new Predicate<Sone>() {
407 public boolean apply(Sone sone) {
408 return !sone.isLocal();
415 * Returns the remote Sone with the given ID.
418 * The ID of the remote Sone to get
420 * {@code true} to always create a Sone, {@code false} to return
421 * {@code null} if no Sone with the given ID exists
422 * @return The Sone with the given ID
424 public Sone getRemoteSone(String id, boolean create) {
425 synchronized (sones) {
426 Sone sone = sones.get(id);
427 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
428 sone = new Sone(id, false);
436 * Returns whether the given Sone has been modified.
439 * The Sone to check for modifications
440 * @return {@code true} if a modification has been detected in the Sone,
441 * {@code false} otherwise
443 public boolean isModifiedSone(Sone sone) {
444 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
448 * Returns the time when the given was first followed by any local Sone.
451 * The Sone to get the time for
452 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
453 * been followed, or {@link Long#MAX_VALUE}
455 public long getSoneFollowingTime(Sone sone) {
456 synchronized (soneFollowingTimes) {
457 return Optional.fromNullable(soneFollowingTimes.get(sone.getId())).or(Long.MAX_VALUE);
462 * Returns whether the target Sone is trusted by the origin Sone.
468 * @return {@code true} if the target Sone is trusted by the origin Sone
470 public boolean isSoneTrusted(Sone origin, Sone target) {
471 checkNotNull(origin, "origin must not be null");
472 checkNotNull(target, "target must not be null");
473 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin’s identity must be an OwnIdentity");
474 return trustedIdentities.containsEntry(origin.getIdentity(), target.getIdentity());
478 * Returns a post builder.
480 * @return A new post builder
482 public PostBuilder postBuilder() {
483 return database.newPostBuilder();
490 public Optional<Post> getPost(String postId) {
491 return database.getPost(postId);
498 public Collection<Post> getPosts(String soneId) {
499 return database.getPosts(soneId);
506 public Collection<Post> getDirectedPosts(final String recipientId) {
507 checkNotNull(recipientId, "recipient must not be null");
508 return database.getDirectedPosts(recipientId);
512 * Returns a post reply builder.
514 * @return A new post reply builder
516 public PostReplyBuilder postReplyBuilder() {
517 return database.newPostReplyBuilder();
524 public Optional<PostReply> getPostReply(String replyId) {
525 return database.getPostReply(replyId);
532 public List<PostReply> getReplies(final String postId) {
533 return database.getReplies(postId);
537 * Returns all Sones that have liked the given post.
540 * The post to get the liking Sones for
541 * @return The Sones that like the given post
543 public Set<Sone> getLikes(Post post) {
544 Set<Sone> sones = new HashSet<Sone>();
545 for (Sone sone : getSones()) {
546 if (sone.getLikedPostIds().contains(post.getId())) {
554 * Returns all Sones that have liked the given reply.
557 * The reply to get the liking Sones for
558 * @return The Sones that like the given reply
560 public Set<Sone> getLikes(PostReply reply) {
561 Set<Sone> sones = new HashSet<Sone>();
562 for (Sone sone : getSones()) {
563 if (sone.getLikedReplyIds().contains(reply.getId())) {
571 * Returns whether the given post is bookmarked.
575 * @return {@code true} if the given post is bookmarked, {@code false}
578 public boolean isBookmarked(Post post) {
579 return isPostBookmarked(post.getId());
583 * Returns whether the post with the given ID is bookmarked.
586 * The ID of the post to check
587 * @return {@code true} if the post with the given ID is bookmarked,
588 * {@code false} otherwise
590 public boolean isPostBookmarked(String id) {
591 synchronized (bookmarkedPosts) {
592 return bookmarkedPosts.contains(id);
597 * Returns all currently known bookmarked posts.
599 * @return All bookmarked posts
601 public Set<Post> getBookmarkedPosts() {
602 Set<Post> posts = new HashSet<Post>();
603 synchronized (bookmarkedPosts) {
604 for (String bookmarkedPostId : bookmarkedPosts) {
605 Optional<Post> post = getPost(bookmarkedPostId);
606 if (post.isPresent()) {
607 posts.add(post.get());
615 * Returns the album with the given ID, creating a new album if no album
616 * with the given ID can be found.
619 * The ID of the album
620 * @return The album with the given ID
622 public Album getAlbum(String albumId) {
623 return getAlbum(albumId, true);
627 * Returns the album with the given ID, optionally creating a new album if
628 * an album with the given ID can not be found.
631 * The ID of the album
633 * {@code true} to create a new album if none exists for the
635 * @return The album with the given ID, or {@code null} if no album with the
636 * given ID exists and {@code create} is {@code false}
638 public Album getAlbum(String albumId, boolean create) {
639 synchronized (albums) {
640 Album album = albums.get(albumId);
641 if (create && (album == null)) {
642 album = new Album(albumId);
643 albums.put(albumId, album);
650 * Returns the image with the given ID, creating it if necessary.
653 * The ID of the image
654 * @return The image with the given ID
656 public Image getImage(String imageId) {
657 return getImage(imageId, true);
661 * Returns the image with the given ID, optionally creating it if it does
665 * The ID of the image
667 * {@code true} to create an image if none exists with the given
669 * @return The image with the given ID, or {@code null} if none exists and
672 public Image getImage(String imageId, boolean create) {
673 synchronized (images) {
674 Image image = images.get(imageId);
675 if (create && (image == null)) {
676 image = new Image(imageId);
677 images.put(imageId, image);
684 * Returns the temporary image with the given ID.
687 * The ID of the temporary image
688 * @return The temporary image, or {@code null} if there is no temporary
689 * image with the given ID
691 public TemporaryImage getTemporaryImage(String imageId) {
692 synchronized (temporaryImages) {
693 return temporaryImages.get(imageId);
702 * Locks the given Sone. A locked Sone will not be inserted by
703 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
709 public void lockSone(Sone sone) {
710 synchronized (lockedSones) {
711 if (lockedSones.add(sone)) {
712 eventBus.post(new SoneLockedEvent(sone));
718 * Unlocks the given Sone.
720 * @see #lockSone(Sone)
724 public void unlockSone(Sone sone) {
725 synchronized (lockedSones) {
726 if (lockedSones.remove(sone)) {
727 eventBus.post(new SoneUnlockedEvent(sone));
733 * Adds a local Sone from the given own identity.
736 * The own identity to create a Sone from
737 * @return The added (or already existing) Sone
739 public Sone addLocalSone(OwnIdentity ownIdentity) {
740 if (ownIdentity == null) {
741 logger.log(Level.WARNING, "Given OwnIdentity is null!");
744 logger.info(String.format("Adding Sone from OwnIdentity: %s", ownIdentity));
745 synchronized (sones) {
748 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
749 } catch (MalformedURLException mue1) {
750 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
753 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
754 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
756 /* TODO - load posts ’n stuff */
757 sones.put(ownIdentity.getId(), sone);
758 final SoneInserter soneInserter = new SoneInserter(this, eventBus, freenetInterface, sone);
759 soneInserters.put(sone, soneInserter);
760 sone.setStatus(SoneStatus.idle);
762 soneInserter.start();
768 * Creates a new Sone for the given own identity.
771 * The own identity to create a Sone for
772 * @return The created Sone
774 public Sone createSone(OwnIdentity ownIdentity) {
775 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
776 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
779 Sone sone = addLocalSone(ownIdentity);
780 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
781 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
782 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
783 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
784 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
785 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
787 followSone(sone, "nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI");
788 touchConfiguration();
793 * Adds the Sone of the given identity.
796 * The identity whose Sone to add
797 * @return The added or already existing Sone
799 public Sone addRemoteSone(Identity identity) {
800 if (identity == null) {
801 logger.log(Level.WARNING, "Given Identity is null!");
804 synchronized (sones) {
805 final Sone sone = getRemoteSone(identity.getId(), true);
806 if (sone.isLocal()) {
809 sone.setIdentity(identity);
810 boolean newSone = sone.getRequestUri() == null;
811 sone.setRequestUri(SoneUri.create(identity.getRequestUri()));
812 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
814 synchronized (knownSones) {
815 newSone = !knownSones.contains(sone.getId());
817 sone.setKnown(!newSone);
819 eventBus.post(new NewSoneFoundEvent(sone));
820 for (Sone localSone : getLocalSones()) {
821 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
822 followSone(localSone, sone.getId());
827 soneDownloader.addSone(sone);
828 soneDownloaders.execute(new Runnable() {
831 @SuppressWarnings("synthetic-access")
833 soneDownloader.fetchSone(sone, sone.getRequestUri());
842 * Lets the given local Sone follow the Sone with the given ID.
845 * The local Sone that should follow another Sone
847 * The ID of the Sone to follow
849 public void followSone(Sone sone, String soneId) {
850 checkNotNull(sone, "sone must not be null");
851 checkNotNull(soneId, "soneId must not be null");
852 sone.addFriend(soneId);
853 synchronized (soneFollowingTimes) {
854 if (!soneFollowingTimes.containsKey(soneId)) {
855 long now = System.currentTimeMillis();
856 soneFollowingTimes.put(soneId, now);
857 Optional<Sone> followedSone = getSone(soneId);
858 if (!followedSone.isPresent()) {
861 for (Post post : followedSone.get().getPosts()) {
862 if (post.getTime() < now) {
866 for (PostReply reply : followedSone.get().getReplies()) {
867 if (reply.getTime() < now) {
868 markReplyKnown(reply);
873 touchConfiguration();
877 * Lets the given local Sone unfollow the Sone with the given ID.
880 * The local Sone that should unfollow another Sone
882 * The ID of the Sone being unfollowed
884 public void unfollowSone(Sone sone, String soneId) {
885 checkNotNull(sone, "sone must not be null");
886 checkNotNull(soneId, "soneId must not be null");
887 sone.removeFriend(soneId);
888 boolean unfollowedSoneStillFollowed = false;
889 for (Sone localSone : getLocalSones()) {
890 unfollowedSoneStillFollowed |= localSone.hasFriend(soneId);
892 if (!unfollowedSoneStillFollowed) {
893 synchronized (soneFollowingTimes) {
894 soneFollowingTimes.remove(soneId);
897 touchConfiguration();
901 * Sets the trust value of the given origin Sone for the target Sone.
908 * The trust value (from {@code -100} to {@code 100})
910 public void setTrust(Sone origin, Sone target, int trustValue) {
911 checkNotNull(origin, "origin must not be null");
912 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
913 checkNotNull(target, "target must not be null");
914 checkArgument((trustValue >= -100) && (trustValue <= 100), "trustValue must be within [-100, 100]");
915 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
919 * Removes any trust assignment for the given target Sone.
926 public void removeTrust(Sone origin, Sone target) {
927 checkNotNull(origin, "origin must not be null");
928 checkNotNull(target, "target must not be null");
929 checkArgument(origin.getIdentity() instanceof OwnIdentity, "origin must be a local Sone");
930 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
934 * Assigns the configured positive trust value for the given target.
941 public void trustSone(Sone origin, Sone target) {
942 setTrust(origin, target, preferences.getPositiveTrust());
946 * Assigns the configured negative trust value for the given target.
953 public void distrustSone(Sone origin, Sone target) {
954 setTrust(origin, target, preferences.getNegativeTrust());
958 * Removes the trust assignment for the given target.
965 public void untrustSone(Sone origin, Sone target) {
966 removeTrust(origin, target);
970 * Updates the stored Sone with the given Sone.
975 public void updateSone(Sone sone) {
976 updateSone(sone, false);
980 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
981 * {@code true}, an older Sone than the current Sone can be given to restore
986 * @param soneRescueMode
987 * {@code true} if the stored Sone should be updated regardless
988 * of the age of the given Sone
990 public void updateSone(Sone sone, boolean soneRescueMode) {
991 Optional<Sone> storedSone = getSone(sone.getId());
992 if (storedSone.isPresent()) {
993 if (!soneRescueMode && !(sone.getTime() > storedSone.get().getTime())) {
994 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
997 /* find removed posts. */
998 Collection<Post> existingPosts = database.getPosts(sone.getId());
999 for (Post oldPost : existingPosts) {
1000 if (!sone.getPosts().contains(oldPost)) {
1001 eventBus.post(new PostRemovedEvent(oldPost));
1004 /* find new posts. */
1005 for (Post newPost : sone.getPosts()) {
1006 if (existingPosts.contains(newPost)) {
1009 if (newPost.getTime() < getSoneFollowingTime(sone)) {
1010 newPost.setKnown(true);
1011 } else if (!newPost.isKnown()) {
1012 eventBus.post(new NewPostFoundEvent(newPost));
1016 database.storePosts(sone, sone.getPosts());
1017 if (!soneRescueMode) {
1018 for (PostReply reply : storedSone.get().getReplies()) {
1019 if (!sone.getReplies().contains(reply)) {
1020 eventBus.post(new PostReplyRemovedEvent(reply));
1024 Set<PostReply> storedReplies = storedSone.get().getReplies();
1025 for (PostReply reply : sone.getReplies()) {
1026 if (storedReplies.contains(reply)) {
1029 if (reply.getTime() < getSoneFollowingTime(sone)) {
1030 reply.setKnown(true);
1031 } else if (!reply.isKnown()) {
1032 eventBus.post(new NewPostReplyFoundEvent(reply));
1035 database.storePostReplies(sone, sone.getReplies());
1036 synchronized (albums) {
1037 synchronized (images) {
1038 for (Album album : storedSone.get().getRootAlbum().getAlbums()) {
1039 albums.remove(album.getId());
1040 for (Image image : album.getImages()) {
1041 images.remove(image.getId());
1044 for (Album album : sone.getRootAlbum().getAlbums()) {
1045 albums.put(album.getId(), album);
1046 for (Image image : album.getImages()) {
1047 images.put(image.getId(), image);
1052 synchronized (sones) {
1053 sone.setOptions(storedSone.get().getOptions());
1054 sone.setKnown(storedSone.get().isKnown());
1055 sone.setStatus((sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
1056 if (sone.isLocal()) {
1057 soneInserters.get(storedSone.get()).setSone(sone);
1058 touchConfiguration();
1060 sones.put(sone.getId(), sone);
1066 * Deletes the given Sone. This will remove the Sone from the
1067 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1068 * remove the context from its identity.
1071 * The Sone to delete
1073 public void deleteSone(Sone sone) {
1074 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1075 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1078 synchronized (sones) {
1079 if (!getLocalSones().contains(sone)) {
1080 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1083 sones.remove(sone.getId());
1084 SoneInserter soneInserter = soneInserters.remove(sone);
1085 soneInserter.stop();
1087 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1088 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1090 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1091 } catch (ConfigurationException ce1) {
1092 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1097 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1098 * known} before, a {@link MarkSoneKnownEvent} is fired.
1101 * The Sone to mark as known
1103 public void markSoneKnown(Sone sone) {
1104 if (!sone.isKnown()) {
1105 sone.setKnown(true);
1106 synchronized (knownSones) {
1107 knownSones.add(sone.getId());
1109 eventBus.post(new MarkSoneKnownEvent(sone));
1110 touchConfiguration();
1115 * Loads and updates the given Sone from the configuration. If any error is
1116 * encountered, loading is aborted and the given Sone is not changed.
1119 * The Sone to load and update
1121 public void loadSone(Sone sone) {
1122 if (!sone.isLocal()) {
1123 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1126 logger.info(String.format("Loading local Sone: %s", sone));
1128 /* initialize options. */
1129 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1130 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1131 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1132 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1133 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1134 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1137 String sonePrefix = "Sone/" + sone.getId();
1138 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1139 if (soneTime == null) {
1140 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1143 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1146 Profile profile = new Profile(sone);
1147 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1148 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1149 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1150 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1151 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1152 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1154 /* load profile fields. */
1156 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1157 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1158 if (fieldName == null) {
1161 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1162 profile.addField(fieldName).setValue(fieldValue);
1166 Set<Post> posts = new HashSet<Post>();
1168 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1169 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1170 if (postId == null) {
1173 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1174 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1175 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1176 if ((postTime == 0) || (postText == null)) {
1177 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1180 PostBuilder postBuilder = postBuilder().withId(postId).from(sone.getId()).withTime(postTime).withText(postText);
1181 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1182 postBuilder.to(postRecipientId);
1184 posts.add(postBuilder.build());
1188 Set<PostReply> replies = new HashSet<PostReply>();
1190 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1191 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1192 if (replyId == null) {
1195 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1196 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1197 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1198 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1199 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1202 PostReplyBuilder postReplyBuilder = postReplyBuilder().withId(replyId).from(sone.getId()).to(postId).withTime(replyTime).withText(replyText);
1203 replies.add(postReplyBuilder.build());
1206 /* load post likes. */
1207 Set<String> likedPostIds = new HashSet<String>();
1209 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1210 if (likedPostId == null) {
1213 likedPostIds.add(likedPostId);
1216 /* load reply likes. */
1217 Set<String> likedReplyIds = new HashSet<String>();
1219 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1220 if (likedReplyId == null) {
1223 likedReplyIds.add(likedReplyId);
1227 Set<String> friends = new HashSet<String>();
1229 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1230 if (friendId == null) {
1233 friends.add(friendId);
1237 List<Album> topLevelAlbums = new ArrayList<Album>();
1238 int albumCounter = 0;
1240 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1241 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1242 if (albumId == null) {
1245 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1246 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1247 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1248 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1249 if ((albumTitle == null) || (albumDescription == null)) {
1250 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1253 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1254 if (albumParentId != null) {
1255 Album parentAlbum = getAlbum(albumParentId, false);
1256 if (parentAlbum == null) {
1257 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1260 parentAlbum.addAlbum(album);
1262 if (!topLevelAlbums.contains(album)) {
1263 topLevelAlbums.add(album);
1269 int imageCounter = 0;
1271 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1272 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1273 if (imageId == null) {
1276 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1277 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1278 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1279 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1280 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1281 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1282 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1283 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1284 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1287 Album album = getAlbum(albumId, false);
1288 if (album == null) {
1289 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1292 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1293 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1294 album.addImage(image);
1298 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1299 if (avatarId != null) {
1300 profile.setAvatar(getImage(avatarId, false));
1304 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1305 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1306 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1307 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1308 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1309 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1311 /* if we’re still here, Sone was loaded successfully. */
1312 synchronized (sone) {
1313 sone.setTime(soneTime);
1314 sone.setProfile(profile);
1315 sone.setPosts(posts);
1316 sone.setReplies(replies);
1317 sone.setLikePostIds(likedPostIds);
1318 sone.setLikeReplyIds(likedReplyIds);
1319 for (String friendId : friends) {
1320 followSone(sone, friendId);
1322 for (Album album : sone.getRootAlbum().getAlbums()) {
1323 sone.getRootAlbum().removeAlbum(album);
1325 for (Album album : topLevelAlbums) {
1326 sone.getRootAlbum().addAlbum(album);
1328 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1330 synchronized (knownSones) {
1331 for (String friend : friends) {
1332 knownSones.add(friend);
1335 database.storePosts(sone, posts);
1336 for (Post post : posts) {
1337 post.setKnown(true);
1339 database.storePostReplies(sone, replies);
1340 for (PostReply reply : replies) {
1341 reply.setKnown(true);
1344 logger.info(String.format("Sone loaded successfully: %s", sone));
1348 * Creates a new post.
1351 * The Sone that creates the post
1353 * The text of the post
1354 * @return The created post
1356 public Post createPost(Sone sone, String text) {
1357 return createPost(sone, System.currentTimeMillis(), text);
1361 * Creates a new post.
1364 * The Sone that creates the post
1366 * The time of the post
1368 * The text of the post
1369 * @return The created post
1371 public Post createPost(Sone sone, long time, String text) {
1372 return createPost(sone, null, time, text);
1376 * Creates a new post.
1379 * The Sone that creates the post
1381 * The recipient Sone, or {@code null} if this post does not have
1384 * The text of the post
1385 * @return The created post
1387 public Post createPost(Sone sone, Optional<Sone> recipient, String text) {
1388 return createPost(sone, recipient, System.currentTimeMillis(), text);
1392 * Creates a new post.
1395 * The Sone that creates the post
1397 * The recipient Sone, or {@code null} if this post does not have
1400 * The time of the post
1402 * The text of the post
1403 * @return The created post
1405 public Post createPost(Sone sone, Optional<Sone> recipient, long time, String text) {
1406 checkNotNull(text, "text must not be null");
1407 checkArgument(text.trim().length() > 0, "text must not be empty");
1408 if (!sone.isLocal()) {
1409 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1412 PostBuilder postBuilder = database.newPostBuilder();
1413 postBuilder.from(sone.getId()).randomId().withTime(time).withText(text.trim());
1414 if (recipient.isPresent()) {
1415 postBuilder.to(recipient.get().getId());
1417 final Post post = postBuilder.build();
1418 database.storePost(post);
1419 eventBus.post(new NewPostFoundEvent(post));
1421 touchConfiguration();
1422 localElementTicker.schedule(new Runnable() {
1429 markPostKnown(post);
1431 }, 10, TimeUnit.SECONDS);
1436 * Deletes the given post.
1439 * The post to delete
1441 public void deletePost(Post post) {
1442 if (!post.getSone().isLocal()) {
1443 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1446 database.removePost(post);
1447 eventBus.post(new PostRemovedEvent(post));
1448 markPostKnown(post);
1449 touchConfiguration();
1453 * Marks the given post as known, if it is currently not a known post
1454 * (according to {@link Post#isKnown()}).
1457 * The post to mark as known
1459 public void markPostKnown(Post post) {
1460 post.setKnown(true);
1461 eventBus.post(new MarkPostKnownEvent(post));
1462 touchConfiguration();
1463 for (PostReply reply : getReplies(post.getId())) {
1464 markReplyKnown(reply);
1469 * Bookmarks the given post.
1472 * The post to bookmark
1474 public void bookmark(Post post) {
1475 bookmarkPost(post.getId());
1479 * Bookmarks the post with the given ID.
1482 * The ID of the post to bookmark
1484 public void bookmarkPost(String id) {
1485 synchronized (bookmarkedPosts) {
1486 bookmarkedPosts.add(id);
1491 * Removes the given post from the bookmarks.
1494 * The post to unbookmark
1496 public void unbookmark(Post post) {
1497 unbookmarkPost(post.getId());
1501 * Removes the post with the given ID from the bookmarks.
1504 * The ID of the post to unbookmark
1506 public void unbookmarkPost(String id) {
1507 synchronized (bookmarkedPosts) {
1508 bookmarkedPosts.remove(id);
1513 * Creates a new reply.
1516 * The Sone that creates the reply
1518 * The post that this reply refers to
1520 * The text of the reply
1521 * @return The created reply
1523 public PostReply createReply(Sone sone, Post post, String text) {
1524 checkNotNull(text, "text must not be null");
1525 checkArgument(text.trim().length() > 0, "text must not be empty");
1526 if (!sone.isLocal()) {
1527 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1530 PostReplyBuilder postReplyBuilder = postReplyBuilder();
1531 postReplyBuilder.randomId().from(sone.getId()).to(post.getId()).currentTime().withText(text.trim());
1532 final PostReply reply = postReplyBuilder.build();
1533 database.storePostReply(reply);
1534 eventBus.post(new NewPostReplyFoundEvent(reply));
1535 sone.addReply(reply);
1536 touchConfiguration();
1537 localElementTicker.schedule(new Runnable() {
1544 markReplyKnown(reply);
1546 }, 10, TimeUnit.SECONDS);
1551 * Deletes the given reply.
1554 * The reply to delete
1556 public void deleteReply(PostReply reply) {
1557 Sone sone = reply.getSone();
1558 if (!sone.isLocal()) {
1559 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1562 database.removePostReply(reply);
1563 markReplyKnown(reply);
1564 sone.removeReply(reply);
1565 touchConfiguration();
1569 * Marks the given reply as known, if it is currently not a known reply
1570 * (according to {@link Reply#isKnown()}).
1573 * The reply to mark as known
1575 public void markReplyKnown(PostReply reply) {
1576 boolean previouslyKnown = reply.isKnown();
1577 reply.setKnown(true);
1578 eventBus.post(new MarkPostReplyKnownEvent(reply));
1579 if (!previouslyKnown) {
1580 touchConfiguration();
1585 * Creates a new top-level album for the given Sone.
1588 * The Sone to create the album for
1589 * @return The new album
1591 public Album createAlbum(Sone sone) {
1592 return createAlbum(sone, sone.getRootAlbum());
1596 * Creates a new album for the given Sone.
1599 * The Sone to create the album for
1601 * The parent of the album (may be {@code null} to create a
1603 * @return The new album
1605 public Album createAlbum(Sone sone, Album parent) {
1606 Album album = new Album();
1607 synchronized (albums) {
1608 albums.put(album.getId(), album);
1610 album.setSone(sone);
1611 parent.addAlbum(album);
1616 * Deletes the given album. The owner of the album has to be a local Sone,
1617 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1620 * The album to remove
1622 public void deleteAlbum(Album album) {
1623 checkNotNull(album, "album must not be null");
1624 checkArgument(album.getSone().isLocal(), "album’s Sone must be a local Sone");
1625 if (!album.isEmpty()) {
1628 album.getParent().removeAlbum(album);
1629 synchronized (albums) {
1630 albums.remove(album.getId());
1632 touchConfiguration();
1636 * Creates a new image.
1639 * The Sone creating the image
1641 * The album the image will be inserted into
1642 * @param temporaryImage
1643 * The temporary image to create the image from
1644 * @return The newly created image
1646 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1647 checkNotNull(sone, "sone must not be null");
1648 checkNotNull(album, "album must not be null");
1649 checkNotNull(temporaryImage, "temporaryImage must not be null");
1650 checkArgument(sone.isLocal(), "sone must be a local Sone");
1651 checkArgument(sone.equals(album.getSone()), "album must belong to the given Sone");
1652 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1653 album.addImage(image);
1654 synchronized (images) {
1655 images.put(image.getId(), image);
1657 imageInserter.insertImage(temporaryImage, image);
1662 * Deletes the given image. This method will also delete a matching
1665 * @see #deleteTemporaryImage(TemporaryImage)
1667 * The image to delete
1669 public void deleteImage(Image image) {
1670 checkNotNull(image, "image must not be null");
1671 checkArgument(image.getSone().isLocal(), "image must belong to a local Sone");
1672 deleteTemporaryImage(image.getId());
1673 image.getAlbum().removeImage(image);
1674 synchronized (images) {
1675 images.remove(image.getId());
1677 touchConfiguration();
1681 * Creates a new temporary image.
1684 * The MIME type of the temporary image
1686 * The encoded data of the image
1687 * @return The temporary image
1689 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1690 TemporaryImage temporaryImage = new TemporaryImage();
1691 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1692 synchronized (temporaryImages) {
1693 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1695 return temporaryImage;
1699 * Deletes the given temporary image.
1701 * @param temporaryImage
1702 * The temporary image to delete
1704 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1705 checkNotNull(temporaryImage, "temporaryImage must not be null");
1706 deleteTemporaryImage(temporaryImage.getId());
1710 * Deletes the temporary image with the given ID.
1713 * The ID of the temporary image to delete
1715 public void deleteTemporaryImage(String imageId) {
1716 checkNotNull(imageId, "imageId must not be null");
1717 synchronized (temporaryImages) {
1718 temporaryImages.remove(imageId);
1720 Image image = getImage(imageId, false);
1721 if (image != null) {
1722 imageInserter.cancelImageInsert(image);
1727 * Notifies the core that the configuration, either of the core or of a
1728 * single local Sone, has changed, and that the configuration should be
1731 public void touchConfiguration() {
1732 lastConfigurationUpdate = System.currentTimeMillis();
1743 public void serviceStart() {
1744 loadConfiguration();
1745 updateChecker.start();
1746 identityManager.start();
1747 webOfTrustUpdater.init();
1748 webOfTrustUpdater.start();
1756 public void serviceRun() {
1757 long lastSaved = System.currentTimeMillis();
1758 while (!shouldStop()) {
1760 long now = System.currentTimeMillis();
1761 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1762 for (Sone localSone : getLocalSones()) {
1763 saveSone(localSone);
1765 saveConfiguration();
1775 public void serviceStop() {
1776 localElementTicker.shutdownNow();
1777 synchronized (sones) {
1778 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1779 soneInserter.getValue().stop();
1780 saveSone(soneInserter.getKey());
1783 saveConfiguration();
1785 webOfTrustUpdater.stop();
1786 updateChecker.stop();
1787 soneDownloader.stop();
1788 soneDownloaders.shutdown();
1789 identityManager.stop();
1797 * Saves the given Sone. This will persist all local settings for the given
1798 * Sone, such as the friends list and similar, private options.
1803 private synchronized void saveSone(Sone sone) {
1804 if (!sone.isLocal()) {
1805 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1808 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1809 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1813 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1815 /* save Sone into configuration. */
1816 String sonePrefix = "Sone/" + sone.getId();
1817 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1818 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1821 Profile profile = sone.getProfile();
1822 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1823 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1824 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1825 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1826 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1827 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1828 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1830 /* save profile fields. */
1831 int fieldCounter = 0;
1832 for (Field profileField : profile.getFields()) {
1833 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1834 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1835 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1837 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1840 int postCounter = 0;
1841 for (Post post : sone.getPosts()) {
1842 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1843 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1844 configuration.getStringValue(postPrefix + "/Recipient").setValue(post.getRecipientId().orNull());
1845 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1846 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1848 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1851 int replyCounter = 0;
1852 for (PostReply reply : sone.getReplies()) {
1853 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1854 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1855 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPostId());
1856 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1857 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1859 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1861 /* save post likes. */
1862 int postLikeCounter = 0;
1863 for (String postId : sone.getLikedPostIds()) {
1864 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1866 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1868 /* save reply likes. */
1869 int replyLikeCounter = 0;
1870 for (String replyId : sone.getLikedReplyIds()) {
1871 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1873 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1876 int friendCounter = 0;
1877 for (String friendId : sone.getFriends()) {
1878 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1880 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1882 /* save albums. first, collect in a flat structure, top-level first. */
1883 List<Album> albums = FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).toList();
1885 int albumCounter = 0;
1886 for (Album album : albums) {
1887 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1888 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1889 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1890 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1891 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent().equals(sone.getRootAlbum()) ? null : album.getParent().getId());
1892 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1894 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1897 int imageCounter = 0;
1898 for (Album album : albums) {
1899 for (Image image : album.getImages()) {
1900 if (!image.isInserted()) {
1903 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1904 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
1905 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
1906 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
1907 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
1908 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
1909 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
1910 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
1911 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
1914 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
1917 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
1918 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
1919 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
1920 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
1921 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
1922 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
1924 configuration.save();
1926 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
1928 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
1929 } catch (ConfigurationException ce1) {
1930 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
1935 * Saves the current options.
1937 private void saveConfiguration() {
1938 synchronized (configuration) {
1939 if (storingConfiguration) {
1940 logger.log(Level.FINE, "Already storing configuration…");
1943 storingConfiguration = true;
1946 /* store the options first. */
1948 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
1949 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
1950 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
1951 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
1952 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
1953 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
1954 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
1955 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
1956 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
1957 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
1958 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
1959 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
1961 /* save known Sones. */
1962 int soneCounter = 0;
1963 synchronized (knownSones) {
1964 for (String knownSoneId : knownSones) {
1965 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
1967 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
1970 /* save Sone following times. */
1972 synchronized (soneFollowingTimes) {
1973 for (Entry<String, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
1974 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey());
1975 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
1978 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
1981 /* save known posts. */
1984 /* save bookmarked posts. */
1985 int bookmarkedPostCounter = 0;
1986 synchronized (bookmarkedPosts) {
1987 for (String bookmarkedPostId : bookmarkedPosts) {
1988 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
1991 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
1994 configuration.save();
1996 } catch (ConfigurationException ce1) {
1997 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
1998 } catch (DatabaseException de1) {
1999 logger.log(Level.SEVERE, "Could not save database!", de1);
2001 synchronized (configuration) {
2002 storingConfiguration = false;
2008 * Loads the configuration.
2010 private void loadConfiguration() {
2011 /* create options. */
2012 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2015 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2016 SoneInserter.setInsertionDelay(newValue);
2020 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2021 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
2022 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2023 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer> or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
2024 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2025 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
2026 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
2027 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2028 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2031 @SuppressWarnings("synthetic-access")
2032 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2033 fcpInterface.setActive(newValue);
2036 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2039 @SuppressWarnings("synthetic-access")
2040 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2041 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2046 loadConfigurationValue("InsertionDelay");
2047 loadConfigurationValue("PostsPerPage");
2048 loadConfigurationValue("ImagesPerPage");
2049 loadConfigurationValue("CharactersPerPost");
2050 loadConfigurationValue("PostCutOffLength");
2051 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2052 loadConfigurationValue("PositiveTrust");
2053 loadConfigurationValue("NegativeTrust");
2054 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2055 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2056 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2058 /* load known Sones. */
2059 int soneCounter = 0;
2061 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2062 if (knownSoneId == null) {
2065 synchronized (knownSones) {
2066 knownSones.add(knownSoneId);
2070 /* load Sone following times. */
2073 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2074 if (soneId == null) {
2077 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2078 synchronized (soneFollowingTimes) {
2079 soneFollowingTimes.put(soneId, time);
2084 /* load bookmarked posts. */
2085 int bookmarkedPostCounter = 0;
2087 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2088 if (bookmarkedPostId == null) {
2091 synchronized (bookmarkedPosts) {
2092 bookmarkedPosts.add(bookmarkedPostId);
2099 * Loads an {@link Integer} configuration value for the option with the
2100 * given name, logging validation failures.
2103 * The name of the option to load
2105 private void loadConfigurationValue(String optionName) {
2107 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2108 } catch (IllegalArgumentException iae1) {
2109 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2114 * Notifies the core that a new {@link OwnIdentity} was added.
2116 * @param ownIdentityAddedEvent
2120 public void ownIdentityAdded(OwnIdentityAddedEvent ownIdentityAddedEvent) {
2121 OwnIdentity ownIdentity = ownIdentityAddedEvent.ownIdentity();
2122 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2123 if (ownIdentity.hasContext("Sone")) {
2124 addLocalSone(ownIdentity);
2129 * Notifies the core that an {@link OwnIdentity} was removed.
2131 * @param ownIdentityRemovedEvent
2135 public void ownIdentityRemoved(OwnIdentityRemovedEvent ownIdentityRemovedEvent) {
2136 OwnIdentity ownIdentity = ownIdentityRemovedEvent.ownIdentity();
2137 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2138 trustedIdentities.removeAll(ownIdentity);
2142 * Notifies the core that a new {@link Identity} was added.
2144 * @param identityAddedEvent
2148 public void identityAdded(IdentityAddedEvent identityAddedEvent) {
2149 Identity identity = identityAddedEvent.identity();
2150 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2151 trustedIdentities.put(identityAddedEvent.ownIdentity(), identity);
2152 addRemoteSone(identity);
2156 * Notifies the core that an {@link Identity} was updated.
2158 * @param identityUpdatedEvent
2162 public void identityUpdated(IdentityUpdatedEvent identityUpdatedEvent) {
2163 final Identity identity = identityUpdatedEvent.identity();
2164 soneDownloaders.execute(new Runnable() {
2167 @SuppressWarnings("synthetic-access")
2169 Sone sone = getRemoteSone(identity.getId(), false);
2170 if (sone.isLocal()) {
2173 sone.setIdentity(identity);
2174 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2175 soneDownloader.addSone(sone);
2176 soneDownloader.fetchSone(sone);
2182 * Notifies the core that an {@link Identity} was removed.
2184 * @param identityRemovedEvent
2188 public void identityRemoved(IdentityRemovedEvent identityRemovedEvent) {
2189 OwnIdentity ownIdentity = identityRemovedEvent.ownIdentity();
2190 Identity identity = identityRemovedEvent.identity();
2191 trustedIdentities.remove(ownIdentity, identity);
2192 boolean foundIdentity = false;
2193 for (Entry<OwnIdentity, Collection<Identity>> trustedIdentity : trustedIdentities.asMap().entrySet()) {
2194 if (trustedIdentity.getKey().equals(ownIdentity)) {
2197 if (trustedIdentity.getValue().contains(identity)) {
2198 foundIdentity = true;
2201 if (foundIdentity) {
2202 /* some local identity still trusts this identity, don’t remove. */
2205 Optional<Sone> sone = getSone(identity.getId());
2206 if (!sone.isPresent()) {
2207 /* TODO - we don’t have the Sone anymore. should this happen? */
2210 database.removePosts(sone.get());
2211 for (Post post : sone.get().getPosts()) {
2212 eventBus.post(new PostRemovedEvent(post));
2214 database.removePostReplies(sone.get());
2215 for (PostReply reply : sone.get().getReplies()) {
2216 eventBus.post(new PostReplyRemovedEvent(reply));
2218 synchronized (sones) {
2219 sones.remove(identity.getId());
2221 eventBus.post(new SoneRemovedEvent(sone.get()));
2225 * Deletes the temporary image.
2227 * @param imageInsertFinishedEvent
2231 public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
2232 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", imageInsertFinishedEvent.image(), imageInsertFinishedEvent.resultingUri()));
2233 imageInsertFinishedEvent.image().setKey(imageInsertFinishedEvent.resultingUri().toString());
2234 deleteTemporaryImage(imageInsertFinishedEvent.image().getId());
2235 touchConfiguration();