2 * Sone - Core.java - Copyright © 2010 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.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Executors;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.Options.DefaultOption;
35 import net.pterodactylus.sone.core.Options.Option;
36 import net.pterodactylus.sone.core.Options.OptionWatcher;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Client;
39 import net.pterodactylus.sone.data.Image;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.PostReply;
42 import net.pterodactylus.sone.data.Profile;
43 import net.pterodactylus.sone.data.Reply;
44 import net.pterodactylus.sone.data.Sone;
45 import net.pterodactylus.sone.data.Sone.ShowCustomAvatars;
46 import net.pterodactylus.sone.data.TemporaryImage;
47 import net.pterodactylus.sone.data.Profile.Field;
48 import net.pterodactylus.sone.fcp.FcpInterface;
49 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
50 import net.pterodactylus.sone.freenet.wot.Identity;
51 import net.pterodactylus.sone.freenet.wot.IdentityListener;
52 import net.pterodactylus.sone.freenet.wot.IdentityManager;
53 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
54 import net.pterodactylus.sone.freenet.wot.Trust;
55 import net.pterodactylus.sone.freenet.wot.WebOfTrustException;
56 import net.pterodactylus.sone.main.SonePlugin;
57 import net.pterodactylus.util.config.Configuration;
58 import net.pterodactylus.util.config.ConfigurationException;
59 import net.pterodactylus.util.logging.Logging;
60 import net.pterodactylus.util.number.Numbers;
61 import net.pterodactylus.util.service.AbstractService;
62 import net.pterodactylus.util.thread.Ticker;
63 import net.pterodactylus.util.validation.EqualityValidator;
64 import net.pterodactylus.util.validation.IntegerRangeValidator;
65 import net.pterodactylus.util.validation.OrValidator;
66 import net.pterodactylus.util.validation.Validation;
67 import net.pterodactylus.util.version.Version;
68 import freenet.keys.FreenetURI;
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class Core extends AbstractService implements IdentityListener, UpdateListener, SoneProvider, PostProvider, SoneInsertListener, ImageInsertListener {
78 * Enumeration for the possible states of a {@link Sone}.
80 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82 public enum SoneStatus {
84 /** The Sone is unknown, i.e. not yet downloaded. */
87 /** The Sone is idle, i.e. not being downloaded or inserted. */
90 /** The Sone is currently being inserted. */
93 /** The Sone is currently being downloaded. */
98 private static final Logger logger = Logging.getLogger(Core.class);
101 private final Options options = new Options();
103 /** The preferences. */
104 private final Preferences preferences = new Preferences(options);
106 /** The core listener manager. */
107 private final CoreListenerManager coreListenerManager = new CoreListenerManager(this);
109 /** The configuration. */
110 private Configuration configuration;
112 /** Whether we’re currently saving the configuration. */
113 private boolean storingConfiguration = false;
115 /** The identity manager. */
116 private final IdentityManager identityManager;
118 /** Interface to freenet. */
119 private final FreenetInterface freenetInterface;
121 /** The Sone downloader. */
122 private final SoneDownloader soneDownloader;
124 /** The image inserter. */
125 private final ImageInserter imageInserter;
127 /** Sone downloader thread-pool. */
128 private final ExecutorService soneDownloaders = Executors.newFixedThreadPool(10);
130 /** The update checker. */
131 private final UpdateChecker updateChecker;
133 /** The FCP interface. */
134 private volatile FcpInterface fcpInterface;
136 /** The Sones’ statuses. */
137 /* synchronize access on itself. */
138 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
140 /** The times Sones were followed. */
141 private final Map<Sone, Long> soneFollowingTimes = new HashMap<Sone, Long>();
143 /** Locked local Sones. */
144 /* synchronize on itself. */
145 private final Set<Sone> lockedSones = new HashSet<Sone>();
147 /** Sone inserters. */
148 /* synchronize access on this on localSones. */
149 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
151 /** Sone rescuers. */
152 /* synchronize access on this on localSones. */
153 private final Map<Sone, SoneRescuer> soneRescuers = new HashMap<Sone, SoneRescuer>();
155 /** All local Sones. */
156 /* synchronize access on this on itself. */
157 private Map<String, Sone> localSones = new HashMap<String, Sone>();
159 /** All remote Sones. */
160 /* synchronize access on this on itself. */
161 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
163 /** All new Sones. */
164 private Set<String> newSones = new HashSet<String>();
166 /** All known Sones. */
167 /* synchronize access on {@link #newSones}. */
168 private Set<String> knownSones = new HashSet<String>();
171 private Map<String, Post> posts = new HashMap<String, Post>();
173 /** All new posts. */
174 private Set<String> newPosts = new HashSet<String>();
176 /** All known posts. */
177 /* synchronize access on {@link #newPosts}. */
178 private Set<String> knownPosts = new HashSet<String>();
181 private Map<String, PostReply> replies = new HashMap<String, PostReply>();
183 /** All new replies. */
184 private Set<String> newReplies = new HashSet<String>();
186 /** All known replies. */
187 private Set<String> knownReplies = new HashSet<String>();
189 /** All bookmarked posts. */
190 /* synchronize access on itself. */
191 private Set<String> bookmarkedPosts = new HashSet<String>();
193 /** Trusted identities, sorted by own identities. */
194 private Map<OwnIdentity, Set<Identity>> trustedIdentities = Collections.synchronizedMap(new HashMap<OwnIdentity, Set<Identity>>());
196 /** All known albums. */
197 private Map<String, Album> albums = new HashMap<String, Album>();
199 /** All known images. */
200 private Map<String, Image> images = new HashMap<String, Image>();
202 /** All temporary images. */
203 private Map<String, TemporaryImage> temporaryImages = new HashMap<String, TemporaryImage>();
205 /** Ticker for threads that mark own elements as known. */
206 private Ticker localElementTicker = new Ticker();
208 /** The time the configuration was last touched. */
209 private volatile long lastConfigurationUpdate;
212 * Creates a new core.
214 * @param configuration
215 * The configuration of the core
216 * @param freenetInterface
217 * The freenet interface
218 * @param identityManager
219 * The identity manager
221 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
223 this.configuration = configuration;
224 this.freenetInterface = freenetInterface;
225 this.identityManager = identityManager;
226 this.soneDownloader = new SoneDownloader(this, freenetInterface);
227 this.imageInserter = new ImageInserter(this, freenetInterface);
228 this.updateChecker = new UpdateChecker(freenetInterface);
232 // LISTENER MANAGEMENT
236 * Adds a new core listener.
238 * @param coreListener
239 * The listener to add
241 public void addCoreListener(CoreListener coreListener) {
242 coreListenerManager.addListener(coreListener);
246 * Removes a core listener.
248 * @param coreListener
249 * The listener to remove
251 public void removeCoreListener(CoreListener coreListener) {
252 coreListenerManager.removeListener(coreListener);
260 * Sets the configuration to use. This will automatically save the current
261 * configuration to the given configuration.
263 * @param configuration
264 * The new configuration to use
266 public void setConfiguration(Configuration configuration) {
267 this.configuration = configuration;
268 touchConfiguration();
272 * Returns the options used by the core.
274 * @return The options of the core
276 public Preferences getPreferences() {
281 * Returns the identity manager used by the core.
283 * @return The identity manager
285 public IdentityManager getIdentityManager() {
286 return identityManager;
290 * Returns the update checker.
292 * @return The update checker
294 public UpdateChecker getUpdateChecker() {
295 return updateChecker;
299 * Sets the FCP interface to use.
301 * @param fcpInterface
302 * The FCP interface to use
304 public void setFcpInterface(FcpInterface fcpInterface) {
305 this.fcpInterface = fcpInterface;
309 * Returns the status of the given Sone.
312 * The Sone to get the status for
313 * @return The status of the Sone
315 public SoneStatus getSoneStatus(Sone sone) {
316 synchronized (soneStatuses) {
317 return soneStatuses.get(sone);
322 * Sets the status of the given Sone.
325 * The Sone to set the status of
329 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
330 synchronized (soneStatuses) {
331 soneStatuses.put(sone, soneStatus);
336 * Returns the Sone rescuer for the given local Sone.
339 * The local Sone to get the rescuer for
340 * @return The Sone rescuer for the given Sone
342 public SoneRescuer getSoneRescuer(Sone sone) {
343 Validation.begin().isNotNull("Sone", sone).check().is("Local Sone", isLocalSone(sone)).check();
344 synchronized (localSones) {
345 SoneRescuer soneRescuer = soneRescuers.get(sone);
346 if (soneRescuer == null) {
347 soneRescuer = new SoneRescuer(this, soneDownloader, sone);
348 soneRescuers.put(sone, soneRescuer);
356 * Returns whether the given Sone is currently locked.
360 * @return {@code true} if the Sone is locked, {@code false} if it is not
362 public boolean isLocked(Sone sone) {
363 synchronized (lockedSones) {
364 return lockedSones.contains(sone);
369 * Returns all Sones, remote and local.
373 public Set<Sone> getSones() {
374 Set<Sone> allSones = new HashSet<Sone>();
375 allSones.addAll(getLocalSones());
376 allSones.addAll(getRemoteSones());
381 * Returns the Sone with the given ID, regardless whether it’s local or
385 * The ID of the Sone to get
386 * @return The Sone with the given ID, or {@code null} if there is no such
389 public Sone getSone(String id) {
390 return getSone(id, true);
394 * Returns the Sone with the given ID, regardless whether it’s local or
398 * The ID of the Sone to get
400 * {@code true} to create a new Sone if none exists,
401 * {@code false} to return {@code null} if a Sone with the given
403 * @return The Sone with the given ID, or {@code null} if there is no such
407 public Sone getSone(String id, boolean create) {
408 if (isLocalSone(id)) {
409 return getLocalSone(id);
411 return getRemoteSone(id, create);
415 * Checks whether the core knows a Sone with the given ID.
419 * @return {@code true} if there is a Sone with the given ID, {@code false}
422 public boolean hasSone(String id) {
423 return isLocalSone(id) || isRemoteSone(id);
427 * Returns whether the given Sone is a local Sone.
430 * The Sone to check for its locality
431 * @return {@code true} if the given Sone is local, {@code false} otherwise
433 public boolean isLocalSone(Sone sone) {
434 synchronized (localSones) {
435 return localSones.containsKey(sone.getId());
440 * Returns whether the given ID is the ID of a local Sone.
443 * The Sone ID to check for its locality
444 * @return {@code true} if the given ID is a local Sone, {@code false}
447 public boolean isLocalSone(String id) {
448 synchronized (localSones) {
449 return localSones.containsKey(id);
454 * Returns all local Sones.
456 * @return All local Sones
458 public Set<Sone> getLocalSones() {
459 synchronized (localSones) {
460 return new HashSet<Sone>(localSones.values());
465 * Returns the local Sone with the given ID.
468 * The ID of the Sone to get
469 * @return The Sone with the given ID
471 public Sone getLocalSone(String id) {
472 return getLocalSone(id, true);
476 * Returns the local Sone with the given ID, optionally creating a new Sone.
481 * {@code true} to create a new Sone if none exists,
482 * {@code false} to return null if none exists
483 * @return The Sone with the given ID, or {@code null}
485 public Sone getLocalSone(String id, boolean create) {
486 synchronized (localSones) {
487 Sone sone = localSones.get(id);
488 if ((sone == null) && create) {
490 localSones.put(id, sone);
491 setSoneStatus(sone, SoneStatus.unknown);
498 * Returns all remote Sones.
500 * @return All remote Sones
502 public Set<Sone> getRemoteSones() {
503 synchronized (remoteSones) {
504 return new HashSet<Sone>(remoteSones.values());
509 * Returns the remote Sone with the given ID.
512 * The ID of the remote Sone to get
514 * {@code true} to always create a Sone, {@code false} to return
515 * {@code null} if no Sone with the given ID exists
516 * @return The Sone with the given ID
518 public Sone getRemoteSone(String id, boolean create) {
519 synchronized (remoteSones) {
520 Sone sone = remoteSones.get(id);
521 if ((sone == null) && create && (id != null) && (id.length() == 43)) {
523 remoteSones.put(id, sone);
524 setSoneStatus(sone, SoneStatus.unknown);
531 * Returns whether the given Sone is a remote Sone.
535 * @return {@code true} if the given Sone is a remote Sone, {@code false}
538 public boolean isRemoteSone(Sone sone) {
539 synchronized (remoteSones) {
540 return remoteSones.containsKey(sone.getId());
545 * Returns whether the Sone with the given ID is a remote Sone.
548 * The ID of the Sone to check
549 * @return {@code true} if the Sone with the given ID is a remote Sone,
550 * {@code false} otherwise
552 public boolean isRemoteSone(String id) {
553 synchronized (remoteSones) {
554 return remoteSones.containsKey(id);
559 * Returns whether the Sone with the given ID is a new Sone.
562 * The ID of the sone to check for
563 * @return {@code true} if the given Sone is new, false otherwise
565 public boolean isNewSone(String soneId) {
566 synchronized (newSones) {
567 return !knownSones.contains(soneId) && newSones.contains(soneId);
572 * Returns whether the given Sone has been modified.
575 * The Sone to check for modifications
576 * @return {@code true} if a modification has been detected in the Sone,
577 * {@code false} otherwise
579 public boolean isModifiedSone(Sone sone) {
580 return (soneInserters.containsKey(sone)) ? soneInserters.get(sone).isModified() : false;
584 * Returns the time when the given was first followed by any local Sone.
587 * The Sone to get the time for
588 * @return The time (in milliseconds since Jan 1, 1970) the Sone has first
589 * been followed, or {@link Long#MAX_VALUE}
591 public long getSoneFollowingTime(Sone sone) {
592 synchronized (soneFollowingTimes) {
593 if (soneFollowingTimes.containsKey(sone)) {
594 return soneFollowingTimes.get(sone);
596 return Long.MAX_VALUE;
601 * Returns whether the target Sone is trusted by the origin Sone.
607 * @return {@code true} if the target Sone is trusted by the origin Sone
609 public boolean isSoneTrusted(Sone origin, Sone target) {
610 Validation.begin().isNotNull("Origin", origin).isNotNull("Target", target).check().isInstanceOf("Origin’s OwnIdentity", origin.getIdentity(), OwnIdentity.class).check();
611 return trustedIdentities.containsKey(origin.getIdentity()) && trustedIdentities.get(origin.getIdentity()).contains(target.getIdentity());
615 * Returns the post with the given ID.
618 * The ID of the post to get
619 * @return The post with the given ID, or a new post with the given ID
621 public Post getPost(String postId) {
622 return getPost(postId, true);
626 * Returns the post with the given ID, optionally creating a new post.
629 * The ID of the post to get
631 * {@code true} it create a new post if no post with the given ID
632 * exists, {@code false} to return {@code null}
633 * @return The post, or {@code null} if there is no such post
636 public Post getPost(String postId, boolean create) {
637 synchronized (posts) {
638 Post post = posts.get(postId);
639 if ((post == null) && create) {
640 post = new Post(postId);
641 posts.put(postId, post);
648 * Returns whether the given post ID is new.
652 * @return {@code true} if the post is considered to be new, {@code false}
655 public boolean isNewPost(String postId) {
656 synchronized (newPosts) {
657 return !knownPosts.contains(postId) && newPosts.contains(postId);
662 * Returns all posts that have the given Sone as recipient.
664 * @see Post#getRecipient()
666 * The recipient of the posts
667 * @return All posts that have the given Sone as recipient
669 public Set<Post> getDirectedPosts(Sone recipient) {
670 Validation.begin().isNotNull("Recipient", recipient).check();
671 Set<Post> directedPosts = new HashSet<Post>();
672 synchronized (posts) {
673 for (Post post : posts.values()) {
674 if (recipient.equals(post.getRecipient())) {
675 directedPosts.add(post);
679 return directedPosts;
683 * Returns the reply with the given ID. If there is no reply with the given
684 * ID yet, a new one is created.
687 * The ID of the reply to get
690 public PostReply getReply(String replyId) {
691 return getReply(replyId, true);
695 * Returns the reply with the given ID. If there is no reply with the given
696 * ID yet, a new one is created, unless {@code create} is false in which
697 * case {@code null} is returned.
700 * The ID of the reply to get
702 * {@code true} to always return a {@link Reply}, {@code false}
703 * to return {@code null} if no reply can be found
704 * @return The reply, or {@code null} if there is no such reply
706 public PostReply getReply(String replyId, boolean create) {
707 synchronized (replies) {
708 PostReply reply = replies.get(replyId);
709 if (create && (reply == null)) {
710 reply = new PostReply(replyId);
711 replies.put(replyId, reply);
718 * Returns all replies for the given post, order ascending by time.
721 * The post to get all replies for
722 * @return All replies for the given post
724 public List<PostReply> getReplies(Post post) {
725 Set<Sone> sones = getSones();
726 List<PostReply> replies = new ArrayList<PostReply>();
727 for (Sone sone : sones) {
728 for (PostReply reply : sone.getReplies()) {
729 if (reply.getPost().equals(post)) {
734 Collections.sort(replies, Reply.TIME_COMPARATOR);
739 * Returns whether the reply with the given ID is new.
742 * The ID of the reply to check
743 * @return {@code true} if the reply is considered to be new, {@code false}
746 public boolean isNewReply(String replyId) {
747 synchronized (newReplies) {
748 return !knownReplies.contains(replyId) && newReplies.contains(replyId);
753 * Returns all Sones that have liked the given post.
756 * The post to get the liking Sones for
757 * @return The Sones that like the given post
759 public Set<Sone> getLikes(Post post) {
760 Set<Sone> sones = new HashSet<Sone>();
761 for (Sone sone : getSones()) {
762 if (sone.getLikedPostIds().contains(post.getId())) {
770 * Returns all Sones that have liked the given reply.
773 * The reply to get the liking Sones for
774 * @return The Sones that like the given reply
776 public Set<Sone> getLikes(PostReply reply) {
777 Set<Sone> sones = new HashSet<Sone>();
778 for (Sone sone : getSones()) {
779 if (sone.getLikedReplyIds().contains(reply.getId())) {
787 * Returns whether the given post is bookmarked.
791 * @return {@code true} if the given post is bookmarked, {@code false}
794 public boolean isBookmarked(Post post) {
795 return isPostBookmarked(post.getId());
799 * Returns whether the post with the given ID is bookmarked.
802 * The ID of the post to check
803 * @return {@code true} if the post with the given ID is bookmarked,
804 * {@code false} otherwise
806 public boolean isPostBookmarked(String id) {
807 synchronized (bookmarkedPosts) {
808 return bookmarkedPosts.contains(id);
813 * Returns all currently known bookmarked posts.
815 * @return All bookmarked posts
817 public Set<Post> getBookmarkedPosts() {
818 Set<Post> posts = new HashSet<Post>();
819 synchronized (bookmarkedPosts) {
820 for (String bookmarkedPostId : bookmarkedPosts) {
821 Post post = getPost(bookmarkedPostId, false);
831 * Returns the album with the given ID, creating a new album if no album
832 * with the given ID can be found.
835 * The ID of the album
836 * @return The album with the given ID
838 public Album getAlbum(String albumId) {
839 return getAlbum(albumId, true);
843 * Returns the album with the given ID, optionally creating a new album if
844 * an album with the given ID can not be found.
847 * The ID of the album
849 * {@code true} to create a new album if none exists for the
851 * @return The album with the given ID, or {@code null} if no album with the
852 * given ID exists and {@code create} is {@code false}
854 public Album getAlbum(String albumId, boolean create) {
855 synchronized (albums) {
856 Album album = albums.get(albumId);
857 if (create && (album == null)) {
858 album = new Album(albumId);
859 albums.put(albumId, album);
866 * Returns the image with the given ID, creating it if necessary.
869 * The ID of the image
870 * @return The image with the given ID
872 public Image getImage(String imageId) {
873 return getImage(imageId, true);
877 * Returns the image with the given ID, optionally creating it if it does
881 * The ID of the image
883 * {@code true} to create an image if none exists with the given
885 * @return The image with the given ID, or {@code null} if none exists and
888 public Image getImage(String imageId, boolean create) {
889 synchronized (images) {
890 Image image = images.get(imageId);
891 if (create && (image == null)) {
892 image = new Image(imageId);
893 images.put(imageId, image);
900 * Returns the temporary image with the given ID.
903 * The ID of the temporary image
904 * @return The temporary image, or {@code null} if there is no temporary
905 * image with the given ID
907 public TemporaryImage getTemporaryImage(String imageId) {
908 synchronized (temporaryImages) {
909 return temporaryImages.get(imageId);
918 * Locks the given Sone. A locked Sone will not be inserted by
919 * {@link SoneInserter} until it is {@link #unlockSone(Sone) unlocked}
925 public void lockSone(Sone sone) {
926 synchronized (lockedSones) {
927 if (lockedSones.add(sone)) {
928 coreListenerManager.fireSoneLocked(sone);
934 * Unlocks the given Sone.
936 * @see #lockSone(Sone)
940 public void unlockSone(Sone sone) {
941 synchronized (lockedSones) {
942 if (lockedSones.remove(sone)) {
943 coreListenerManager.fireSoneUnlocked(sone);
949 * Adds a local Sone from the given own identity.
952 * The own identity to create a Sone from
953 * @return The added (or already existing) Sone
955 public Sone addLocalSone(OwnIdentity ownIdentity) {
956 if (ownIdentity == null) {
957 logger.log(Level.WARNING, "Given OwnIdentity is null!");
960 synchronized (localSones) {
963 sone = getLocalSone(ownIdentity.getId()).setIdentity(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
964 } catch (MalformedURLException mue1) {
965 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
968 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
969 sone.setClient(new Client("Sone", SonePlugin.VERSION.toString()));
970 /* TODO - load posts ’n stuff */
971 localSones.put(ownIdentity.getId(), sone);
972 final SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
973 soneInserter.addSoneInsertListener(this);
974 soneInserters.put(sone, soneInserter);
975 setSoneStatus(sone, SoneStatus.idle);
977 soneInserter.start();
983 * Creates a new Sone for the given own identity.
986 * The own identity to create a Sone for
987 * @return The created Sone
989 public Sone createSone(OwnIdentity ownIdentity) {
991 ownIdentity.addContext("Sone");
992 } catch (WebOfTrustException wote1) {
993 logger.log(Level.SEVERE, "Could not add “Sone” context to own identity: " + ownIdentity, wote1);
996 Sone sone = addLocalSone(ownIdentity);
997 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
998 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
999 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1000 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1001 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1002 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1004 followSone(sone, getSone("nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI"));
1005 touchConfiguration();
1010 * Adds the Sone of the given identity.
1013 * The identity whose Sone to add
1014 * @return The added or already existing Sone
1016 public Sone addRemoteSone(Identity identity) {
1017 if (identity == null) {
1018 logger.log(Level.WARNING, "Given Identity is null!");
1021 synchronized (remoteSones) {
1022 final Sone sone = getRemoteSone(identity.getId(), true).setIdentity(identity);
1023 boolean newSone = sone.getRequestUri() == null;
1024 sone.setRequestUri(getSoneUri(identity.getRequestUri()));
1025 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), (long) 0));
1027 synchronized (newSones) {
1028 newSone = !knownSones.contains(sone.getId());
1030 newSones.add(sone.getId());
1034 coreListenerManager.fireNewSoneFound(sone);
1035 for (Sone localSone : getLocalSones()) {
1036 if (localSone.getOptions().getBooleanOption("AutoFollow").get()) {
1037 followSone(localSone, sone);
1042 soneDownloader.addSone(sone);
1043 setSoneStatus(sone, SoneStatus.unknown);
1044 soneDownloaders.execute(new Runnable() {
1047 @SuppressWarnings("synthetic-access")
1049 soneDownloader.fetchSone(sone, sone.getRequestUri());
1058 * Lets the given local Sone follow the Sone with the given ID.
1061 * The local Sone that should follow another Sone
1063 * The ID of the Sone to follow
1065 public void followSone(Sone sone, String soneId) {
1066 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1067 Sone followedSone = getSone(soneId, true);
1068 if (followedSone == null) {
1069 logger.log(Level.INFO, String.format("Ignored Sone with invalid ID: %s", soneId));
1072 followSone(sone, getSone(soneId));
1076 * Lets the given local Sone follow the other given Sone. If the given Sone
1077 * was not followed by any local Sone before, this will mark all elements of
1078 * the followed Sone as read that have been created before the current
1082 * The local Sone that should follow the other Sone
1083 * @param followedSone
1084 * The Sone that should be followed
1086 public void followSone(Sone sone, Sone followedSone) {
1087 Validation.begin().isNotNull("Sone", sone).isNotNull("Followed Sone", followedSone).check();
1088 sone.addFriend(followedSone.getId());
1089 synchronized (soneFollowingTimes) {
1090 if (!soneFollowingTimes.containsKey(followedSone)) {
1091 long now = System.currentTimeMillis();
1092 soneFollowingTimes.put(followedSone, now);
1093 for (Post post : followedSone.getPosts()) {
1094 if (post.getTime() < now) {
1095 markPostKnown(post);
1098 for (PostReply reply : followedSone.getReplies()) {
1099 if (reply.getTime() < now) {
1100 markReplyKnown(reply);
1105 touchConfiguration();
1109 * Lets the given local Sone unfollow the Sone with the given ID.
1112 * The local Sone that should unfollow another Sone
1114 * The ID of the Sone being unfollowed
1116 public void unfollowSone(Sone sone, String soneId) {
1117 Validation.begin().isNotNull("Sone", sone).isNotNull("Sone ID", soneId).check();
1118 unfollowSone(sone, getSone(soneId, false));
1122 * Lets the given local Sone unfollow the other given Sone. If the given
1123 * local Sone is the last local Sone that followed the given Sone, its
1124 * following time will be removed.
1127 * The local Sone that should unfollow another Sone
1128 * @param unfollowedSone
1129 * The Sone being unfollowed
1131 public void unfollowSone(Sone sone, Sone unfollowedSone) {
1132 Validation.begin().isNotNull("Sone", sone).isNotNull("Unfollowed Sone", unfollowedSone).check();
1133 sone.removeFriend(unfollowedSone.getId());
1134 boolean unfollowedSoneStillFollowed = false;
1135 for (Sone localSone : getLocalSones()) {
1136 unfollowedSoneStillFollowed |= localSone.hasFriend(unfollowedSone.getId());
1138 if (!unfollowedSoneStillFollowed) {
1139 synchronized (soneFollowingTimes) {
1140 soneFollowingTimes.remove(unfollowedSone);
1143 touchConfiguration();
1147 * Retrieves the trust relationship from the origin to the target. If the
1148 * trust relationship can not be retrieved, {@code null} is returned.
1150 * @see Identity#getTrust(OwnIdentity)
1152 * The origin of the trust tree
1154 * The target of the trust
1155 * @return The trust relationship
1157 public Trust getTrust(Sone origin, Sone target) {
1158 if (!isLocalSone(origin)) {
1159 logger.log(Level.WARNING, "Tried to get trust from remote Sone: %s", origin);
1162 return target.getIdentity().getTrust((OwnIdentity) origin.getIdentity());
1166 * Sets the trust value of the given origin Sone for the target Sone.
1173 * The trust value (from {@code -100} to {@code 100})
1175 public void setTrust(Sone origin, Sone target, int trustValue) {
1176 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();
1178 ((OwnIdentity) origin.getIdentity()).setTrust(target.getIdentity(), trustValue, preferences.getTrustComment());
1179 } catch (WebOfTrustException wote1) {
1180 logger.log(Level.WARNING, "Could not set trust for Sone: " + target, wote1);
1185 * Removes any trust assignment for the given target Sone.
1192 public void removeTrust(Sone origin, Sone target) {
1193 Validation.begin().isNotNull("Trust Origin", origin).isNotNull("Trust Target", target).check().isInstanceOf("Trust Origin Identity", origin.getIdentity(), OwnIdentity.class).check();
1195 ((OwnIdentity) origin.getIdentity()).removeTrust(target.getIdentity());
1196 } catch (WebOfTrustException wote1) {
1197 logger.log(Level.WARNING, "Could not remove trust for Sone: " + target, wote1);
1202 * Assigns the configured positive trust value for the given target.
1209 public void trustSone(Sone origin, Sone target) {
1210 setTrust(origin, target, preferences.getPositiveTrust());
1214 * Assigns the configured negative trust value for the given target.
1221 public void distrustSone(Sone origin, Sone target) {
1222 setTrust(origin, target, preferences.getNegativeTrust());
1226 * Removes the trust assignment for the given target.
1233 public void untrustSone(Sone origin, Sone target) {
1234 removeTrust(origin, target);
1238 * Updates the stored Sone with the given Sone.
1243 public void updateSone(Sone sone) {
1244 updateSone(sone, false);
1248 * Updates the stored Sone with the given Sone. If {@code soneRescueMode} is
1249 * {@code true}, an older Sone than the current Sone can be given to restore
1253 * The Sone to update
1254 * @param soneRescueMode
1255 * {@code true} if the stored Sone should be updated regardless
1256 * of the age of the given Sone
1258 public void updateSone(Sone sone, boolean soneRescueMode) {
1259 if (hasSone(sone.getId())) {
1260 Sone storedSone = getSone(sone.getId());
1261 if (!soneRescueMode && !(sone.getTime() > storedSone.getTime())) {
1262 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
1265 synchronized (posts) {
1266 if (!soneRescueMode) {
1267 for (Post post : storedSone.getPosts()) {
1268 posts.remove(post.getId());
1269 if (!sone.getPosts().contains(post)) {
1270 coreListenerManager.firePostRemoved(post);
1274 List<Post> storedPosts = storedSone.getPosts();
1275 synchronized (newPosts) {
1276 for (Post post : sone.getPosts()) {
1277 post.setSone(storedSone);
1278 if (!storedPosts.contains(post)) {
1279 if (post.getTime() < getSoneFollowingTime(sone)) {
1280 knownPosts.add(post.getId());
1281 } else if (!knownPosts.contains(post.getId())) {
1282 newPosts.add(post.getId());
1283 coreListenerManager.fireNewPostFound(post);
1286 posts.put(post.getId(), post);
1290 synchronized (replies) {
1291 if (!soneRescueMode) {
1292 for (PostReply reply : storedSone.getReplies()) {
1293 replies.remove(reply.getId());
1294 if (!sone.getReplies().contains(reply)) {
1295 coreListenerManager.fireReplyRemoved(reply);
1299 Set<PostReply> storedReplies = storedSone.getReplies();
1300 synchronized (newReplies) {
1301 for (PostReply reply : sone.getReplies()) {
1302 reply.setSone(storedSone);
1303 if (!storedReplies.contains(reply)) {
1304 if (reply.getTime() < getSoneFollowingTime(sone)) {
1305 knownReplies.add(reply.getId());
1306 } else if (!knownReplies.contains(reply.getId())) {
1307 newReplies.add(reply.getId());
1308 coreListenerManager.fireNewReplyFound(reply);
1311 replies.put(reply.getId(), reply);
1315 synchronized (albums) {
1316 synchronized (images) {
1317 for (Album album : storedSone.getAlbums()) {
1318 albums.remove(album.getId());
1319 for (Image image : album.getImages()) {
1320 images.remove(image.getId());
1323 for (Album album : sone.getAlbums()) {
1324 albums.put(album.getId(), album);
1325 for (Image image : album.getImages()) {
1326 images.put(image.getId(), image);
1331 synchronized (storedSone) {
1332 if (!soneRescueMode || (sone.getTime() > storedSone.getTime())) {
1333 storedSone.setTime(sone.getTime());
1335 storedSone.setClient(sone.getClient());
1336 storedSone.setProfile(sone.getProfile());
1337 if (soneRescueMode) {
1338 for (Post post : sone.getPosts()) {
1339 storedSone.addPost(post);
1341 for (PostReply reply : sone.getReplies()) {
1342 storedSone.addReply(reply);
1344 for (String likedPostId : sone.getLikedPostIds()) {
1345 storedSone.addLikedPostId(likedPostId);
1347 for (String likedReplyId : sone.getLikedReplyIds()) {
1348 storedSone.addLikedReplyId(likedReplyId);
1350 for (Album album : sone.getAlbums()) {
1351 storedSone.addAlbum(album);
1354 storedSone.setPosts(sone.getPosts());
1355 storedSone.setReplies(sone.getReplies());
1356 storedSone.setLikePostIds(sone.getLikedPostIds());
1357 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
1358 storedSone.setAlbums(sone.getAlbums());
1360 storedSone.setLatestEdition(sone.getLatestEdition());
1366 * Deletes the given Sone. This will remove the Sone from the
1367 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
1368 * and remove the context from its identity.
1371 * The Sone to delete
1373 public void deleteSone(Sone sone) {
1374 if (!(sone.getIdentity() instanceof OwnIdentity)) {
1375 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
1378 synchronized (localSones) {
1379 if (!localSones.containsKey(sone.getId())) {
1380 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
1383 localSones.remove(sone.getId());
1384 SoneInserter soneInserter = soneInserters.remove(sone);
1385 soneInserter.removeSoneInsertListener(this);
1386 soneInserter.stop();
1389 ((OwnIdentity) sone.getIdentity()).removeContext("Sone");
1390 ((OwnIdentity) sone.getIdentity()).removeProperty("Sone.LatestEdition");
1391 } catch (WebOfTrustException wote1) {
1392 logger.log(Level.WARNING, "Could not remove context and properties from Sone: " + sone, wote1);
1395 configuration.getLongValue("Sone/" + sone.getId() + "/Time").setValue(null);
1396 } catch (ConfigurationException ce1) {
1397 logger.log(Level.WARNING, "Could not remove Sone from configuration!", ce1);
1402 * Marks the given Sone as known. If the Sone was {@link #isNewPost(String)
1403 * new} before, a {@link CoreListener#markSoneKnown(Sone)} event is fired.
1406 * The Sone to mark as known
1408 public void markSoneKnown(Sone sone) {
1409 synchronized (newSones) {
1410 if (newSones.remove(sone.getId())) {
1411 knownSones.add(sone.getId());
1412 coreListenerManager.fireMarkSoneKnown(sone);
1413 touchConfiguration();
1419 * Loads and updates the given Sone from the configuration. If any error is
1420 * encountered, loading is aborted and the given Sone is not changed.
1423 * The Sone to load and update
1425 public void loadSone(Sone sone) {
1426 if (!isLocalSone(sone)) {
1427 logger.log(Level.FINE, "Tried to load non-local Sone: %s", sone);
1431 /* initialize options. */
1432 sone.getOptions().addBooleanOption("AutoFollow", new DefaultOption<Boolean>(false));
1433 sone.getOptions().addBooleanOption("EnableSoneInsertNotifications", new DefaultOption<Boolean>(false));
1434 sone.getOptions().addBooleanOption("ShowNotification/NewSones", new DefaultOption<Boolean>(true));
1435 sone.getOptions().addBooleanOption("ShowNotification/NewPosts", new DefaultOption<Boolean>(true));
1436 sone.getOptions().addBooleanOption("ShowNotification/NewReplies", new DefaultOption<Boolean>(true));
1437 sone.getOptions().addEnumOption("ShowCustomAvatars", new DefaultOption<ShowCustomAvatars>(ShowCustomAvatars.NEVER));
1440 String sonePrefix = "Sone/" + sone.getId();
1441 Long soneTime = configuration.getLongValue(sonePrefix + "/Time").getValue(null);
1442 if (soneTime == null) {
1443 logger.log(Level.INFO, "Could not load Sone because no Sone has been saved.");
1446 String lastInsertFingerprint = configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").getValue("");
1449 Profile profile = new Profile(sone);
1450 profile.setFirstName(configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null));
1451 profile.setMiddleName(configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null));
1452 profile.setLastName(configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null));
1453 profile.setBirthDay(configuration.getIntValue(sonePrefix + "/Profile/BirthDay").getValue(null));
1454 profile.setBirthMonth(configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").getValue(null));
1455 profile.setBirthYear(configuration.getIntValue(sonePrefix + "/Profile/BirthYear").getValue(null));
1457 /* load profile fields. */
1459 String fieldPrefix = sonePrefix + "/Profile/Fields/" + profile.getFields().size();
1460 String fieldName = configuration.getStringValue(fieldPrefix + "/Name").getValue(null);
1461 if (fieldName == null) {
1464 String fieldValue = configuration.getStringValue(fieldPrefix + "/Value").getValue("");
1465 profile.addField(fieldName).setValue(fieldValue);
1469 Set<Post> posts = new HashSet<Post>();
1471 String postPrefix = sonePrefix + "/Posts/" + posts.size();
1472 String postId = configuration.getStringValue(postPrefix + "/ID").getValue(null);
1473 if (postId == null) {
1476 String postRecipientId = configuration.getStringValue(postPrefix + "/Recipient").getValue(null);
1477 long postTime = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
1478 String postText = configuration.getStringValue(postPrefix + "/Text").getValue(null);
1479 if ((postTime == 0) || (postText == null)) {
1480 logger.log(Level.WARNING, "Invalid post found, aborting load!");
1483 Post post = getPost(postId).setSone(sone).setTime(postTime).setText(postText);
1484 if ((postRecipientId != null) && (postRecipientId.length() == 43)) {
1485 post.setRecipient(getSone(postRecipientId));
1491 Set<PostReply> replies = new HashSet<PostReply>();
1493 String replyPrefix = sonePrefix + "/Replies/" + replies.size();
1494 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
1495 if (replyId == null) {
1498 String postId = configuration.getStringValue(replyPrefix + "/Post/ID").getValue(null);
1499 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue((long) 0);
1500 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
1501 if ((postId == null) || (replyTime == 0) || (replyText == null)) {
1502 logger.log(Level.WARNING, "Invalid reply found, aborting load!");
1505 replies.add(getReply(replyId).setSone(sone).setPost(getPost(postId)).setTime(replyTime).setText(replyText));
1508 /* load post likes. */
1509 Set<String> likedPostIds = new HashSet<String>();
1511 String likedPostId = configuration.getStringValue(sonePrefix + "/Likes/Post/" + likedPostIds.size() + "/ID").getValue(null);
1512 if (likedPostId == null) {
1515 likedPostIds.add(likedPostId);
1518 /* load reply likes. */
1519 Set<String> likedReplyIds = new HashSet<String>();
1521 String likedReplyId = configuration.getStringValue(sonePrefix + "/Likes/Reply/" + likedReplyIds.size() + "/ID").getValue(null);
1522 if (likedReplyId == null) {
1525 likedReplyIds.add(likedReplyId);
1529 Set<String> friends = new HashSet<String>();
1531 String friendId = configuration.getStringValue(sonePrefix + "/Friends/" + friends.size() + "/ID").getValue(null);
1532 if (friendId == null) {
1535 friends.add(friendId);
1539 List<Album> topLevelAlbums = new ArrayList<Album>();
1540 int albumCounter = 0;
1542 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
1543 String albumId = configuration.getStringValue(albumPrefix + "/ID").getValue(null);
1544 if (albumId == null) {
1547 String albumTitle = configuration.getStringValue(albumPrefix + "/Title").getValue(null);
1548 String albumDescription = configuration.getStringValue(albumPrefix + "/Description").getValue(null);
1549 String albumParentId = configuration.getStringValue(albumPrefix + "/Parent").getValue(null);
1550 String albumImageId = configuration.getStringValue(albumPrefix + "/AlbumImage").getValue(null);
1551 if ((albumTitle == null) || (albumDescription == null)) {
1552 logger.log(Level.WARNING, "Invalid album found, aborting load!");
1555 Album album = getAlbum(albumId).setSone(sone).setTitle(albumTitle).setDescription(albumDescription).setAlbumImage(albumImageId);
1556 if (albumParentId != null) {
1557 Album parentAlbum = getAlbum(albumParentId, false);
1558 if (parentAlbum == null) {
1559 logger.log(Level.WARNING, "Invalid parent album ID: " + albumParentId);
1562 parentAlbum.addAlbum(album);
1564 topLevelAlbums.add(album);
1569 int imageCounter = 0;
1571 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
1572 String imageId = configuration.getStringValue(imagePrefix + "/ID").getValue(null);
1573 if (imageId == null) {
1576 String albumId = configuration.getStringValue(imagePrefix + "/Album").getValue(null);
1577 String key = configuration.getStringValue(imagePrefix + "/Key").getValue(null);
1578 String title = configuration.getStringValue(imagePrefix + "/Title").getValue(null);
1579 String description = configuration.getStringValue(imagePrefix + "/Description").getValue(null);
1580 Long creationTime = configuration.getLongValue(imagePrefix + "/CreationTime").getValue(null);
1581 Integer width = configuration.getIntValue(imagePrefix + "/Width").getValue(null);
1582 Integer height = configuration.getIntValue(imagePrefix + "/Height").getValue(null);
1583 if ((albumId == null) || (key == null) || (title == null) || (description == null) || (creationTime == null) || (width == null) || (height == null)) {
1584 logger.log(Level.WARNING, "Invalid image found, aborting load!");
1587 Album album = getAlbum(albumId, false);
1588 if (album == null) {
1589 logger.log(Level.WARNING, "Invalid album image encountered, aborting load!");
1592 Image image = getImage(imageId).setSone(sone).setCreationTime(creationTime).setKey(key);
1593 image.setTitle(title).setDescription(description).setWidth(width).setHeight(height);
1594 album.addImage(image);
1598 String avatarId = configuration.getStringValue(sonePrefix + "/Profile/Avatar").getValue(null);
1599 if (avatarId != null) {
1600 profile.setAvatar(getImage(avatarId, false));
1604 sone.getOptions().getBooleanOption("AutoFollow").set(configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").getValue(null));
1605 sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").set(configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").getValue(null));
1606 sone.getOptions().getBooleanOption("ShowNotification/NewSones").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").getValue(null));
1607 sone.getOptions().getBooleanOption("ShowNotification/NewPosts").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").getValue(null));
1608 sone.getOptions().getBooleanOption("ShowNotification/NewReplies").set(configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").getValue(null));
1609 sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").set(ShowCustomAvatars.valueOf(configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").getValue(ShowCustomAvatars.NEVER.name())));
1611 /* if we’re still here, Sone was loaded successfully. */
1612 synchronized (sone) {
1613 sone.setTime(soneTime);
1614 sone.setProfile(profile);
1615 sone.setPosts(posts);
1616 sone.setReplies(replies);
1617 sone.setLikePostIds(likedPostIds);
1618 sone.setLikeReplyIds(likedReplyIds);
1619 for (String friendId : friends) {
1620 followSone(sone, friendId);
1622 sone.setAlbums(topLevelAlbums);
1623 soneInserters.get(sone).setLastInsertFingerprint(lastInsertFingerprint);
1625 synchronized (newSones) {
1626 for (String friend : friends) {
1627 knownSones.add(friend);
1630 synchronized (newPosts) {
1631 for (Post post : posts) {
1632 knownPosts.add(post.getId());
1635 synchronized (newReplies) {
1636 for (PostReply reply : replies) {
1637 knownReplies.add(reply.getId());
1643 * Creates a new post.
1646 * The Sone that creates the post
1648 * The text of the post
1649 * @return The created post
1651 public Post createPost(Sone sone, String text) {
1652 return createPost(sone, System.currentTimeMillis(), text);
1656 * Creates a new post.
1659 * The Sone that creates the post
1661 * The time of the post
1663 * The text of the post
1664 * @return The created post
1666 public Post createPost(Sone sone, long time, String text) {
1667 return createPost(sone, null, time, text);
1671 * Creates a new post.
1674 * The Sone that creates the post
1676 * The recipient Sone, or {@code null} if this post does not have
1679 * The text of the post
1680 * @return The created post
1682 public Post createPost(Sone sone, Sone recipient, String text) {
1683 return createPost(sone, recipient, System.currentTimeMillis(), text);
1687 * Creates a new post.
1690 * The Sone that creates the post
1692 * The recipient Sone, or {@code null} if this post does not have
1695 * The time of the post
1697 * The text of the post
1698 * @return The created post
1700 public Post createPost(Sone sone, Sone recipient, long time, String text) {
1701 if (!isLocalSone(sone)) {
1702 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
1705 final Post post = new Post(sone, time, text);
1706 if (recipient != null) {
1707 post.setRecipient(recipient);
1709 synchronized (posts) {
1710 posts.put(post.getId(), post);
1712 synchronized (newPosts) {
1713 newPosts.add(post.getId());
1714 coreListenerManager.fireNewPostFound(post);
1717 touchConfiguration();
1718 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1725 markPostKnown(post);
1727 }, "Mark " + post + " read.");
1732 * Deletes the given post.
1735 * The post to delete
1737 public void deletePost(Post post) {
1738 if (!isLocalSone(post.getSone())) {
1739 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
1742 post.getSone().removePost(post);
1743 synchronized (posts) {
1744 posts.remove(post.getId());
1746 coreListenerManager.firePostRemoved(post);
1747 synchronized (newPosts) {
1748 markPostKnown(post);
1749 knownPosts.remove(post.getId());
1751 touchConfiguration();
1755 * Marks the given post as known, if it is currently a new post (according
1756 * to {@link #isNewPost(String)}).
1759 * The post to mark as known
1761 public void markPostKnown(Post post) {
1762 synchronized (newPosts) {
1763 if (newPosts.remove(post.getId())) {
1764 knownPosts.add(post.getId());
1765 coreListenerManager.fireMarkPostKnown(post);
1766 touchConfiguration();
1772 * Bookmarks the given post.
1775 * The post to bookmark
1777 public void bookmark(Post post) {
1778 bookmarkPost(post.getId());
1782 * Bookmarks the post with the given ID.
1785 * The ID of the post to bookmark
1787 public void bookmarkPost(String id) {
1788 synchronized (bookmarkedPosts) {
1789 bookmarkedPosts.add(id);
1794 * Removes the given post from the bookmarks.
1797 * The post to unbookmark
1799 public void unbookmark(Post post) {
1800 unbookmarkPost(post.getId());
1804 * Removes the post with the given ID from the bookmarks.
1807 * The ID of the post to unbookmark
1809 public void unbookmarkPost(String id) {
1810 synchronized (bookmarkedPosts) {
1811 bookmarkedPosts.remove(id);
1816 * Creates a new reply.
1819 * The Sone that creates the reply
1821 * The post that this reply refers to
1823 * The text of the reply
1824 * @return The created reply
1826 public PostReply createReply(Sone sone, Post post, String text) {
1827 return createReply(sone, post, System.currentTimeMillis(), text);
1831 * Creates a new reply.
1834 * The Sone that creates the reply
1836 * The post that this reply refers to
1838 * The time of the reply
1840 * The text of the reply
1841 * @return The created reply
1843 public PostReply createReply(Sone sone, Post post, long time, String text) {
1844 if (!isLocalSone(sone)) {
1845 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
1848 final PostReply reply = new PostReply(sone, post, System.currentTimeMillis(), text);
1849 synchronized (replies) {
1850 replies.put(reply.getId(), reply);
1852 synchronized (newReplies) {
1853 newReplies.add(reply.getId());
1854 coreListenerManager.fireNewReplyFound(reply);
1856 sone.addReply(reply);
1857 touchConfiguration();
1858 localElementTicker.registerEvent(System.currentTimeMillis() + 10 * 1000, new Runnable() {
1865 markReplyKnown(reply);
1867 }, "Mark " + reply + " read.");
1872 * Deletes the given reply.
1875 * The reply to delete
1877 public void deleteReply(PostReply reply) {
1878 Sone sone = reply.getSone();
1879 if (!isLocalSone(sone)) {
1880 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
1883 synchronized (replies) {
1884 replies.remove(reply.getId());
1886 synchronized (newReplies) {
1887 markReplyKnown(reply);
1888 knownReplies.remove(reply.getId());
1890 sone.removeReply(reply);
1891 touchConfiguration();
1895 * Marks the given reply as known, if it is currently a new reply (according
1896 * to {@link #isNewReply(String)}).
1899 * The reply to mark as known
1901 public void markReplyKnown(PostReply reply) {
1902 synchronized (newReplies) {
1903 if (newReplies.remove(reply.getId())) {
1904 knownReplies.add(reply.getId());
1905 coreListenerManager.fireMarkReplyKnown(reply);
1906 touchConfiguration();
1912 * Creates a new top-level album for the given Sone.
1915 * The Sone to create the album for
1916 * @return The new album
1918 public Album createAlbum(Sone sone) {
1919 return createAlbum(sone, null);
1923 * Creates a new album for the given Sone.
1926 * The Sone to create the album for
1928 * The parent of the album (may be {@code null} to create a
1930 * @return The new album
1932 public Album createAlbum(Sone sone, Album parent) {
1933 Album album = new Album();
1934 synchronized (albums) {
1935 albums.put(album.getId(), album);
1937 album.setSone(sone);
1938 if (parent != null) {
1939 parent.addAlbum(album);
1941 sone.addAlbum(album);
1947 * Deletes the given album. The owner of the album has to be a local Sone,
1948 * and the album has to be {@link Album#isEmpty() empty} to be deleted.
1951 * The album to remove
1953 public void deleteAlbum(Album album) {
1954 Validation.begin().isNotNull("Album", album).check().is("Local Sone", isLocalSone(album.getSone())).check();
1955 if (!album.isEmpty()) {
1958 if (album.getParent() == null) {
1959 album.getSone().removeAlbum(album);
1961 album.getParent().removeAlbum(album);
1963 synchronized (albums) {
1964 albums.remove(album.getId());
1966 saveSone(album.getSone());
1970 * Creates a new image.
1973 * The Sone creating the image
1975 * The album the image will be inserted into
1976 * @param temporaryImage
1977 * The temporary image to create the image from
1978 * @return The newly created image
1980 public Image createImage(Sone sone, Album album, TemporaryImage temporaryImage) {
1981 Validation.begin().isNotNull("Sone", sone).isNotNull("Album", album).isNotNull("Temporary Image", temporaryImage).check().is("Local Sone", isLocalSone(sone)).check().isEqual("Owner and Album Owner", sone, album.getSone()).check();
1982 Image image = new Image(temporaryImage.getId()).setSone(sone).setCreationTime(System.currentTimeMillis());
1983 album.addImage(image);
1984 synchronized (images) {
1985 images.put(image.getId(), image);
1987 imageInserter.insertImage(temporaryImage, image);
1992 * Deletes the given image. This method will also delete a matching
1995 * @see #deleteTemporaryImage(TemporaryImage)
1997 * The image to delete
1999 public void deleteImage(Image image) {
2000 Validation.begin().isNotNull("Image", image).check().is("Local Sone", isLocalSone(image.getSone())).check();
2001 deleteTemporaryImage(image.getId());
2002 image.getAlbum().removeImage(image);
2003 synchronized (images) {
2004 images.remove(image.getId());
2006 saveSone(image.getSone());
2010 * Creates a new temporary image.
2013 * The MIME type of the temporary image
2015 * The encoded data of the image
2016 * @return The temporary image
2018 public TemporaryImage createTemporaryImage(String mimeType, byte[] imageData) {
2019 TemporaryImage temporaryImage = new TemporaryImage();
2020 temporaryImage.setMimeType(mimeType).setImageData(imageData);
2021 synchronized (temporaryImages) {
2022 temporaryImages.put(temporaryImage.getId(), temporaryImage);
2024 return temporaryImage;
2028 * Deletes the given temporary image.
2030 * @param temporaryImage
2031 * The temporary image to delete
2033 public void deleteTemporaryImage(TemporaryImage temporaryImage) {
2034 Validation.begin().isNotNull("Temporary Image", temporaryImage).check();
2035 deleteTemporaryImage(temporaryImage.getId());
2039 * Deletes the temporary image with the given ID.
2042 * The ID of the temporary image to delete
2044 public void deleteTemporaryImage(String imageId) {
2045 Validation.begin().isNotNull("Temporary Image ID", imageId).check();
2046 synchronized (temporaryImages) {
2047 temporaryImages.remove(imageId);
2049 Image image = getImage(imageId, false);
2050 if (image != null) {
2051 imageInserter.cancelImageInsert(image);
2056 * Notifies the core that the configuration, either of the core or of a
2057 * single local Sone, has changed, and that the configuration should be
2060 public void touchConfiguration() {
2061 lastConfigurationUpdate = System.currentTimeMillis();
2072 public void serviceStart() {
2073 loadConfiguration();
2074 updateChecker.addUpdateListener(this);
2075 updateChecker.start();
2082 public void serviceRun() {
2083 long lastSaved = System.currentTimeMillis();
2084 while (!shouldStop()) {
2086 long now = System.currentTimeMillis();
2087 if (shouldStop() || ((lastConfigurationUpdate > lastSaved) && ((now - lastConfigurationUpdate) > 5000))) {
2088 for (Sone localSone : getLocalSones()) {
2089 saveSone(localSone);
2091 saveConfiguration();
2101 public void serviceStop() {
2102 synchronized (localSones) {
2103 for (SoneInserter soneInserter : soneInserters.values()) {
2104 soneInserter.removeSoneInsertListener(this);
2105 soneInserter.stop();
2108 updateChecker.stop();
2109 updateChecker.removeUpdateListener(this);
2110 soneDownloader.stop();
2118 * Saves the given Sone. This will persist all local settings for the given
2119 * Sone, such as the friends list and similar, private options.
2124 private synchronized void saveSone(Sone sone) {
2125 if (!isLocalSone(sone)) {
2126 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
2129 if (!(sone.getIdentity() instanceof OwnIdentity)) {
2130 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
2134 logger.log(Level.INFO, "Saving Sone: %s", sone);
2136 /* save Sone into configuration. */
2137 String sonePrefix = "Sone/" + sone.getId();
2138 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
2139 configuration.getStringValue(sonePrefix + "/LastInsertFingerprint").setValue(soneInserters.get(sone).getLastInsertFingerprint());
2142 Profile profile = sone.getProfile();
2143 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
2144 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
2145 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
2146 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
2147 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
2148 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
2149 configuration.getStringValue(sonePrefix + "/Profile/Avatar").setValue(profile.getAvatar());
2151 /* save profile fields. */
2152 int fieldCounter = 0;
2153 for (Field profileField : profile.getFields()) {
2154 String fieldPrefix = sonePrefix + "/Profile/Fields/" + fieldCounter++;
2155 configuration.getStringValue(fieldPrefix + "/Name").setValue(profileField.getName());
2156 configuration.getStringValue(fieldPrefix + "/Value").setValue(profileField.getValue());
2158 configuration.getStringValue(sonePrefix + "/Profile/Fields/" + fieldCounter + "/Name").setValue(null);
2161 int postCounter = 0;
2162 for (Post post : sone.getPosts()) {
2163 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
2164 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
2165 configuration.getStringValue(postPrefix + "/Recipient").setValue((post.getRecipient() != null) ? post.getRecipient().getId() : null);
2166 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
2167 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
2169 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
2172 int replyCounter = 0;
2173 for (PostReply reply : sone.getReplies()) {
2174 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
2175 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
2176 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
2177 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
2178 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
2180 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
2182 /* save post likes. */
2183 int postLikeCounter = 0;
2184 for (String postId : sone.getLikedPostIds()) {
2185 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
2187 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
2189 /* save reply likes. */
2190 int replyLikeCounter = 0;
2191 for (String replyId : sone.getLikedReplyIds()) {
2192 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
2194 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
2197 int friendCounter = 0;
2198 for (String friendId : sone.getFriends()) {
2199 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter++ + "/ID").setValue(friendId);
2201 configuration.getStringValue(sonePrefix + "/Friends/" + friendCounter + "/ID").setValue(null);
2203 /* save albums. first, collect in a flat structure, top-level first. */
2204 List<Album> albums = sone.getAllAlbums();
2206 int albumCounter = 0;
2207 for (Album album : albums) {
2208 String albumPrefix = sonePrefix + "/Albums/" + albumCounter++;
2209 configuration.getStringValue(albumPrefix + "/ID").setValue(album.getId());
2210 configuration.getStringValue(albumPrefix + "/Title").setValue(album.getTitle());
2211 configuration.getStringValue(albumPrefix + "/Description").setValue(album.getDescription());
2212 configuration.getStringValue(albumPrefix + "/Parent").setValue(album.getParent() == null ? null : album.getParent().getId());
2213 configuration.getStringValue(albumPrefix + "/AlbumImage").setValue(album.getAlbumImage() == null ? null : album.getAlbumImage().getId());
2215 configuration.getStringValue(sonePrefix + "/Albums/" + albumCounter + "/ID").setValue(null);
2218 int imageCounter = 0;
2219 for (Album album : albums) {
2220 for (Image image : album.getImages()) {
2221 if (!image.isInserted()) {
2224 String imagePrefix = sonePrefix + "/Images/" + imageCounter++;
2225 configuration.getStringValue(imagePrefix + "/ID").setValue(image.getId());
2226 configuration.getStringValue(imagePrefix + "/Album").setValue(album.getId());
2227 configuration.getStringValue(imagePrefix + "/Key").setValue(image.getKey());
2228 configuration.getStringValue(imagePrefix + "/Title").setValue(image.getTitle());
2229 configuration.getStringValue(imagePrefix + "/Description").setValue(image.getDescription());
2230 configuration.getLongValue(imagePrefix + "/CreationTime").setValue(image.getCreationTime());
2231 configuration.getIntValue(imagePrefix + "/Width").setValue(image.getWidth());
2232 configuration.getIntValue(imagePrefix + "/Height").setValue(image.getHeight());
2235 configuration.getStringValue(sonePrefix + "/Images/" + imageCounter + "/ID").setValue(null);
2238 configuration.getBooleanValue(sonePrefix + "/Options/AutoFollow").setValue(sone.getOptions().getBooleanOption("AutoFollow").getReal());
2239 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewSones").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewSones").getReal());
2240 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewPosts").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewPosts").getReal());
2241 configuration.getBooleanValue(sonePrefix + "/Options/ShowNotification/NewReplies").setValue(sone.getOptions().getBooleanOption("ShowNotification/NewReplies").getReal());
2242 configuration.getBooleanValue(sonePrefix + "/Options/EnableSoneInsertNotifications").setValue(sone.getOptions().getBooleanOption("EnableSoneInsertNotifications").getReal());
2243 configuration.getStringValue(sonePrefix + "/Options/ShowCustomAvatars").setValue(sone.getOptions().<ShowCustomAvatars> getEnumOption("ShowCustomAvatars").get().name());
2245 configuration.save();
2247 ((OwnIdentity) sone.getIdentity()).setProperty("Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
2249 logger.log(Level.INFO, "Sone %s saved.", sone);
2250 } catch (ConfigurationException ce1) {
2251 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
2252 } catch (WebOfTrustException wote1) {
2253 logger.log(Level.WARNING, "Could not set WoT property for Sone: " + sone, wote1);
2258 * Saves the current options.
2260 private void saveConfiguration() {
2261 synchronized (configuration) {
2262 if (storingConfiguration) {
2263 logger.log(Level.FINE, "Already storing configuration…");
2266 storingConfiguration = true;
2269 /* store the options first. */
2271 configuration.getIntValue("Option/ConfigurationVersion").setValue(0);
2272 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
2273 configuration.getIntValue("Option/PostsPerPage").setValue(options.getIntegerOption("PostsPerPage").getReal());
2274 configuration.getIntValue("Option/CharactersPerPost").setValue(options.getIntegerOption("CharactersPerPost").getReal());
2275 configuration.getIntValue("Option/PostCutOffLength").setValue(options.getIntegerOption("PostCutOffLength").getReal());
2276 configuration.getBooleanValue("Option/RequireFullAccess").setValue(options.getBooleanOption("RequireFullAccess").getReal());
2277 configuration.getIntValue("Option/PositiveTrust").setValue(options.getIntegerOption("PositiveTrust").getReal());
2278 configuration.getIntValue("Option/NegativeTrust").setValue(options.getIntegerOption("NegativeTrust").getReal());
2279 configuration.getStringValue("Option/TrustComment").setValue(options.getStringOption("TrustComment").getReal());
2280 configuration.getBooleanValue("Option/ActivateFcpInterface").setValue(options.getBooleanOption("ActivateFcpInterface").getReal());
2281 configuration.getIntValue("Option/FcpFullAccessRequired").setValue(options.getIntegerOption("FcpFullAccessRequired").getReal());
2282 configuration.getBooleanValue("Option/SoneRescueMode").setValue(options.getBooleanOption("SoneRescueMode").getReal());
2283 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
2284 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
2286 /* save known Sones. */
2287 int soneCounter = 0;
2288 synchronized (newSones) {
2289 for (String knownSoneId : knownSones) {
2290 configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").setValue(knownSoneId);
2292 configuration.getStringValue("KnownSone/" + soneCounter + "/ID").setValue(null);
2295 /* save Sone following times. */
2297 synchronized (soneFollowingTimes) {
2298 for (Entry<Sone, Long> soneFollowingTime : soneFollowingTimes.entrySet()) {
2299 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(soneFollowingTime.getKey().getId());
2300 configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").setValue(soneFollowingTime.getValue());
2303 configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").setValue(null);
2306 /* save known posts. */
2307 int postCounter = 0;
2308 synchronized (newPosts) {
2309 for (String knownPostId : knownPosts) {
2310 configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").setValue(knownPostId);
2312 configuration.getStringValue("KnownPosts/" + postCounter + "/ID").setValue(null);
2315 /* save known replies. */
2316 int replyCounter = 0;
2317 synchronized (newReplies) {
2318 for (String knownReplyId : knownReplies) {
2319 configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").setValue(knownReplyId);
2321 configuration.getStringValue("KnownReplies/" + replyCounter + "/ID").setValue(null);
2324 /* save bookmarked posts. */
2325 int bookmarkedPostCounter = 0;
2326 synchronized (bookmarkedPosts) {
2327 for (String bookmarkedPostId : bookmarkedPosts) {
2328 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(bookmarkedPostId);
2331 configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").setValue(null);
2334 configuration.save();
2336 } catch (ConfigurationException ce1) {
2337 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
2339 synchronized (configuration) {
2340 storingConfiguration = false;
2346 * Loads the configuration.
2348 @SuppressWarnings("unchecked")
2349 private void loadConfiguration() {
2350 /* create options. */
2351 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangeValidator(0, Integer.MAX_VALUE), new OptionWatcher<Integer>() {
2354 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2355 SoneInserter.setInsertionDelay(newValue);
2359 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangeValidator(1, Integer.MAX_VALUE)));
2360 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2361 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, new OrValidator<Integer>(new IntegerRangeValidator(50, Integer.MAX_VALUE), new EqualityValidator<Integer>(-1))));
2362 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
2363 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangeValidator(0, 100)));
2364 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangeValidator(-100, 100)));
2365 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
2366 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false, new OptionWatcher<Boolean>() {
2369 @SuppressWarnings("synthetic-access")
2370 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
2371 fcpInterface.setActive(newValue);
2374 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2, new OptionWatcher<Integer>() {
2377 @SuppressWarnings("synthetic-access")
2378 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
2379 fcpInterface.setFullAccessRequired(FullAccessRequired.values()[newValue]);
2383 options.addBooleanOption("SoneRescueMode", new DefaultOption<Boolean>(false));
2384 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
2385 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
2387 /* read options from configuration. */
2388 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
2389 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
2390 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
2391 options.getBooleanOption("ClearOnNextRestart").set(null);
2392 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
2393 if (clearConfiguration) {
2394 /* stop loading the configuration. */
2398 loadConfigurationValue("InsertionDelay");
2399 loadConfigurationValue("PostsPerPage");
2400 loadConfigurationValue("CharactersPerPost");
2401 loadConfigurationValue("PostCutOffLength");
2402 options.getBooleanOption("RequireFullAccess").set(configuration.getBooleanValue("Option/RequireFullAccess").getValue(null));
2403 loadConfigurationValue("PositiveTrust");
2404 loadConfigurationValue("NegativeTrust");
2405 options.getStringOption("TrustComment").set(configuration.getStringValue("Option/TrustComment").getValue(null));
2406 options.getBooleanOption("ActivateFcpInterface").set(configuration.getBooleanValue("Option/ActivateFcpInterface").getValue(null));
2407 options.getIntegerOption("FcpFullAccessRequired").set(configuration.getIntValue("Option/FcpFullAccessRequired").getValue(null));
2408 options.getBooleanOption("SoneRescueMode").set(configuration.getBooleanValue("Option/SoneRescueMode").getValue(null));
2410 /* load known Sones. */
2411 int soneCounter = 0;
2413 String knownSoneId = configuration.getStringValue("KnownSone/" + soneCounter++ + "/ID").getValue(null);
2414 if (knownSoneId == null) {
2417 synchronized (newSones) {
2418 knownSones.add(knownSoneId);
2422 /* load Sone following times. */
2425 String soneId = configuration.getStringValue("SoneFollowingTimes/" + soneCounter + "/Sone").getValue(null);
2426 if (soneId == null) {
2429 long time = configuration.getLongValue("SoneFollowingTimes/" + soneCounter + "/Time").getValue(Long.MAX_VALUE);
2430 Sone followedSone = getSone(soneId);
2431 if (followedSone == null) {
2432 logger.log(Level.WARNING, String.format("Ignoring Sone with invalid ID: %s", soneId));
2434 synchronized (soneFollowingTimes) {
2435 soneFollowingTimes.put(getSone(soneId), time);
2441 /* load known posts. */
2442 int postCounter = 0;
2444 String knownPostId = configuration.getStringValue("KnownPosts/" + postCounter++ + "/ID").getValue(null);
2445 if (knownPostId == null) {
2448 synchronized (newPosts) {
2449 knownPosts.add(knownPostId);
2453 /* load known replies. */
2454 int replyCounter = 0;
2456 String knownReplyId = configuration.getStringValue("KnownReplies/" + replyCounter++ + "/ID").getValue(null);
2457 if (knownReplyId == null) {
2460 synchronized (newReplies) {
2461 knownReplies.add(knownReplyId);
2465 /* load bookmarked posts. */
2466 int bookmarkedPostCounter = 0;
2468 String bookmarkedPostId = configuration.getStringValue("Bookmarks/Post/" + bookmarkedPostCounter++ + "/ID").getValue(null);
2469 if (bookmarkedPostId == null) {
2472 synchronized (bookmarkedPosts) {
2473 bookmarkedPosts.add(bookmarkedPostId);
2480 * Loads an {@link Integer} configuration value for the option with the
2481 * given name, logging validation failures.
2484 * The name of the option to load
2486 private void loadConfigurationValue(String optionName) {
2488 options.getIntegerOption(optionName).set(configuration.getIntValue("Option/" + optionName).getValue(null));
2489 } catch (IllegalArgumentException iae1) {
2490 logger.log(Level.WARNING, "Invalid value for " + optionName + " in configuration, using default.");
2495 * Generate a Sone URI from the given URI and latest edition.
2498 * The URI to derive the Sone URI from
2499 * @return The derived URI
2501 private FreenetURI getSoneUri(String uriString) {
2503 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]);
2505 } catch (MalformedURLException mue1) {
2506 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
2512 // INTERFACE IdentityListener
2519 public void ownIdentityAdded(OwnIdentity ownIdentity) {
2520 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
2521 if (ownIdentity.hasContext("Sone")) {
2522 trustedIdentities.put(ownIdentity, Collections.synchronizedSet(new HashSet<Identity>()));
2523 addLocalSone(ownIdentity);
2531 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
2532 logger.log(Level.FINEST, "Removing OwnIdentity: " + ownIdentity);
2533 trustedIdentities.remove(ownIdentity);
2540 public void identityAdded(OwnIdentity ownIdentity, Identity identity) {
2541 logger.log(Level.FINEST, "Adding Identity: " + identity);
2542 trustedIdentities.get(ownIdentity).add(identity);
2543 addRemoteSone(identity);
2550 public void identityUpdated(OwnIdentity ownIdentity, final Identity identity) {
2551 new Thread(new Runnable() {
2554 @SuppressWarnings("synthetic-access")
2556 Sone sone = getRemoteSone(identity.getId(), false);
2557 sone.setIdentity(identity);
2558 sone.setLatestEdition(Numbers.safeParseLong(identity.getProperty("Sone.LatestEdition"), sone.getLatestEdition()));
2559 soneDownloader.addSone(sone);
2560 soneDownloader.fetchSone(sone);
2569 public void identityRemoved(OwnIdentity ownIdentity, Identity identity) {
2570 trustedIdentities.get(ownIdentity).remove(identity);
2571 boolean foundIdentity = false;
2572 for (Entry<OwnIdentity, Set<Identity>> trustedIdentity : trustedIdentities.entrySet()) {
2573 if (trustedIdentity.getKey().equals(ownIdentity)) {
2576 if (trustedIdentity.getValue().contains(identity)) {
2577 foundIdentity = true;
2580 if (foundIdentity) {
2581 /* some local identity still trusts this identity, don’t remove. */
2584 Sone sone = getSone(identity.getId(), false);
2586 /* TODO - we don’t have the Sone anymore. should this happen? */
2589 synchronized (posts) {
2590 synchronized (newPosts) {
2591 for (Post post : sone.getPosts()) {
2592 posts.remove(post.getId());
2593 newPosts.remove(post.getId());
2594 coreListenerManager.firePostRemoved(post);
2598 synchronized (replies) {
2599 synchronized (newReplies) {
2600 for (PostReply reply : sone.getReplies()) {
2601 replies.remove(reply.getId());
2602 newReplies.remove(reply.getId());
2603 coreListenerManager.fireReplyRemoved(reply);
2607 synchronized (remoteSones) {
2608 remoteSones.remove(identity.getId());
2610 synchronized (newSones) {
2611 newSones.remove(identity.getId());
2612 coreListenerManager.fireSoneRemoved(sone);
2617 // INTERFACE UpdateListener
2624 public void updateFound(Version version, long releaseTime, long latestEdition) {
2625 coreListenerManager.fireUpdateFound(version, releaseTime, latestEdition);
2629 // INTERFACE ImageInsertListener
2636 public void insertStarted(Sone sone) {
2637 coreListenerManager.fireSoneInserting(sone);
2644 public void insertFinished(Sone sone, long insertDuration) {
2645 coreListenerManager.fireSoneInserted(sone, insertDuration);
2652 public void insertAborted(Sone sone, Throwable cause) {
2653 coreListenerManager.fireSoneInsertAborted(sone, cause);
2657 // SONEINSERTLISTENER METHODS
2664 public void imageInsertStarted(Image image) {
2665 logger.log(Level.WARNING, "Image insert started for " + image);
2666 coreListenerManager.fireImageInsertStarted(image);
2673 public void imageInsertAborted(Image image) {
2674 logger.log(Level.WARNING, "Image insert aborted for " + image);
2675 coreListenerManager.fireImageInsertAborted(image);
2682 public void imageInsertFinished(Image image, FreenetURI key) {
2683 logger.log(Level.WARNING, "Image insert finished for " + image + ": " + key);
2684 image.setKey(key.toString());
2685 deleteTemporaryImage(image.getId());
2686 saveSone(image.getSone());
2687 coreListenerManager.fireImageInsertFinished(image);
2694 public void imageInsertFailed(Image image, Throwable cause) {
2695 logger.log(Level.WARNING, "Image insert failed for " + image, cause);
2696 coreListenerManager.fireImageInsertFailed(image, cause);
2700 * Convenience interface for external classes that want to access the core’s
2703 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
2705 public static class Preferences {
2707 /** The wrapped options. */
2708 private final Options options;
2711 * Creates a new preferences object wrapped around the given options.
2714 * The options to wrap
2716 public Preferences(Options options) {
2717 this.options = options;
2721 * Returns the insertion delay.
2723 * @return The insertion delay
2725 public int getInsertionDelay() {
2726 return options.getIntegerOption("InsertionDelay").get();
2730 * Validates the given insertion delay.
2732 * @param insertionDelay
2733 * The insertion delay to validate
2734 * @return {@code true} if the given insertion delay was valid, {@code
2737 public boolean validateInsertionDelay(Integer insertionDelay) {
2738 return options.getIntegerOption("InsertionDelay").validate(insertionDelay);
2742 * Sets the insertion delay
2744 * @param insertionDelay
2745 * The new insertion delay, or {@code null} to restore it to
2747 * @return This preferences
2749 public Preferences setInsertionDelay(Integer insertionDelay) {
2750 options.getIntegerOption("InsertionDelay").set(insertionDelay);
2755 * Returns the number of posts to show per page.
2757 * @return The number of posts to show per page
2759 public int getPostsPerPage() {
2760 return options.getIntegerOption("PostsPerPage").get();
2764 * Validates the number of posts per page.
2766 * @param postsPerPage
2767 * The number of posts per page
2768 * @return {@code true} if the number of posts per page was valid,
2769 * {@code false} otherwise
2771 public boolean validatePostsPerPage(Integer postsPerPage) {
2772 return options.getIntegerOption("PostsPerPage").validate(postsPerPage);
2776 * Sets the number of posts to show per page.
2778 * @param postsPerPage
2779 * The number of posts to show per page
2780 * @return This preferences object
2782 public Preferences setPostsPerPage(Integer postsPerPage) {
2783 options.getIntegerOption("PostsPerPage").set(postsPerPage);
2788 * Returns the number of characters per post, or <code>-1</code> if the
2789 * posts should not be cut off.
2791 * @return The numbers of characters per post
2793 public int getCharactersPerPost() {
2794 return options.getIntegerOption("CharactersPerPost").get();
2798 * Validates the number of characters per post.
2800 * @param charactersPerPost
2801 * The number of characters per post
2802 * @return {@code true} if the number of characters per post was valid,
2803 * {@code false} otherwise
2805 public boolean validateCharactersPerPost(Integer charactersPerPost) {
2806 return options.getIntegerOption("CharactersPerPost").validate(charactersPerPost);
2810 * Sets the number of characters per post.
2812 * @param charactersPerPost
2813 * The number of characters per post, or <code>-1</code> to
2814 * not cut off the posts
2815 * @return This preferences objects
2817 public Preferences setCharactersPerPost(Integer charactersPerPost) {
2818 options.getIntegerOption("CharactersPerPost").set(charactersPerPost);