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 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);
78 /** The configuration. */
79 private Configuration configuration;
81 /** Interface to freenet. */
82 private FreenetInterface freenetInterface;
84 /** The Sone downloader. */
85 private SoneDownloader soneDownloader;
87 /** The local Sones. */
88 private final Set<Sone> localSones = new HashSet<Sone>();
90 /** Sone inserters. */
91 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
93 /** The Sones’ statuses. */
94 private final Map<Sone, SoneStatus> soneStatuses = Collections.synchronizedMap(new HashMap<Sone, SoneStatus>());
96 /* various caches follow here. */
98 /** Cache for all known Sones. */
99 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
101 /** Cache for all known posts. */
102 private final Map<String, Post> postCache = new HashMap<String, Post>();
104 /** Cache for all known replies. */
105 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
108 * Creates a new core.
111 super("Sone Core", false);
119 * Sets the configuration of the core.
121 * @param configuration
122 * The configuration of the core
123 * @return This core (for method chaining)
125 public Core configuration(Configuration configuration) {
126 this.configuration = configuration;
131 * Sets the Freenet interface to use.
133 * @param freenetInterface
134 * The Freenet interface to use
135 * @return This core (for method chaining)
137 public Core freenetInterface(FreenetInterface freenetInterface) {
138 this.freenetInterface = freenetInterface;
139 soneDownloader = new SoneDownloader(this, freenetInterface);
140 soneDownloader.start();
145 * Returns the local Sones.
147 * @return The local Sones
149 public Set<Sone> getSones() {
150 return Collections.unmodifiableSet(localSones);
154 * Returns the Sone with the given ID, or an empty Sone that has been
155 * initialized with the given ID.
161 public Sone getSone(String soneId) {
162 if (!soneCache.containsKey(soneId)) {
163 Sone sone = new Sone(soneId);
164 soneCache.put(soneId, sone);
165 setSoneStatus(sone, SoneStatus.unknown);
167 return soneCache.get(soneId);
171 * Returns all known sones.
173 * @return All known sones
175 public Collection<Sone> getKnownSones() {
176 return soneCache.values();
180 * Gets all known Sones that are not local Sones.
182 * @return All remote Sones
184 public Collection<Sone> getRemoteSones() {
185 return Filters.filteredCollection(getKnownSones(), new Filter<Sone>() {
188 @SuppressWarnings("synthetic-access")
189 public boolean filterObject(Sone object) {
190 return !localSones.contains(object);
196 * Returns the status of the given Sone.
199 * The Sone to get the status for
200 * @return The status of the Sone
202 public SoneStatus getSoneStatus(Sone sone) {
203 return soneStatuses.get(sone);
207 * Sets the status of the Sone.
210 * The Sone to set the status for
212 * The status of the Sone
214 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
215 soneStatuses.put(sone, soneStatus);
219 * Creates a new post and adds it to the given Sone.
222 * The sone that creates the post
224 * The text of the post
225 * @return The created post
227 public Post createPost(Sone sone, String text) {
228 return createPost(sone, System.currentTimeMillis(), text);
232 * Creates a new post and adds it to the given Sone.
235 * The Sone that creates the post
237 * The time of the post
239 * The text of the post
240 * @return The created post
242 public Post createPost(Sone sone, long time, String text) {
243 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
252 * The Sone that posts the reply
254 * The post the reply refers to
256 * The text of the reply
257 * @return The created reply
259 public Reply createReply(Sone sone, Post post, String text) {
260 return createReply(sone, post, System.currentTimeMillis(), text);
267 * The Sone that posts the reply
269 * The post the reply refers to
271 * The time of the post
273 * The text of the reply
274 * @return The created reply
276 public Reply createReply(Sone sone, Post post, long time, String text) {
277 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
278 sone.addReply(reply);
287 * Adds a Sone to watch for updates. The Sone needs to be completely
291 * The Sone to watch for updates
293 public void addSone(Sone sone) {
294 soneCache.put(sone.getId(), sone);
295 if (!localSones.contains(sone)) {
296 soneDownloader.addSone(sone);
301 * Adds the given Sone.
306 public void addLocalSone(Sone sone) {
307 if (localSones.add(sone)) {
308 setSoneStatus(sone, SoneStatus.idle);
309 SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
310 soneInserter.start();
311 soneInserters.put(sone, soneInserter);
316 * Creates a new Sone at a random location.
319 * The name of the Sone
320 * @return The created Sone
321 * @throws SoneException
322 * if a Sone error occurs
324 public Sone createSone(String name) throws SoneException {
325 return createSone(name, "Sone-" + name, null, null);
329 * Creates a new Sone at the given location. If one of {@code requestUri} or
330 * {@code insertUrI} is {@code null}, the Sone is created at a random
334 * The name of the Sone
335 * @param documentName
336 * The document name in the SSK
338 * The request URI of the Sone, or {@link NullPointerException}
339 * to create a Sone at a random location
341 * The insert URI of the Sone, or {@code null} to create a Sone
342 * at a random location
343 * @return The created Sone
344 * @throws SoneException
345 * if a Sone error occurs
347 public Sone createSone(String name, String documentName, String requestUri, String insertUri) throws SoneException {
348 if ((name == null) || (name.trim().length() == 0)) {
349 throw new SoneException(Type.INVALID_SONE_NAME);
351 String finalRequestUri;
352 String finalInsertUri;
353 if ((requestUri == null) || (insertUri == null)) {
354 String[] keyPair = freenetInterface.generateKeyPair();
355 finalRequestUri = keyPair[0];
356 finalInsertUri = keyPair[1];
358 finalRequestUri = requestUri;
359 finalInsertUri = insertUri;
363 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
364 sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName(documentName)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName(documentName));
365 sone.setProfile(new Profile());
366 /* set modification counter to 1 so it is inserted immediately. */
367 sone.setModificationCounter(1);
369 } catch (MalformedURLException mue1) {
370 throw new SoneException(Type.INVALID_URI);
376 * Loads the Sone from the given request URI. The fetching of the data is
377 * performed in a new thread so this method returns immediately.
380 * The request URI to load the Sone from
382 public void loadSone(final String requestUri) {
383 loadSone(requestUri, null);
387 * Loads the Sone from the given request URI. The fetching of the data is
388 * performed in a new thread so this method returns immediately. If
389 * {@code insertUri} is not {@code null} the loaded Sone is converted into a
390 * local Sone and available using as any other local Sone.
393 * The request URI to load the Sone from
395 * The insert URI of the Sone
397 public void loadSone(final String requestUri, final String insertUri) {
398 new Thread(new Runnable() {
401 @SuppressWarnings("synthetic-access")
404 FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
405 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
406 if (fetchResult == null) {
409 Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
410 if (parsedSone != null) {
411 if (insertUri != null) {
412 parsedSone.setInsertUri(new FreenetURI(insertUri));
413 addLocalSone(parsedSone);
418 } catch (MalformedURLException mue1) {
419 logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
422 }, "Sone Downloader").start();
426 * Loads and updates the given Sone.
431 public void loadSone(final Sone sone) {
432 new Thread(new Runnable() {
435 @SuppressWarnings("synthetic-access")
437 FreenetURI realRequestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
438 setSoneStatus(sone, SoneStatus.downloading);
440 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
441 if (fetchResult == null) {
442 /* TODO - mark Sone as bad. */
445 Sone parsedSone = soneDownloader.parseSone(sone, fetchResult, realRequestUri);
446 if (parsedSone != null) {
450 setSoneStatus(sone, (sone.getTime() == 0) ? SoneStatus.unknown : SoneStatus.idle);
453 }, "Sone Downloader").start();
457 * Deletes the given Sone from this plugin instance.
462 public void deleteSone(Sone sone) {
463 SoneInserter soneInserter = soneInserters.remove(sone);
465 localSones.remove(sone);
469 * Returns the post with the given ID. If no post exists yet with the given
470 * ID, a new post is returned.
476 public Post getPost(String postId) {
477 if (!postCache.containsKey(postId)) {
478 postCache.put(postId, new Post(postId));
480 return postCache.get(postId);
484 * Returns the reply with the given ID. If no reply exists yet with the
485 * given ID, a new reply is returned.
488 * The ID of the reply
491 public Reply getReply(String replyId) {
492 if (!replyCache.containsKey(replyId)) {
493 replyCache.put(replyId, new Reply(replyId));
495 return replyCache.get(replyId);
499 * Gets all replies to the given post, sorted by date, oldest first.
502 * The post the replies refer to
503 * @return The sorted list of replies for the post
505 public List<Reply> getReplies(Post post) {
506 List<Reply> replies = new ArrayList<Reply>();
507 for (Reply reply : replyCache.values()) {
508 if (reply.getPost().equals(post)) {
512 Collections.sort(replies, new Comparator<Reply>() {
518 public int compare(Reply leftReply, Reply rightReply) {
519 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
526 * Deletes the given reply. It is removed from its Sone and from the reply
530 * The reply to remove
532 public void deleteReply(Reply reply) {
533 reply.getSone().removeReply(reply);
534 replyCache.remove(reply.getId());
545 protected void serviceStart() {
553 protected void serviceStop() {
554 soneDownloader.stop();
555 /* stop all Sone inserters. */
556 for (SoneInserter soneInserter : soneInserters.values()) {
567 * Loads the configuration.
569 private void loadConfiguration() {
570 logger.entering(Core.class.getName(), "loadConfiguration()");
572 /* parse local Sones. */
573 logger.log(Level.INFO, "Loading Sones…");
576 String sonePrefix = "Sone/Sone." + soneId++;
577 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
581 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
582 long time = configuration.getLongValue(sonePrefix + "/Time").getValue((long) 0);
583 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
584 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
585 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
586 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
587 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
588 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
590 Profile profile = new Profile();
591 profile.setFirstName(firstName);
592 profile.setMiddleName(middleName);
593 profile.setLastName(lastName);
594 Sone sone = getSone(id).setName(name).setTime(time).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
595 sone.setProfile(profile);
598 String postPrefix = sonePrefix + "/Post." + postId++;
599 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
603 time = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
604 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
605 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
608 int replyCounter = 0;
610 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
611 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
612 if (replyId == null) {
615 Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
616 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
617 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
618 Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
619 sone.addReply(reply);
623 int friendCounter = 0;
625 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
626 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
627 if (friendId == null) {
630 Sone friendSone = getSone(friendId);
631 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
632 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
633 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
634 sone.addFriend(friendSone);
637 /* load blocked Sone IDs. */
638 int blockedSoneCounter = 0;
640 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
641 String blockedSoneId = configuration.getStringValue(blockedSonePrefix + "/ID").getValue(null);
642 if (blockedSoneId == null) {
645 sone.addBlockedSoneId(blockedSoneId);
648 sone.setModificationCounter(modificationCounter);
650 } catch (MalformedURLException mue1) {
651 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
654 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
656 /* load all known Sones. */
657 int knownSonesCounter = 0;
659 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
660 String knownSoneId = configuration.getStringValue(knownSonePrefix + "/ID").getValue(null);
661 if (knownSoneId == null) {
664 String knownSoneName = configuration.getStringValue(knownSonePrefix + "/Name").getValue(null);
665 String knownSoneKey = configuration.getStringValue(knownSonePrefix + "/Key").getValue(null);
667 getSone(knownSoneId).setName(knownSoneName).setRequestUri(new FreenetURI(knownSoneKey));
668 } catch (MalformedURLException mue1) {
669 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + knownSoneKey + "”)!", mue1);
673 /* load all remote Sones. */
674 for (Sone remoteSone : getRemoteSones()) {
675 loadSone(remoteSone);
678 logger.exiting(Core.class.getName(), "loadConfiguration()");
682 * Saves the configuraiton.
684 private void saveConfiguration() {
685 Set<Sone> sones = getSones();
686 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
688 /* store all Sones. */
690 for (Sone sone : localSones) {
691 String sonePrefix = "Sone/Sone." + soneId++;
692 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
693 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
694 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
695 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
696 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
697 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
698 Profile profile = sone.getProfile();
699 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
700 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
701 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
703 for (Post post : sone.getPosts()) {
704 String postPrefix = sonePrefix + "/Post." + postId++;
705 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
706 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
707 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
709 /* write null ID as terminator. */
710 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
713 for (Reply reply : sone.getReplies()) {
714 String replyPrefix = sonePrefix + "/Reply." + replyId++;
715 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
716 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
717 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
718 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
720 /* write null ID as terminator. */
721 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
724 for (Sone friend : sone.getFriends()) {
725 String friendPrefix = sonePrefix + "/Friend." + friendId++;
726 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
727 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
728 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
730 /* write null ID as terminator. */
731 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
733 /* write all blocked Sones. */
734 int blockedSoneCounter = 0;
735 for (String blockedSoneId : sone.getBlockedSoneIds()) {
736 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
737 configuration.getStringValue(blockedSonePrefix + "/ID").setValue(blockedSoneId);
739 configuration.getStringValue(sonePrefix + "/BlockedSone." + blockedSoneCounter + "/ID").setValue(null);
742 /* write null ID as terminator. */
743 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
745 /* write all known Sones. */
746 int knownSonesCounter = 0;
747 for (Sone knownSone : getRemoteSones()) {
748 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
749 configuration.getStringValue(knownSonePrefix + "/ID").setValue(knownSone.getId());
750 configuration.getStringValue(knownSonePrefix + "/Name").setValue(knownSone.getName());
751 configuration.getStringValue(knownSonePrefix + "/Key").setValue(knownSone.getRequestUri().toString());
752 /* TODO - store all known stuff? */
754 configuration.getStringValue("KnownSone." + knownSonesCounter + "/ID").setValue(null);
756 } catch (ConfigurationException ce1) {
757 logger.log(Level.WARNING, "Could not store configuration!", ce1);