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.Reply;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.freenet.wot.Identity;
38 import net.pterodactylus.sone.freenet.wot.IdentityListener;
39 import net.pterodactylus.sone.freenet.wot.IdentityManager;
40 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
41 import net.pterodactylus.util.config.Configuration;
42 import net.pterodactylus.util.config.ConfigurationException;
43 import net.pterodactylus.util.logging.Logging;
44 import net.pterodactylus.util.number.Numbers;
45 import freenet.keys.FreenetURI;
50 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52 public class Core implements IdentityListener {
55 * Enumeration for the possible states of a {@link Sone}.
57 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59 public enum SoneStatus {
61 /** The Sone is unknown, i.e. not yet downloaded. */
64 /** The Sone is idle, i.e. not being downloaded or inserted. */
67 /** The Sone is currently being inserted. */
70 /** The Sone is currently being downloaded. */
75 private static final Logger logger = Logging.getLogger(Core.class);
78 private final Options options = new Options();
80 /** The configuration. */
81 private final Configuration configuration;
83 /** The identity manager. */
84 private final IdentityManager identityManager;
86 /** Interface to freenet. */
87 private final FreenetInterface freenetInterface;
89 /** The Sone downloader. */
90 private final SoneDownloader soneDownloader;
92 /** The Sones’ statuses. */
93 /* synchronize access on itself. */
94 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
96 /** Sone inserters. */
97 /* synchronize access on this on localSones. */
98 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
100 /** All local Sones. */
101 /* synchronize access on this on itself. */
102 private Map<String, Sone> localSones = new HashMap<String, Sone>();
104 /** All remote Sones. */
105 /* synchronize access on this on itself. */
106 private Map<String, Sone> remoteSones = new HashMap<String, Sone>();
109 private Map<String, Post> posts = new HashMap<String, Post>();
112 private Map<String, Reply> replies = new HashMap<String, Reply>();
115 * Creates a new core.
117 * @param configuration
118 * The configuration of the core
119 * @param freenetInterface
120 * The freenet interface
121 * @param identityManager
122 * The identity manager
124 public Core(Configuration configuration, FreenetInterface freenetInterface, IdentityManager identityManager) {
125 this.configuration = configuration;
126 this.freenetInterface = freenetInterface;
127 this.identityManager = identityManager;
128 this.soneDownloader = new SoneDownloader(this, freenetInterface);
136 * Returns the options used by the core.
138 * @return The options of the core
140 public Options getOptions() {
145 * Returns the identity manager used by the core.
147 * @return The identity manager
149 public IdentityManager getIdentityManager() {
150 return identityManager;
154 * Returns the status of the given Sone.
157 * The Sone to get the status for
158 * @return The status of the Sone
160 public SoneStatus getSoneStatus(Sone sone) {
161 synchronized (soneStatuses) {
162 return soneStatuses.get(sone);
167 * Sets the status of the given Sone.
170 * The Sone to set the status of
174 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
175 synchronized (soneStatuses) {
176 soneStatuses.put(sone, soneStatus);
181 * Returns all Sones, remote and local.
185 public Set<Sone> getSones() {
186 Set<Sone> allSones = new HashSet<Sone>();
187 allSones.addAll(getLocalSones());
188 allSones.addAll(getRemoteSones());
193 * Returns the Sone with the given ID, regardless whether it’s local or
197 * The ID of the Sone to get
198 * @return The Sone with the given ID, or {@code null} if there is no such
201 public Sone getSone(String id) {
202 Sone sone = getRemoteSone(id);
206 sone = getLocalSone(id);
211 * Returns whether the given Sone is a local Sone.
214 * The Sone to check for its locality
215 * @return {@code true} if the given Sone is local, {@code false} otherwise
217 public boolean isLocalSone(Sone sone) {
218 synchronized (localSones) {
219 return localSones.containsKey(sone.getId());
224 * Returns all local Sones.
226 * @return All local Sones
228 public Set<Sone> getLocalSones() {
229 synchronized (localSones) {
230 return new HashSet<Sone>(localSones.values());
235 * Returns the local Sone with the given ID.
238 * The ID of the Sone to get
239 * @return The Sone, or {@code null} if there is no Sone with the given ID
241 public Sone getLocalSone(String id) {
242 synchronized (localSones) {
243 return localSones.get(id);
248 * Returns all remote Sones.
250 * @return All remote Sones
252 public Set<Sone> getRemoteSones() {
253 synchronized (remoteSones) {
254 return new HashSet<Sone>(remoteSones.values());
259 * Returns the remote Sone with the given ID.
262 * The ID of the remote Sone to get
263 * @return The Sone, or {@code null} if there is no such Sone
265 public Sone getRemoteSone(String id) {
266 synchronized (remoteSones) {
267 return remoteSones.get(id);
272 * Returns whether the given Sone is a remote Sone.
276 * @return {@code true} if the given Sone is a remote Sone, {@code false}
279 public boolean isRemoteSone(Sone sone) {
280 synchronized (remoteSones) {
281 return remoteSones.containsKey(sone.getId());
286 * Returns the post with the given ID.
289 * The ID of the post to get
290 * @return The post, or {@code null} if there is no such post
292 public Post getPost(String postId) {
293 synchronized (posts) {
294 return posts.get(postId);
299 * Returns the reply with the given ID.
302 * The ID of the reply to get
303 * @return The reply, or {@code null} if there is no such reply
305 public Reply getReply(String replyId) {
306 synchronized (replies) {
307 return replies.get(replyId);
312 * Returns all replies for the given post, order ascending by time.
315 * The post to get all replies for
316 * @return All replies for the given post
318 public List<Reply> getReplies(Post post) {
319 Set<Sone> sones = getSones();
320 List<Reply> replies = new ArrayList<Reply>();
321 for (Sone sone : sones) {
322 for (Reply reply : sone.getReplies()) {
323 if (reply.getPost().equals(post)) {
328 Collections.sort(replies, Reply.TIME_COMPARATOR);
333 * Returns all Sones that have liked the given post.
336 * The post to get the liking Sones for
337 * @return The Sones that like the given post
339 public Set<Sone> getLikes(Post post) {
340 Set<Sone> sones = new HashSet<Sone>();
341 for (Sone sone : getSones()) {
342 if (sone.getLikedPostIds().contains(post.getId())) {
350 * Returns all Sones that have liked the given reply.
353 * The reply to get the liking Sones for
354 * @return The Sones that like the given reply
356 public Set<Sone> getLikes(Reply reply) {
357 Set<Sone> sones = new HashSet<Sone>();
358 for (Sone sone : getSones()) {
359 if (sone.getLikedPostIds().contains(reply.getId())) {
371 * Adds a local Sone from the given ID which has to be the ID of an own
375 * The ID of an own identity to add a Sone for
376 * @return The added (or already existing) Sone
378 public Sone addLocalSone(String id) {
379 synchronized (localSones) {
380 if (localSones.containsKey(id)) {
381 logger.log(Level.FINE, "Tried to add known local Sone: %s", id);
382 return localSones.get(id);
384 OwnIdentity ownIdentity = identityManager.getOwnIdentity(id);
385 if (ownIdentity == null) {
386 logger.log(Level.INFO, "Invalid Sone ID: %s", id);
389 return addLocalSone(ownIdentity);
394 * Adds a local Sone from the given own identity.
397 * The own identity to create a Sone from
398 * @return The added (or already existing) Sone
400 public Sone addLocalSone(OwnIdentity ownIdentity) {
401 if (ownIdentity == null) {
402 logger.log(Level.WARNING, "Given OwnIdentity is null!");
405 synchronized (localSones) {
406 if (localSones.containsKey(ownIdentity.getId())) {
407 logger.log(Level.FINE, "Tried to add known local Sone: %s", ownIdentity);
408 return localSones.get(ownIdentity.getId());
410 String latestEdition = ownIdentity.getProperty("Sone.LatestEdition");
411 final Sone sone = new Sone(ownIdentity).setInsertUri(getSoneUri(ownIdentity.getInsertUri(), latestEdition)).setRequestUri(getSoneUri(ownIdentity.getRequestUri(), latestEdition));
412 /* TODO - load posts ’n stuff */
413 localSones.put(ownIdentity.getId(), sone);
414 SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
415 soneInserters.put(sone, soneInserter);
416 soneInserter.start();
417 setSoneStatus(sone, SoneStatus.idle);
418 new Thread(new Runnable() {
421 @SuppressWarnings("synthetic-access")
423 soneDownloader.fetchSone(sone);
426 }, "Sone Downloader").start();
432 * Creates a new Sone for the given own identity.
435 * The own identity to create a Sone for
436 * @return The created Sone
438 public Sone createSone(OwnIdentity ownIdentity) {
439 identityManager.addContext(ownIdentity, "Sone");
440 Sone sone = addLocalSone(ownIdentity);
441 synchronized (sone) {
442 /* mark as modified so that it gets inserted immediately. */
443 sone.setModificationCounter(sone.getModificationCounter() + 1);
449 * Adds the Sone of the given identity.
452 * The identity whose Sone to add
453 * @return The added or already existing Sone
455 public Sone addRemoteSone(Identity identity) {
456 if (identity == null) {
457 logger.log(Level.WARNING, "Given Identity is null!");
460 synchronized (remoteSones) {
461 if (remoteSones.containsKey(identity.getId())) {
462 logger.log(Level.FINE, "Identity already exists: %s", identity);
463 return remoteSones.get(identity.getId());
465 Sone sone = new Sone(identity);
466 sone.setRequestUri(getSoneUri(identity.getRequestUri(), identity.getProperty("Sone.LatestEdition")));
467 remoteSones.put(identity.getId(), sone);
468 soneDownloader.addSone(sone);
469 setSoneStatus(sone, SoneStatus.idle);
475 * Updates the stores Sone with the given Sone.
480 public void updateSone(Sone sone) {
481 if (isRemoteSone(sone)) {
482 Sone storedSone = getRemoteSone(sone.getId());
483 if (!(sone.getTime() > storedSone.getTime())) {
484 logger.log(Level.FINE, "Downloaded Sone %s is not newer than stored Sone %s.", new Object[] { sone, storedSone });
487 synchronized (posts) {
488 for (Post post : storedSone.getPosts()) {
489 posts.remove(post.getId());
491 for (Post post : sone.getPosts()) {
492 posts.put(post.getId(), post);
495 synchronized (replies) {
496 for (Reply reply : storedSone.getReplies()) {
497 replies.remove(reply.getId());
499 for (Reply reply : sone.getReplies()) {
500 replies.put(reply.getId(), reply);
503 synchronized (storedSone) {
504 storedSone.setTime(sone.getTime());
505 storedSone.setProfile(sone.getProfile());
506 storedSone.setPosts(sone.getPosts());
507 storedSone.setReplies(sone.getReplies());
508 storedSone.setLikePostIds(sone.getLikedPostIds());
509 storedSone.setLikeReplyIds(sone.getLikedReplyIds());
510 storedSone.updateUris(sone.getRequestUri().getEdition());
512 saveSone(storedSone);
517 * Deletes the given Sone. This will remove the Sone from the
518 * {@link #getLocalSone(String) local Sones}, stops its {@link SoneInserter}
519 * and remove the context from its identity.
524 public void deleteSone(Sone sone) {
525 if (!(sone.getIdentity() instanceof OwnIdentity)) {
526 logger.log(Level.WARNING, "Tried to delete Sone of non-own identity: %s", sone);
529 synchronized (localSones) {
530 if (!localSones.containsKey(sone.getId())) {
531 logger.log(Level.WARNING, "Tried to delete non-local Sone: %s", sone);
534 localSones.remove(sone.getId());
535 soneInserters.remove(sone.getId()).stop();
537 identityManager.removeContext((OwnIdentity) sone.getIdentity(), "Sone");
541 * Saves the given Sone. This will persist all local settings for the given
542 * Sone, such as the friends list and similar, private options.
547 public void saveSone(Sone sone) {
548 if (!isLocalSone(sone)) {
549 logger.log(Level.FINE, "Tried to save non-local Sone: %s", sone);
551 /* TODO - implement saving. */
555 * Creates a new post.
558 * The Sone that creates the post
560 * The text of the post
562 public void createPost(Sone sone, String text) {
563 createPost(sone, System.currentTimeMillis(), text);
567 * Creates a new post.
570 * The Sone that creates the post
572 * The time of the post
574 * The text of the post
576 public void createPost(Sone sone, long time, String text) {
577 if (!isLocalSone(sone)) {
578 logger.log(Level.FINE, "Tried to create post for non-local Sone: %s", sone);
581 Post post = new Post(sone, time, text);
582 synchronized (posts) {
583 posts.put(post.getId(), post);
590 * Deletes the given post.
595 public void deletePost(Post post) {
596 if (!isLocalSone(post.getSone())) {
597 logger.log(Level.WARNING, "Tried to delete post of non-local Sone: %s", post.getSone());
600 post.getSone().removePost(post);
601 synchronized (posts) {
602 posts.remove(post.getId());
604 saveSone(post.getSone());
608 * Creates a new reply.
611 * The Sone that creates the reply
613 * The post that this reply refers to
615 * The text of the reply
617 public void createReply(Sone sone, Post post, String text) {
618 createReply(sone, post, System.currentTimeMillis(), text);
622 * Creates a new reply.
625 * The Sone that creates the reply
627 * The post that this reply refers to
629 * The time of the reply
631 * The text of the reply
633 public void createReply(Sone sone, Post post, long time, String text) {
634 if (!isLocalSone(sone)) {
635 logger.log(Level.FINE, "Tried to create reply for non-local Sone: %s", sone);
638 Reply reply = new Reply(sone, post, System.currentTimeMillis(), text);
639 synchronized (replies) {
640 replies.put(reply.getId(), reply);
642 sone.addReply(reply);
647 * Deletes the given reply.
650 * The reply to delete
652 public void deleteReply(Reply reply) {
653 Sone sone = reply.getSone();
654 if (!isLocalSone(sone)) {
655 logger.log(Level.FINE, "Tried to delete non-local reply: %s", reply);
658 synchronized (replies) {
659 replies.remove(reply.getId());
661 sone.removeReply(reply);
668 public void start() {
676 synchronized (localSones) {
677 for (SoneInserter soneInserter : soneInserters.values()) {
689 * Loads the configuration.
691 @SuppressWarnings("unchecked")
692 private void loadConfiguration() {
693 /* create options. */
694 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new OptionWatcher<Integer>() {
697 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
698 SoneInserter.setInsertionDelay(newValue);
702 options.addBooleanOption("ClearOnNextRestart", new DefaultOption<Boolean>(false));
703 options.addBooleanOption("ReallyClearOnNextRestart", new DefaultOption<Boolean>(false));
705 /* read options from configuration. */
706 options.getBooleanOption("ClearOnNextRestart").set(configuration.getBooleanValue("Option/ClearOnNextRestart").getValue(null));
707 options.getBooleanOption("ReallyClearOnNextRestart").set(configuration.getBooleanValue("Option/ReallyClearOnNextRestart").getValue(null));
708 boolean clearConfiguration = options.getBooleanOption("ClearOnNextRestart").get() && options.getBooleanOption("ReallyClearOnNextRestart").get();
709 options.getBooleanOption("ClearOnNextRestart").set(null);
710 options.getBooleanOption("ReallyClearOnNextRestart").set(null);
711 if (clearConfiguration) {
712 /* stop loading the configuration. */
716 options.getIntegerOption("InsertionDelay").set(configuration.getIntValue("Option/InsertionDelay").getValue(null));
721 * Saves the current options.
723 private void saveConfiguration() {
724 /* store the options first. */
726 configuration.getIntValue("Option/InsertionDelay").setValue(options.getIntegerOption("InsertionDelay").getReal());
727 configuration.getBooleanValue("Option/ClearOnNextRestart").setValue(options.getBooleanOption("ClearOnNextRestart").getReal());
728 configuration.getBooleanValue("Option/ReallyClearOnNextRestart").setValue(options.getBooleanOption("ReallyClearOnNextRestart").getReal());
729 } catch (ConfigurationException ce1) {
730 logger.log(Level.SEVERE, "Could not store configuration!", ce1);
735 * Generate a Sone URI from the given URI and latest edition.
738 * The URI to derive the Sone URI from
739 * @param latestEditionString
740 * The latest edition as a {@link String}, or {@code null}
741 * @return The derived URI
743 private FreenetURI getSoneUri(String uriString, String latestEditionString) {
745 FreenetURI uri = new FreenetURI(uriString).setDocName("Sone").setMetaString(new String[0]).setSuggestedEdition(Numbers.safeParseLong(latestEditionString, (long) 0));
747 } catch (MalformedURLException mue1) {
748 logger.log(Level.WARNING, "Could not create Sone URI from URI: " + uriString, mue1);
754 // INTERFACE IdentityListener
761 public void ownIdentityAdded(OwnIdentity ownIdentity) {
762 logger.log(Level.FINEST, "Adding OwnIdentity: " + ownIdentity);
763 if (ownIdentity.hasContext("Sone")) {
764 addLocalSone(ownIdentity);
772 public void ownIdentityRemoved(OwnIdentity ownIdentity) {
780 public void identityAdded(Identity identity) {
781 logger.log(Level.FINEST, "Adding Identity: " + identity);
782 addRemoteSone(identity);
789 public void identityUpdated(Identity identity) {
797 public void identityRemoved(Identity identity) {