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.data.Album;
39 import net.pterodactylus.sone.data.Client;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Post;
42 import net.pterodactylus.sone.data.PostReply;
43 import net.pterodactylus.sone.data.Profile;
44 import net.pterodactylus.sone.data.Profile.Field;
45 import net.pterodactylus.sone.data.Reply;
46 import net.pterodactylus.sone.data.Sone;
47 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
48 import net.pterodactylus.sone.data.Sone.SoneStatus;
49 import net.pterodactylus.sone.data.TemporaryImage;
50 import net.pterodactylus.sone.database.Database;
51 import net.pterodactylus.sone.fcp.FcpInterface;
52 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
53 import net.pterodactylus.sone.freenet.wot.Identity;
54 import net.pterodactylus.sone.freenet.wot.IdentityListener;
55 import net.pterodactylus.sone.freenet.wot.IdentityManager;
56 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
57 import net.pterodactylus.sone.freenet.wot.Trust;
58 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
59 import net.pterodactylus.sone.main.SonePlugin;
60 import net.pterodactylus.util.config.Configuration;
61 import net.pterodactylus.util.config.ConfigurationException;
62 import net.pterodactylus.util.logging.Logging;
63 import net.pterodactylus.util.number.Numbers;
64 import net.pterodactylus.util.service.AbstractService;
65 import net.pterodactylus.util.thread.Ticker;
66 import net.pterodactylus.util.validation.EqualityValidator;
67 import net.pterodactylus.util.validation.IntegerRangeValidator;
68 import net.pterodactylus.util.validation.OrValidator;
69 import net.pterodactylus.util.validation.Validation;
70 import net.pterodactylus.util.version.Version;
71 import freenet.keys.FreenetURI;
76 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
81 private static final Logger logger = Logging.getLogger(Core.class);
84 private final Options options = new Options();
86 /** The preferences. */
87 private final Preferences preferences = new Preferences(options);
89 /** The core listener manager. */
90 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
92 /** The configuration. */
93 private Configuration configuration;
95 /** Whether we’re currently saving the configuration. */
96 private boolean storingConfiguration = false;
99 private Database database;
101 /** The identity manager. */
102 private final IdentityManager identityManager;
104 /** Interface to freenet. */
105 private final FreenetInterface freenetInterface;
107 /** The Sone downloader. */
108 private final SoneDownloader soneDownloader;
110 /** The image inserter. */
111 private final ImageInserter imageInserter;
113 /** Sone downloader thread-pool. */
114 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
116 /** The update checker. */
117 private final UpdateChecker updateChecker;
119 /** The FCP interface. */
120 private volatile FcpInterface fcpInterface;
122 /** The times Sones were followed. */
123 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
125 /** Locked local Sones. */
126 /* synchronize on itself. */
127 private final Set<Sone> lockedSones = new HashSet<Sone>();
129 /** Sone inserters. */
130 /* synchronize access on this on localSones. */
131 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
133 /** Sone rescuers. */
134 /* synchronize access on this on localSones. */
135 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
137 /** All known Sones. */
138 private final Set<String> knownSones = new HashSet<String>();
141 private final Map<String, Post> posts = new HashMap<String, Post>();
143 /** All known posts. */
144 private final Set<String> knownPosts = new HashSet<String>();
147 private final Map<String, PostReply> replies = new HashMap<String, PostReply>();
149 /** All known replies. */
150 private final Set<String> knownReplies = new HashSet<String>();
152 /** All bookmarked posts. */
153 /* synchronize access on itself. */
154 private final Set<String> bookmarkedPosts = new HashSet<String>();
156 /** Trusted identities, sorted by own identities. */
157 private final Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
159 /** All known albums. */
160 private final Map<String, Album> albums = new HashMap<String, Album>();
162 /** All known images. */
163 private final Map<String, Image> images = new HashMap<String, Image>();
165 /** All temporary images. */
166 private final Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
168 /** Ticker for threads that mark own elements as known. */
169 private final Ticker localElementTicker = new Ticker();
171 /** The time the configuration was last touched. */
172 private volatile long lastConfigurationUpdate;
175 * Creates a new core.
177 * @param configuration
178 * The configuration of the core
180 * The database to use
181 * @param freenetInterface
182 * The freenet interface
183 * @param identityManager
184 * The identity manager
186 public Core(Configuration configuration, Database database, FreenetInterface freenetInterface, IdentityManager identityManager) {
188 this.configuration = configuration;
189 this.database = database;
190 this.freenetInterface = freenetInterface;
191 this.identityManager = identityManager;
192 this.soneDownloader = new SoneDownloader(this, freenetInterface);
193 this.imageInserter = new ImageInserter(this, freenetInterface);
194 this.updateChecker = new UpdateChecker(freenetInterface);
198 // LISTENER MANAGEMENT
202 * Adds a new core listener.
204 * @param coreListener
205 * The listener to add
207 public void addCoreListener(CoreListener coreListener) {
208 coreListenerManager.addListener(coreListener);
212 * Removes a core listener.
214 * @param coreListener
215 * The listener to remove
217 public void removeCoreListener(CoreListener coreListener) {
218 coreListenerManager.removeListener(coreListener);
226 * Sets the configuration to use. This will automatically save the current
227 * configuration to the given configuration.
229 * @param configuration
230 * The new configuration to use
232 public void setConfiguration(Configuration configuration) {
233 this.configuration = configuration;
234 touchConfiguration();
238 * Returns the options used by the core.
240 * @return The options of the core
242 public Preferences getPreferences() {
247 * Returns the identity manager used by the core.
249 * @return The identity manager
251 public IdentityManager getIdentityManager() {
252 return identityManager;
256 * Returns the update checker.
258 * @return The update checker
260 public UpdateChecker getUpdateChecker() {
261 return updateChecker;
265 * Sets the FCP interface to use.
267 * @param fcpInterface
268 * The FCP interface to use
270 public void setFcpInterface(FcpInterface fcpInterface) {
271 this.fcpInterface = fcpInterface;
275 * Returns the Sone rescuer for the given local Sone.
278 * The local Sone to get the rescuer for
279 * @return The Sone rescuer for the given Sone
281 public SoneRescuer getSoneRescuer(Sone sone) {
282 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", sone.isLocal()).check();
283 synchronized (soneRescuers) {
284 SoneRescuer soneRescuer = soneRescuers.get(sone);
285 if (soneRescuer == null) {
286 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
287 soneRescuers.put(sone, soneRescuer);
295 * Returns whether the given Sone is currently locked.
299 * @return {@code true} if the Sone is locked, {@code false} if it is not
301 public boolean isLocked(Sone sone) {
302 synchronized (lockedSones) {
303 return lockedSones.contains(sone);
308 * Returns all Sones, remote and local.
312 public Collection<Sone> getSones() {
313 return database.getSones();
317 * Returns the Sone with the given ID, regardless whether it’s local or
321 * The ID of the Sone to get
322 * @return The Sone with the given ID, or {@code null} if there is no such
325 public Sone getSone(String id) {
326 return getSone(id, true);
330 * Returns the Sone with the given ID, regardless whether it’s local or
334 * The ID of the Sone to get
336 * {@code true} to create a new Sone if none exists,
337 * {@code false} to return {@code null} if a Sone with the given
339 * @return The Sone with the given ID, or {@code null} if there is no such
343 public Sone getSone(String id, boolean create) {
344 return database.getSone(id, create);
348 * Checks whether the core knows a Sone with the given ID.
352 * @return {@code true} if there is a Sone with the given ID, {@code false}
355 public boolean hasSone(String id) {
356 return database.getSone(id, false) != null;
360 * Returns all local Sones.
362 * @return All local Sones
364 public Collection<Sone> getLocalSones() {
365 return database.getLocalSones();
369 * Returns the local Sone with the given ID.
372 * The ID of the Sone to get
373 * @return The Sone with the given ID
375 public Sone getLocalSone(String id) {
376 return getLocalSone(id, true);
380 * Returns the local Sone with the given ID, optionally creating a new Sone.
385 * {@code true} to create a new Sone if none exists,
386 * {@code false} to return null if none exists
387 * @return The Sone with the given ID, or {@code null}
389 public Sone getLocalSone(String id, boolean create) {
390 return database.getLocalSone(id, create);
394 * Returns all remote Sones.
396 * @return All remote Sones
398 public Collection<Sone> getRemoteSones() {
399 return database.getRemoteSones();
403 * Returns the remote Sone with the given ID.
406 * The ID of the remote Sone to get
408 * {@code true} to always create a Sone, {@code false} to return
409 * {@code null} if no Sone with the given ID exists
410 * @return The Sone with the given ID
412 public Sone getRemoteSone(String id, boolean create) {
413 return database.getRemoteSone(id, create);
417 * Returns whether the given Sone has been modified.
420 * The Sone to check for modifications
421 * @return {@code true} if a modification has been detected in the Sone,
422 * {@code false} otherwise
424 public boolean isModifiedSone(Sone sone) {
425 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
429 * Returns the time when the given was first followed by any local Sone.
432 * The Sone to get the time for
433 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
434 * been followed, or {@link Long#MAX_VALUE}
436 public long getSoneFollowingTime(Sone sone) {
437 synchronized (soneFollowingTimes) {
438 if (soneFollowingTimes.containsKey(sone)) {
439 return soneFollowingTimes.get(sone);
441 return Long.MAX_VALUE;
446 * Returns whether the target Sone is trusted by the origin Sone.
452 * @return {@code true} if the target Sone is trusted by the origin Sone
454 public boolean isSoneTrusted(Sone origin, Sone target) {
455 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
456 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
460 * Returns the post with the given ID, optionally creating a new post.
463 * The ID of the post to get
465 * {@code true} it create a new post if no post with the given ID
466 * exists, {@code false} to return {@code null}
467 * @return The post, or {@code null} if there is no such post
470 public Post getPost(String postId, boolean create) {
471 synchronized (posts) {
472 Post post = posts.get(postId);
473 if ((post == null) && create) {
474 post = new Post(postId);
475 posts.put(postId, post);
482 * Returns all posts that have the given Sone as recipient.
484 * @see Post#getRecipient()
486 * The recipient of the posts
487 * @return All posts that have the given Sone as recipient
489 public Set<Post> getDirectedPosts(Sone recipient) {
490 Validation.begin().isNotNull("Recipient", recipient).check();
491 Set<Post> directedPosts = new HashSet<Post>();
492 synchronized (posts) {
493 for (Post post : posts.values()) {
494 if (recipient.equals(post.getRecipient())) {
495 directedPosts.add(post);
499 return directedPosts;
503 * Returns the reply with the given ID. If there is no reply with the given
504 * ID yet, a new one is created.
507 * The ID of the reply to get
510 public PostReply getReply(String replyId) {
511 return getReply(replyId, true);
515 * Returns the reply with the given ID. If there is no reply with the given
516 * ID yet, a new one is created, unless {@code create} is false in which
517 * case {@code null} is returned.
520 * The ID of the reply to get
522 * {@code true} to always return a {@link Reply}, {@code false}
523 * to return {@code null} if no reply can be found
524 * @return The reply, or {@code null} if there is no such reply
526 public PostReply getReply(String replyId, boolean create) {
527 synchronized (replies) {
528 PostReply reply = replies.get(replyId);
529 if (create && (reply == null)) {
530 reply = new PostReply(replyId);
531 replies.put(replyId, reply);
538 * Returns all replies for the given post, order ascending by time.
541 * The post to get all replies for
542 * @return All replies for the given post
544 public List<PostReply> getReplies(Post post) {
545 Collection<Sone> sones = getSones();
546 List<PostReply> replies = new ArrayList<PostReply>();
547 for (Sone sone : sones) {
548 for (PostReply reply : sone.getReplies()) {
549 if (reply.getPost().equals(post)) {
554 Collections.sort(replies, Reply.TIME_COMPARATOR);
559 * Returns all Sones that have liked the given post.
562 * The post to get the liking Sones for
563 * @return The Sones that like the given post
565 public Set<Sone> getLikes(Post post) {
566 Set<Sone> sones = new HashSet<Sone>();
567 for (Sone sone : getSones()) {
568 if (sone.getLikedPostIds().contains(post.getId())) {
576 * Returns all Sones that have liked the given reply.
579 * The reply to get the liking Sones for
580 * @return The Sones that like the given reply
582 public Set<Sone> getLikes(PostReply reply) {
583 Set<Sone> sones = new HashSet<Sone>();
584 for (Sone sone : getSones()) {
585 if (sone.getLikedReplyIds().contains(reply.getId())) {
593 * Returns whether the given post is bookmarked.
597 * @return {@code true} if the given post is bookmarked, {@code false}
600 public boolean isBookmarked(Post post) {
601 return isPostBookmarked(post.getId());
605 * Returns whether the post with the given ID is bookmarked.
608 * The ID of the post to check
609 * @return {@code true} if the post with the given ID is bookmarked,
610 * {@code false} otherwise
612 public boolean isPostBookmarked(String id) {
613 synchronized (bookmarkedPosts) {
614 return bookmarkedPosts.contains(id);
619 * Returns all currently known bookmarked posts.
621 * @return All bookmarked posts
623 public Set<Post> getBookmarkedPosts() {
624 Set<Post> posts = new HashSet<Post>();
625 synchronized (bookmarkedPosts) {
626 for (String bookmarkedPostId : bookmarkedPosts) {
627 Post post = getPost(bookmarkedPostId, false);
637 * Returns the album with the given ID, creating a new album if no album
638 * with the given ID can be found.
641 * The ID of the album
642 * @return The album with the given ID
644 public Album getAlbum(String albumId) {
645 return getAlbum(albumId, true);
649 * Returns the album with the given ID, optionally creating a new album if
650 * an album with the given ID can not be found.
653 * The ID of the album
655 * {@code true} to create a new album if none exists for the
657 * @return The album with the given ID, or {@code null} if no album with the
658 * given ID exists and {@code create} is {@code false}
660 public Album getAlbum(String albumId, boolean create) {
661 synchronized (albums) {
662 Album album = albums.get(albumId);
663 if (create && (album == null)) {
664 album = new Album(albumId);
665 albums.put(albumId, album);
672 * Returns the image with the given ID, creating it if necessary.
675 * The ID of the image
676 * @return The image with the given ID
678 public Image getImage(String imageId) {
679 return getImage(imageId, true);
683 * Returns the image with the given ID, optionally creating it if it does
687 * The ID of the image
689 * {@code true} to create an image if none exists with the given
691 * @return The image with the given ID, or {@code null} if none exists and
694 public Image getImage(String imageId, boolean create) {
695 synchronized (images) {
696 Image image = images.get(imageId);
697 if (create && (image == null)) {
698 image = new Image(imageId);
699 images.put(imageId, image);
706 * Returns the temporary image with the given ID.
709 * The ID of the temporary image
710 * @return The temporary image, or {@code null} if there is no temporary
711 * image with the given ID
713 public TemporaryImage getTemporaryImage(String imageId) {
714 synchronized (temporaryImages) {
715 return temporaryImages.get(imageId);
724 * Locks the given Sone. A locked Sone will not be inserted by
725 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
731 public void lockSone(Sone sone) {
732 synchronized (lockedSones) {
733 if (lockedSones.add(sone)) {
734 coreListenerManager.fireSoneLocked(sone);
740 * Unlocks the given Sone.
742 * @see #lockSone(Sone)
746 public void unlockSone(Sone sone) {
747 synchronized (lockedSones) {
748 if (lockedSones.remove(sone)) {
749 coreListenerManager.fireSoneUnlocked(sone);
757 * Adds a local Sone from the given ID which has to be the ID of an own
761 * The ID of an own identity to add a Sone for
762 * @return The added (or already existing) Sone
764 public Sone addLocalSone(String id) {
765 if (database.getLocalSone(id, false) != null) {
766 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
767 return database.getLocalSone(id, false);
769 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
770 if (ownIdentity == null) {
771 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
774 return addLocalSone(ownIdentity);
778 >>>>>>> 4f36598... Store locality of a Sone in the Sone itself, remove related methods from Database.
779 * Adds a local Sone from the given own identity.
782 * The own identity to create a Sone from
783 * @return The added (or already existing) Sone
785 public Sone addLocalSone(OwnIdentity ownIdentity) {
786 if (ownIdentity == null) {
787 logger.log(Level.WARNING, "Given OwnIdentity is null!");
792 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
793 } catch (MalformedURLException mue1) {
794 logger.log(Level.SEVERE, String.format("Could not convert the Identity’s URIs to Freenet URIs: %s, %s", ownIdentity.getInsertUri(), ownIdentity.getRequestUri()), mue1);
797 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
798 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
800 /* TODO - load posts ’n stuff */
801 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
802 soneInserter.addSoneInsertListener(this);
803 soneInserters.put(sone, soneInserter);
804 sone.setStatus(SoneStatus.idle);
806 soneInserter.start();
807 database.saveSone(sone);
812 * Creates a new Sone for the given own identity.
815 * The own identity to create a Sone for
816 * @return The created Sone
818 public Sone createSone(OwnIdentity ownIdentity) {
820 ownIdentity.addContext("Sone");
821 } catch (WebOfTrustException wote1) {
822 logger.log(Level.SEVERE, String.format("Could not add “Sone” context to own identity: %s", ownIdentity), wote1);
825 Sone sone = addLocalSone(ownIdentity);
826 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
827 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
828 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
829 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
830 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
831 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
833 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
834 touchConfiguration();
839 * Adds the Sone of the given identity.
842 * The identity whose Sone to add
843 * @return The added or already existing Sone
845 public Sone addRemoteSone(Identity identity) {
846 if (identity == null) {
847 logger.log(Level.WARNING, "Given Identity is null!");
850 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
851 boolean newSone = sone.getRequestUri() == null;
852 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
853 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
855 synchronized (knownSones) {
856 newSone = !knownSones.contains(sone.getId());
858 sone.setKnown(!newSone);
860 coreListenerManager.fireNewSoneFound(sone);
861 for (Sone localSone : getLocalSones()) {
862 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
863 followSone(localSone, sone);
868 soneDownloader.addSone(sone);
869 soneDownloaders.execute(new Runnable() {
872 @SuppressWarnings("synthetic-access")
874 soneDownloader.fetchSone(sone, sone.getRequestUri());
878 database.saveSone(sone);
883 * Lets the given local Sone follow the Sone with the given ID.
886 * The local Sone that should follow another Sone
888 * The ID of the Sone to follow
890 public void followSone(Sone sone, String soneId) {
891 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
892 Sone followedSone = getSone(soneId, true);
893 if (followedSone == null) {
894 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
897 followSone(sone, getSone(soneId));
901 * Lets the given local Sone follow the other given Sone. If the given Sone
902 * was not followed by any local Sone before, this will mark all elements of
903 * the followed Sone as read that have been created before the current
907 * The local Sone that should follow the other Sone
908 * @param followedSone
909 * The Sone that should be followed
911 public void followSone(Sone sone, Sone followedSone) {
912 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
913 sone.addFriend(followedSone.getId());
914 synchronized (soneFollowingTimes) {
915 if (!soneFollowingTimes.containsKey(followedSone)) {
916 long now = System.currentTimeMillis();
917 soneFollowingTimes.put(followedSone, now);
918 for (Post post : followedSone.getPosts()) {
919 if (post.getTime() < now) {
923 for (PostReply reply : followedSone.getReplies()) {
924 if (reply.getTime() < now) {
925 markReplyKnown(reply);
930 touchConfiguration();
934 * Lets the given local Sone unfollow the Sone with the given ID.
937 * The local Sone that should unfollow another Sone
939 * The ID of the Sone being unfollowed
941 public void unfollowSone(Sone sone, String soneId) {
942 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
943 unfollowSone(sone, getSone(soneId, false));
947 * Lets the given local Sone unfollow the other given Sone. If the given
948 * local Sone is the last local Sone that followed the given Sone, its
949 * following time will be removed.
952 * The local Sone that should unfollow another Sone
953 * @param unfollowedSone
954 * The Sone being unfollowed
956 public void unfollowSone(Sone sone, Sone unfollowedSone) {
957 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
958 sone.removeFriend(unfollowedSone.getId());
959 boolean unfollowedSoneStillFollowed = false;
960 for (Sone localSone : getLocalSones()) {
961 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
963 if (!unfollowedSoneStillFollowed) {
964 synchronized (soneFollowingTimes) {
965 soneFollowingTimes.remove(unfollowedSone);
968 touchConfiguration();
972 * Retrieves the trust relationship from the origin to the target. If the
973 * trust relationship can not be retrieved, {@code null} is returned.
975 * @see Identity#getTrust(OwnIdentity)
977 * The origin of the trust tree
979 * The target of the trust
980 * @return The trust relationship
982 public Trust getTrust(Sone origin, Sone target) {
983 if (!origin.isLocal()) {
984 logger.log(Level.WARNING, String.format("Tried to get trust from remote Sone: %s", origin));
987 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
991 * Sets the trust value of the given origin Sone for the target Sone.
998 * The trust value (from {@code -100} to {@code 100})
1000 public void setTrust(Sone origin, Sone target, int trustValue) {
1001 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();
1003 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1004 } catch (WebOfTrustException wote1) {
1005 logger.log(Level.WARNING, String.format("Could not set trust for Sone: %s", target), wote1);
1010 * Removes any trust assignment for the given target Sone.
1017 public void removeTrust(Sone origin, Sone target) {
1018 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1020 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1021 } catch (WebOfTrustException wote1) {
1022 logger.log(Level.WARNING, String.format("Could not remove trust for Sone: %s", target), wote1);
1027 * Assigns the configured positive trust value for the given target.
1034 public void trustSone(Sone origin, Sone target) {
1035 setTrust(origin, target, preferences.getPositiveTrust());
1039 * Assigns the configured negative trust value for the given target.
1046 public void distrustSone(Sone origin, Sone target) {
1047 setTrust(origin, target, preferences.getNegativeTrust());
1051 * Removes the trust assignment for the given target.
1058 public void untrustSone(Sone origin, Sone target) {
1059 removeTrust(origin, target);
1063 * Updates the stored Sone with the given Sone.
1068 public void updateSone(Sone sone) {
1069 updateSone(sone, false);
1073 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1074 * {@code true}, an older Sone than the current Sone can be given to restore
1078 * The Sone to update
1079 * @param soneRescueMode
1080 * {@code true} if the stored Sone should be updated regardless
1081 * of the age of the given Sone
1083 public void updateSone(Sone sone, boolean soneRescueMode) {
1084 if (hasSone(sone.getId())) {
1085 Sone storedSone = getSone(sone.getId());
1086 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1087 logger.log(Level.FINE, String.format("Downloaded Sone %s is not newer than stored Sone %s.", sone, storedSone));
1090 synchronized (posts) {
1091 if (!soneRescueMode) {
1092 for (Post post : storedSone.getPosts()) {
1093 posts.remove(post.getId());
1094 if (!sone.getPosts().contains(post)) {
1095 coreListenerManager.firePostRemoved(post);
1099 List<Post> storedPosts = storedSone.getPosts();
1100 synchronized (knownPosts) {
1101 for (Post post : sone.getPosts()) {
1102 post.setSone(storedSone).setKnown(knownPosts.contains(post.getId()));
1103 if (!storedPosts.contains(post)) {
1104 if (post.getTime() < getSoneFollowingTime(sone)) {
1105 knownPosts.add(post.getId());
1106 } else if (!knownPosts.contains(post.getId())) {
1107 sone.setKnown(false);
1108 coreListenerManager.fireNewPostFound(post);
1111 posts.put(post.getId(), post);
1115 synchronized (replies) {
1116 if (!soneRescueMode) {
1117 for (PostReply reply : storedSone.getReplies()) {
1118 replies.remove(reply.getId());
1119 if (!sone.getReplies().contains(reply)) {
1120 coreListenerManager.fireReplyRemoved(reply);
1124 Set<PostReply> storedReplies = storedSone.getReplies();
1125 synchronized (knownReplies) {
1126 for (PostReply reply : sone.getReplies()) {
1127 reply.setSone(storedSone).setKnown(knownReplies.contains(reply.getId()));
1128 if (!storedReplies.contains(reply)) {
1129 if (reply.getTime() < getSoneFollowingTime(sone)) {
1130 knownReplies.add(reply.getId());
1131 } else if (!knownReplies.contains(reply.getId())) {
1132 reply.setKnown(false);
1133 coreListenerManager.fireNewReplyFound(reply);
1136 replies.put(reply.getId(), reply);
1140 synchronized (albums) {
1141 synchronized (images) {
1142 for (Album album : storedSone.getAlbums()) {
1143 albums.remove(album.getId());
1144 for (Image image : album.getImages()) {
1145 images.remove(image.getId());
1148 for (Album album : sone.getAlbums()) {
1149 albums.put(album.getId(), album);
1150 for (Image image : album.getImages()) {
1151 images.put(image.getId(), image);
1156 synchronized (storedSone) {
1157 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1158 storedSone.setTime(sone.getTime());
1160 storedSone.setClient(sone.getClient());
1161 storedSone.setProfile(sone.getProfile());
1162 if (soneRescueMode) {
1163 for (Post post : sone.getPosts()) {
1164 storedSone.addPost(post);
1166 for (PostReply reply : sone.getReplies()) {
1167 storedSone.addReply(reply);
1169 for (String likedPostId : sone.getLikedPostIds()) {
1170 storedSone.addLikedPostId(likedPostId);
1172 for (String likedReplyId : sone.getLikedReplyIds()) {
1173 storedSone.addLikedReplyId(likedReplyId);
1175 for (Album album : sone.getAlbums()) {
1176 storedSone.addAlbum(album);
1179 storedSone.setPosts(sone.getPosts());
1180 storedSone.setReplies(sone.getReplies());
1181 storedSone.setLikePostIds(sone.getLikedPostIds());
1182 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1183 storedSone.setAlbums(sone.getAlbums());
1185 storedSone.setLatestEdition(sone.getLatestEdition());
1191 * Deletes the given Sone. This will remove the Sone from the
1192 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1193 * and remove the context from its identity.
1196 * The Sone to delete
1198 public void deleteSone(Sone sone) {
1199 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1200 logger.log(Level.WARNING, String.format("Tried to delete Sone of non-own identity: %s", sone));
1203 if (!sone.isLocal()) {
1204 logger.log(Level.WARNING, String.format("Tried to delete non-local Sone: %s", sone));
1207 database.removeSone(sone.getId());
1208 SoneInserter soneInserter = soneInserters.remove(sone);
1209 soneInserter.removeSoneInsertListener(this);
1210 soneInserter.stop();
1212 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1213 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1214 } catch (WebOfTrustException wote1) {
1215 logger.log(Level.WARNING, String.format("Could not remove context and properties from Sone: %s", sone), wote1);
1218 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1219 } catch (ConfigurationException ce1) {
1220 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1225 * Marks the given Sone as known. If the Sone was not {@link Post#isKnown()
1226 * known} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1229 * The Sone to mark as known
1231 public void markSoneKnown(Sone sone) {
1232 if (!sone.isKnown()) {
1233 sone.setKnown(true);
1234 synchronized (knownSones) {
1235 knownSones.add(sone.getId());
1237 coreListenerManager.fireMarkSoneKnown(sone);
1238 touchConfiguration();
1243 * Loads and updates the given Sone from the configuration. If any error is
1244 * encountered, loading is aborted and the given Sone is not changed.
1247 * The Sone to load and update
1249 public void loadSone(Sone sone) {
1250 if (!sone.isLocal()) {
1251 logger.log(Level.FINE, String.format("Tried to load non-local Sone: %s", sone));
1255 /* initialize options. */
1256 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1257 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1258 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1259 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1260 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1261 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1264 String sonePrefix = "Sone/" + sone.getId();
1265 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1266 if (soneTime == null) {
1267 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1270 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1273 Profile profile = new Profile(sone);
1274 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1275 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1276 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1277 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1278 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1279 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1281 /* load profile fields. */
1283 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1284 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1285 if (fieldName == null) {
1288 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1289 profile.addField(fieldName).setValue(fieldValue);
1293 Set<Post> posts = new HashSet<Post>();
1295 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1296 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1297 if (postId == null) {
1300 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1301 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1302 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1303 if ((postTime == 0) || (postText == null)) {
1304 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1307 Post post = getPost(postId, true).setSone(sone).setTime(postTime).setText(postText);
1308 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1309 post.setRecipient(getSone(postRecipientId));
1315 Set<PostReply> replies = new HashSet<PostReply>();
1317 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1318 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1319 if (replyId == null) {
1322 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1323 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1324 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1325 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1326 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1329 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId, true)).setTime(replyTime).setText(replyText));
1332 /* load post likes. */
1333 Set<String> likedPostIds = new HashSet<String>();
1335 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1336 if (likedPostId == null) {
1339 likedPostIds.add(likedPostId);
1342 /* load reply likes. */
1343 Set<String> likedReplyIds = new HashSet<String>();
1345 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1346 if (likedReplyId == null) {
1349 likedReplyIds.add(likedReplyId);
1353 Set<String> friends = new HashSet<String>();
1355 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1356 if (friendId == null) {
1359 friends.add(friendId);
1363 List<Album> topLevelAlbums = new ArrayList<Album>();
1364 int albumCounter = 0;
1366 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1367 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1368 if (albumId == null) {
1371 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1372 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1373 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1374 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1375 if ((albumTitle == null) || (albumDescription == null)) {
1376 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1379 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1380 if (albumParentId != null) {
1381 Album parentAlbum = getAlbum(albumParentId, false);
1382 if (parentAlbum == null) {
1383 logger.log(Level.WARNING, String.format("Invalid parent album ID: %s", albumParentId));
1386 parentAlbum.addAlbum(album);
1388 if (!topLevelAlbums.contains(album)) {
1389 topLevelAlbums.add(album);
1395 int imageCounter = 0;
1397 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1398 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1399 if (imageId == null) {
1402 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1403 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1404 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1405 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1406 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1407 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1408 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1409 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1410 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1413 Album album = getAlbum(albumId, false);
1414 if (album == null) {
1415 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1418 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1419 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1420 album.addImage(image);
1424 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1425 if (avatarId != null) {
1426 profile.setAvatar(getImage(avatarId, false));
1430 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1431 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1432 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1433 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1434 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1435 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1437 /* if we’re still here, Sone was loaded successfully. */
1438 synchronized (sone) {
1439 sone.setTime(soneTime);
1440 sone.setProfile(profile);
1441 sone.setPosts(posts);
1442 sone.setReplies(replies);
1443 sone.setLikePostIds(likedPostIds);
1444 sone.setLikeReplyIds(likedReplyIds);
1445 for (String friendId : friends) {
1446 followSone(sone, friendId);
1448 sone.setAlbums(topLevelAlbums);
1449 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1451 synchronized (knownSones) {
1452 for (String friend : friends) {
1453 knownSones.add(friend);
1456 synchronized (knownPosts) {
1457 for (Post post : posts) {
1458 knownPosts.add(post.getId());
1461 synchronized (knownReplies) {
1462 for (PostReply reply : replies) {
1463 knownReplies.add(reply.getId());
1469 * Creates a new post.
1472 * The Sone that creates the post
1474 * The recipient Sone, or {@code null} if this post does not have
1477 * The time of the post
1479 * The text of the post
1480 * @return The created post
1482 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1483 if (!sone.isLocal()) {
1484 logger.log(Level.FINE, String.format("Tried to create post for non-local Sone: %s", sone));
1487 final Post post = new Post(sone, time, text);
1488 if (recipient != null) {
1489 post.setRecipient(recipient);
1491 synchronized (posts) {
1492 posts.put(post.getId(), post);
1494 coreListenerManager.fireNewPostFound(post);
1496 touchConfiguration();
1497 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1504 markPostKnown(post);
1506 }, "Mark " + post + " read.");
1511 * Deletes the given post.
1514 * The post to delete
1516 public void deletePost(Post post) {
1517 if (!post.getSone().isLocal()) {
1518 logger.log(Level.WARNING, String.format("Tried to delete post of non-local Sone: %s", post.getSone()));
1521 post.getSone().removePost(post);
1522 synchronized (posts) {
1523 posts.remove(post.getId());
1525 coreListenerManager.firePostRemoved(post);
1526 markPostKnown(post);
1527 touchConfiguration();
1531 * Marks the given post as known, if it is currently not a known post
1532 * (according to {@link Post#isKnown()}).
1535 * The post to mark as known
1537 public void markPostKnown(Post post) {
1538 post.setKnown(true);
1539 synchronized (knownPosts) {
1540 coreListenerManager.fireMarkPostKnown(post);
1541 if (knownPosts.add(post.getId())) {
1542 touchConfiguration();
1545 for (PostReply reply : getReplies(post)) {
1546 markReplyKnown(reply);
1551 * Bookmarks the given post.
1554 * The post to bookmark
1556 public void bookmark(Post post) {
1557 bookmarkPost(post.getId());
1561 * Bookmarks the post with the given ID.
1564 * The ID of the post to bookmark
1566 public void bookmarkPost(String id) {
1567 synchronized (bookmarkedPosts) {
1568 bookmarkedPosts.add(id);
1573 * Removes the given post from the bookmarks.
1576 * The post to unbookmark
1578 public void unbookmark(Post post) {
1579 unbookmarkPost(post.getId());
1583 * Removes the post with the given ID from the bookmarks.
1586 * The ID of the post to unbookmark
1588 public void unbookmarkPost(String id) {
1589 synchronized (bookmarkedPosts) {
1590 bookmarkedPosts.remove(id);
1595 * Creates a new reply.
1598 * The Sone that creates the reply
1600 * The post that this reply refers to
1602 * The text of the reply
1603 * @return The created reply
1605 public PostReply createReply(Sone sone, Post post, String text) {
1606 return createReply(sone, post, System.currentTimeMillis(), text);
1610 * Creates a new reply.
1613 * The Sone that creates the reply
1615 * The post that this reply refers to
1617 * The time of the reply
1619 * The text of the reply
1620 * @return The created reply
1622 public PostReply createReply(Sone sone, Post post, long time, String text) {
1623 if (!sone.isLocal()) {
1624 logger.log(Level.FINE, String.format("Tried to create reply for non-local Sone: %s", sone));
1627 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1628 synchronized (replies) {
1629 replies.put(reply.getId(), reply);
1631 synchronized (knownReplies) {
1632 coreListenerManager.fireNewReplyFound(reply);
1634 sone.addReply(reply);
1635 touchConfiguration();
1636 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1643 markReplyKnown(reply);
1645 }, "Mark " + reply + " read.");
1650 * Deletes the given reply.
1653 * The reply to delete
1655 public void deleteReply(PostReply reply) {
1656 Sone sone = reply.getSone();
1657 if (!sone.isLocal()) {
1658 logger.log(Level.FINE, String.format("Tried to delete non-local reply: %s", reply));
1661 synchronized (replies) {
1662 replies.remove(reply.getId());
1664 synchronized (knownReplies) {
1665 markReplyKnown(reply);
1666 knownReplies.remove(reply.getId());
1668 sone.removeReply(reply);
1669 touchConfiguration();
1673 * Marks the given reply as known, if it is currently not a known reply
1674 * (according to {@link Reply#isKnown()}).
1677 * The reply to mark as known
1679 public void markReplyKnown(PostReply reply) {
1680 reply.setKnown(true);
1681 synchronized (knownReplies) {
1682 coreListenerManager.fireMarkReplyKnown(reply);
1683 if (knownReplies.add(reply.getId())) {
1684 touchConfiguration();
1690 * Creates a new top-level album for the given Sone.
1693 * The Sone to create the album for
1694 * @return The new album
1696 public Album createAlbum(Sone sone) {
1697 return createAlbum(sone, null);
1701 * Creates a new album for the given Sone.
1704 * The Sone to create the album for
1706 * The parent of the album (may be {@code null} to create a
1708 * @return The new album
1710 public Album createAlbum(Sone sone, Album parent) {
1711 Album album = new Album();
1712 synchronized (albums) {
1713 albums.put(album.getId(), album);
1715 album.setSone(sone);
1716 if (parent != null) {
1717 parent.addAlbum(album);
1719 sone.addAlbum(album);
1725 * Deletes the given album. The owner of the album has to be a local Sone,
1726 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1729 * The album to remove
1731 public void deleteAlbum(Album album) {
1732 Validation.begin().isNotNull("Album", album).check().is("Local Sone", album.getSone().isLocal()).check();
1733 if (!album.isEmpty()) {
1736 if (album.getParent() == null) {
1737 album.getSone().removeAlbum(album);
1739 album.getParent().removeAlbum(album);
1741 synchronized (albums) {
1742 albums.remove(album.getId());
1744 saveSone(album.getSone());
1748 * Creates a new image.
1751 * The Sone creating the image
1753 * The album the image will be inserted into
1754 * @param temporaryImage
1755 * The temporary image to create the image from
1756 * @return The newly created image
1758 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1759 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();
1760 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1761 album.addImage(image);
1762 synchronized (images) {
1763 images.put(image.getId(), image);
1765 imageInserter.insertImage(temporaryImage, image);
1770 * Deletes the given image. This method will also delete a matching
1773 * @see #deleteTemporaryImage(TemporaryImage)
1775 * The image to delete
1777 public void deleteImage(Image image) {
1778 Validation.begin().isNotNull("Image", image).check().is("Local Sone", image.getSone().isLocal()).check();
1779 deleteTemporaryImage(image.getId());
1780 image.getAlbum().removeImage(image);
1781 synchronized (images) {
1782 images.remove(image.getId());
1784 saveSone(image.getSone());
1788 * Creates a new temporary image.
1791 * The MIME type of the temporary image
1793 * The encoded data of the image
1794 * @return The temporary image
1796 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
1797 TemporaryImage temporaryImage = new TemporaryImage();
1798 temporaryImage.setMimeType(mimeType).setImageData(imageData);
1799 synchronized (temporaryImages) {
1800 temporaryImages.put(temporaryImage.getId(), temporaryImage);
1802 return temporaryImage;
1806 * Deletes the given temporary image.
1808 * @param temporaryImage
1809 * The temporary image to delete
1811 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
1812 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
1813 deleteTemporaryImage(temporaryImage.getId());
1817 * Deletes the temporary image with the given ID.
1820 * The ID of the temporary image to delete
1822 public void deleteTemporaryImage(String imageId) {
1823 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
1824 synchronized (temporaryImages) {
1825 temporaryImages.remove(imageId);
1827 Image image = getImage(imageId, false);
1828 if (image != null) {
1829 imageInserter.cancelImageInsert(image);
1834 * Notifies the core that the configuration, either of the core or of a
1835 * single local Sone, has changed, and that the configuration should be
1838 public void touchConfiguration() {
1839 lastConfigurationUpdate = System.currentTimeMillis();
1850 public void serviceStart() {
1851 loadConfiguration();
1852 updateChecker.addUpdateListener(this);
1853 updateChecker.start();
1860 public void serviceRun() {
1861 long lastSaved = System.currentTimeMillis();
1862 while (!shouldStop()) {
1864 long now = System.currentTimeMillis();
1865 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
1866 for (Sone localSone : getLocalSones()) {
1867 saveSone(localSone);
1869 saveConfiguration();
1879 public void serviceStop() {
1880 for (SoneInserter soneInserter : soneInserters.values()) {
1881 soneInserter.removeSoneInsertListener(this);
1882 soneInserter.stop();
1884 updateChecker.stop();
1885 updateChecker.removeUpdateListener(this);
1886 soneDownloader.stop();
1894 * Saves the given Sone. This will persist all local settings for the given
1895 * Sone, such as the friends list and similar, private options.
1900 private synchronized void saveSone(Sone sone) {
1901 if (!sone.isLocal()) {
1902 logger.log(Level.FINE, String.format("Tried to save non-local Sone: %s", sone));
1905 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1906 logger.log(Level.WARNING, String.format("Local Sone without OwnIdentity found, refusing to save: %s", sone));
1910 logger.log(Level.INFO, String.format("Saving Sone: %s", sone));
1912 /* save Sone into configuration. */
1913 String sonePrefix = "Sone/" + sone.getId();
1914 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
1915 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
1918 Profile profile = sone.getProfile();
1919 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
1920 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
1921 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
1922 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
1923 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
1924 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
1925 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
1927 /* save profile fields. */
1928 int fieldCounter = 0;
1929 for (Field profileField : profile.getFields()) {
1930 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
1931 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
1932 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
1934 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
1937 int postCounter = 0;
1938 for (Post post : sone.getPosts()) {
1939 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
1940 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
1941 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
1942 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
1943 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
1945 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
1948 int replyCounter = 0;
1949 for (PostReply reply : sone.getReplies()) {
1950 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
1951 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
1952 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
1953 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
1954 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
1956 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
1958 /* save post likes. */
1959 int postLikeCounter = 0;
1960 for (String postId : sone.getLikedPostIds()) {
1961 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
1963 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
1965 /* save reply likes. */
1966 int replyLikeCounter = 0;
1967 for (String replyId : sone.getLikedReplyIds()) {
1968 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
1970 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
1973 int friendCounter = 0;
1974 for (String friendId : sone.getFriends()) {
1975 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
1977 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
1979 /* save albums. first, collect in a flat structure, top-level first. */
1980 List<Album> albums = sone.getAllAlbums();
1982 int albumCounter = 0;
1983 for (Album album : albums) {
1984 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1985 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
1986 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
1987 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
1988 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
1989 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
1991 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
1994 int imageCounter = 0;
1995 for (Album album : albums) {
1996 for (Image image : album.getImages()) {
1997 if (!image.isInserted()) {
2000 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2001 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2002 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2003 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2004 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2005 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2006 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2007 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2008 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2011 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2014 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2015 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2016 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2017 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2018 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2019 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2021 configuration.save();
2023 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2025 logger.log(Level.INFO, String.format("Sone %s saved.", sone));
2026 } catch (ConfigurationException ce1) {
2027 logger.log(Level.WARNING, String.format("Could not save Sone: %s", sone), ce1);
2028 } catch (WebOfTrustException wote1) {
2029 logger.log(Level.WARNING, String.format("Could not set WoT property for Sone: %s", sone), wote1);
2034 * Saves the current options.
2036 private void saveConfiguration() {
2037 synchronized (configuration) {
2038 if (storingConfiguration) {
2039 logger.log(Level.FINE, "Already storing configuration…");
2042 storingConfiguration = true;
2045 /* store the options first. */
2047 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2048 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2049 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2050 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2051 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2052 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2053 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2054 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2055 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2056 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2057 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2058 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2059 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2060 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2062 /* save known Sones. */
2063 int soneCounter = 0;
2064 synchronized (knownSones) {
2065 for (String knownSoneId : knownSones) {
2066 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2068 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2071 /* save Sone following times. */
2073 synchronized (soneFollowingTimes) {
2074 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2075 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2076 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2079 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2082 /* save known posts. */
2083 int postCounter = 0;
2084 synchronized (knownPosts) {
2085 for (String knownPostId : knownPosts) {
2086 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2088 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2091 /* save known replies. */
2092 int replyCounter = 0;
2093 synchronized (knownReplies) {
2094 for (String knownReplyId : knownReplies) {
2095 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2097 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2100 /* save bookmarked posts. */
2101 int bookmarkedPostCounter = 0;
2102 synchronized (bookmarkedPosts) {
2103 for (String bookmarkedPostId : bookmarkedPosts) {
2104 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2107 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2110 configuration.save();
2112 } catch (ConfigurationException ce1) {
2113 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2115 synchronized (configuration) {
2116 storingConfiguration = false;
2122 * Loads the configuration.
2124 @SuppressWarnings("unchecked")
2125 private void loadConfiguration() {
2126 /* create options. */
2127 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2130 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2131 SoneInserter.setInsertionDelay(newValue);
2135 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2136 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2137 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2138 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2139 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2140 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2141 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2142 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2145 @SuppressWarnings("synthetic-access")
2146 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2147 fcpInterface.setActive(newValue);
2150 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2153 @SuppressWarnings("synthetic-access")
2154 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2155 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2159 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2160 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2161 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2163 /* read options from configuration. */
2164 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2165 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2166 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2167 options.getBooleanOption("ClearOnNextRestart").set(null);
2168 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2169 if (clearConfiguration) {
2170 /* stop loading the configuration. */
2174 loadConfigurationValue("InsertionDelay");
2175 loadConfigurationValue("PostsPerPage");
2176 loadConfigurationValue("CharactersPerPost");
2177 loadConfigurationValue("PostCutOffLength");
2178 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2179 loadConfigurationValue("PositiveTrust");
2180 loadConfigurationValue("NegativeTrust");
2181 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2182 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2183 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2184 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2186 /* load known Sones. */
2187 int soneCounter = 0;
2189 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2190 if (knownSoneId == null) {
2193 synchronized (knownSones) {
2194 knownSones.add(knownSoneId);
2198 /* load Sone following times. */
2201 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2202 if (soneId == null) {
2205 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2206 Sone followedSone = getSone(soneId);
2207 if (followedSone == null) {
2208 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2210 synchronized (soneFollowingTimes) {
2211 soneFollowingTimes.put(getSone(soneId), time);
2217 /* load known posts. */
2218 int postCounter = 0;
2220 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2221 if (knownPostId == null) {
2224 synchronized (knownPosts) {
2225 knownPosts.add(knownPostId);
2229 /* load known replies. */
2230 int replyCounter = 0;
2232 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2233 if (knownReplyId == null) {
2236 synchronized (knownReplies) {
2237 knownReplies.add(knownReplyId);
2241 /* load bookmarked posts. */
2242 int bookmarkedPostCounter = 0;
2244 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2245 if (bookmarkedPostId == null) {
2248 synchronized (bookmarkedPosts) {
2249 bookmarkedPosts.add(bookmarkedPostId);
2256 * Loads an {@link Integer} configuration value for the option with the
2257 * given name, logging validation failures.
2260 * The name of the option to load
2262 private void loadConfigurationValue(String optionName) {
2264 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2265 } catch (IllegalArgumentException iae1) {
2266 logger.log(Level.WARNING, String.format("Invalid value for %s in configuration, using default.", optionName));
2271 * Generate a Sone URI from the given URI and latest edition.
2274 * The URI to derive the Sone URI from
2275 * @return The derived URI
2277 private FreenetURI getSoneUri(String uriString) {
2279 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2281 } catch (MalformedURLException mue1) {
2282 logger.log(Level.WARNING, String.format("Could not create Sone URI from URI: %s", uriString, mue1));
2288 // INTERFACE IdentityListener
2295 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2296 logger.log(Level.FINEST, String.format("Adding OwnIdentity: %s", ownIdentity));
2297 if (ownIdentity.hasContext("Sone")) {
2298 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2299 addLocalSone(ownIdentity);
2307 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2308 logger.log(Level.FINEST, String.format("Removing OwnIdentity: %s", ownIdentity));
2309 trustedIdentities.remove(ownIdentity);
2316 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2317 logger.log(Level.FINEST, String.format("Adding Identity: %s", identity));
2318 trustedIdentities.get(ownIdentity).add(identity);
2319 addRemoteSone(identity);
2326 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2327 new Thread(new Runnable() {
2330 @SuppressWarnings("synthetic-access")
2332 Sone sone = getRemoteSone(identity.getId(), false);
2333 sone.setIdentity(identity);
2334 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2335 soneDownloader.addSone(sone);
2336 soneDownloader.fetchSone(sone);
2345 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2346 trustedIdentities.get(ownIdentity).remove(identity);
2347 boolean foundIdentity = false;
2348 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2349 if (trustedIdentity.getKey().equals(ownIdentity)) {
2352 if (trustedIdentity.getValue().contains(identity)) {
2353 foundIdentity = true;
2356 if (foundIdentity) {
2357 /* some local identity still trusts this identity, don’t remove. */
2360 Sone sone = getSone(identity.getId(), false);
2362 /* TODO - we don’t have the Sone anymore. should this happen? */
2365 synchronized (posts) {
2366 synchronized (knownPosts) {
2367 for (Post post : sone.getPosts()) {
2368 posts.remove(post.getId());
2369 coreListenerManager.firePostRemoved(post);
2373 synchronized (replies) {
2374 synchronized (knownReplies) {
2375 for (PostReply reply : sone.getReplies()) {
2376 replies.remove(reply.getId());
2377 coreListenerManager.fireReplyRemoved(reply);
2381 database.removeSone(identity.getId());
2382 coreListenerManager.fireSoneRemoved(sone);
2386 // INTERFACE UpdateListener
2393 public void updateFound(Version version, long releaseTime, long latestEdition) {
2394 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2398 // INTERFACE ImageInsertListener
2405 public void insertStarted(Sone sone) {
2406 coreListenerManager.fireSoneInserting(sone);
2413 public void insertFinished(Sone sone, long insertDuration) {
2414 coreListenerManager.fireSoneInserted(sone, insertDuration);
2421 public void insertAborted(Sone sone, Throwable cause) {
2422 coreListenerManager.fireSoneInsertAborted(sone, cause);
2426 // SONEINSERTLISTENER METHODS
2433 public void imageInsertStarted(Image image) {
2434 logger.log(Level.WARNING, String.format("Image insert started for %s...", image));
2435 coreListenerManager.fireImageInsertStarted(image);
2442 public void imageInsertAborted(Image image) {
2443 logger.log(Level.WARNING, String.format("Image insert aborted for %s.", image));
2444 coreListenerManager.fireImageInsertAborted(image);
2451 public void imageInsertFinished(Image image, FreenetURI key) {
2452 logger.log(Level.WARNING, String.format("Image insert finished for %s: %s", image, key));
2453 image.setKey(key.toString());
2454 deleteTemporaryImage(image.getId());
2455 saveSone(image.getSone());
2456 coreListenerManager.fireImageInsertFinished(image);
2463 public void imageInsertFailed(Image image, Throwable cause) {
2464 logger.log(Level.WARNING, String.format("Image insert failed for %s." + image), cause);
2465 coreListenerManager.fireImageInsertFailed(image, cause);
2469 * Convenience interface for external classes that want to access the core’s
2472 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2474 public static class Preferences {
2476 /** The wrapped options. */
2477 private final Options options;
2480 * Creates a new preferences object wrapped around the given options.
2483 * The options to wrap
2485 public Preferences(Options options) {
2486 this.options = options;
2490 * Returns the insertion delay.
2492 * @return The insertion delay
2494 public int getInsertionDelay() {
2495 return options.getIntegerOption("InsertionDelay").get();
2499 * Validates the given insertion delay.
2501 * @param insertionDelay
2502 * The insertion delay to validate
2503 * @return {@code true} if the given insertion delay was valid,
2504 * {@code false} otherwise
2506 public boolean validateInsertionDelay(Integer insertionDelay) {
2507 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2511 * Sets the insertion delay
2513 * @param insertionDelay
2514 * The new insertion delay, or {@code null} to restore it to
2516 * @return This preferences
2518 public Preferences setInsertionDelay(Integer insertionDelay) {
2519 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2524 * Returns the number of posts to show per page.
2526 * @return The number of posts to show per page
2528 public int getPostsPerPage() {
2529 return options.getIntegerOption("PostsPerPage").get();
2533 * Validates the number of posts per page.
2535 * @param postsPerPage
2536 * The number of posts per page
2537 * @return {@code true} if the number of posts per page was valid,
2538 * {@code false} otherwise
2540 public boolean validatePostsPerPage(Integer postsPerPage) {
2541 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2545 * Sets the number of posts to show per page.
2547 * @param postsPerPage
2548 * The number of posts to show per page
2549 * @return This preferences object
2551 public Preferences setPostsPerPage(Integer postsPerPage) {
2552 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2557 * Returns the number of characters per post, or <code>-1</code> if the
2558 * posts should not be cut off.
2560 * @return The numbers of characters per post
2562 public int getCharactersPerPost() {
2563 return options.getIntegerOption("CharactersPerPost").get();
2567 * Validates the number of characters per post.
2569 * @param charactersPerPost
2570 * The number of characters per post
2571 * @return {@code true} if the number of characters per post was valid,
2572 * {@code false} otherwise
2574 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2575 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2579 * Sets the number of characters per post.
2581 * @param charactersPerPost
2582 * The number of characters per post, or <code>-1</code> to
2583 * not cut off the posts
2584 * @return This preferences objects
2586 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2587 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);
2592 * Returns the number of characters the shortened post should have.
2594 * @return The number of characters of the snippet
2596 public int getPostCutOffLength() {
2597 return options.getIntegerOption("PostCutOffLength").get();
2601 * Validates the number of characters after which to cut off the post.
2603 * @param postCutOffLength
2604 * The number of characters of the snippet
2605 * @return {@code true} if the number of characters of the snippet is
2606 * valid, {@code false} otherwise
2608 public boolean validatePostCutOffLength(Integer postCutOffLength) {
2609 return options.getIntegerOption("PostCutOffLength").validate(postCutOffLength);
2613 * Sets the number of characters the shortened post should have.
2615 * @param postCutOffLength
2616 * The number of characters of the snippet
2617 * @return This preferences
2619 public Preferences setPostCutOffLength(Integer postCutOffLength) {
2620 options.getIntegerOption("PostCutOffLength").set(postCutOffLength);
2625 * Returns whether Sone requires full access to be even visible.
2627 * @return {@code true} if Sone requires full access, {@code false}
2630 public boolean isRequireFullAccess() {
2631 return options.getBooleanOption("RequireFullAccess").get();
2635 * Sets whether Sone requires full access to be even visible.
2637 * @param requireFullAccess
2638 * {@code true} if Sone requires full access, {@code false}
2641 public void setRequireFullAccess(Boolean requireFullAccess) {
2642 options.getBooleanOption("RequireFullAccess").set(requireFullAccess);
2646 * Returns the positive trust.
2648 * @return The positive trust
2650 public int getPositiveTrust() {
2651 return options.getIntegerOption("PositiveTrust").get();
2655 * Validates the positive trust.
2657 * @param positiveTrust
2658 * The positive trust to validate
2659 * @return {@code true} if the positive trust was valid, {@code false}
2662 public boolean validatePositiveTrust(Integer positiveTrust) {
2663 return options.getIntegerOption("PositiveTrust").validate(positiveTrust);
2667 * Sets the positive trust.
2669 * @param positiveTrust
2670 * The new positive trust, or {@code null} to restore it to
2672 * @return This preferences
2674 public Preferences setPositiveTrust(Integer positiveTrust) {
2675 options.getIntegerOption("PositiveTrust").set(positiveTrust);
2680 * Returns the negative trust.
2682 * @return The negative trust
2684 public int getNegativeTrust() {
2685 return options.getIntegerOption("NegativeTrust").get();
2689 * Validates the negative trust.
2691 * @param negativeTrust
2692 * The negative trust to validate
2693 * @return {@code true} if the negative trust was valid, {@code false}
2696 public boolean validateNegativeTrust(Integer negativeTrust) {
2697 return options.getIntegerOption("NegativeTrust").validate(negativeTrust);
2701 * Sets the negative trust.
2703 * @param negativeTrust
2704 * The negative trust, or {@code null} to restore it to the
2706 * @return The preferences
2708 public Preferences setNegativeTrust(Integer negativeTrust) {
2709 options.getIntegerOption("NegativeTrust").set(negativeTrust);
2714 * Returns the trust comment. This is the comment that is set in the web
2715 * of trust when a trust value is assigned to an identity.
2717 * @return The trust comment
2719 public String getTrustComment() {
2720 return options.getStringOption("TrustComment").get();
2724 * Sets the trust comment.
2726 * @param trustComment
2727 * The trust comment, or {@code null} to restore it to the
2729 * @return This preferences
2731 public Preferences setTrustComment(String trustComment) {
2732 options.getStringOption("TrustComment").set(trustComment);
2737 * Returns whether the {@link FcpInterface FCP interface} is currently
2740 * @see FcpInterface#setActive(boolean)
2741 * @return {@code true} if the FCP interface is currently active,
2742 * {@code false} otherwise
2744 public boolean isFcpInterfaceActive() {
2745 return options.getBooleanOption("ActivateFcpInterface").get();
2749 * Sets whether the {@link FcpInterface FCP interface} is currently
2752 * @see FcpInterface#setActive(boolean)
2753 * @param fcpInterfaceActive
2754 * {@code true} to activate the FCP interface, {@code false}
2755 * to deactivate the FCP interface
2756 * @return This preferences object
2758 public Preferences setFcpInterfaceActive(boolean fcpInterfaceActive) {
2759 options.getBooleanOption("ActivateFcpInterface").set(fcpInterfaceActive);
2764 * Returns the action level for which full access to the FCP interface
2767 * @return The action level for which full access to the FCP interface
2770 public FullAccessRequired getFcpFullAccessRequired() {
2771 return FullAccessRequired.values()[options.getIntegerOption("FcpFullAccessRequired").get()];
2775 * Sets the action level for which full access to the FCP interface is
2778 * @param fcpFullAccessRequired
2780 * @return This preferences
2782 public Preferences setFcpFullAccessRequired(FullAccessRequired fcpFullAccessRequired) {
2783 options.getIntegerOption("FcpFullAccessRequired").set((fcpFullAccessRequired != null) ? fcpFullAccessRequired.ordinal() : null);
2788 * Returns whether Sone should clear its settings on the next restart.
2789 * In order to be effective, {@link #isReallyClearOnNextRestart()} needs
2790 * to return {@code true} as well!
2792 * @return {@code true} if Sone should clear its settings on the next
2793 * restart, {@code false} otherwise
2795 public boolean isClearOnNextRestart() {
2796 return options.getBooleanOption("ClearOnNextRestart").get();
2800 * Sets whether Sone will clear its settings on the next restart.
2802 * @param clearOnNextRestart
2803 * {@code true} if Sone should clear its settings on the next
2804 * restart, {@code false} otherwise
2805 * @return This preferences
2807 public Preferences setClearOnNextRestart(Boolean clearOnNextRestart) {
2808 options.getBooleanOption("ClearOnNextRestart").set(clearOnNextRestart);
2813 * Returns whether Sone should really clear its settings on next
2814 * restart. This is a confirmation option that needs to be set in
2815 * addition to {@link #isClearOnNextRestart()} in order to clear Sone’s
2816 * settings on the next restart.
2818 * @return {@code true} if Sone should really clear its settings on the
2819 * next restart, {@code false} otherwise
2821 public boolean isReallyClearOnNextRestart() {
2822 return options.getBooleanOption("ReallyClearOnNextRestart").get();
2826 * Sets whether Sone should really clear its settings on the next
2829 * @param reallyClearOnNextRestart
2830 * {@code true} if Sone should really clear its settings on
2831 * the next restart, {@code false} otherwise
2832 * @return This preferences
2834 public Preferences setReallyClearOnNextRestart(Boolean reallyClearOnNextRestart) {
2835 options.getBooleanOption("ReallyClearOnNextRestart").set(reallyClearOnNextRestart);