2 * FreenetSone - 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.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
30 import java.util.UUID;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.SoneException.Type;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.util.config.Configuration;
40 import net.pterodactylus.util.config.ConfigurationException;
41 import net.pterodactylus.util.filter.Filter;
42 import net.pterodactylus.util.filter.Filters;
43 import net.pterodactylus.util.logging.Logging;
44 import net.pterodactylus.util.service.AbstractService;
45 import freenet.client.FetchResult;
46 import freenet.keys.FreenetURI;
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 public class Core extends AbstractService {
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 idle, i.e. not being downloaded or inserted. */
65 /** The Sone is currently being inserted. */
68 /** The Sone is currently being downloaded. */
73 private static final Logger logger = Logging.getLogger(Core.class);
75 /** The configuration. */
76 private Configuration configuration;
78 /** Interface to freenet. */
79 private FreenetInterface freenetInterface;
81 /** The Sone downloader. */
82 private SoneDownloader soneDownloader;
84 /** The local Sones. */
85 private final Set<Sone> localSones = new HashSet<Sone>();
87 /** Sone inserters. */
88 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
90 /** The Sones’ statuses. */
91 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
93 /* various caches follow here. */
95 /** Cache for all known Sones. */
96 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
98 /** Cache for all known posts. */
99 private final Map<String, Post> postCache = new HashMap<String, Post>();
101 /** Cache for all known replies. */
102 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
105 * Creates a new core.
116 * Sets the configuration of the core.
118 * @param configuration
119 * The configuration of the core
120 * @return This core (for method chaining)
122 public Core configuration(Configuration configuration) {
123 this.configuration = configuration;
128 * Sets the Freenet interface to use.
130 * @param freenetInterface
131 * The Freenet interface to use
132 * @return This core (for method chaining)
134 public Core freenetInterface(FreenetInterface freenetInterface) {
135 this.freenetInterface = freenetInterface;
136 soneDownloader = new SoneDownloader(this, freenetInterface);
137 soneDownloader.start();
142 * Returns the local Sones.
144 * @return The local Sones
146 public Set<Sone> getSones() {
147 return Collections.unmodifiableSet(localSones);
151 * Returns the Sone with the given ID, or an empty Sone that has been
152 * initialized with the given ID.
158 public Sone getSone(String soneId) {
159 if (!soneCache.containsKey(soneId)) {
160 Sone sone = new Sone(soneId);
161 soneCache.put(soneId, sone);
162 setSoneStatus(sone, SoneStatus.idle);
164 return soneCache.get(soneId);
168 * Returns all known sones.
170 * @return All known sones
172 public Collection<Sone> getKnownSones() {
173 return soneCache.values();
177 * Gets all known Sones that are not local Sones.
179 * @return All remote Sones
181 public Collection<Sone> getRemoteSones() {
182 return Filters.filteredCollection(getKnownSones(), new Filter<Sone>() {
185 @SuppressWarnings("synthetic-access")
186 public boolean filterObject(Sone object) {
187 return !localSones.contains(object);
193 * Returns the status of the given Sone.
196 * The Sone to get the status for
197 * @return The status of the Sone
199 public SoneStatus getSoneStatus(Sone sone) {
200 return soneStatuses.get(sone);
204 * Sets the status of the Sone.
207 * The Sone to set the status for
209 * The status of the Sone
211 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
212 soneStatuses.put(sone, soneStatus);
216 * Creates a new post and adds it to the given Sone.
219 * The sone that creates the post
221 * The text of the post
222 * @return The created post
224 public Post createPost(Sone sone, String text) {
225 return createPost(sone, System.currentTimeMillis(), text);
229 * Creates a new post and adds it to the given Sone.
232 * The Sone that creates the post
234 * The time of the post
236 * The text of the post
237 * @return The created post
239 public Post createPost(Sone sone, long time, String text) {
240 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
249 * The Sone that posts the reply
251 * The post the reply refers to
253 * The text of the reply
254 * @return The created reply
256 public Reply createReply(Sone sone, Post post, String text) {
257 return createReply(sone, post, System.currentTimeMillis(), text);
264 * The Sone that posts the reply
266 * The post the reply refers to
268 * The time of the post
270 * The text of the reply
271 * @return The created reply
273 public Reply createReply(Sone sone, Post post, long time, String text) {
274 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
275 sone.addReply(reply);
284 * Adds a Sone to watch for updates. The Sone needs to be completely
288 * The Sone to watch for updates
290 public void addSone(Sone sone) {
291 soneCache.put(sone.getId(), sone);
292 if (!localSones.contains(sone)) {
293 soneDownloader.addSone(sone);
298 * Adds the given Sone.
303 public void addLocalSone(Sone sone) {
304 if (localSones.add(sone)) {
305 SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
306 soneInserter.start();
307 soneInserters.put(sone, soneInserter);
312 * Creates a new Sone at a random location.
315 * The name of the Sone
316 * @return The created Sone
317 * @throws SoneException
318 * if a Sone error occurs
320 public Sone createSone(String name) throws SoneException {
321 return createSone(name, "Sone-" + name, null, null);
325 * Creates a new Sone at the given location. If one of {@code requestUri} or
326 * {@code insertUrI} is {@code null}, the Sone is created at a random
330 * The name of the Sone
331 * @param documentName
332 * The document name in the SSK
334 * The request URI of the Sone, or {@link NullPointerException}
335 * to create a Sone at a random location
337 * The insert URI of the Sone, or {@code null} to create a Sone
338 * at a random location
339 * @return The created Sone
340 * @throws SoneException
341 * if a Sone error occurs
343 public Sone createSone(String name, String documentName, String requestUri, String insertUri) throws SoneException {
344 if ((name == null) || (name.trim().length() == 0)) {
345 throw new SoneException(Type.INVALID_SONE_NAME);
347 String finalRequestUri;
348 String finalInsertUri;
349 if ((requestUri == null) || (insertUri == null)) {
350 String[] keyPair = freenetInterface.generateKeyPair();
351 finalRequestUri = keyPair[0];
352 finalInsertUri = keyPair[1];
354 finalRequestUri = requestUri;
355 finalInsertUri = insertUri;
359 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
360 sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName(documentName)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName(documentName));
361 sone.setProfile(new Profile());
362 /* set modification counter to 1 so it is inserted immediately. */
363 sone.setModificationCounter(1);
365 } catch (MalformedURLException mue1) {
366 throw new SoneException(Type.INVALID_URI);
372 * Loads the Sone from the given request URI. The fetching of the data is
373 * performed in a new thread so this method returns immediately.
376 * The request URI to load the Sone from
378 public void loadSone(final String requestUri) {
379 loadSone(requestUri, null);
383 * Loads the Sone from the given request URI. The fetching of the data is
384 * performed in a new thread so this method returns immediately. If
385 * {@code insertUri} is not {@code null} the loaded Sone is converted into a
386 * local Sone and available using as any other local Sone.
389 * The request URI to load the Sone from
391 * The insert URI of the Sone
393 public void loadSone(final String requestUri, final String insertUri) {
394 new Thread(new Runnable() {
397 @SuppressWarnings("synthetic-access")
400 FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
401 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
402 if (fetchResult == null) {
405 Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
406 if (parsedSone != null) {
407 if (insertUri != null) {
408 parsedSone.setInsertUri(new FreenetURI(insertUri));
409 addLocalSone(parsedSone);
414 } catch (MalformedURLException mue1) {
415 logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
418 }, "Sone Downloader").start();
422 * Loads and updates the given Sone.
427 public void loadSone(final Sone sone) {
428 new Thread(new Runnable() {
431 @SuppressWarnings("synthetic-access")
433 FreenetURI realRequestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
434 setSoneStatus(sone, SoneStatus.downloading);
436 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
437 if (fetchResult == null) {
438 /* TODO - mark Sone as bad. */
441 Sone parsedSone = soneDownloader.parseSone(sone, fetchResult, realRequestUri);
442 if (parsedSone != null) {
446 setSoneStatus(sone, SoneStatus.idle);
449 }, "Sone Downloader").start();
453 * Deletes the given Sone from this plugin instance.
458 public void deleteSone(Sone sone) {
459 SoneInserter soneInserter = soneInserters.remove(sone);
461 localSones.remove(sone);
465 * Returns the post with the given ID. If no post exists yet with the given
466 * ID, a new post is returned.
472 public Post getPost(String postId) {
473 if (!postCache.containsKey(postId)) {
474 postCache.put(postId, new Post(postId));
476 return postCache.get(postId);
480 * Returns the reply with the given ID. If no reply exists yet with the
481 * given ID, a new reply is returned.
484 * The ID of the reply
487 public Reply getReply(String replyId) {
488 if (!replyCache.containsKey(replyId)) {
489 replyCache.put(replyId, new Reply(replyId));
491 return replyCache.get(replyId);
495 * Gets all replies to the given post, sorted by date, oldest first.
498 * The post the replies refer to
499 * @return The sorted list of replies for the post
501 public List<Reply> getReplies(Post post) {
502 List<Reply> replies = new ArrayList<Reply>();
503 for (Reply reply : replyCache.values()) {
504 if (reply.getPost().equals(post)) {
508 Collections.sort(replies, new Comparator<Reply>() {
514 public int compare(Reply leftReply, Reply rightReply) {
515 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
529 protected void serviceStart() {
537 protected void serviceStop() {
538 soneDownloader.stop();
539 /* stop all Sone inserters. */
540 for (SoneInserter soneInserter : soneInserters.values()) {
551 * Loads the configuration.
553 private void loadConfiguration() {
554 logger.entering(Core.class.getName(), "loadConfiguration()");
556 /* parse local Sones. */
557 logger.log(Level.INFO, "Loading Sones…");
560 String sonePrefix = "Sone/Sone." + soneId++;
561 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
565 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
566 long time = configuration.getLongValue(sonePrefix + "/Time").getValue((long) 0);
567 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
568 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
569 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
570 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
571 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
572 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
574 Profile profile = new Profile();
575 profile.setFirstName(firstName);
576 profile.setMiddleName(middleName);
577 profile.setLastName(lastName);
578 Sone sone = getSone(id).setName(name).setTime(time).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
579 sone.setProfile(profile);
582 String postPrefix = sonePrefix + "/Post." + postId++;
583 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
587 time = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
588 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
589 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
592 int replyCounter = 0;
594 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
595 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
596 if (replyId == null) {
599 Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
600 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
601 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
602 Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
603 sone.addReply(reply);
607 int friendCounter = 0;
609 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
610 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
611 if (friendId == null) {
614 Sone friendSone = getSone(friendId);
615 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
616 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
617 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
618 sone.addFriend(friendSone);
621 /* load blocked Sone IDs. */
622 int blockedSoneCounter = 0;
624 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
625 String blockedSoneId = configuration.getStringValue(blockedSonePrefix + "/ID").getValue(null);
626 if (blockedSoneId == null) {
629 sone.addBlockedSoneId(blockedSoneId);
632 sone.setModificationCounter(modificationCounter);
634 } catch (MalformedURLException mue1) {
635 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
638 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
640 /* load all known Sones. */
641 int knownSonesCounter = 0;
643 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
644 String knownSoneId = configuration.getStringValue(knownSonePrefix + "/ID").getValue(null);
645 if (knownSoneId == null) {
648 String knownSoneName = configuration.getStringValue(knownSonePrefix + "/Name").getValue(null);
649 String knownSoneKey = configuration.getStringValue(knownSonePrefix + "/Key").getValue(null);
651 getSone(knownSoneId).setName(knownSoneName).setRequestUri(new FreenetURI(knownSoneKey));
652 } catch (MalformedURLException mue1) {
653 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + knownSoneKey + "”)!", mue1);
657 /* load all remote Sones. */
658 for (Sone remoteSone : getRemoteSones()) {
659 loadSone(remoteSone);
662 logger.exiting(Core.class.getName(), "loadConfiguration()");
666 * Saves the configuraiton.
668 private void saveConfiguration() {
669 Set<Sone> sones = getSones();
670 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
672 /* store all Sones. */
674 for (Sone sone : localSones) {
675 String sonePrefix = "Sone/Sone." + soneId++;
676 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
677 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
678 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
679 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
680 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
681 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
682 Profile profile = sone.getProfile();
683 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
684 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
685 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
687 for (Post post : sone.getPosts()) {
688 String postPrefix = sonePrefix + "/Post." + postId++;
689 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
690 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
691 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
693 /* write null ID as terminator. */
694 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
697 for (Reply reply : sone.getReplies()) {
698 String replyPrefix = sonePrefix + "/Reply." + replyId++;
699 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
700 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
701 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
702 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
704 /* write null ID as terminator. */
705 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
708 for (Sone friend : sone.getFriends()) {
709 String friendPrefix = sonePrefix + "/Friend." + friendId++;
710 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
711 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
712 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
714 /* write null ID as terminator. */
715 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
717 /* write all blocked Sones. */
718 int blockedSoneCounter = 0;
719 for (String blockedSoneId : sone.getBlockedSoneIds()) {
720 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
721 configuration.getStringValue(blockedSonePrefix + "/ID").setValue(blockedSoneId);
723 configuration.getStringValue(sonePrefix + "/BlockedSone." + blockedSoneCounter + "/ID").setValue(null);
726 /* write null ID as terminator. */
727 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
729 /* write all known Sones. */
730 int knownSonesCounter = 0;
731 for (Sone knownSone : getRemoteSones()) {
732 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
733 configuration.getStringValue(knownSonePrefix + "/ID").setValue(knownSone.getId());
734 configuration.getStringValue(knownSonePrefix + "/Name").setValue(knownSone.getName());
735 configuration.getStringValue(knownSonePrefix + "/Key").setValue(knownSone.getRequestUri().toString());
736 /* TODO - store all known stuff? */
738 configuration.getStringValue("KnownSone." + knownSonesCounter + "/ID").setValue(null);
740 } catch (ConfigurationException ce1) {
741 logger.log(Level.WARNING, "Could not store configuration!", ce1);