2 * FreenetSone - FreenetInterface.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.Collections;
22 import java.util.HashMap;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
27 import net.pterodactylus.sone.data.Sone;
28 import net.pterodactylus.util.collection.Pair;
29 import net.pterodactylus.util.logging.Logging;
31 import com.db4o.ObjectContainer;
33 import freenet.client.FetchException;
34 import freenet.client.FetchResult;
35 import freenet.client.HighLevelSimpleClient;
36 import freenet.client.HighLevelSimpleClientImpl;
37 import freenet.client.InsertException;
38 import freenet.client.async.ClientContext;
39 import freenet.client.async.USKCallback;
40 import freenet.keys.FreenetURI;
41 import freenet.keys.USK;
42 import freenet.node.Node;
43 import freenet.node.RequestStarter;
46 * Contains all necessary functionality for interacting with the Freenet node.
48 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50 public class FreenetInterface {
53 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
55 /** The node to interact with. */
56 private final Node node;
58 /** The high-level client to use for requests. */
59 private final HighLevelSimpleClient client;
61 /** The USK callbacks. */
62 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
64 /** The not-Sone-related USK callbacks. */
65 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
68 * Creates a new Freenet interface.
71 * The node to interact with
73 public FreenetInterface(Node node) {
75 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
83 * Fetches the given URI.
87 * @return The result of the fetch, or {@code null} if an error occured
89 public Pair<FreenetURI, FetchResult> fetchUri(FreenetURI uri) {
90 FetchResult fetchResult = null;
91 FreenetURI currentUri = new FreenetURI(uri);
94 fetchResult = client.fetch(currentUri);
95 return new Pair<FreenetURI, FetchResult>(currentUri, fetchResult);
96 } catch (FetchException fe1) {
97 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
98 currentUri = fe1.newURI;
101 logger.log(Level.WARNING, "Could not fetch “" + uri + "”!", fe1);
108 * Creates a key pair.
110 * @return The request key at index 0, the insert key at index 1
112 public String[] generateKeyPair() {
113 FreenetURI[] keyPair = client.generateKeyPair("");
114 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
118 * Inserts a directory into Freenet.
122 * @param manifestEntries
123 * The directory entries
125 * The name of the default file
126 * @return The generated URI
127 * @throws SoneException
128 * if an insert error occurs
130 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
132 return client.insertManifest(insertUri, manifestEntries, defaultFile);
133 } catch (InsertException ie1) {
134 throw new SoneException(null, ie1);
139 * Registers the USK for the given Sone and notifies the given
140 * {@link SoneDownloader} if an update was found.
144 * @param soneDownloader
145 * The Sone download to notify on updates
147 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
149 logger.log(Level.FINE, "Registering Sone “%s” for USK updates at %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
150 USKCallback uskCallback = new USKCallback() {
153 @SuppressWarnings("synthetic-access")
154 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
155 logger.log(Level.FINE, "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.", new Object[] { sone, key, newKnownGood, newSlotToo });
157 sone.setLatestEdition(key.suggestedEdition);
158 new Thread(new Runnable() {
162 soneDownloader.fetchSone(sone);
164 }, "Sone Downloader").start();
169 public short getPollingPriorityProgress() {
170 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
174 public short getPollingPriorityNormal() {
175 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
178 soneUskCallbacks.put(sone.getId(), uskCallback);
179 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, true, (HighLevelSimpleClientImpl) client);
180 } catch (MalformedURLException mue1) {
181 logger.log(Level.WARNING, "Could not subscribe USK “" + sone.getRequestUri() + "”!", mue1);
186 * Unsubscribes the request URI of the given Sone.
189 * The Sone to unregister
191 public void unregisterUsk(Sone sone) {
192 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
193 if (uskCallback == null) {
197 logger.log(Level.FINEST, "Unsubscribing from USK for %s…", new Object[] { sone });
198 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
199 } catch (MalformedURLException mue1) {
200 logger.log(Level.FINE, "Could not unsubscribe USK “" + sone.getRequestUri() + "”!", mue1);
205 * Registers an arbitrary URI and calls the given callback if a new edition
211 * The callback to call
213 public void registerUsk(FreenetURI uri, final Callback callback) {
214 USKCallback uskCallback = new USKCallback() {
217 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
218 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
222 public short getPollingPriorityNormal() {
223 return RequestStarter.PREFETCH_PRIORITY_CLASS;
227 public short getPollingPriorityProgress() {
228 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
233 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
234 uriUskCallbacks.put(uri, uskCallback);
235 } catch (MalformedURLException mue1) {
236 logger.log(Level.WARNING, "Could not subscribe to USK: " + uri, uri);
241 * Unregisters the USK watcher for the given URI.
244 * The URI to unregister the USK watcher for
246 public void unregisterUsk(FreenetURI uri) {
247 USKCallback uskCallback = uriUskCallbacks.remove(uri);
248 if (uskCallback == null) {
249 logger.log(Level.INFO, "Could not unregister unknown USK: " + uri);
253 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
254 } catch (MalformedURLException mue1) {
255 logger.log(Level.INFO, "Could not unregister invalid USK: " + uri);
260 * Callback for USK watcher events.
262 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
264 public static interface Callback {
267 * Notifies a listener that a new edition was found for a URI.
270 * The URI that a new edition was found for
273 * @param newKnownGood
274 * Whether the found edition was actually fetched
276 * Whether the found edition is higher than all previously
279 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);