2 * Sone - FreenetInterface.java - Copyright © 2010–2016 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.io.IOException;
27 import java.net.MalformedURLException;
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;
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.Inject;
47 import com.google.inject.Singleton;
49 import freenet.client.ClientMetadata;
50 import freenet.client.FetchContext;
51 import freenet.client.FetchException;
52 import freenet.client.FetchException.FetchExceptionMode;
53 import freenet.client.FetchResult;
54 import freenet.client.HighLevelSimpleClient;
55 import freenet.client.InsertBlock;
56 import freenet.client.InsertContext;
57 import freenet.client.InsertException;
58 import freenet.client.Metadata;
59 import freenet.client.async.BaseClientPutter;
60 import freenet.client.async.ClientContext;
61 import freenet.client.async.ClientGetCallback;
62 import freenet.client.async.ClientGetter;
63 import freenet.client.async.ClientPutCallback;
64 import freenet.client.async.ClientPutter;
65 import freenet.client.async.SnoopMetadata;
66 import freenet.client.async.USKCallback;
67 import freenet.keys.FreenetURI;
68 import freenet.keys.InsertableClientSSK;
69 import freenet.keys.USK;
70 import freenet.node.Node;
71 import freenet.node.RequestClient;
72 import freenet.node.RequestClientBuilder;
73 import freenet.node.RequestStarter;
74 import freenet.support.api.Bucket;
75 import freenet.support.api.RandomAccessBucket;
76 import freenet.support.io.ArrayBucket;
77 import freenet.support.io.ResumeFailedException;
80 * Contains all necessary functionality for interacting with the Freenet node.
82 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
85 public class FreenetInterface {
88 private static final Logger logger = getLogger(FreenetInterface.class.getName());
91 private final EventBus eventBus;
93 /** The node to interact with. */
94 private final Node node;
96 /** The high-level client to use for requests. */
97 private final HighLevelSimpleClient client;
99 /** The USK callbacks. */
100 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
102 /** The not-Sone-related USK callbacks. */
103 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
105 private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
106 private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
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);
151 public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
152 ClientGetCallback callback = new ClientGetCallback() {
154 public void onSuccess(FetchResult result, ClientGetter state) {
156 backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
157 } catch (IOException e) {
158 backgroundFetchCallback.failed(uri);
163 public void onFailure(FetchException e, ClientGetter state) {
164 backgroundFetchCallback.failed(uri);
168 public void onResume(ClientContext context) throws ResumeFailedException {
173 public RequestClient getRequestClient() {
177 SnoopMetadata snoop = new SnoopMetadata() {
179 public boolean snoopMetadata(Metadata meta, ClientContext context) {
180 String mimeType = meta.getMIMEType();
181 return (mimeType == null) || backgroundFetchCallback.cancelForMimeType(uri, mimeType);
184 FetchContext fetchContext = client.getFetchContext();
186 ClientGetter clientGetter = client.fetch(uri, 1048576, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
187 clientGetter.setMetaSnoop(snoop);
188 clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
189 } catch (FetchException fe) {
190 /* stupid exception that can not actually be thrown! */
194 public interface BackgroundFetchCallback {
195 boolean cancelForMimeType(@Nonnull FreenetURI uri, @Nonnull String mimeType);
196 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
197 void failed(@Nonnull FreenetURI uri);
201 * Inserts the image data of the given {@link TemporaryImage} and returns
202 * the given insert token that can be used to add listeners or cancel the
205 * @param temporaryImage
206 * The temporary image data
211 * @throws SoneException
212 * if the insert could not be started
214 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
215 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
216 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
217 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
218 InsertContext insertContext = client.getInsertContext(true);
219 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
220 insertToken.setBucket(bucket);
221 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
222 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
224 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
225 insertToken.setClientPutter(clientPutter);
226 } catch (InsertException ie1) {
227 throw new SoneInsertException("Could not start image insert.", ie1);
232 * Inserts a directory into Freenet.
236 * @param manifestEntries
237 * The directory entries
239 * The name of the default file
240 * @return The generated URI
241 * @throws SoneException
242 * if an insert error occurs
244 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
246 return client.insertManifest(insertUri, manifestEntries, defaultFile);
247 } catch (InsertException ie1) {
248 throw new SoneException(ie1);
252 public void registerActiveUsk(FreenetURI requestUri,
253 USKCallback uskCallback) {
255 soneUskCallbacks.put(routingKey(requestUri), uskCallback);
256 node.clientCore.uskManager.subscribe(create(requestUri),
257 uskCallback, true, (RequestClient) client);
258 } catch (MalformedURLException mue1) {
259 logger.log(WARNING, format("Could not subscribe USK “%s”!",
264 public void registerPassiveUsk(FreenetURI requestUri,
265 USKCallback uskCallback) {
267 soneUskCallbacks.put(routingKey(requestUri), uskCallback);
270 .subscribe(create(requestUri), uskCallback, false,
271 (RequestClient) client);
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 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
287 if (uskCallback == null) {
291 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
292 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
293 } catch (MalformedURLException mue1) {
294 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
299 * Registers an arbitrary URI and calls the given callback if a new edition
305 * The callback to call
307 public void registerUsk(FreenetURI uri, final Callback callback) {
308 USKCallback uskCallback = new USKCallback() {
311 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
312 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
316 public short getPollingPriorityNormal() {
317 return RequestStarter.PREFETCH_PRIORITY_CLASS;
321 public short getPollingPriorityProgress() {
322 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
327 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
328 uriUskCallbacks.put(uri, uskCallback);
329 } catch (MalformedURLException mue1) {
330 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
335 * Unregisters the USK watcher for the given URI.
338 * The URI to unregister the USK watcher for
340 public void unregisterUsk(FreenetURI uri) {
341 USKCallback uskCallback = uriUskCallbacks.remove(uri);
342 if (uskCallback == null) {
343 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
347 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
348 } catch (MalformedURLException mue1) {
349 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
354 * Container for a fetched URI and the {@link FetchResult}.
356 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
358 public static class Fetched {
360 /** The fetched URI. */
361 private final FreenetURI freenetUri;
363 /** The fetch result. */
364 private final FetchResult fetchResult;
367 * Creates a new fetched URI.
370 * The URI that was fetched
374 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
375 this.freenetUri = freenetUri;
376 this.fetchResult = fetchResult;
384 * Returns the fetched URI.
386 * @return The fetched URI
388 public FreenetURI getFreenetUri() {
393 * Returns the fetch result.
395 * @return The fetch result
397 public FetchResult getFetchResult() {
404 * Callback for USK watcher events.
406 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
408 public static interface Callback {
411 * Notifies a listener that a new edition was found for a URI.
414 * The URI that a new edition was found for
417 * @param newKnownGood
418 * Whether the found edition was actually fetched
420 * Whether the found edition is higher than all previously
423 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
428 * Insert token that can cancel a running insert and sends events.
430 * @see ImageInsertAbortedEvent
431 * @see ImageInsertStartedEvent
432 * @see ImageInsertFailedEvent
433 * @see ImageInsertFinishedEvent
434 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
436 public class InsertToken implements ClientPutCallback {
438 /** The image being inserted. */
439 private final Image image;
441 /** The client putter. */
442 private ClientPutter clientPutter;
443 private Bucket bucket;
445 /** The final URI. */
446 private volatile FreenetURI resultingUri;
449 * Creates a new insert token for the given image.
452 * The image being inserted
454 public InsertToken(Image image) {
463 * Sets the client putter that is inserting the image. This will also
464 * signal all registered listeners that the image has started.
466 * @param clientPutter
469 @SuppressWarnings("synthetic-access")
470 public void setClientPutter(ClientPutter clientPutter) {
471 this.clientPutter = clientPutter;
472 eventBus.post(new ImageInsertStartedEvent(image));
475 public void setBucket(Bucket bucket) {
476 this.bucket = bucket;
484 * Cancels the running insert.
486 @SuppressWarnings("synthetic-access")
487 public void cancel() {
488 clientPutter.cancel(node.clientCore.clientContext);
489 eventBus.post(new ImageInsertAbortedEvent(image));
494 // INTERFACE ClientPutCallback
498 public RequestClient getRequestClient() {
503 public void onResume(ClientContext context) throws ResumeFailedException {
511 @SuppressWarnings("synthetic-access")
512 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
513 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
514 eventBus.post(new ImageInsertAbortedEvent(image));
516 eventBus.post(new ImageInsertFailedEvent(image, insertException));
525 public void onFetchable(BaseClientPutter clientPutter) {
526 /* ignore, we don’t care. */
533 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
534 /* ignore, we don’t care. */
541 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
542 resultingUri = generatedUri;
549 @SuppressWarnings("synthetic-access")
550 public void onSuccess(BaseClientPutter clientPutter) {
551 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
557 public class InsertTokenSupplier implements Function<Image, InsertToken> {
560 public InsertToken apply(Image image) {
561 return new InsertToken(image);