2 * Sone - FreenetInterface.java - Copyright © 2010–2020 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 private final SoneUriCreator soneUriCreator;
96 /** The high-level client to use for requests. */
97 private final HighLevelSimpleClient client;
98 private final RequestClient requestClient = new RequestClientBuilder().realTime().build();
100 /** The USK callbacks. */
101 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<>();
103 /** The not-Sone-related USK callbacks. */
104 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
106 private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
107 private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
110 public FreenetInterface(EventBus eventBus, Node node, SoneUriCreator soneUriCreator) {
111 this.eventBus = eventBus;
113 this.soneUriCreator = soneUriCreator;
114 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
122 * Fetches the given URI.
126 * @return The result of the fetch, or {@code null} if an error occured
128 public Fetched fetchUri(FreenetURI uri) {
129 FreenetURI currentUri = new FreenetURI(uri);
132 FetchResult fetchResult = client.fetch(currentUri);
133 return new Fetched(currentUri, fetchResult);
134 } catch (FetchException fe1) {
135 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
136 currentUri = fe1.newURI;
139 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
145 public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
146 ClientGetCallback callback = new ClientGetCallback() {
148 public void onSuccess(FetchResult result, ClientGetter state) {
150 backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
151 } catch (IOException e) {
152 backgroundFetchCallback.failed(uri);
157 public void onFailure(FetchException e, ClientGetter state) {
158 backgroundFetchCallback.failed(uri);
162 public void onResume(ClientContext context) throws ResumeFailedException {
167 public RequestClient getRequestClient() {
171 SnoopMetadata snoop = new SnoopMetadata() {
173 public boolean snoopMetadata(Metadata meta, ClientContext context) {
174 String mimeType = meta.getMIMEType();
175 boolean cancel = (mimeType == null) || backgroundFetchCallback.shouldCancel(uri, mimeType, meta.dataLength());
177 backgroundFetchCallback.failed(uri);
182 FetchContext fetchContext = client.getFetchContext();
184 ClientGetter clientGetter = client.fetch(uri, 2097152, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
185 clientGetter.setMetaSnoop(snoop);
186 clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
187 } catch (FetchException fe) {
188 /* stupid exception that can not actually be thrown! */
192 public interface BackgroundFetchCallback {
193 boolean shouldCancel(@Nonnull FreenetURI uri, @Nonnull String mimeType, long size);
194 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
195 void failed(@Nonnull FreenetURI uri);
199 * Inserts the image data of the given {@link TemporaryImage} and returns
200 * the given insert token that can be used to add listeners or cancel the
203 * @param temporaryImage
204 * The temporary image data
209 * @throws SoneException
210 * if the insert could not be started
212 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
213 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
214 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
215 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
216 InsertContext insertContext = client.getInsertContext(true);
217 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
218 insertToken.setBucket(bucket);
219 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
220 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
222 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
223 insertToken.setClientPutter(clientPutter);
224 } catch (InsertException ie1) {
225 throw new SoneInsertException("Could not start image insert.", ie1);
230 * Inserts a directory into Freenet.
234 * @param manifestEntries
235 * The directory entries
237 * The name of the default file
238 * @return The generated URI
239 * @throws SoneException
240 * if an insert error occurs
242 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
244 return client.insertManifest(insertUri, manifestEntries, defaultFile);
245 } catch (InsertException ie1) {
246 throw new SoneException(ie1);
250 public void registerActiveUsk(FreenetURI requestUri,
251 USKCallback uskCallback) {
253 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
254 node.clientCore.uskManager.subscribe(create(requestUri),
255 uskCallback, true, requestClient);
256 } catch (MalformedURLException mue1) {
257 logger.log(WARNING, format("Could not subscribe USK “%s”!",
262 public void registerPassiveUsk(FreenetURI requestUri,
263 USKCallback uskCallback) {
265 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
268 .subscribe(create(requestUri), uskCallback, false, requestClient);
269 } catch (MalformedURLException mue1) {
271 format("Could not subscribe USK “%s”!", requestUri),
277 * Unsubscribes the request URI of the given Sone.
280 * The Sone to unregister
282 public void unregisterUsk(Sone sone) {
283 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
284 if (uskCallback == null) {
288 logger.log(Level.FINE, String.format("Unsubscribing from USK for %s…", sone));
289 logger.log(Level.FINEST, String.format("USKs left: %d", soneUskCallbacks.size()));
290 node.clientCore.uskManager.unsubscribe(USK.create(soneUriCreator.getRequestUri(sone)), uskCallback);
291 } catch (MalformedURLException mue1) {
292 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", soneUriCreator.getRequestUri(sone)), mue1);
297 * Registers an arbitrary URI and calls the given callback if a new edition
303 * The callback to call
305 public void registerUsk(FreenetURI uri, final Callback callback) {
306 USKCallback uskCallback = new USKCallback() {
309 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
310 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
314 public short getPollingPriorityNormal() {
315 return RequestStarter.PREFETCH_PRIORITY_CLASS;
319 public short getPollingPriorityProgress() {
320 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
325 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
326 uriUskCallbacks.put(USK.create(uri).clearCopy().getURI(), uskCallback);
327 } catch (MalformedURLException mue1) {
328 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
333 * Unregisters the USK watcher for the given URI.
336 * The URI to unregister the USK watcher for
338 public void unregisterUsk(FreenetURI uri) {
340 USKCallback uskCallback = uriUskCallbacks.remove(USK.create(uri).clearCopy().getURI());
341 if (uskCallback == null) {
342 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
345 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
346 } catch (MalformedURLException mue1) {
347 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
352 * Callback for USK watcher events.
354 public static interface Callback {
357 * Notifies a listener that a new edition was found for a URI.
360 * The URI that a new edition was found for
363 * @param newKnownGood
364 * Whether the found edition was actually fetched
366 * Whether the found edition is higher than all previously
369 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
374 * Insert token that can cancel a running insert and sends events.
376 * @see ImageInsertAbortedEvent
377 * @see ImageInsertStartedEvent
378 * @see ImageInsertFailedEvent
379 * @see ImageInsertFinishedEvent
381 public class InsertToken implements ClientPutCallback {
383 /** The image being inserted. */
384 private final Image image;
386 /** The client putter. */
387 private ClientPutter clientPutter;
388 private Bucket bucket;
390 /** The final URI. */
391 private volatile FreenetURI resultingUri;
394 * Creates a new insert token for the given image.
397 * The image being inserted
399 public InsertToken(Image image) {
408 * Sets the client putter that is inserting the image. This will also
409 * signal all registered listeners that the image has started.
411 * @param clientPutter
414 @SuppressWarnings("synthetic-access")
415 public void setClientPutter(ClientPutter clientPutter) {
416 this.clientPutter = clientPutter;
417 eventBus.post(new ImageInsertStartedEvent(image));
420 public void setBucket(Bucket bucket) {
421 this.bucket = bucket;
429 * Cancels the running insert.
431 @SuppressWarnings("synthetic-access")
432 public void cancel() {
433 clientPutter.cancel(node.clientCore.clientContext);
434 eventBus.post(new ImageInsertAbortedEvent(image));
439 // INTERFACE ClientPutCallback
443 public RequestClient getRequestClient() {
448 public void onResume(ClientContext context) throws ResumeFailedException {
456 @SuppressWarnings("synthetic-access")
457 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
458 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
459 eventBus.post(new ImageInsertAbortedEvent(image));
461 eventBus.post(new ImageInsertFailedEvent(image, insertException));
470 public void onFetchable(BaseClientPutter clientPutter) {
471 /* ignore, we don’t care. */
478 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
479 /* ignore, we don’t care. */
486 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
487 resultingUri = generatedUri;
494 @SuppressWarnings("synthetic-access")
495 public void onSuccess(BaseClientPutter clientPutter) {
496 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
502 public static class InsertTokenSupplier implements Function<Image, InsertToken> {
504 private final FreenetInterface freenetInterface;
507 public InsertTokenSupplier(FreenetInterface freenetInterface) {
508 this.freenetInterface = freenetInterface;
512 public InsertToken apply(Image image) {
513 return freenetInterface.new InsertToken(image);