2 * Sone - FreenetInterface.java - Copyright © 2010–2019 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;
25 import java.io.IOException;
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 javax.annotation.Nonnull;
34 import javax.inject.Inject;
36 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
37 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
38 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.TemporaryImage;
44 import com.google.common.base.Function;
45 import com.google.common.eventbus.EventBus;
46 import com.google.inject.Singleton;
48 import freenet.client.ClientMetadata;
49 import freenet.client.FetchContext;
50 import freenet.client.FetchException;
51 import freenet.client.FetchException.FetchExceptionMode;
52 import freenet.client.FetchResult;
53 import freenet.client.HighLevelSimpleClient;
54 import freenet.client.InsertBlock;
55 import freenet.client.InsertContext;
56 import freenet.client.InsertException;
57 import freenet.client.Metadata;
58 import freenet.client.async.BaseClientPutter;
59 import freenet.client.async.ClientContext;
60 import freenet.client.async.ClientGetCallback;
61 import freenet.client.async.ClientGetter;
62 import freenet.client.async.ClientPutCallback;
63 import freenet.client.async.ClientPutter;
64 import freenet.client.async.SnoopMetadata;
65 import freenet.client.async.USKCallback;
66 import freenet.keys.FreenetURI;
67 import freenet.keys.InsertableClientSSK;
68 import freenet.keys.USK;
69 import freenet.node.Node;
70 import freenet.node.RequestClient;
71 import freenet.node.RequestClientBuilder;
72 import freenet.node.RequestStarter;
73 import freenet.support.api.Bucket;
74 import freenet.support.api.RandomAccessBucket;
75 import freenet.support.io.ArrayBucket;
76 import freenet.support.io.ResumeFailedException;
77 import net.pterodactylus.sone.freenet.*;
80 * Contains all necessary functionality for interacting with the Freenet node.
83 public class FreenetInterface {
86 private static final Logger logger = getLogger(FreenetInterface.class.getName());
89 private final EventBus eventBus;
91 /** The node to interact with. */
92 private final Node node;
94 /** The high-level client to use for requests. */
95 private final HighLevelSimpleClient client;
96 private final RequestClient requestClient = new RequestClientBuilder().realTime().build();
98 /** The USK callbacks. */
99 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<>();
101 /** The not-Sone-related USK callbacks. */
102 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
104 private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
105 private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
108 * Creates a new Freenet interface.
113 * The node to interact with
116 public FreenetInterface(EventBus eventBus, Node node) {
117 this.eventBus = eventBus;
119 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
127 * Fetches the given URI.
131 * @return The result of the fetch, or {@code null} if an error occured
133 public Fetched fetchUri(FreenetURI uri) {
134 FreenetURI currentUri = new FreenetURI(uri);
137 FetchResult fetchResult = client.fetch(currentUri);
138 return new Fetched(currentUri, fetchResult);
139 } catch (FetchException fe1) {
140 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
141 currentUri = fe1.newURI;
144 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
150 public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
151 ClientGetCallback callback = new ClientGetCallback() {
153 public void onSuccess(FetchResult result, ClientGetter state) {
155 backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
156 } catch (IOException e) {
157 backgroundFetchCallback.failed(uri);
162 public void onFailure(FetchException e, ClientGetter state) {
163 backgroundFetchCallback.failed(uri);
167 public void onResume(ClientContext context) throws ResumeFailedException {
172 public RequestClient getRequestClient() {
176 SnoopMetadata snoop = new SnoopMetadata() {
178 public boolean snoopMetadata(Metadata meta, ClientContext context) {
179 String mimeType = meta.getMIMEType();
180 boolean cancel = (mimeType == null) || backgroundFetchCallback.shouldCancel(uri, mimeType, meta.dataLength());
182 backgroundFetchCallback.failed(uri);
187 FetchContext fetchContext = client.getFetchContext();
189 ClientGetter clientGetter = client.fetch(uri, 2097152, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
190 clientGetter.setMetaSnoop(snoop);
191 clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
192 } catch (FetchException fe) {
193 /* stupid exception that can not actually be thrown! */
197 public interface BackgroundFetchCallback {
198 boolean shouldCancel(@Nonnull FreenetURI uri, @Nonnull String mimeType, long size);
199 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
200 void failed(@Nonnull FreenetURI uri);
204 * Inserts the image data of the given {@link TemporaryImage} and returns
205 * the given insert token that can be used to add listeners or cancel the
208 * @param temporaryImage
209 * The temporary image data
214 * @throws SoneException
215 * if the insert could not be started
217 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
218 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
219 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
220 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
221 InsertContext insertContext = client.getInsertContext(true);
222 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
223 insertToken.setBucket(bucket);
224 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
225 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
227 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
228 insertToken.setClientPutter(clientPutter);
229 } catch (InsertException ie1) {
230 throw new SoneInsertException("Could not start image insert.", ie1);
235 * Inserts a directory into Freenet.
239 * @param manifestEntries
240 * The directory entries
242 * The name of the default file
243 * @return The generated URI
244 * @throws SoneException
245 * if an insert error occurs
247 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
249 return client.insertManifest(insertUri, manifestEntries, defaultFile);
250 } catch (InsertException ie1) {
251 throw new SoneException(ie1);
255 public void registerActiveUsk(FreenetURI requestUri,
256 USKCallback uskCallback) {
258 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
259 node.clientCore.uskManager.subscribe(create(requestUri),
260 uskCallback, true, requestClient);
261 } catch (MalformedURLException mue1) {
262 logger.log(WARNING, format("Could not subscribe USK “%s”!",
267 public void registerPassiveUsk(FreenetURI requestUri,
268 USKCallback uskCallback) {
270 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
273 .subscribe(create(requestUri), uskCallback, false, requestClient);
274 } catch (MalformedURLException mue1) {
276 format("Could not subscribe USK “%s”!", requestUri),
282 * Unsubscribes the request URI of the given Sone.
285 * The Sone to unregister
287 public void unregisterUsk(Sone sone) {
288 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
289 if (uskCallback == null) {
293 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
294 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
295 } catch (MalformedURLException mue1) {
296 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
301 * Registers an arbitrary URI and calls the given callback if a new edition
307 * The callback to call
309 public void registerUsk(FreenetURI uri, final Callback callback) {
310 USKCallback uskCallback = new USKCallback() {
313 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
314 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
318 public short getPollingPriorityNormal() {
319 return RequestStarter.PREFETCH_PRIORITY_CLASS;
323 public short getPollingPriorityProgress() {
324 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
329 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
330 uriUskCallbacks.put(USK.create(uri).clearCopy().getURI(), uskCallback);
331 } catch (MalformedURLException mue1) {
332 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
337 * Unregisters the USK watcher for the given URI.
340 * The URI to unregister the USK watcher for
342 public void unregisterUsk(FreenetURI uri) {
344 USKCallback uskCallback = uriUskCallbacks.remove(USK.create(uri).clearCopy().getURI());
345 if (uskCallback == null) {
346 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
349 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
350 } catch (MalformedURLException mue1) {
351 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
356 * Callback for USK watcher events.
358 public static interface Callback {
361 * Notifies a listener that a new edition was found for a URI.
364 * The URI that a new edition was found for
367 * @param newKnownGood
368 * Whether the found edition was actually fetched
370 * Whether the found edition is higher than all previously
373 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
378 * Insert token that can cancel a running insert and sends events.
380 * @see ImageInsertAbortedEvent
381 * @see ImageInsertStartedEvent
382 * @see ImageInsertFailedEvent
383 * @see ImageInsertFinishedEvent
385 public class InsertToken implements ClientPutCallback {
387 /** The image being inserted. */
388 private final Image image;
390 /** The client putter. */
391 private ClientPutter clientPutter;
392 private Bucket bucket;
394 /** The final URI. */
395 private volatile FreenetURI resultingUri;
398 * Creates a new insert token for the given image.
401 * The image being inserted
403 public InsertToken(Image image) {
412 * Sets the client putter that is inserting the image. This will also
413 * signal all registered listeners that the image has started.
415 * @param clientPutter
418 @SuppressWarnings("synthetic-access")
419 public void setClientPutter(ClientPutter clientPutter) {
420 this.clientPutter = clientPutter;
421 eventBus.post(new ImageInsertStartedEvent(image));
424 public void setBucket(Bucket bucket) {
425 this.bucket = bucket;
433 * Cancels the running insert.
435 @SuppressWarnings("synthetic-access")
436 public void cancel() {
437 clientPutter.cancel(node.clientCore.clientContext);
438 eventBus.post(new ImageInsertAbortedEvent(image));
443 // INTERFACE ClientPutCallback
447 public RequestClient getRequestClient() {
452 public void onResume(ClientContext context) throws ResumeFailedException {
460 @SuppressWarnings("synthetic-access")
461 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
462 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
463 eventBus.post(new ImageInsertAbortedEvent(image));
465 eventBus.post(new ImageInsertFailedEvent(image, insertException));
474 public void onFetchable(BaseClientPutter clientPutter) {
475 /* ignore, we don’t care. */
482 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
483 /* ignore, we don’t care. */
490 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
491 resultingUri = generatedUri;
498 @SuppressWarnings("synthetic-access")
499 public void onSuccess(BaseClientPutter clientPutter) {
500 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
506 public static class InsertTokenSupplier implements Function<Image, InsertToken> {
508 private final FreenetInterface freenetInterface;
511 public InsertTokenSupplier(FreenetInterface freenetInterface) {
512 this.freenetInterface = freenetInterface;
516 public InsertToken apply(Image image) {
517 return freenetInterface.new InsertToken(image);