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 /** 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 public FreenetInterface(EventBus eventBus, Node node) {
109 this.eventBus = eventBus;
111 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
119 * Fetches the given URI.
123 * @return The result of the fetch, or {@code null} if an error occured
125 public Fetched fetchUri(FreenetURI uri) {
126 FreenetURI currentUri = new FreenetURI(uri);
129 FetchResult fetchResult = client.fetch(currentUri);
130 return new Fetched(currentUri, fetchResult);
131 } catch (FetchException fe1) {
132 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
133 currentUri = fe1.newURI;
136 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
142 public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
143 ClientGetCallback callback = new ClientGetCallback() {
145 public void onSuccess(FetchResult result, ClientGetter state) {
147 backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
148 } catch (IOException e) {
149 backgroundFetchCallback.failed(uri);
154 public void onFailure(FetchException e, ClientGetter state) {
155 backgroundFetchCallback.failed(uri);
159 public void onResume(ClientContext context) throws ResumeFailedException {
164 public RequestClient getRequestClient() {
168 SnoopMetadata snoop = new SnoopMetadata() {
170 public boolean snoopMetadata(Metadata meta, ClientContext context) {
171 String mimeType = meta.getMIMEType();
172 boolean cancel = (mimeType == null) || backgroundFetchCallback.shouldCancel(uri, mimeType, meta.dataLength());
174 backgroundFetchCallback.failed(uri);
179 FetchContext fetchContext = client.getFetchContext();
181 ClientGetter clientGetter = client.fetch(uri, 2097152, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
182 clientGetter.setMetaSnoop(snoop);
183 clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
184 } catch (FetchException fe) {
185 /* stupid exception that can not actually be thrown! */
189 public interface BackgroundFetchCallback {
190 boolean shouldCancel(@Nonnull FreenetURI uri, @Nonnull String mimeType, long size);
191 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
192 void failed(@Nonnull FreenetURI uri);
196 * Inserts the image data of the given {@link TemporaryImage} and returns
197 * the given insert token that can be used to add listeners or cancel the
200 * @param temporaryImage
201 * The temporary image data
206 * @throws SoneException
207 * if the insert could not be started
209 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
210 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
211 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
212 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
213 InsertContext insertContext = client.getInsertContext(true);
214 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
215 insertToken.setBucket(bucket);
216 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
217 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
219 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
220 insertToken.setClientPutter(clientPutter);
221 } catch (InsertException ie1) {
222 throw new SoneInsertException("Could not start image insert.", ie1);
227 * Inserts a directory into Freenet.
231 * @param manifestEntries
232 * The directory entries
234 * The name of the default file
235 * @return The generated URI
236 * @throws SoneException
237 * if an insert error occurs
239 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
241 return client.insertManifest(insertUri, manifestEntries, defaultFile);
242 } catch (InsertException ie1) {
243 throw new SoneException(ie1);
247 public void registerActiveUsk(FreenetURI requestUri,
248 USKCallback uskCallback) {
250 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
251 node.clientCore.uskManager.subscribe(create(requestUri),
252 uskCallback, true, requestClient);
253 } catch (MalformedURLException mue1) {
254 logger.log(WARNING, format("Could not subscribe USK “%s”!",
259 public void registerPassiveUsk(FreenetURI requestUri,
260 USKCallback uskCallback) {
262 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
265 .subscribe(create(requestUri), uskCallback, false, requestClient);
266 } catch (MalformedURLException mue1) {
268 format("Could not subscribe USK “%s”!", requestUri),
274 * Unsubscribes the request URI of the given Sone.
277 * The Sone to unregister
279 public void unregisterUsk(Sone sone) {
280 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
281 if (uskCallback == null) {
285 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
286 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
287 } catch (MalformedURLException mue1) {
288 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
293 * Registers an arbitrary URI and calls the given callback if a new edition
299 * The callback to call
301 public void registerUsk(FreenetURI uri, final Callback callback) {
302 USKCallback uskCallback = new USKCallback() {
305 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
306 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
310 public short getPollingPriorityNormal() {
311 return RequestStarter.PREFETCH_PRIORITY_CLASS;
315 public short getPollingPriorityProgress() {
316 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
321 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
322 uriUskCallbacks.put(USK.create(uri).clearCopy().getURI(), uskCallback);
323 } catch (MalformedURLException mue1) {
324 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
329 * Unregisters the USK watcher for the given URI.
332 * The URI to unregister the USK watcher for
334 public void unregisterUsk(FreenetURI uri) {
336 USKCallback uskCallback = uriUskCallbacks.remove(USK.create(uri).clearCopy().getURI());
337 if (uskCallback == null) {
338 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
341 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
342 } catch (MalformedURLException mue1) {
343 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
348 * Callback for USK watcher events.
350 public static interface Callback {
353 * Notifies a listener that a new edition was found for a URI.
356 * The URI that a new edition was found for
359 * @param newKnownGood
360 * Whether the found edition was actually fetched
362 * Whether the found edition is higher than all previously
365 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
370 * Insert token that can cancel a running insert and sends events.
372 * @see ImageInsertAbortedEvent
373 * @see ImageInsertStartedEvent
374 * @see ImageInsertFailedEvent
375 * @see ImageInsertFinishedEvent
377 public class InsertToken implements ClientPutCallback {
379 /** The image being inserted. */
380 private final Image image;
382 /** The client putter. */
383 private ClientPutter clientPutter;
384 private Bucket bucket;
386 /** The final URI. */
387 private volatile FreenetURI resultingUri;
390 * Creates a new insert token for the given image.
393 * The image being inserted
395 public InsertToken(Image image) {
404 * Sets the client putter that is inserting the image. This will also
405 * signal all registered listeners that the image has started.
407 * @param clientPutter
410 @SuppressWarnings("synthetic-access")
411 public void setClientPutter(ClientPutter clientPutter) {
412 this.clientPutter = clientPutter;
413 eventBus.post(new ImageInsertStartedEvent(image));
416 public void setBucket(Bucket bucket) {
417 this.bucket = bucket;
425 * Cancels the running insert.
427 @SuppressWarnings("synthetic-access")
428 public void cancel() {
429 clientPutter.cancel(node.clientCore.clientContext);
430 eventBus.post(new ImageInsertAbortedEvent(image));
435 // INTERFACE ClientPutCallback
439 public RequestClient getRequestClient() {
444 public void onResume(ClientContext context) throws ResumeFailedException {
452 @SuppressWarnings("synthetic-access")
453 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
454 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
455 eventBus.post(new ImageInsertAbortedEvent(image));
457 eventBus.post(new ImageInsertFailedEvent(image, insertException));
466 public void onFetchable(BaseClientPutter clientPutter) {
467 /* ignore, we don’t care. */
474 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
475 /* ignore, we don’t care. */
482 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
483 resultingUri = generatedUri;
490 @SuppressWarnings("synthetic-access")
491 public void onSuccess(BaseClientPutter clientPutter) {
492 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
498 public static class InsertTokenSupplier implements Function<Image, InsertToken> {
500 private final FreenetInterface freenetInterface;
503 public InsertTokenSupplier(FreenetInterface freenetInterface) {
504 this.freenetInterface = freenetInterface;
508 public InsertToken apply(Image image) {
509 return freenetInterface.new InsertToken(image);