2 * Sone - FreenetInterface.java - Copyright © 2010–2013 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.concurrent.TimeUnit;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
28 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
29 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
30 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
31 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
32 import net.pterodactylus.sone.data.Image;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.data.TemporaryImage;
35 import net.pterodactylus.util.logging.Logging;
37 import com.db4o.ObjectContainer;
38 import com.google.common.eventbus.EventBus;
39 import com.google.inject.Inject;
41 import freenet.client.ClientMetadata;
42 import freenet.client.FetchException;
43 import freenet.client.FetchResult;
44 import freenet.client.HighLevelSimpleClient;
45 import freenet.client.HighLevelSimpleClientImpl;
46 import freenet.client.InsertBlock;
47 import freenet.client.InsertContext;
48 import freenet.client.InsertException;
49 import freenet.client.async.BaseClientPutter;
50 import freenet.client.async.ClientContext;
51 import freenet.client.async.ClientPutCallback;
52 import freenet.client.async.ClientPutter;
53 import freenet.client.async.USKCallback;
54 import freenet.keys.FreenetURI;
55 import freenet.keys.InsertableClientSSK;
56 import freenet.keys.USK;
57 import freenet.node.Node;
58 import freenet.node.RequestStarter;
59 import freenet.support.api.Bucket;
60 import freenet.support.io.ArrayBucket;
63 * Contains all necessary functionality for interacting with the Freenet node.
65 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
67 public class FreenetInterface {
70 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
73 private final EventBus eventBus;
75 /** The node to interact with. */
76 private final Node node;
78 /** The high-level client to use for requests. */
79 private final HighLevelSimpleClient client;
81 /** The USK callbacks. */
82 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
84 /** The not-Sone-related USK callbacks. */
85 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
88 * Creates a new Freenet interface.
93 * The node to interact with
96 public FreenetInterface(EventBus eventBus, Node node) {
97 this.eventBus = eventBus;
99 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
107 * Fetches the given URI.
111 * @return The result of the fetch, or {@code null} if an error occured
113 public Fetched fetchUri(FreenetURI uri) {
114 FetchResult fetchResult = null;
115 FreenetURI currentUri = new FreenetURI(uri);
118 fetchResult = client.fetch(currentUri);
119 return new Fetched(currentUri, fetchResult);
120 } catch (FetchException fe1) {
121 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
122 currentUri = fe1.newURI;
125 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
132 * Creates a key pair.
134 * @return The request key at index 0, the insert key at index 1
136 public String[] generateKeyPair() {
137 FreenetURI[] keyPair = client.generateKeyPair("");
138 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
142 * Inserts the image data of the given {@link TemporaryImage} and returns
143 * the given insert token that can be used to add listeners or cancel the
146 * @param temporaryImage
147 * The temporary image data
152 * @throws SoneException
153 * if the insert could not be started
155 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
156 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
157 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
158 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
159 InsertContext insertContext = client.getInsertContext(true);
160 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
161 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
162 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
164 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
165 insertToken.setClientPutter(clientPutter);
166 } catch (InsertException ie1) {
167 throw new SoneInsertException("Could not start image insert.", ie1);
172 * Inserts a directory into Freenet.
176 * @param manifestEntries
177 * The directory entries
179 * The name of the default file
180 * @return The generated URI
181 * @throws SoneException
182 * if an insert error occurs
184 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
186 return client.insertManifest(insertUri, manifestEntries, defaultFile);
187 } catch (InsertException ie1) {
188 throw new SoneException(ie1);
193 * Registers the USK for the given Sone and notifies the given
194 * {@link SoneDownloader} if an update was found.
198 * @param soneDownloader
199 * The Sone download to notify on updates
201 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
203 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
204 USKCallback uskCallback = new USKCallback() {
207 @SuppressWarnings("synthetic-access")
208 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
209 logger.log(Level.FINE, String.format("Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.", sone, key, newKnownGood, newSlotToo));
210 if (edition > sone.getLatestEdition()) {
211 sone.setLatestEdition(edition);
212 new Thread(new Runnable() {
216 soneDownloader.fetchSone(sone);
218 }, "Sone Downloader").start();
223 public short getPollingPriorityProgress() {
224 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
228 public short getPollingPriorityNormal() {
229 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
232 soneUskCallbacks.put(sone.getId(), uskCallback);
233 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
234 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (HighLevelSimpleClientImpl) client);
235 } catch (MalformedURLException mue1) {
236 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
241 * Unsubscribes the request URI of the given Sone.
244 * The Sone to unregister
246 public void unregisterUsk(Sone sone) {
247 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
248 if (uskCallback == null) {
252 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
253 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
254 } catch (MalformedURLException mue1) {
255 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
260 * Registers an arbitrary URI and calls the given callback if a new edition
266 * The callback to call
268 public void registerUsk(FreenetURI uri, final Callback callback) {
269 USKCallback uskCallback = new USKCallback() {
272 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
273 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
277 public short getPollingPriorityNormal() {
278 return RequestStarter.PREFETCH_PRIORITY_CLASS;
282 public short getPollingPriorityProgress() {
283 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
288 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
289 uriUskCallbacks.put(uri, uskCallback);
290 } catch (MalformedURLException mue1) {
291 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
296 * Unregisters the USK watcher for the given URI.
299 * The URI to unregister the USK watcher for
301 public void unregisterUsk(FreenetURI uri) {
302 USKCallback uskCallback = uriUskCallbacks.remove(uri);
303 if (uskCallback == null) {
304 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
308 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
309 } catch (MalformedURLException mue1) {
310 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
315 * Container for a fetched URI and the {@link FetchResult}.
317 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
319 public static class Fetched {
321 /** The fetched URI. */
322 private final FreenetURI freenetUri;
324 /** The fetch result. */
325 private final FetchResult fetchResult;
328 * Creates a new fetched URI.
331 * The URI that was fetched
335 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
336 this.freenetUri = freenetUri;
337 this.fetchResult = fetchResult;
345 * Returns the fetched URI.
347 * @return The fetched URI
349 public FreenetURI getFreenetUri() {
354 * Returns the fetch result.
356 * @return The fetch result
358 public FetchResult getFetchResult() {
365 * Callback for USK watcher events.
367 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
369 public static interface Callback {
372 * Notifies a listener that a new edition was found for a URI.
375 * The URI that a new edition was found for
378 * @param newKnownGood
379 * Whether the found edition was actually fetched
381 * Whether the found edition is higher than all previously
384 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
389 * Insert token that can cancel a running insert and sends events.
391 * @see ImageInsertAbortedEvent
392 * @see ImageInsertStartedEvent
393 * @see ImageInsertFailedEvent
394 * @see ImageInsertFinishedEvent
395 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
397 public class InsertToken implements ClientPutCallback {
399 /** The image being inserted. */
400 private final Image image;
402 /** The client putter. */
403 private ClientPutter clientPutter;
405 /** The final URI. */
406 private volatile FreenetURI resultingUri;
409 * Creates a new insert token for the given image.
412 * The image being inserted
414 public InsertToken(Image image) {
423 * Sets the client putter that is inserting the image. This will also
424 * signal all registered listeners that the image has started.
426 * @param clientPutter
429 @SuppressWarnings("synthetic-access")
430 public void setClientPutter(ClientPutter clientPutter) {
431 this.clientPutter = clientPutter;
432 eventBus.post(new ImageInsertStartedEvent(image));
440 * Cancels the running insert.
442 @SuppressWarnings("synthetic-access")
443 public void cancel() {
444 clientPutter.cancel(null, node.clientCore.clientContext);
445 eventBus.post(new ImageInsertAbortedEvent(image));
449 // INTERFACE ClientPutCallback
456 public void onMajorProgress(ObjectContainer objectContainer) {
457 /* ignore, we don’t care. */
464 @SuppressWarnings("synthetic-access")
465 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
466 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
467 eventBus.post(new ImageInsertAbortedEvent(image));
469 eventBus.post(new ImageInsertFailedEvent(image, insertException));
477 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
478 /* ignore, we don’t care. */
485 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
486 /* ignore, we don’t care. */
493 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
494 resultingUri = generatedUri;
501 @SuppressWarnings("synthetic-access")
502 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
503 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));