2 * Sone - Core.java - Copyright © 2010–2012 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 java.net.MalformedURLException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.core.Options.DefaultOption;
36 import net.pterodactylus.sone.core.Options.Option;
37 import net.pterodactylus.sone.core.Options.OptionWatcher;
38 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
40 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
41 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
42 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
43 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
44 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
45 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
46 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
47 import net.pterodactylus.sone.core.event.PostRemovedEvent;
48 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
49 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
50 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
51 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
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.core.event.UpdateFoundEvent;
56 import net.pterodactylus.sone.data.Album;
57 import net.pterodactylus.sone.data.Client;
58 import net.pterodactylus.sone.data.Image;
59 import net.pterodactylus.sone.data.Post;
60 import net.pterodactylus.sone.data.PostReply;
61 import net.pterodactylus.sone.data.Profile;
62 import net.pterodactylus.sone.data.Profile.Field;
63 import net.pterodactylus.sone.data.Reply;
64 import net.pterodactylus.sone.data.Sone;
65 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
66 import net.pterodactylus.sone.data.Sone.SoneStatus;
67 import net.pterodactylus.sone.data.TemporaryImage;
68 import net.pterodactylus.sone.data.impl.PostImpl;
69 import net.pterodactylus.sone.fcp.FcpInterface;
70 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
71 import net.pterodactylus.sone.freenet.wot.Identity;
72 import net.pterodactylus.sone.freenet.wot.IdentityListener;
73 import net.pterodactylus.sone.freenet.wot.IdentityManager;
74 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
75 import net.pterodactylus.sone.main.SonePlugin;
76 import net.pterodactylus.util.config.Configuration;
77 import net.pterodactylus.util.config.ConfigurationException;
78 import net.pterodactylus.util.logging.Logging;
79 import net.pterodactylus.util.number.Numbers;
80 import net.pterodactylus.util.service.AbstractService;
81 import net.pterodactylus.util.thread.NamedThreadFactory;
82 import net.pterodactylus.util.thread.Ticker;
83 import net.pterodactylus.util.validation.EqualityValidator;
84 import net.pterodactylus.util.validation.IntegerRangeValidator;
85 import net.pterodactylus.util.validation.OrValidator;
86 import net.pterodactylus.util.validation.Validation;
87 import net.pterodactylus.util.version.Version;
89 import com.google.common.base.Predicate;
90 import com.google.common.collect.Collections2;
91 import com.google.common.eventbus.EventBus;
92 import com.google.inject.Inject;
94 import freenet.keys.FreenetURI;
99 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
101 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
104 private static final Logger logger = Logging.getLogger(Core.class);
106 /** The start time. */
107 private final long startupTime = System.currentTimeMillis();
110 private final Options options = new Options();
112 /** The preferences. */
113 private final Preferences preferences = new Preferences(options);
115 /** The core listener manager. */
116 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
118 /** The event bus. */
119 private final EventBus eventBus;
121 /** The configuration. */
122 private Configuration configuration;
124 /** Whether we’re currently saving the configuration. */
125 private boolean storingConfiguration = false;
127 /** The identity manager. */
128 private final IdentityManager identityManager;
130 /** Interface to freenet. */
131 private final FreenetInterface freenetInterface;
133 /** The Sone downloader. */
134 private final SoneDownloader soneDownloader;
136 /** The image inserter. */
137 private final ImageInserter imageInserter;
139 /** Sone downloader thread-pool. */
140 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10, new NamedThreadFactory("Sone Downloader %2$d"));
142 /** The update checker. */
143 private final UpdateChecker updateChecker;
145 /** The trust updater. */
146 private final WebOfTrustUpdater webOfTrustUpdater;
148 /** The FCP interface. */
149 private volatile FcpInterface fcpInterface;
151 /** The times Sones were followed. */
152 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
154 /** Locked local Sones. */
155 /* synchronize on itself. */
156 private final Set<Sone> lockedSones = new HashSet<Sone>();
158 /** Sone inserters. */
159 /* synchronize access on this on sones. */
160 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
162 /** Sone rescuers. */
163 /* synchronize access on this on sones. */
164 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
167 /* synchronize access on this on itself. */
168 private final Map<String, Sone> sones = new HashMap<String, Sone>();
170 /** All known Sones. */
171 private final Set<String> knownSones = new HashSet<String>();
174 private final Map<String, Post> posts = new HashMap<String, Post>();
176 /** All known posts. */
177 private final Set<String> knownPosts = new HashSet<String>();
180 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
182 /** All known replies. */
183 private final Set<String> knownReplies = new HashSet<String>();
185 /** All bookmarked posts. */
186 /* synchronize access on itself. */
187 private final Set<String> bookmarkedPosts = new HashSet<String>();
189 /** Trusted identities, sorted by own identities. */
190 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
192 /** All known albums. */
193 private final Map<String, Album> albums = new HashMap<String, Album>();
195 /** All known images. */
196 private final Map<String, Image> images = new HashMap<String, Image>();
198 /** All temporary images. */
199 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
201 /** Ticker for threads that mark own elements as known. */
202 private final Ticker localElementTicker = new Ticker();
204 /** The time the configuration was last touched. */
205 private volatile long lastConfigurationUpdate;
208 * Creates a new core.
210 * @param configuration
211 * The configuration of the core
212 * @param freenetInterface
213 * The freenet interface
214 * @param identityManager
215 * The identity manager
216 * @param webOfTrustUpdater
217 * The WebOfTrust updater
222 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager, WebOfTrustUpdater webOfTrustUpdater, EventBus eventBus) {
224 this.configuration = configuration;
225 this.freenetInterface = freenetInterface;
226 this.identityManager = identityManager;
227 this.soneDownloader = new SoneDownloader(this, freenetInterface);
228 this.imageInserter = new ImageInserter(this, freenetInterface);
229 this.updateChecker = new UpdateChecker(freenetInterface);
230 this.webOfTrustUpdater = webOfTrustUpdater;
231 this.eventBus = eventBus;
235 // LISTENER MANAGEMENT
239 * Adds a new core listener.
241 * @param coreListener
242 * The listener to add
244 public void addCoreListener(CoreListener coreListener) {
245 coreListenerManager.addListener(coreListener);
249 * Removes a core listener.
251 * @param coreListener
252 * The listener to remove
254 public void removeCoreListener(CoreListener coreListener) {
255 coreListenerManager.removeListener(coreListener);
263 * Returns the time Sone was started.
265 * @return The startup time (in milliseconds since Jan 1, 1970 UTC)
267 public long getStartupTime() {
272 * Sets the configuration to use. This will automatically save the current
273 * configuration to the given configuration.
275 * @param configuration
276 * The new configuration to use
278 public void setConfiguration(Configuration configuration) {
279 this.configuration = configuration;
280 touchConfiguration();
284 * Returns the options used by the core.
286 * @return The options of the core
288 public Preferences getPreferences() {
293 * Returns the identity manager used by the core.
295 * @return The identity manager
297 public IdentityManager getIdentityManager() {
298 return identityManager;
302 * Returns the update checker.
304 * @return The update checker
306 public UpdateChecker getUpdateChecker() {
307 return updateChecker;
311 * Sets the FCP interface to use.
313 * @param fcpInterface
314 * The FCP interface to use
316 public void setFcpInterface(FcpInterface fcpInterface) {
317 this.fcpInterface = fcpInterface;
321 * Returns the Sone rescuer for the given local Sone.
324 * The local Sone to get the rescuer for
325 * @return The Sone rescuer for the given Sone
327 public SoneRescuer getSoneRescuer(Sone sone) {
328 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
329 synchronized (sones) {
330 SoneRescuer soneRescuer = soneRescuers.get(sone);
331 if (soneRescuer == null) {
332 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
333 soneRescuers.put(sone, soneRescuer);
341 * Returns whether the given Sone is currently locked.
345 * @return {@code true} if the Sone is locked, {@code false} if it is not
347 public boolean isLocked(Sone sone) {
348 synchronized (lockedSones) {
349 return lockedSones.contains(sone);
354 * Returns all Sones, remote and local.
358 public Set<Sone> getSones() {
359 return new HashSet<Sone>(sones.values());
363 * Returns the Sone with the given ID, regardless whether it’s local or
367 * The ID of the Sone to get
368 * @return The Sone with the given ID, or {@code null} if there is no such
371 public Sone getSone(String id) {
372 return getSone(id, true);
376 * Returns the Sone with the given ID, regardless whether it’s local or
380 * The ID of the Sone to get
382 * {@code true} to create a new Sone if none exists,
383 * {@code false} to return {@code null} if a Sone with the given
385 * @return The Sone with the given ID, or {@code null} if there is no such
389 public Sone getSone(String id, boolean create) {
390 synchronized (sones) {
391 if (!sones.containsKey(id)) {
392 Sone sone = new Sone(id, false);
395 return sones.get(id);
400 * Checks whether the core knows a Sone with the given ID.
404 * @return {@code true} if there is a Sone with the given ID, {@code false}
407 public boolean hasSone(String id) {
408 synchronized (sones) {
409 return sones.containsKey(id);
414 * Returns all local Sones.
416 * @return All local Sones
418 public Collection<Sone> getLocalSones() {
419 synchronized (sones) {
420 return Collections2.filter(sones.values(), new Predicate<Sone>() {
423 public boolean apply(Sone sone) {
424 return sone.isLocal();
431 * Returns the local Sone with the given ID, optionally creating a new Sone.
436 * {@code true} to create a new Sone if none exists,
437 * {@code false} to return null if none exists
438 * @return The Sone with the given ID, or {@code null}
440 public Sone getLocalSone(String id, boolean create) {
441 synchronized (sones) {
442 Sone sone = sones.get(id);
443 if ((sone == null) && create) {
444 sone = new Sone(id, true);
447 if ((sone != null) && !sone.isLocal()) {
448 sone = new Sone(id, true);
456 * Returns all remote Sones.
458 * @return All remote Sones
460 public Collection<Sone> getRemoteSones() {
461 synchronized (sones) {
462 return Collections2.filter(sones.values(), new Predicate<Sone>() {
465 public boolean apply(Sone sone) {
466 return !sone.isLocal();
473 * Returns the remote Sone with the given ID.
476 * The ID of the remote Sone to get
478 * {@code true} to always create a Sone, {@code false} to return
479 * {@code null} if no Sone with the given ID exists
480 * @return The Sone with the given ID
482 public Sone getRemoteSone(String id, boolean create) {
483 synchronized (sones) {
484 Sone sone = sones.get(id);
485 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
486 sone = new Sone(id, false);
494 * Returns whether the given Sone has been modified.
497 * The Sone to check for modifications
498 * @return {@code true} if a modification has been detected in the Sone,
499 * {@code false} otherwise
501 public boolean isModifiedSone(Sone sone) {
502 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
506 * Returns the time when the given was first followed by any local Sone.
509 * The Sone to get the time for
510 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
511 * been followed, or {@link Long#MAX_VALUE}
513 public long getSoneFollowingTime(Sone sone) {
514 synchronized (soneFollowingTimes) {
515 if (soneFollowingTimes.containsKey(sone)) {
516 return soneFollowingTimes.get(sone);
518 return Long.MAX_VALUE;
523 * Returns whether the target Sone is trusted by the origin Sone.
529 * @return {@code true} if the target Sone is trusted by the origin Sone
531 public boolean isSoneTrusted(Sone origin, Sone target) {
532 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
533 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
537 * Returns the post with the given ID.
540 * The ID of the post to get
541 * @return The post with the given ID, or a new post with the given ID
543 public Post getPost(String postId) {
544 return getPost(postId, true);
548 * Returns the post with the given ID, optionally creating a new post.
551 * The ID of the post to get
553 * {@code true} it create a new post if no post with the given ID
554 * exists, {@code false} to return {@code null}
555 * @return The post, or {@code null} if there is no such post
558 public Post getPost(String postId, boolean create) {
559 synchronized (posts) {
560 Post post = posts.get(postId);
561 if ((post == null) && create) {
562 post = new PostImpl(postId);
563 posts.put(postId, post);
570 * Returns all posts that have the given Sone as recipient.
572 * @see Post#getRecipient()
574 * The recipient of the posts
575 * @return All posts that have the given Sone as recipient
577 public Set<Post> getDirectedPosts(Sone recipient) {
578 Validation.begin().isNotNull("Recipient", recipient).check();
579 Set<Post> directedPosts = new HashSet<Post>();
580 synchronized (posts) {
581 for (Post post : posts.values()) {
582 if (recipient.equals(post.getRecipient())) {
583 directedPosts.add(post);
587 return directedPosts;
591 * Returns the reply with the given ID. If there is no reply with the given
592 * ID yet, a new one is created, unless {@code create} is false in which
593 * case {@code null} is returned.
596 * The ID of the reply to get
598 * {@code true} to always return a {@link Reply}, {@code false}
599 * to return {@code null} if no reply can be found
600 * @return The reply, or {@code null} if there is no such reply
602 public PostReply getPostReply(String replyId, boolean create) {
603 synchronized (replies) {
604 PostReply reply = replies.get(replyId);
605 if (create && (reply == null)) {
606 reply = new PostReply(replyId);
607 replies.put(replyId, reply);
614 * Returns all replies for the given post, order ascending by time.
617 * The post to get all replies for
618 * @return All replies for the given post
620 public List<PostReply> getReplies(Post post) {
621 Set<Sone> sones = getSones();
622 List<PostReply> replies = new ArrayList<PostReply>();
623 for (Sone sone : sones) {
624 for (PostReply reply : sone.getReplies()) {
625 if (reply.getPost().equals(post)) {
630 Collections.sort(replies, Reply.TIME_COMPARATOR);
635 * Returns all Sones that have liked the given post.
638 * The post to get the liking Sones for
639 * @return The Sones that like the given post
641 public Set<Sone> getLikes(Post post) {
642 Set<Sone> sones = new HashSet<Sone>();
643 for (Sone sone : getSones()) {
644 if (sone.getLikedPostIds().contains(post.getId())) {
652 * Returns all Sones that have liked the given reply.
655 * The reply to get the liking Sones for
656 * @return The Sones that like the given reply
658 public Set<Sone> getLikes(PostReply reply) {
659 Set<Sone> sones = new HashSet<Sone>();
660 for (Sone sone : getSones()) {
661 if (sone.getLikedReplyIds().contains(reply.getId())) {
669 * Returns whether the given post is bookmarked.
673 * @return {@code true} if the given post is bookmarked, {@code false}
676 public boolean isBookmarked(Post post) {
677 return isPostBookmarked(post.getId());
681 * Returns whether the post with the given ID is bookmarked.
684 * The ID of the post to check
685 * @return {@code true} if the post with the given ID is bookmarked,
686 * {@code false} otherwise
688 public boolean isPostBookmarked(String id) {
689 synchronized (bookmarkedPosts) {
690 return bookmarkedPosts.contains(id);
695 * Returns all currently known bookmarked posts.
697 * @return All bookmarked posts
699 public Set<Post> getBookmarkedPosts() {
700 Set<Post> posts = new HashSet<Post>();
701 synchronized (bookmarkedPosts) {
702 for (String bookmarkedPostId : bookmarkedPosts) {
703 Post post = getPost(bookmarkedPostId, false);
713 * Returns the album with the given ID, creating a new album if no album
714 * with the given ID can be found.
717 * The ID of the album
718 * @return The album with the given ID
720 public Album getAlbum(String albumId) {
721 return getAlbum(albumId, true);
725 * Returns the album with the given ID, optionally creating a new album if
726 * an album with the given ID can not be found.
729 * The ID of the album
731 * {@code true} to create a new album if none exists for the
733 * @return The album with the given ID, or {@code null} if no album with the
734 * given ID exists and {@code create} is {@code false}
736 public Album getAlbum(String albumId, boolean create) {
737 synchronized (albums) {
738 Album album = albums.get(albumId);
739 if (create && (album == null)) {
740 album = new Album(albumId);
741 albums.put(albumId, album);
748 * Returns the image with the given ID, creating it if necessary.
751 * The ID of the image
752 * @return The image with the given ID
754 public Image getImage(String imageId) {
755 return getImage(imageId, true);
759 * Returns the image with the given ID, optionally creating it if it does
763 * The ID of the image
765 * {@code true} to create an image if none exists with the given
767 * @return The image with the given ID, or {@code null} if none exists and
770 public Image getImage(String imageId, boolean create) {
771 synchronized (images) {
772 Image image = images.get(imageId);
773 if (create && (image == null)) {
774 image = new Image(imageId);
775 images.put(imageId, image);
782 * Returns the temporary image with the given ID.
785 * The ID of the temporary image
786 * @return The temporary image, or {@code null} if there is no temporary
787 * image with the given ID
789 public TemporaryImage getTemporaryImage(String imageId) {
790 synchronized (temporaryImages) {
791 return temporaryImages.get(imageId);
800 * Locks the given Sone. A locked Sone will not be inserted by
801 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
807 public void lockSone(Sone sone) {
808 synchronized (lockedSones) {
809 if (lockedSones.add(sone)) {
810 eventBus.post(new SoneLockedEvent(sone));
816 * Unlocks the given Sone.
818 * @see #lockSone(Sone)
822 public void unlockSone(Sone sone) {
823 synchronized (lockedSones) {
824 if (lockedSones.remove(sone)) {
825 eventBus.post(new SoneUnlockedEvent(sone));
831 * Adds a local Sone from the given own identity.
834 * The own identity to create a Sone from
835 * @return The added (or already existing) Sone
837 public Sone addLocalSone(OwnIdentity ownIdentity) {
838 if (ownIdentity == null) {
839 logger.log(Level.WARNING, "Given OwnIdentity is null!");
842 synchronized (sones) {
845 sone = getLocalSone(ownIdentity.getId(), true).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
846 } catch (MalformedURLException mue1) {
847 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
850 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
851 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
853 /* TODO - load posts ’n stuff */
854 sones.put(ownIdentity.getId(), sone);
855 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
856 soneInserter.addSoneInsertListener(this);
857 soneInserters.put(sone, soneInserter);
858 sone.setStatus(SoneStatus.idle);
860 soneInserter.start();
866 * Creates a new Sone for the given own identity.
869 * The own identity to create a Sone for
870 * @return The created Sone
872 public Sone createSone(OwnIdentity ownIdentity) {
873 if (!webOfTrustUpdater.addContextWait(ownIdentity, "Sone")) {
874 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity));
877 Sone sone = addLocalSone(ownIdentity);
878 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
879 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
880 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
881 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
882 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
883 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
885 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
886 touchConfiguration();
891 * Adds the Sone of the given identity.
894 * The identity whose Sone to add
895 * @return The added or already existing Sone
897 public Sone addRemoteSone(Identity identity) {
898 if (identity == null) {
899 logger.log(Level.WARNING, "Given Identity is null!");
902 synchronized (sones) {
903 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
904 boolean newSone = sone.getRequestUri() == null;
905 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
906 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
908 synchronized (knownSones) {
909 newSone = !knownSones.contains(sone.getId());
911 sone.setKnown(!newSone);
913 eventBus.post(new NewSoneFoundEvent(sone));
914 for (Sone localSone : getLocalSones()) {
915 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
916 followSone(localSone, sone);
921 soneDownloader.addSone(sone);
922 soneDownloaders.execute(new Runnable() {
925 @SuppressWarnings("synthetic-access")
927 soneDownloader.fetchSone(sone, sone.getRequestUri());
936 * Lets the given local Sone follow the Sone with the given ID.
939 * The local Sone that should follow another Sone
941 * The ID of the Sone to follow
943 public void followSone(Sone sone, String soneId) {
944 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
945 Sone followedSone = getSone(soneId, true);
946 if (followedSone == null) {
947 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
950 followSone(sone, getSone(soneId));
954 * Lets the given local Sone follow the other given Sone. If the given Sone
955 * was not followed by any local Sone before, this will mark all elements of
956 * the followed Sone as read that have been created before the current
960 * The local Sone that should follow the other Sone
961 * @param followedSone
962 * The Sone that should be followed
964 public void followSone(Sone sone, Sone followedSone) {
965 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
966 sone.addFriend(followedSone.getId());
967 synchronized (soneFollowingTimes) {
968 if (!soneFollowingTimes.containsKey(followedSone)) {
969 long now = System.currentTimeMillis();
970 soneFollowingTimes.put(followedSone, now);
971 for (Post post : followedSone.getPosts()) {
972 if (post.getTime() < now) {
976 for (PostReply reply : followedSone.getReplies()) {
977 if (reply.getTime() < now) {
978 markReplyKnown(reply);
983 touchConfiguration();
987 * Lets the given local Sone unfollow the Sone with the given ID.
990 * The local Sone that should unfollow another Sone
992 * The ID of the Sone being unfollowed
994 public void unfollowSone(Sone sone, String soneId) {
995 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
996 unfollowSone(sone, getSone(soneId, false));
1000 * Lets the given local Sone unfollow the other given Sone. If the given
1001 * local Sone is the last local Sone that followed the given Sone, its
1002 * following time will be removed.
1005 * The local Sone that should unfollow another Sone
1006 * @param unfollowedSone
1007 * The Sone being unfollowed
1009 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1010 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1011 sone.removeFriend(unfollowedSone.getId());
1012 boolean unfollowedSoneStillFollowed = false;
1013 for (Sone localSone : getLocalSones()) {
1014 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1016 if (!unfollowedSoneStillFollowed) {
1017 synchronized (soneFollowingTimes) {
1018 soneFollowingTimes.remove(unfollowedSone);
1021 touchConfiguration();
1025 * Sets the trust value of the given origin Sone for the target Sone.
1032 * The trust value (from {@code -100} to {@code 100})
1034 public void setTrust(Sone origin, Sone target, int trustValue) {
1035 Validation.begin().isNotNull("Trust Origin", origin).check().isInstanceOf("Trust Origin", origin.getIdentity(), OwnIdentity.class).isNotNull("Trust Target", target).isLessOrEqual("Trust Value", trustValue, 100).isGreaterOrEqual("Trust Value", trustValue, -100).check();
1036 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), trustValue, preferences.getTrustComment());
1040 * Removes any trust assignment for the given target Sone.
1047 public void removeTrust(Sone origin, Sone target) {
1048 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1049 webOfTrustUpdater.setTrust((OwnIdentity) origin.getIdentity(), target.getIdentity(), null, null);
1053 * Assigns the configured positive trust value for the given target.
1060 public void trustSone(Sone origin, Sone target) {
1061 setTrust(origin, target, preferences.getPositiveTrust());
1065 * Assigns the configured negative trust value for the given target.
1072 public void distrustSone(Sone origin, Sone target) {
1073 setTrust(origin, target, preferences.getNegativeTrust());
1077 * Removes the trust assignment for the given target.
1084 public void untrustSone(Sone origin, Sone target) {
1085 removeTrust(origin, target);
1089 * Updates the stored Sone with the given Sone.
1094 public void updateSone(Sone sone) {
1095 updateSone(sone, false);
1099 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1100 * {@code true}, an older Sone than the current Sone can be given to restore
1104 * The Sone to update
1105 * @param soneRescueMode
1106 * {@code true} if the stored Sone should be updated regardless
1107 * of the age of the given Sone
1109 public void updateSone(Sone sone, boolean soneRescueMode) {
1110 if (hasSone(sone.getId())) {
1111 Sone storedSone = getSone(sone.getId());
1112 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1113 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1116 synchronized (posts) {
1117 if (!soneRescueMode) {
1118 for (Post post : storedSone.getPosts()) {
1119 posts.remove(post.getId());
1120 if (!sone.getPosts().contains(post)) {
1121 eventBus.post(new PostRemovedEvent(post));
1125 List<Post> storedPosts = storedSone.getPosts();
1126 synchronized (knownPosts) {
1127 for (Post post : sone.getPosts()) {
1128 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1129 if (!storedPosts.contains(post)) {
1130 if (post.getTime() < getSoneFollowingTime(sone)) {
1131 knownPosts.add(post.getId());
1132 post.setKnown(true);
1133 } else if (!knownPosts.contains(post.getId())) {
1134 eventBus.post(new NewPostFoundEvent(post));
1137 posts.put(post.getId(), post);
1141 synchronized (replies) {
1142 if (!soneRescueMode) {
1143 for (PostReply reply : storedSone.getReplies()) {
1144 replies.remove(reply.getId());
1145 if (!sone.getReplies().contains(reply)) {
1146 eventBus.post(new PostReplyRemovedEvent(reply));
1150 Set<PostReply> storedReplies = storedSone.getReplies();
1151 synchronized (knownReplies) {
1152 for (PostReply reply : sone.getReplies()) {
1153 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1154 if (!storedReplies.contains(reply)) {
1155 if (reply.getTime() < getSoneFollowingTime(sone)) {
1156 knownReplies.add(reply.getId());
1157 reply.setKnown(true);
1158 } else if (!knownReplies.contains(reply.getId())) {
1159 eventBus.post(new NewPostReplyFoundEvent(reply));
1162 replies.put(reply.getId(), reply);
1166 synchronized (albums) {
1167 synchronized (images) {
1168 for (Album album : storedSone.getAlbums()) {
1169 albums.remove(album.getId());
1170 for (Image image : album.getImages()) {
1171 images.remove(image.getId());
1174 for (Album album : sone.getAlbums()) {
1175 albums.put(album.getId(), album);
1176 for (Image image : album.getImages()) {
1177 images.put(image.getId(), image);
1182 synchronized (storedSone) {
1183 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1184 storedSone.setTime(sone.getTime());
1186 storedSone.setClient(sone.getClient());
1187 storedSone.setProfile(sone.getProfile());
1188 if (soneRescueMode) {
1189 for (Post post : sone.getPosts()) {
1190 storedSone.addPost(post);
1192 for (PostReply reply : sone.getReplies()) {
1193 storedSone.addReply(reply);
1195 for (String likedPostId : sone.getLikedPostIds()) {
1196 storedSone.addLikedPostId(likedPostId);
1198 for (String likedReplyId : sone.getLikedReplyIds()) {
1199 storedSone.addLikedReplyId(likedReplyId);
1201 for (Album album : sone.getAlbums()) {
1202 storedSone.addAlbum(album);
1205 storedSone.setPosts(sone.getPosts());
1206 storedSone.setReplies(sone.getReplies());
1207 storedSone.setLikePostIds(sone.getLikedPostIds());
1208 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1209 storedSone.setAlbums(sone.getAlbums());
1211 storedSone.setLatestEdition(sone.getLatestEdition());
1217 * Deletes the given Sone. This will remove the Sone from the
1218 * {@link #getLocalSones() local Sones}, stop its {@link SoneInserter} and
1219 * remove the context from its identity.
1222 * The Sone to delete
1224 public void deleteSone(Sone sone) {
1225 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1226 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1229 synchronized (sones) {
1230 if (!getLocalSones().contains(sone)) {
1231 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1234 sones.remove(sone.getId());
1235 SoneInserter soneInserter = soneInserters.remove(sone);
1236 soneInserter.removeSoneInsertListener(this);
1237 soneInserter.stop();
1239 webOfTrustUpdater.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
1240 webOfTrustUpdater.removeProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition");
1242 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1243 } catch (ConfigurationException ce1) {
1244 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1249 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1250 * known} before, a {@link MarkSoneKnownEvent} is fired.
1253 * The Sone to mark as known
1255 public void markSoneKnown(Sone sone) {
1256 if (!sone.isKnown()) {
1257 sone.setKnown(true);
1258 synchronized (knownSones) {
1259 knownSones.add(sone.getId());
1261 eventBus.post(new MarkSoneKnownEvent(sone));
1262 touchConfiguration();
1267 * Loads and updates the given Sone from the configuration. If any error is
1268 * encountered, loading is aborted and the given Sone is not changed.
1271 * The Sone to load and update
1273 public void loadSone(Sone sone) {
1274 if (!sone.isLocal()) {
1275 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1279 /* initialize options. */
1280 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1281 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1282 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1283 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1284 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1285 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1288 String sonePrefix = "Sone/" + sone.getId();
1289 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1290 if (soneTime == null) {
1291 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1294 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1297 Profile profile = new Profile(sone);
1298 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1299 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1300 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1301 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1302 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1303 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1305 /* load profile fields. */
1307 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1308 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1309 if (fieldName == null) {
1312 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1313 profile.addField(fieldName).setValue(fieldValue);
1317 Set<Post> posts = new HashSet<Post>();
1319 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1320 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1321 if (postId == null) {
1324 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1325 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1326 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1327 if ((postTime == 0) || (postText == null)) {
1328 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1331 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1332 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1333 post.setRecipient(getSone(postRecipientId));
1339 Set<PostReply> replies = new HashSet<PostReply>();
1341 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1342 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1343 if (replyId == null) {
1346 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1347 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1348 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1349 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1350 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1353 replies.add(getPostReply(replyId, true).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1356 /* load post likes. */
1357 Set<String> likedPostIds = new HashSet<String>();
1359 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1360 if (likedPostId == null) {
1363 likedPostIds.add(likedPostId);
1366 /* load reply likes. */
1367 Set<String> likedReplyIds = new HashSet<String>();
1369 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1370 if (likedReplyId == null) {
1373 likedReplyIds.add(likedReplyId);
1377 Set<String> friends = new HashSet<String>();
1379 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1380 if (friendId == null) {
1383 friends.add(friendId);
1387 List<Album> topLevelAlbums = new ArrayList<Album>();
1388 int albumCounter = 0;
1390 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1391 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1392 if (albumId == null) {
1395 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1396 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1397 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1398 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1399 if ((albumTitle == null) || (albumDescription == null)) {
1400 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1403 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1404 if (albumParentId != null) {
1405 Album parentAlbum = getAlbum(albumParentId, false);
1406 if (parentAlbum == null) {
1407 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1410 parentAlbum.addAlbum(album);
1412 if (!topLevelAlbums.contains(album)) {
1413 topLevelAlbums.add(album);
1419 int imageCounter = 0;
1421 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1422 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1423 if (imageId == null) {
1426 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1427 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1428 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1429 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1430 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1431 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1432 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1433 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1434 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1437 Album album = getAlbum(albumId, false);
1438 if (album == null) {
1439 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1442 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1443 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1444 album.addImage(image);
1448 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1449 if (avatarId != null) {
1450 profile.setAvatar(getImage(avatarId, false));
1454 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1455 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1456 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1457 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1458 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1459 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1461 /* if we’re still here, Sone was loaded successfully. */
1462 synchronized (sone) {
1463 sone.setTime(soneTime);
1464 sone.setProfile(profile);
1465 sone.setPosts(posts);
1466 sone.setReplies(replies);
1467 sone.setLikePostIds(likedPostIds);
1468 sone.setLikeReplyIds(likedReplyIds);
1469 for (String friendId : friends) {
1470 followSone(sone, friendId);
1472 sone.setAlbums(topLevelAlbums);
1473 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1475 synchronized (knownSones) {
1476 for (String friend : friends) {
1477 knownSones.add(friend);
1480 synchronized (knownPosts) {
1481 for (Post post : posts) {
1482 knownPosts.add(post.getId());
1485 synchronized (knownReplies) {
1486 for (PostReply reply : replies) {
1487 knownReplies.add(reply.getId());
1493 * Creates a new post.
1496 * The Sone that creates the post
1498 * The text of the post
1499 * @return The created post
1501 public Post createPost(Sone sone, String text) {
1502 return createPost(sone, System.currentTimeMillis(), text);
1506 * Creates a new post.
1509 * The Sone that creates the post
1511 * The time of the post
1513 * The text of the post
1514 * @return The created post
1516 public Post createPost(Sone sone, long time, String text) {
1517 return createPost(sone, null, time, text);
1521 * Creates a new post.
1524 * The Sone that creates the post
1526 * The recipient Sone, or {@code null} if this post does not have
1529 * The text of the post
1530 * @return The created post
1532 public Post createPost(Sone sone, Sone recipient, String text) {
1533 return createPost(sone, recipient, System.currentTimeMillis(), text);
1537 * Creates a new post.
1540 * The Sone that creates the post
1542 * The recipient Sone, or {@code null} if this post does not have
1545 * The time of the post
1547 * The text of the post
1548 * @return The created post
1550 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1551 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.length(), 0).check();
1552 if (!sone.isLocal()) {
1553 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1556 final Post post = new PostImpl(sone, time, text);
1557 if (recipient != null) {
1558 post.setRecipient(recipient);
1560 synchronized (posts) {
1561 posts.put(post.getId(), post);
1563 eventBus.post(new NewPostFoundEvent(post));
1565 touchConfiguration();
1566 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1573 markPostKnown(post);
1575 }, "Mark " + post + " read.");
1580 * Deletes the given post.
1583 * The post to delete
1585 public void deletePost(Post post) {
1586 if (!post.getSone().isLocal()) {
1587 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1590 post.getSone().removePost(post);
1591 synchronized (posts) {
1592 posts.remove(post.getId());
1594 eventBus.post(new PostRemovedEvent(post));
1595 markPostKnown(post);
1596 touchConfiguration();
1600 * Marks the given post as known, if it is currently not a known post
1601 * (according to {@link Post#isKnown()}).
1604 * The post to mark as known
1606 public void markPostKnown(Post post) {
1607 post.setKnown(true);
1608 synchronized (knownPosts) {
1609 eventBus.post(new MarkPostKnownEvent(post));
1610 if (knownPosts.add(post.getId())) {
1611 touchConfiguration();
1614 for (PostReply reply : getReplies(post)) {
1615 markReplyKnown(reply);
1620 * Bookmarks the given post.
1623 * The post to bookmark
1625 public void bookmark(Post post) {
1626 bookmarkPost(post.getId());
1630 * Bookmarks the post with the given ID.
1633 * The ID of the post to bookmark
1635 public void bookmarkPost(String id) {
1636 synchronized (bookmarkedPosts) {
1637 bookmarkedPosts.add(id);
1642 * Removes the given post from the bookmarks.
1645 * The post to unbookmark
1647 public void unbookmark(Post post) {
1648 unbookmarkPost(post.getId());
1652 * Removes the post with the given ID from the bookmarks.
1655 * The ID of the post to unbookmark
1657 public void unbookmarkPost(String id) {
1658 synchronized (bookmarkedPosts) {
1659 bookmarkedPosts.remove(id);
1664 * Creates a new reply.
1667 * The Sone that creates the reply
1669 * The post that this reply refers to
1671 * The text of the reply
1672 * @return The created reply
1674 public PostReply createReply(Sone sone, Post post, String text) {
1675 return createReply(sone, post, System.currentTimeMillis(), text);
1679 * Creates a new reply.
1682 * The Sone that creates the reply
1684 * The post that this reply refers to
1686 * The time of the reply
1688 * The text of the reply
1689 * @return The created reply
1691 public PostReply createReply(Sone sone, Post post, long time, String text) {
1692 Validation.begin().isNotNull("Text", text).check().isGreater("Text Length", text.trim().length(), 0).check();
1693 if (!sone.isLocal()) {
1694 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1697 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1698 synchronized (replies) {
1699 replies.put(reply.getId(), reply);
1701 synchronized (knownReplies) {
1702 eventBus.post(new NewPostReplyFoundEvent(reply));
1704 sone.addReply(reply);
1705 touchConfiguration();
1706 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1713 markReplyKnown(reply);
1715 }, "Mark " + reply + " read.");
1720 * Deletes the given reply.
1723 * The reply to delete
1725 public void deleteReply(PostReply reply) {
1726 Sone sone = reply.getSone();
1727 if (!sone.isLocal()) {
1728 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1731 synchronized (replies) {
1732 replies.remove(reply.getId());
1734 synchronized (knownReplies) {
1735 markReplyKnown(reply);
1736 knownReplies.remove(reply.getId());
1738 sone.removeReply(reply);
1739 touchConfiguration();
1743 * Marks the given reply as known, if it is currently not a known reply
1744 * (according to {@link Reply#isKnown()}).
1747 * The reply to mark as known
1749 public void markReplyKnown(PostReply reply) {
1750 reply.setKnown(true);
1751 synchronized (knownReplies) {
1752 eventBus.post(new MarkPostReplyKnownEvent(reply));
1753 if (knownReplies.add(reply.getId())) {
1754 touchConfiguration();
1760 * Creates a new top-level album for the given Sone.
1763 * The Sone to create the album for
1764 * @return The new album
1766 public Album createAlbum(Sone sone) {
1767 return createAlbum(sone, null);
1771 * Creates a new album for the given Sone.
1774 * The Sone to create the album for
1776 * The parent of the album (may be {@code null} to create a
1778 * @return The new album
1780 public Album createAlbum(Sone sone, Album parent) {
1781 Album album = new Album();
1782 synchronized (albums) {
1783 albums.put(album.getId(), album);
1785 album.setSone(sone);
1786 if (parent != null) {
1787 parent.addAlbum(album);
1789 sone.addAlbum(album);
1795 * Deletes the given album. The owner of the album has to be a local Sone,
1796 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1799 * The album to remove
1801 public void deleteAlbum(Album album) {
1802 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1803 if (!album.isEmpty()) {
1806 if (album.getParent() == null) {
1807 album.getSone().removeAlbum(album);
1809 album.getParent().removeAlbum(album);
1811 synchronized (albums) {
1812 albums.remove(album.getId());
1814 touchConfiguration();
1818 * Creates a new image.
1821 * The Sone creating the image
1823 * The album the image will be inserted into
1824 * @param temporaryImage
1825 * The temporary image to create the image from
1826 * @return The newly created image
1828 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1829 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", sone.isLocal()).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1830 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1831 album.addImage(image);
1832 synchronized (images) {
1833 images.put(image.getId(), image);
1835 imageInserter.insertImage(temporaryImage, image);
1840 * Deletes the given image. This method will also delete a matching
1843 * @see #deleteTemporaryImage(TemporaryImage)
1845 * The image to delete
1847 public void deleteImage(Image image) {
1848 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1849 deleteTemporaryImage(image.getId());
1850 image.getAlbum().removeImage(image);
1851 synchronized (images) {
1852 images.remove(image.getId());
1854 touchConfiguration();
1858 * Creates a new temporary image.
1861 * The MIME type of the temporary image
1863 * The encoded data of the image
1864 * @return The temporary image
1866 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1867 TemporaryImage temporaryImage = new TemporaryImage();
1868 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1869 synchronized (temporaryImages) {
1870 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1872 return temporaryImage;
1876 * Deletes the given temporary image.
1878 * @param temporaryImage
1879 * The temporary image to delete
1881 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1882 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1883 deleteTemporaryImage(temporaryImage.getId());
1887 * Deletes the temporary image with the given ID.
1890 * The ID of the temporary image to delete
1892 public void deleteTemporaryImage(String imageId) {
1893 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1894 synchronized (temporaryImages) {
1895 temporaryImages.remove(imageId);
1897 Image image = getImage(imageId, false);
1898 if (image != null) {
1899 imageInserter.cancelImageInsert(image);
1904 * Notifies the core that the configuration, either of the core or of a
1905 * single local Sone, has changed, and that the configuration should be
1908 public void touchConfiguration() {
1909 lastConfigurationUpdate = System.currentTimeMillis();
1920 public void serviceStart() {
1921 loadConfiguration();
1922 updateChecker.addUpdateListener(this);
1923 updateChecker.start();
1924 identityManager.addIdentityListener(this);
1925 identityManager.start();
1926 webOfTrustUpdater.init();
1927 webOfTrustUpdater.start();
1934 public void serviceRun() {
1935 long lastSaved = System.currentTimeMillis();
1936 while (!shouldStop()) {
1938 long now = System.currentTimeMillis();
1939 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1940 for (Sone localSone : getLocalSones()) {
1941 saveSone(localSone);
1943 saveConfiguration();
1953 public void serviceStop() {
1954 synchronized (sones) {
1955 for (Entry<Sone, SoneInserter> soneInserter : soneInserters.entrySet()) {
1956 soneInserter.getValue().removeSoneInsertListener(this);
1957 soneInserter.getValue().stop();
1958 saveSone(soneInserter.getKey());
1961 saveConfiguration();
1962 webOfTrustUpdater.stop();
1963 updateChecker.stop();
1964 updateChecker.removeUpdateListener(this);
1965 soneDownloader.stop();
1966 identityManager.removeIdentityListener(this);
1967 identityManager.stop();
1975 * Saves the given Sone. This will persist all local settings for the given
1976 * Sone, such as the friends list and similar, private options.
1981 private synchronized void saveSone(Sone sone) {
1982 if (!sone.isLocal()) {
1983 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1986 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1987 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1991 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1993 /* save Sone into configuration. */
1994 String sonePrefix = "Sone/" + sone.getId();
1995 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1996 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1999 Profile profile = sone.getProfile();
2000 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2001 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2002 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2003 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2004 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2005 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2006 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2008 /* save profile fields. */
2009 int fieldCounter = 0;
2010 for (Field profileField : profile.getFields()) {
2011 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2012 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2013 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2015 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2018 int postCounter = 0;
2019 for (Post post : sone.getPosts()) {
2020 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2021 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2022 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2023 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2024 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2026 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2029 int replyCounter = 0;
2030 for (PostReply reply : sone.getReplies()) {
2031 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2032 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2033 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2034 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2035 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2037 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2039 /* save post likes. */
2040 int postLikeCounter = 0;
2041 for (String postId : sone.getLikedPostIds()) {
2042 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2044 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2046 /* save reply likes. */
2047 int replyLikeCounter = 0;
2048 for (String replyId : sone.getLikedReplyIds()) {
2049 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2051 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2054 int friendCounter = 0;
2055 for (String friendId : sone.getFriends()) {
2056 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2058 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2060 /* save albums. first, collect in a flat structure, top-level first. */
2061 List<Album> albums = sone.getAllAlbums();
2063 int albumCounter = 0;
2064 for (Album album : albums) {
2065 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2066 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2067 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2068 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2069 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2070 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2072 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2075 int imageCounter = 0;
2076 for (Album album : albums) {
2077 for (Image image : album.getImages()) {
2078 if (!image.isInserted()) {
2081 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2082 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2083 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2084 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2085 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2086 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2087 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2088 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2089 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2092 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2095 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2096 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2097 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2098 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2099 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2100 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2102 configuration.save();
2104 webOfTrustUpdater.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2106 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2107 } catch (ConfigurationException ce1) {
2108 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2113 * Saves the current options.
2115 private void saveConfiguration() {
2116 synchronized (configuration) {
2117 if (storingConfiguration) {
2118 logger.log(Level.FINE, "Already storing configuration…");
2121 storingConfiguration = true;
2124 /* store the options first. */
2126 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2127 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2128 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2129 configuration.getIntValue("Option/ImagesPerPage").setValue(options.getIntegerOption("ImagesPerPage").getReal());
2130 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2131 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2132 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2133 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2134 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2135 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2136 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2137 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2139 /* save known Sones. */
2140 int soneCounter = 0;
2141 synchronized (knownSones) {
2142 for (String knownSoneId : knownSones) {
2143 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2145 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2148 /* save Sone following times. */
2150 synchronized (soneFollowingTimes) {
2151 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2152 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2153 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2156 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2159 /* save known posts. */
2160 int postCounter = 0;
2161 synchronized (knownPosts) {
2162 for (String knownPostId : knownPosts) {
2163 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2165 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2168 /* save known replies. */
2169 int replyCounter = 0;
2170 synchronized (knownReplies) {
2171 for (String knownReplyId : knownReplies) {
2172 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2174 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2177 /* save bookmarked posts. */
2178 int bookmarkedPostCounter = 0;
2179 synchronized (bookmarkedPosts) {
2180 for (String bookmarkedPostId : bookmarkedPosts) {
2181 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2184 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2187 configuration.save();
2189 } catch (ConfigurationException ce1) {
2190 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2192 synchronized (configuration) {
2193 storingConfiguration = false;
2199 * Loads the configuration.
2201 @SuppressWarnings("unchecked")
2202 private void loadConfiguration() {
2203 /* create options. */
2204 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2207 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2208 SoneInserter.setInsertionDelay(newValue);
2212 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2213 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2214 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2215 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2216 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2217 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2218 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2219 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2220 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2223 @SuppressWarnings("synthetic-access")
2224 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2225 fcpInterface.setActive(newValue);
2228 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2231 @SuppressWarnings("synthetic-access")
2232 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2233 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2238 loadConfigurationValue("InsertionDelay");
2239 loadConfigurationValue("PostsPerPage");
2240 loadConfigurationValue("ImagesPerPage");
2241 loadConfigurationValue("CharactersPerPost");
2242 loadConfigurationValue("PostCutOffLength");
2243 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2244 loadConfigurationValue("PositiveTrust");
2245 loadConfigurationValue("NegativeTrust");
2246 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2247 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2248 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2250 /* load known Sones. */
2251 int soneCounter = 0;
2253 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2254 if (knownSoneId == null) {
2257 synchronized (knownSones) {
2258 knownSones.add(knownSoneId);
2262 /* load Sone following times. */
2265 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2266 if (soneId == null) {
2269 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2270 Sone followedSone = getSone(soneId);
2271 if (followedSone == null) {
2272 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2274 synchronized (soneFollowingTimes) {
2275 soneFollowingTimes.put(getSone(soneId), time);
2281 /* load known posts. */
2282 int postCounter = 0;
2284 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2285 if (knownPostId == null) {
2288 synchronized (knownPosts) {
2289 knownPosts.add(knownPostId);
2293 /* load known replies. */
2294 int replyCounter = 0;
2296 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2297 if (knownReplyId == null) {
2300 synchronized (knownReplies) {
2301 knownReplies.add(knownReplyId);
2305 /* load bookmarked posts. */
2306 int bookmarkedPostCounter = 0;
2308 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2309 if (bookmarkedPostId == null) {
2312 synchronized (bookmarkedPosts) {
2313 bookmarkedPosts.add(bookmarkedPostId);
2320 * Loads an {@link Integer} configuration value for the option with the
2321 * given name, logging validation failures.
2324 * The name of the option to load
2326 private void loadConfigurationValue(String optionName) {
2328 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2329 } catch (IllegalArgumentException iae1) {
2330 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2335 * Generate a Sone URI from the given URI and latest edition.
2338 * The URI to derive the Sone URI from
2339 * @return The derived URI
2341 private static FreenetURI getSoneUri(String uriString) {
2343 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2345 } catch (MalformedURLException mue1) {
2346 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString), mue1);
2352 // INTERFACE IdentityListener
2359 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2360 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2361 if (ownIdentity.hasContext("Sone")) {
2362 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2363 addLocalSone(ownIdentity);
2371 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2372 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2373 trustedIdentities.remove(ownIdentity);
2380 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2381 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2382 trustedIdentities.get(ownIdentity).add(identity);
2383 addRemoteSone(identity);
2390 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2391 soneDownloaders.execute(new Runnable() {
2394 @SuppressWarnings("synthetic-access")
2396 Sone sone = getRemoteSone(identity.getId(), false);
2397 sone.setIdentity(identity);
2398 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2399 soneDownloader.addSone(sone);
2400 soneDownloader.fetchSone(sone);
2409 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2410 trustedIdentities.get(ownIdentity).remove(identity);
2411 boolean foundIdentity = false;
2412 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2413 if (trustedIdentity.getKey().equals(ownIdentity)) {
2416 if (trustedIdentity.getValue().contains(identity)) {
2417 foundIdentity = true;
2420 if (foundIdentity) {
2421 /* some local identity still trusts this identity, don’t remove. */
2424 Sone sone = getSone(identity.getId(), false);
2426 /* TODO - we don’t have the Sone anymore. should this happen? */
2429 synchronized (posts) {
2430 synchronized (knownPosts) {
2431 for (Post post : sone.getPosts()) {
2432 posts.remove(post.getId());
2433 eventBus.post(new PostRemovedEvent(post));
2437 synchronized (replies) {
2438 synchronized (knownReplies) {
2439 for (PostReply reply : sone.getReplies()) {
2440 replies.remove(reply.getId());
2441 eventBus.post(new PostReplyRemovedEvent(reply));
2445 synchronized (sones) {
2446 sones.remove(identity.getId());
2448 eventBus.post(new SoneRemovedEvent(sone));
2452 // INTERFACE UpdateListener
2459 public void updateFound(Version version, long releaseTime, long latestEdition) {
2460 eventBus.post(new UpdateFoundEvent(version, releaseTime, latestEdition));
2464 // INTERFACE ImageInsertListener
2471 public void insertStarted(Sone sone) {
2472 eventBus.post(new SoneInsertingEvent(sone));
2479 public void insertFinished(Sone sone, long insertDuration) {
2480 eventBus.post(new SoneInsertedEvent(sone, insertDuration));
2487 public void insertAborted(Sone sone, Throwable cause) {
2488 eventBus.post(new SoneInsertAbortedEvent(sone, cause));
2492 // SONEINSERTLISTENER METHODS
2499 public void imageInsertStarted(Image image) {
2500 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2501 eventBus.post(new ImageInsertStartedEvent(image));
2508 public void imageInsertAborted(Image image) {
2509 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2510 eventBus.post(new ImageInsertAbortedEvent(image));
2517 public void imageInsertFinished(Image image, FreenetURI key) {
2518 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2519 image.setKey(key.toString());
2520 deleteTemporaryImage(image.getId());
2521 touchConfiguration();
2522 eventBus.post(new ImageInsertFinishedEvent(image));
2529 public void imageInsertFailed(Image image, Throwable cause) {
2530 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2531 coreListenerManager.fireImageInsertFailed(image, cause);
2535 * Convenience interface for external classes that want to access the core’s
2538 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2540 public static class Preferences {
2542 /** The wrapped options. */
2543 private final Options options;
2546 * Creates a new preferences object wrapped around the given options.
2549 * The options to wrap
2551 public Preferences(Options options) {
2552 this.options = options;
2556 * Returns the insertion delay.
2558 * @return The insertion delay
2560 public int getInsertionDelay() {
2561 return options.getIntegerOption("InsertionDelay").get();
2565 * Validates the given insertion delay.
2567 * @param insertionDelay
2568 * The insertion delay to validate
2569 * @return {@code true} if the given insertion delay was valid,
2570 * {@code false} otherwise
2572 public boolean validateInsertionDelay(Integer insertionDelay) {
2573 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2577 * Sets the insertion delay
2579 * @param insertionDelay
2580 * The new insertion delay, or {@code null} to restore it to
2582 * @return This preferences
2584 public Preferences setInsertionDelay(Integer insertionDelay) {
2585 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2590 * Returns the number of posts to show per page.
2592 * @return The number of posts to show per page
2594 public int getPostsPerPage() {
2595 return options.getIntegerOption("PostsPerPage").get();
2599 * Validates the number of posts per page.
2601 * @param postsPerPage
2602 * The number of posts per page
2603 * @return {@code true} if the number of posts per page was valid,
2604 * {@code false} otherwise
2606 public boolean validatePostsPerPage(Integer postsPerPage) {
2607 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2611 * Sets the number of posts to show per page.
2613 * @param postsPerPage
2614 * The number of posts to show per page
2615 * @return This preferences object
2617 public Preferences setPostsPerPage(Integer postsPerPage) {
2618 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2623 * Returns the number of images to show per page.
2625 * @return The number of images to show per page
2627 public int getImagesPerPage() {
2628 return options.getIntegerOption("ImagesPerPage").get();
2632 * Validates the number of images per page.
2634 * @param imagesPerPage
2635 * The number of images per page
2636 * @return {@code true} if the number of images per page was valid,
2637 * {@code false} otherwise
2639 public boolean validateImagesPerPage(Integer imagesPerPage) {
2640 return options.getIntegerOption("ImagesPerPage").validate(imagesPerPage);
2644 * Sets the number of images per page.
2646 * @param imagesPerPage
2647 * The number of images per page
2648 * @return This preferences object
2650 public Preferences setImagesPerPage(Integer imagesPerPage) {
2651 options.getIntegerOption("ImagesPerPage").set(imagesPerPage);
2656 * Returns the number of characters per post, or <code>-1</code> if the
2657 * posts should not be cut off.
2659 * @return The numbers of characters per post
2661 public int getCharactersPerPost() {
2662 return options.getIntegerOption("CharactersPerPost").get();
2666 * Validates the number of characters per post.
2668 * @param charactersPerPost
2669 * The number of characters per post
2670 * @return {@code true} if the number of characters per post was valid,
2671 * {@code false} otherwise
2673 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2674 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2678 * Sets the number of characters per post.
2680 * @param charactersPerPost
2681 * The number of characters per post, or <code>-1</code> to
2682 * not cut off the posts
2683 * @return This preferences objects
2685 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2686 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2691 * Returns the number of characters the shortened post should have.
2693 * @return The number of characters of the snippet
2695 public int getPostCutOffLength() {
2696 return options.getIntegerOption("PostCutOffLength").get();
2700 * Validates the number of characters after which to cut off the post.
2702 * @param postCutOffLength
2703 * The number of characters of the snippet
2704 * @return {@code true} if the number of characters of the snippet is
2705 * valid, {@code false} otherwise
2707 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2708 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2712 * Sets the number of characters the shortened post should have.
2714 * @param postCutOffLength
2715 * The number of characters of the snippet
2716 * @return This preferences
2718 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2719 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2724 * Returns whether Sone requires full access to be even visible.
2726 * @return {@code true} if Sone requires full access, {@code false}
2729 public boolean isRequireFullAccess() {
2730 return options.getBooleanOption("RequireFullAccess").get();
2734 * Sets whether Sone requires full access to be even visible.
2736 * @param requireFullAccess
2737 * {@code true} if Sone requires full access, {@code false}
2740 public void setRequireFullAccess(Boolean requireFullAccess) {
2741 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2745 * Returns the positive trust.
2747 * @return The positive trust
2749 public int getPositiveTrust() {
2750 return options.getIntegerOption("PositiveTrust").get();
2754 * Validates the positive trust.
2756 * @param positiveTrust
2757 * The positive trust to validate
2758 * @return {@code true} if the positive trust was valid, {@code false}
2761 public boolean validatePositiveTrust(Integer positiveTrust) {
2762 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2766 * Sets the positive trust.
2768 * @param positiveTrust
2769 * The new positive trust, or {@code null} to restore it to
2771 * @return This preferences
2773 public Preferences setPositiveTrust(Integer positiveTrust) {
2774 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2779 * Returns the negative trust.
2781 * @return The negative trust
2783 public int getNegativeTrust() {
2784 return options.getIntegerOption("NegativeTrust").get();
2788 * Validates the negative trust.
2790 * @param negativeTrust
2791 * The negative trust to validate
2792 * @return {@code true} if the negative trust was valid, {@code false}
2795 public boolean validateNegativeTrust(Integer negativeTrust) {
2796 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2800 * Sets the negative trust.
2802 * @param negativeTrust
2803 * The negative trust, or {@code null} to restore it to the
2805 * @return The preferences
2807 public Preferences setNegativeTrust(Integer negativeTrust) {
2808 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2813 * Returns the trust comment. This is the comment that is set in the web
2814 * of trust when a trust value is assigned to an identity.
2816 * @return The trust comment
2818 public String getTrustComment() {
2819 return options.getStringOption("TrustComment").get();
2823 * Sets the trust comment.
2825 * @param trustComment
2826 * The trust comment, or {@code null} to restore it to the
2828 * @return This preferences
2830 public Preferences setTrustComment(String trustComment) {
2831 options.getStringOption("TrustComment").set(trustComment);
2836 * Returns whether the {@link FcpInterface FCP interface} is currently
2839 * @see FcpInterface#setActive(boolean)
2840 * @return {@code true} if the FCP interface is currently active,
2841 * {@code false} otherwise
2843 public boolean isFcpInterfaceActive() {
2844 return options.getBooleanOption("ActivateFcpInterface").get();
2848 * Sets whether the {@link FcpInterface FCP interface} is currently
2851 * @see FcpInterface#setActive(boolean)
2852 * @param fcpInterfaceActive
2853 * {@code true} to activate the FCP interface, {@code false}
2854 * to deactivate the FCP interface
2855 * @return This preferences object
2857 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2858 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2863 * Returns the action level for which full access to the FCP interface
2866 * @return The action level for which full access to the FCP interface
2869 public FullAccessRequired getFcpFullAccessRequired() {
2870 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2874 * Sets the action level for which full access to the FCP interface is
2877 * @param fcpFullAccessRequired
2879 * @return This preferences
2881 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2882 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);