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.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.core.Options.DefaultOption;
32 import net.pterodactylus.sone.core.Options.Option;
33 import net.pterodactylus.sone.core.Options.OptionWatcher;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.Profile;
36 import net.pterodactylus.sone.data.Reply;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.freenet.wot.Identity;
39 import net.pterodactylus.sone.freenet.wot.IdentityListener;
40 import net.pterodactylus.sone.freenet.wot.IdentityManager;
41 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
42 import net.pterodactylus.util.config.Configuration;
43 import net.pterodactylus.util.config.ConfigurationException;
44 import net.pterodactylus.util.logging.Logging;
45 import net.pterodactylus.util.number.Numbers;
46 import freenet.keys.FreenetURI;
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 public class Core implements IdentityListener {
56 * Enumeration for the possible states of a {@link Sone}.
58 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
60 public enum SoneStatus {
62 /** The Sone is unknown, i.e. not yet downloaded. */
65 /** The Sone is idle, i.e. not being downloaded or inserted. */
68 /** The Sone is currently being inserted. */
71 /** The Sone is currently being downloaded. */
76 private static final Logger logger = Logging.getLogger(Core.class);
79 private final Options options = new Options();
81 /** The configuration. */
82 private final Configuration configuration;
84 /** The identity manager. */
85 private final IdentityManager identityManager;
87 /** Interface to freenet. */
88 private final FreenetInterface freenetInterface;
90 /** The Sone downloader. */
91 private final SoneDownloader soneDownloader;
93 /** The Sones’ statuses. */
94 /* synchronize access on itself. */
95 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
97 /** Sone inserters. */
98 /* synchronize access on this on localSones. */
99 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
101 /** All local Sones. */
102 /* synchronize access on this on itself. */
103 private Map<String, Sone> localSones = new HashMap<String, Sone>();
105 /** All remote Sones. */
106 /* synchronize access on this on itself. */
107 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
110 private Map<String, Post> posts = new HashMap<String, Post>();
113 private Map<String, Reply> replies = new HashMap<String, Reply>();
116 * Creates a new core.
118 * @param configuration
119 * The configuration of the core
120 * @param freenetInterface
121 * The freenet interface
122 * @param identityManager
123 * The identity manager
125 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
126 this.configuration = configuration;
127 this.freenetInterface = freenetInterface;
128 this.identityManager = identityManager;
129 this.soneDownloader = new SoneDownloader(this, freenetInterface);
137 * Returns the options used by the core.
139 * @return The options of the core
141 public Options getOptions() {
146 * Returns the identity manager used by the core.
148 * @return The identity manager
150 public IdentityManager getIdentityManager() {
151 return identityManager;
155 * Returns the status of the given Sone.
158 * The Sone to get the status for
159 * @return The status of the Sone
161 public SoneStatus getSoneStatus(Sone sone) {
162 synchronized (soneStatuses) {
163 return soneStatuses.get(sone);
168 * Sets the status of the given Sone.
171 * The Sone to set the status of
175 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
176 synchronized (soneStatuses) {
177 soneStatuses.put(sone, soneStatus);
182 * Returns all Sones, remote and local.
186 public Set<Sone> getSones() {
187 Set<Sone> allSones = new HashSet<Sone>();
188 allSones.addAll(getLocalSones());
189 allSones.addAll(getRemoteSones());
194 * Returns the Sone with the given ID, regardless whether it’s local or
198 * The ID of the Sone to get
199 * @return The Sone with the given ID, or {@code null} if there is no such
202 public Sone getSone(String id) {
203 Sone sone = getRemoteSone(id);
207 sone = getLocalSone(id);
212 * Returns whether the given Sone is a local Sone.
215 * The Sone to check for its locality
216 * @return {@code true} if the given Sone is local, {@code false} otherwise
218 public boolean isLocalSone(Sone sone) {
219 synchronized (localSones) {
220 return localSones.containsKey(sone.getId());
225 * Returns all local Sones.
227 * @return All local Sones
229 public Set<Sone> getLocalSones() {
230 synchronized (localSones) {
231 return new HashSet<Sone>(localSones.values());
236 * Returns the local Sone with the given ID.
239 * The ID of the Sone to get
240 * @return The Sone, or {@code null} if there is no Sone with the given ID
242 public Sone getLocalSone(String id) {
243 synchronized (localSones) {
244 return localSones.get(id);
249 * Returns all remote Sones.
251 * @return All remote Sones
253 public Set<Sone> getRemoteSones() {
254 synchronized (remoteSones) {
255 return new HashSet<Sone>(remoteSones.values());
260 * Returns the remote Sone with the given ID.
263 * The ID of the remote Sone to get
264 * @return The Sone, or {@code null} if there is no such Sone
266 public Sone getRemoteSone(String id) {
267 synchronized (remoteSones) {
268 return remoteSones.get(id);
273 * Returns whether the given Sone is a remote Sone.
277 * @return {@code true} if the given Sone is a remote Sone, {@code false}
280 public boolean isRemoteSone(Sone sone) {
281 synchronized (remoteSones) {
282 return remoteSones.containsKey(sone.getId());
287 * Returns the post with the given ID.
290 * The ID of the post to get
291 * @return The post, or {@code null} if there is no such post
293 public Post getPost(String postId) {
294 synchronized (posts) {
295 return posts.get(postId);
300 * Returns the reply with the given ID.
303 * The ID of the reply to get
304 * @return The reply, or {@code null} if there is no such reply
306 public Reply getReply(String replyId) {
307 synchronized (replies) {
308 return replies.get(replyId);
313 * Returns all replies for the given post, order ascending by time.
316 * The post to get all replies for
317 * @return All replies for the given post
319 public List<Reply> getReplies(Post post) {
320 Set<Sone> sones = getSones();
321 List<Reply> replies = new ArrayList<Reply>();
322 for (Sone sone : sones) {
323 for (Reply reply : sone.getReplies()) {
324 if (reply.getPost().equals(post)) {
329 Collections.sort(replies, Reply.TIME_COMPARATOR);
334 * Returns all Sones that have liked the given post.
337 * The post to get the liking Sones for
338 * @return The Sones that like the given post
340 public Set<Sone> getLikes(Post post) {
341 Set<Sone> sones = new HashSet<Sone>();
342 for (Sone sone : getSones()) {
343 if (sone.getLikedPostIds().contains(post.getId())) {
351 * Returns all Sones that have liked the given reply.
354 * The reply to get the liking Sones for
355 * @return The Sones that like the given reply
357 public Set<Sone> getLikes(Reply reply) {
358 Set<Sone> sones = new HashSet<Sone>();
359 for (Sone sone : getSones()) {
360 if (sone.getLikedPostIds().contains(reply.getId())) {
372 * Adds a local Sone from the given ID which has to be the ID of an own
376 * The ID of an own identity to add a Sone for
377 * @return The added (or already existing) Sone
379 public Sone addLocalSone(String id) {
380 synchronized (localSones) {
381 if (localSones.containsKey(id)) {
382 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
383 return localSones.get(id);
385 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
386 if (ownIdentity == null) {
387 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
390 return addLocalSone(ownIdentity);
395 * Adds a local Sone from the given own identity.
398 * The own identity to create a Sone from
399 * @return The added (or already existing) Sone
401 public Sone addLocalSone(OwnIdentity ownIdentity) {
402 if (ownIdentity == null) {
403 logger.log(Level.WARNING, "Given OwnIdentity is null!");
406 synchronized (localSones) {
407 if (localSones.containsKey(ownIdentity.getId())) {
408 logger.log(Level.FINE, "Tried to add known local Sone: %s", ownIdentity);
409 return localSones.get(ownIdentity.getId());
413 sone = new Sone(ownIdentity).setInsertUri(new FreenetURI(ownIdentity.getInsertUri())).setRequestUri(new FreenetURI(ownIdentity.getRequestUri()));
414 sone.setLatestEdition(Numbers.safeParseLong(ownIdentity.getProperty("Sone.LatestEdition"), (long) 0));
415 } catch (MalformedURLException mue1) {
416 logger.log(Level.SEVERE, "Could not convert the Identity’s URIs to Freenet URIs: " + ownIdentity.getInsertUri() + ", " + ownIdentity.getRequestUri(), mue1);
419 /* TODO - load posts ’n stuff */
420 localSones.put(ownIdentity.getId(), sone);
421 SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
422 soneInserters.put(sone, soneInserter);
423 soneInserter.start();
424 setSoneStatus(sone, SoneStatus.idle);
425 new Thread(new Runnable() {
428 @SuppressWarnings("synthetic-access")
430 soneDownloader.fetchSone(sone);
433 }, "Sone Downloader").start();
439 * Creates a new Sone for the given own identity.
442 * The own identity to create a Sone for
443 * @return The created Sone
445 public Sone createSone(OwnIdentity ownIdentity) {
446 identityManager.addContext(ownIdentity, "Sone");
447 Sone sone = addLocalSone(ownIdentity);
448 synchronized (sone) {
449 /* mark as modified so that it gets inserted immediately. */
450 sone.setModificationCounter(sone.getModificationCounter() + 1);
456 * Adds the Sone of the given identity.
459 * The identity whose Sone to add
460 * @return The added or already existing Sone
462 public Sone addRemoteSone(Identity identity) {
463 if (identity == null) {
464 logger.log(Level.WARNING, "Given Identity is null!");
467 synchronized (remoteSones) {
468 if (remoteSones.containsKey(identity.getId())) {
469 logger.log(Level.FINE, "Identity already exists: %s", identity);
470 return remoteSones.get(identity.getId());
472 Sone sone = new Sone(identity);
473 sone.setRequestUri(getSoneUri(identity.getRequestUri(), identity.getProperty("Sone.LatestEdition")));
474 remoteSones.put(identity.getId(), sone);
475 soneDownloader.addSone(sone);
476 setSoneStatus(sone, SoneStatus.idle);
482 * Updates the stores Sone with the given Sone.
487 public void updateSone(Sone sone) {
488 if (isRemoteSone(sone)) {
489 Sone storedSone = getRemoteSone(sone.getId());
490 if (!(sone.getTime() > storedSone.getTime())) {
491 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
494 synchronized (posts) {
495 for (Post post : storedSone.getPosts()) {
496 posts.remove(post.getId());
498 for (Post post : sone.getPosts()) {
499 posts.put(post.getId(), post);
502 synchronized (replies) {
503 for (Reply reply : storedSone.getReplies()) {
504 replies.remove(reply.getId());
506 for (Reply reply : sone.getReplies()) {
507 replies.put(reply.getId(), reply);
510 synchronized (storedSone) {
511 storedSone.setTime(sone.getTime());
512 storedSone.setProfile(sone.getProfile());
513 storedSone.setPosts(sone.getPosts());
514 storedSone.setReplies(sone.getReplies());
515 storedSone.setLikePostIds(sone.getLikedPostIds());
516 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
517 storedSone.setLatestEdition(sone.getRequestUri().getEdition());
519 saveSone(storedSone);
524 * Deletes the given Sone. This will remove the Sone from the
525 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
526 * and remove the context from its identity.
531 public void deleteSone(Sone sone) {
532 if (!(sone.getIdentity() instanceof OwnIdentity)) {
533 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
536 synchronized (localSones) {
537 if (!localSones.containsKey(sone.getId())) {
538 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
541 localSones.remove(sone.getId());
542 soneInserters.remove(sone.getId()).stop();
544 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
548 * Saves the given Sone. This will persist all local settings for the given
549 * Sone, such as the friends list and similar, private options.
554 public void saveSone(Sone sone) {
555 if (!isLocalSone(sone)) {
556 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
559 if (!(sone.getIdentity() instanceof OwnIdentity)) {
560 logger.log(Level.WARNING, "Local Sone without OwnIdentity found, refusing to save: %s", sone);
564 logger.log(Level.INFO, "Saving Sone: %s", sone);
565 identityManager.setProperty((OwnIdentity) sone.getIdentity(), "Sone.LatestEdition", String.valueOf(sone.getLatestEdition()));
567 /* save Sone into configuration. */
568 String sonePrefix = "Sone/" + sone.getId();
569 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
572 Profile profile = sone.getProfile();
573 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
574 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
575 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
576 configuration.getIntValue(sonePrefix + "/Profile/BirthDay").setValue(profile.getBirthDay());
577 configuration.getIntValue(sonePrefix + "/Profile/BirthMonth").setValue(profile.getBirthMonth());
578 configuration.getIntValue(sonePrefix + "/Profile/BirthYear").setValue(profile.getBirthYear());
582 for (Post post : sone.getPosts()) {
583 String postPrefix = sonePrefix + "/Posts/" + postCounter++;
584 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
585 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
586 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
588 configuration.getStringValue(sonePrefix + "/Posts/" + postCounter + "/ID").setValue(null);
591 int replyCounter = 0;
592 for (Reply reply : sone.getReplies()) {
593 String replyPrefix = sonePrefix + "/Replies/" + replyCounter++;
594 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
595 configuration.getStringValue(replyPrefix + "/Post/ID").setValue(reply.getPost().getId());
596 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
597 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
599 configuration.getStringValue(sonePrefix + "/Replies/" + replyCounter + "/ID").setValue(null);
601 /* save post likes. */
602 int postLikeCounter = 0;
603 for (String postId : sone.getLikedPostIds()) {
604 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter++ + "/ID").setValue(postId);
606 configuration.getStringValue(sonePrefix + "/Likes/Post/" + postLikeCounter + "/ID").setValue(null);
608 /* save reply likes. */
609 int replyLikeCounter = 0;
610 for (String replyId : sone.getLikedReplyIds()) {
611 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter++ + "/ID").setValue(replyId);
613 configuration.getStringValue(sonePrefix + "/Likes/Reply/" + replyLikeCounter + "/ID").setValue(null);
615 logger.log(Level.INFO, "Sone %s saved.", sone);
616 } catch (ConfigurationException ce1) {
617 logger.log(Level.WARNING, "Could not save Sone: " + sone, ce1);
622 * Creates a new post.
625 * The Sone that creates the post
627 * The text of the post
629 public void createPost(Sone sone, String text) {
630 createPost(sone, System.currentTimeMillis(), text);
634 * Creates a new post.
637 * The Sone that creates the post
639 * The time of the post
641 * The text of the post
643 public void createPost(Sone sone, long time, String text) {
644 if (!isLocalSone(sone)) {
645 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
648 Post post = new Post(sone, time, text);
649 synchronized (posts) {
650 posts.put(post.getId(), post);
657 * Deletes the given post.
662 public void deletePost(Post post) {
663 if (!isLocalSone(post.getSone())) {
664 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
667 post.getSone().removePost(post);
668 synchronized (posts) {
669 posts.remove(post.getId());
671 saveSone(post.getSone());
675 * Creates a new reply.
678 * The Sone that creates the reply
680 * The post that this reply refers to
682 * The text of the reply
684 public void createReply(Sone sone, Post post, String text) {
685 createReply(sone, post, System.currentTimeMillis(), text);
689 * Creates a new reply.
692 * The Sone that creates the reply
694 * The post that this reply refers to
696 * The time of the reply
698 * The text of the reply
700 public void createReply(Sone sone, Post post, long time, String text) {
701 if (!isLocalSone(sone)) {
702 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
705 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
706 synchronized (replies) {
707 replies.put(reply.getId(), reply);
709 sone.addReply(reply);
714 * Deletes the given reply.
717 * The reply to delete
719 public void deleteReply(Reply reply) {
720 Sone sone = reply.getSone();
721 if (!isLocalSone(sone)) {
722 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
725 synchronized (replies) {
726 replies.remove(reply.getId());
728 sone.removeReply(reply);
735 public void start() {
743 synchronized (localSones) {
744 for (SoneInserter soneInserter : soneInserters.values()) {
756 * Loads the configuration.
758 @SuppressWarnings("unchecked")
759 private void loadConfiguration() {
760 /* create options. */
761 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
764 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
765 SoneInserter.setInsertionDelay(newValue);
769 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
770 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
772 /* read options from configuration. */
773 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
774 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
775 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
776 options.getBooleanOption("ClearOnNextRestart").set(null);
777 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
778 if (clearConfiguration) {
779 /* stop loading the configuration. */
783 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
788 * Saves the current options.
790 private void saveConfiguration() {
791 /* store the options first. */
793 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
794 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
795 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
796 } catch (ConfigurationException ce1) {
797 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
802 * Generate a Sone URI from the given URI and latest edition.
805 * The URI to derive the Sone URI from
806 * @param latestEditionString
807 * The latest edition as a {@link String}, or {@code null}
808 * @return The derived URI
810 private FreenetURI getSoneUri(String uriString, String latestEditionString) {
812 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]).setSuggestedEdition(Numbers.safeParseLong(latestEditionString, (long) 0));
814 } catch (MalformedURLException mue1) {
815 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
821 // INTERFACE IdentityListener
828 public void ownIdentityAdded(OwnIdentity ownIdentity) {
829 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
830 if (ownIdentity.hasContext("Sone")) {
831 addLocalSone(ownIdentity);
839 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
847 public void identityAdded(Identity identity) {
848 logger.log(Level.FINEST, "Adding Identity: " + identity);
849 addRemoteSone(identity);
856 public void identityUpdated(Identity identity) {
864 public void identityRemoved(Identity identity) {