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.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import javax.annotation.Nonnull;
35 import javax.inject.Inject;
37 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
38 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
40 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
41 import net.pterodactylus.sone.data.Image;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.data.TemporaryImage;
45 import com.google.common.base.Function;
46 import com.google.common.collect.ArrayListMultimap;
47 import com.google.common.collect.Multimap;
48 import com.google.common.eventbus.EventBus;
49 import com.google.inject.Singleton;
51 import freenet.client.ClientMetadata;
52 import freenet.client.FetchContext;
53 import freenet.client.FetchException;
54 import freenet.client.FetchException.FetchExceptionMode;
55 import freenet.client.FetchResult;
56 import freenet.client.HighLevelSimpleClient;
57 import freenet.client.InsertBlock;
58 import freenet.client.InsertContext;
59 import freenet.client.InsertException;
60 import freenet.client.Metadata;
61 import freenet.client.async.BaseClientPutter;
62 import freenet.client.async.ClientContext;
63 import freenet.client.async.ClientGetCallback;
64 import freenet.client.async.ClientGetter;
65 import freenet.client.async.ClientPutCallback;
66 import freenet.client.async.ClientPutter;
67 import freenet.client.async.SnoopMetadata;
68 import freenet.client.async.USKCallback;
69 import freenet.keys.FreenetURI;
70 import freenet.keys.InsertableClientSSK;
71 import freenet.keys.USK;
72 import freenet.node.Node;
73 import freenet.node.RequestClient;
74 import freenet.node.RequestClientBuilder;
75 import freenet.node.RequestStarter;
76 import freenet.support.api.Bucket;
77 import freenet.support.api.RandomAccessBucket;
78 import freenet.support.io.ArrayBucket;
79 import freenet.support.io.ResumeFailedException;
80 import net.pterodactylus.sone.freenet.*;
83 * Contains all necessary functionality for interacting with the Freenet node.
86 public class FreenetInterface {
89 private static final Logger logger = getLogger(FreenetInterface.class.getName());
92 private final EventBus eventBus;
94 /** The node to interact with. */
95 private final Node node;
97 private final SoneUriCreator soneUriCreator;
99 /** The high-level client to use for requests. */
100 private final HighLevelSimpleClient client;
101 private final RequestClient requestClient = new RequestClientBuilder().realTime().build();
103 /** The USK callbacks. */
104 private final Multimap<String, USKCallback> soneUskCallbacks = ArrayListMultimap.create();
106 /** The not-Sone-related USK callbacks. */
107 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
109 private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
110 private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
113 public FreenetInterface(EventBus eventBus, Node node, SoneUriCreator soneUriCreator) {
114 this.eventBus = eventBus;
116 this.soneUriCreator = soneUriCreator;
117 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
125 * Fetches the given URI.
129 * @return The result of the fetch, or {@code null} if an error occured
131 public Fetched fetchUri(FreenetURI uri) {
132 FreenetURI currentUri = new FreenetURI(uri);
135 FetchResult fetchResult = client.fetch(currentUri);
136 return new Fetched(currentUri, fetchResult);
137 } catch (FetchException fe1) {
138 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
139 currentUri = fe1.newURI;
142 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
148 public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
149 ClientGetCallback callback = new ClientGetCallback() {
151 public void onSuccess(FetchResult result, ClientGetter state) {
153 backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
154 } catch (IOException e) {
155 backgroundFetchCallback.failed(uri);
160 public void onFailure(FetchException e, ClientGetter state) {
161 backgroundFetchCallback.failed(uri);
165 public void onResume(ClientContext context) throws ResumeFailedException {
170 public RequestClient getRequestClient() {
174 SnoopMetadata snoop = new SnoopMetadata() {
176 public boolean snoopMetadata(Metadata meta, ClientContext context) {
177 String mimeType = meta.getMIMEType();
178 boolean cancel = (mimeType == null) || backgroundFetchCallback.shouldCancel(uri, mimeType, meta.dataLength());
180 backgroundFetchCallback.failed(uri);
185 FetchContext fetchContext = client.getFetchContext();
187 ClientGetter clientGetter = client.fetch(uri, 2097152, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
188 clientGetter.setMetaSnoop(snoop);
189 clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
190 } catch (FetchException fe) {
191 /* stupid exception that can not actually be thrown! */
195 public interface BackgroundFetchCallback {
196 boolean shouldCancel(@Nonnull FreenetURI uri, @Nonnull String mimeType, long size);
197 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
198 void failed(@Nonnull FreenetURI uri);
202 * Inserts the image data of the given {@link TemporaryImage} and returns
203 * the given insert token that can be used to add listeners or cancel the
206 * @param temporaryImage
207 * The temporary image data
212 * @throws SoneException
213 * if the insert could not be started
215 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
216 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
217 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
218 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
219 InsertContext insertContext = client.getInsertContext(true);
220 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
221 insertToken.setBucket(bucket);
222 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
223 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
225 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
226 insertToken.setClientPutter(clientPutter);
227 } catch (InsertException ie1) {
228 throw new SoneInsertException("Could not start image insert.", ie1);
233 * Inserts a directory into Freenet.
237 * @param manifestEntries
238 * The directory entries
240 * The name of the default file
241 * @return The generated URI
242 * @throws SoneException
243 * if an insert error occurs
245 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
247 return client.insertManifest(insertUri, manifestEntries, defaultFile);
248 } catch (InsertException ie1) {
249 throw new SoneException(ie1);
253 public void registerActiveUsk(FreenetURI requestUri,
254 USKCallback uskCallback) {
256 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
257 node.clientCore.uskManager.subscribe(create(requestUri),
258 uskCallback, true, requestClient);
259 } catch (MalformedURLException mue1) {
260 logger.log(WARNING, format("Could not subscribe USK “%s”!",
265 public void registerPassiveUsk(FreenetURI requestUri,
266 USKCallback uskCallback) {
268 soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
271 .subscribe(create(requestUri), uskCallback, false, requestClient);
272 } catch (MalformedURLException mue1) {
274 format("Could not subscribe USK “%s”!", requestUri),
280 * Unsubscribes the request URI of the given Sone.
283 * The Sone to unregister
285 public void unregisterUsk(Sone sone) {
286 Collection<USKCallback> uskCallbacks = soneUskCallbacks.removeAll(sone.getId());
287 if (uskCallbacks.isEmpty()) {
290 logger.log(Level.FINE, String.format("Unsubscribing %d from USK for %s…", uskCallbacks.size(), sone));
291 logger.log(Level.FINEST, String.format("USKs left: %d", soneUskCallbacks.size()));
292 uskCallbacks.forEach(uskCallback -> {
294 node.clientCore.uskManager.unsubscribe(USK.create(soneUriCreator.getRequestUri(sone)), uskCallback);
295 } catch (MalformedURLException mue1) {
296 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", soneUriCreator.getRequestUri(sone)), mue1);
302 * Registers an arbitrary URI and calls the given callback if a new edition
308 * The callback to call
310 public void registerUsk(FreenetURI uri, final Callback callback) {
311 USKCallback uskCallback = new USKCallback() {
314 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
315 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
319 public short getPollingPriorityNormal() {
320 return RequestStarter.PREFETCH_PRIORITY_CLASS;
324 public short getPollingPriorityProgress() {
325 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
330 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
331 uriUskCallbacks.put(USK.create(uri).clearCopy().getURI(), uskCallback);
332 } catch (MalformedURLException mue1) {
333 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
338 * Unregisters the USK watcher for the given URI.
341 * The URI to unregister the USK watcher for
343 public void unregisterUsk(FreenetURI uri) {
345 USKCallback uskCallback = uriUskCallbacks.remove(USK.create(uri).clearCopy().getURI());
346 if (uskCallback == null) {
347 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
350 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
351 } catch (MalformedURLException mue1) {
352 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
357 * Callback for USK watcher events.
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
386 public class InsertToken implements ClientPutCallback {
388 /** The image being inserted. */
389 private final Image image;
391 /** The client putter. */
392 private ClientPutter clientPutter;
393 private Bucket bucket;
395 /** The final URI. */
396 private volatile FreenetURI resultingUri;
399 * Creates a new insert token for the given image.
402 * The image being inserted
404 public InsertToken(Image image) {
413 * Sets the client putter that is inserting the image. This will also
414 * signal all registered listeners that the image has started.
416 * @param clientPutter
419 @SuppressWarnings("synthetic-access")
420 public void setClientPutter(ClientPutter clientPutter) {
421 this.clientPutter = clientPutter;
422 eventBus.post(new ImageInsertStartedEvent(image));
425 public void setBucket(Bucket bucket) {
426 this.bucket = bucket;
434 * Cancels the running insert.
436 @SuppressWarnings("synthetic-access")
437 public void cancel() {
438 clientPutter.cancel(node.clientCore.clientContext);
439 eventBus.post(new ImageInsertAbortedEvent(image));
444 // INTERFACE ClientPutCallback
448 public RequestClient getRequestClient() {
453 public void onResume(ClientContext context) throws ResumeFailedException {
461 @SuppressWarnings("synthetic-access")
462 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
463 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
464 eventBus.post(new ImageInsertAbortedEvent(image));
466 eventBus.post(new ImageInsertFailedEvent(image, insertException));
475 public void onFetchable(BaseClientPutter clientPutter) {
476 /* ignore, we don’t care. */
483 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
484 /* ignore, we don’t care. */
491 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
492 resultingUri = generatedUri;
499 @SuppressWarnings("synthetic-access")
500 public void onSuccess(BaseClientPutter clientPutter) {
501 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
507 public static class InsertTokenSupplier implements Function<Image, InsertToken> {
509 private final FreenetInterface freenetInterface;
512 public InsertTokenSupplier(FreenetInterface freenetInterface) {
513 this.freenetInterface = freenetInterface;
517 public InsertToken apply(Image image) {
518 return freenetInterface.new InsertToken(image);