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 static freenet.keys.USK.create;
21 import static java.lang.String.format;
22 import static java.util.logging.Level.WARNING;
23 import static java.util.logging.Logger.getLogger;
24 import static net.pterodactylus.sone.freenet.Key.routingKey;
26 import java.net.MalformedURLException;
27 import java.util.Collections;
28 import java.util.HashMap;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
34 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
35 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
36 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.data.TemporaryImage;
41 import com.google.common.base.Function;
42 import com.google.common.eventbus.EventBus;
43 import com.google.inject.Inject;
44 import com.google.inject.Singleton;
46 import freenet.client.ClientMetadata;
47 import freenet.client.FetchException;
48 import freenet.client.FetchException.FetchExceptionMode;
49 import freenet.client.FetchResult;
50 import freenet.client.HighLevelSimpleClient;
51 import freenet.client.InsertBlock;
52 import freenet.client.InsertContext;
53 import freenet.client.InsertException;
54 import freenet.client.async.BaseClientPutter;
55 import freenet.client.async.ClientContext;
56 import freenet.client.async.ClientPutCallback;
57 import freenet.client.async.ClientPutter;
58 import freenet.client.async.USKCallback;
59 import freenet.keys.FreenetURI;
60 import freenet.keys.InsertableClientSSK;
61 import freenet.keys.USK;
62 import freenet.node.Node;
63 import freenet.node.RequestClient;
64 import freenet.node.RequestStarter;
65 import freenet.support.api.Bucket;
66 import freenet.support.api.RandomAccessBucket;
67 import freenet.support.io.ArrayBucket;
68 import freenet.support.io.ResumeFailedException;
71 * Contains all necessary functionality for interacting with the Freenet node.
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76 public class FreenetInterface {
79 private static final Logger logger = getLogger(FreenetInterface.class.getName());
82 private final EventBus eventBus;
84 /** The node to interact with. */
85 private final Node node;
87 /** The high-level client to use for requests. */
88 private final HighLevelSimpleClient client;
90 /** The USK callbacks. */
91 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
93 /** The not-Sone-related USK callbacks. */
94 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
96 private final RequestClient imageInserts = new RequestClient() {
98 public boolean persistent() {
103 public boolean realTimeFlag() {
109 * Creates a new Freenet interface.
114 * The node to interact with
117 public FreenetInterface(EventBus eventBus, Node node) {
118 this.eventBus = eventBus;
120 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
128 * Fetches the given URI.
132 * @return The result of the fetch, or {@code null} if an error occured
134 public Fetched fetchUri(FreenetURI uri) {
135 FreenetURI currentUri = new FreenetURI(uri);
138 FetchResult fetchResult = client.fetch(currentUri);
139 return new Fetched(currentUri, fetchResult);
140 } catch (FetchException fe1) {
141 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
142 currentUri = fe1.newURI;
145 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
152 * Inserts the image data of the given {@link TemporaryImage} and returns
153 * the given insert token that can be used to add listeners or cancel the
156 * @param temporaryImage
157 * The temporary image data
162 * @throws SoneException
163 * if the insert could not be started
165 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
166 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
167 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
168 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
169 InsertContext insertContext = client.getInsertContext(true);
170 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
171 insertToken.setBucket(bucket);
172 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
173 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
175 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
176 insertToken.setClientPutter(clientPutter);
177 } catch (InsertException ie1) {
178 throw new SoneInsertException("Could not start image insert.", ie1);
183 * Inserts a directory into Freenet.
187 * @param manifestEntries
188 * The directory entries
190 * The name of the default file
191 * @return The generated URI
192 * @throws SoneException
193 * if an insert error occurs
195 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
197 return client.insertManifest(insertUri, manifestEntries, defaultFile);
198 } catch (InsertException ie1) {
199 throw new SoneException(ie1);
203 public void registerActiveUsk(FreenetURI requestUri,
204 USKCallback uskCallback) {
206 soneUskCallbacks.put(routingKey(requestUri), uskCallback);
207 node.clientCore.uskManager.subscribe(create(requestUri),
208 uskCallback, true, (RequestClient) client);
209 } catch (MalformedURLException mue1) {
210 logger.log(WARNING, format("Could not subscribe USK “%s”!",
215 public void registerPassiveUsk(FreenetURI requestUri,
216 USKCallback uskCallback) {
218 soneUskCallbacks.put(routingKey(requestUri), uskCallback);
221 .subscribe(create(requestUri), uskCallback, false,
222 (RequestClient) client);
223 } catch (MalformedURLException mue1) {
225 format("Could not subscribe USK “%s”!", requestUri),
231 * Unsubscribes the request URI of the given Sone.
234 * The Sone to unregister
236 public void unregisterUsk(Sone sone) {
237 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
238 if (uskCallback == null) {
242 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
243 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
244 } catch (MalformedURLException mue1) {
245 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
250 * Registers an arbitrary URI and calls the given callback if a new edition
256 * The callback to call
258 public void registerUsk(FreenetURI uri, final Callback callback) {
259 USKCallback uskCallback = new USKCallback() {
262 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
263 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
267 public short getPollingPriorityNormal() {
268 return RequestStarter.PREFETCH_PRIORITY_CLASS;
272 public short getPollingPriorityProgress() {
273 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
278 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
279 uriUskCallbacks.put(uri, uskCallback);
280 } catch (MalformedURLException mue1) {
281 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
286 * Unregisters the USK watcher for the given URI.
289 * The URI to unregister the USK watcher for
291 public void unregisterUsk(FreenetURI uri) {
292 USKCallback uskCallback = uriUskCallbacks.remove(uri);
293 if (uskCallback == null) {
294 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
298 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
299 } catch (MalformedURLException mue1) {
300 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
305 * Container for a fetched URI and the {@link FetchResult}.
307 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
309 public static class Fetched {
311 /** The fetched URI. */
312 private final FreenetURI freenetUri;
314 /** The fetch result. */
315 private final FetchResult fetchResult;
318 * Creates a new fetched URI.
321 * The URI that was fetched
325 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
326 this.freenetUri = freenetUri;
327 this.fetchResult = fetchResult;
335 * Returns the fetched URI.
337 * @return The fetched URI
339 public FreenetURI getFreenetUri() {
344 * Returns the fetch result.
346 * @return The fetch result
348 public FetchResult getFetchResult() {
355 * Callback for USK watcher events.
357 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
359 public static interface Callback {
362 * Notifies a listener that a new edition was found for a URI.
365 * The URI that a new edition was found for
368 * @param newKnownGood
369 * Whether the found edition was actually fetched
371 * Whether the found edition is higher than all previously
374 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
379 * Insert token that can cancel a running insert and sends events.
381 * @see ImageInsertAbortedEvent
382 * @see ImageInsertStartedEvent
383 * @see ImageInsertFailedEvent
384 * @see ImageInsertFinishedEvent
385 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
387 public class InsertToken implements ClientPutCallback {
389 /** The image being inserted. */
390 private final Image image;
392 /** The client putter. */
393 private ClientPutter clientPutter;
394 private Bucket bucket;
396 /** The final URI. */
397 private volatile FreenetURI resultingUri;
400 * Creates a new insert token for the given image.
403 * The image being inserted
405 public InsertToken(Image image) {
414 * Sets the client putter that is inserting the image. This will also
415 * signal all registered listeners that the image has started.
417 * @param clientPutter
420 @SuppressWarnings("synthetic-access")
421 public void setClientPutter(ClientPutter clientPutter) {
422 this.clientPutter = clientPutter;
423 eventBus.post(new ImageInsertStartedEvent(image));
426 public void setBucket(Bucket bucket) {
427 this.bucket = bucket;
435 * Cancels the running insert.
437 @SuppressWarnings("synthetic-access")
438 public void cancel() {
439 clientPutter.cancel(node.clientCore.clientContext);
440 eventBus.post(new ImageInsertAbortedEvent(image));
445 // INTERFACE ClientPutCallback
449 public RequestClient getRequestClient() {
454 public void onResume(ClientContext context) throws ResumeFailedException {
462 @SuppressWarnings("synthetic-access")
463 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
464 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
465 eventBus.post(new ImageInsertAbortedEvent(image));
467 eventBus.post(new ImageInsertFailedEvent(image, insertException));
476 public void onFetchable(BaseClientPutter clientPutter) {
477 /* ignore, we don’t care. */
484 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
485 /* ignore, we don’t care. */
492 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
493 resultingUri = generatedUri;
500 @SuppressWarnings("synthetic-access")
501 public void onSuccess(BaseClientPutter clientPutter) {
502 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
508 public class InsertTokenSupplier implements Function<Image, InsertToken> {
511 public InsertToken apply(Image image) {
512 return new InsertToken(image);