X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Fcore%2FFreenetInterface.java;h=e77badf3006ac23602c4998206e6d220036c592b;hb=a5743ce8177323159e4d1828dced6021d27c4d62;hp=9b061c202d1ee6419bb93bbb14b1b8f666bc6def;hpb=c8567f1c6105ae1aa8ffce59868ae2ccf0bfe4c2;p=Sone.git
diff --git a/src/main/java/net/pterodactylus/sone/core/FreenetInterface.java b/src/main/java/net/pterodactylus/sone/core/FreenetInterface.java
index 9b061c2..e77badf 100644
--- a/src/main/java/net/pterodactylus/sone/core/FreenetInterface.java
+++ b/src/main/java/net/pterodactylus/sone/core/FreenetInterface.java
@@ -1,5 +1,5 @@
/*
- * Sone - FreenetInterface.java - Copyright © 2010â2016 David Roden
+ * Sone - FreenetInterface.java - Copyright © 2010â2020 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,15 +21,19 @@ import static freenet.keys.USK.create;
import static java.lang.String.format;
import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
-import static net.pterodactylus.sone.freenet.Key.routingKey;
+import java.io.IOException;
import java.net.MalformedURLException;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.annotation.Nonnull;
+import javax.inject.Inject;
+
import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
@@ -39,11 +43,13 @@ import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.data.TemporaryImage;
import com.google.common.base.Function;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Multimap;
import com.google.common.eventbus.EventBus;
-import com.google.inject.Inject;
import com.google.inject.Singleton;
import freenet.client.ClientMetadata;
+import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchException.FetchExceptionMode;
import freenet.client.FetchResult;
@@ -51,10 +57,14 @@ import freenet.client.HighLevelSimpleClient;
import freenet.client.InsertBlock;
import freenet.client.InsertContext;
import freenet.client.InsertException;
+import freenet.client.Metadata;
import freenet.client.async.BaseClientPutter;
import freenet.client.async.ClientContext;
+import freenet.client.async.ClientGetCallback;
+import freenet.client.async.ClientGetter;
import freenet.client.async.ClientPutCallback;
import freenet.client.async.ClientPutter;
+import freenet.client.async.SnoopMetadata;
import freenet.client.async.USKCallback;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableClientSSK;
@@ -67,11 +77,10 @@ import freenet.support.api.Bucket;
import freenet.support.api.RandomAccessBucket;
import freenet.support.io.ArrayBucket;
import freenet.support.io.ResumeFailedException;
+import net.pterodactylus.sone.freenet.*;
/**
* Contains all necessary functionality for interacting with the Freenet node.
- *
- * @author David âBombeâ Roden
*/
@Singleton
public class FreenetInterface {
@@ -85,29 +94,26 @@ public class FreenetInterface {
/** The node to interact with. */
private final Node node;
+ private final SoneUriCreator soneUriCreator;
+
/** The high-level client to use for requests. */
private final HighLevelSimpleClient client;
+ private final RequestClient requestClient = new RequestClientBuilder().realTime().build();
/** The USK callbacks. */
- private final Map soneUskCallbacks = new HashMap();
+ private final Multimap soneUskCallbacks = ArrayListMultimap.create();
/** The not-Sone-related USK callbacks. */
private final Map uriUskCallbacks = Collections.synchronizedMap(new HashMap());
private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
+ private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
- /**
- * Creates a new Freenet interface.
- *
- * @param eventBus
- * The event bus
- * @param node
- * The node to interact with
- */
@Inject
- public FreenetInterface(EventBus eventBus, Node node) {
+ public FreenetInterface(EventBus eventBus, Node node, SoneUriCreator soneUriCreator) {
this.eventBus = eventBus;
this.node = node;
+ this.soneUriCreator = soneUriCreator;
this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
}
@@ -139,6 +145,59 @@ public class FreenetInterface {
}
}
+ public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
+ ClientGetCallback callback = new ClientGetCallback() {
+ @Override
+ public void onSuccess(FetchResult result, ClientGetter state) {
+ try {
+ backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
+ } catch (IOException e) {
+ backgroundFetchCallback.failed(uri);
+ }
+ }
+
+ @Override
+ public void onFailure(FetchException e, ClientGetter state) {
+ backgroundFetchCallback.failed(uri);
+ }
+
+ @Override
+ public void onResume(ClientContext context) throws ResumeFailedException {
+ /* do nothing. */
+ }
+
+ @Override
+ public RequestClient getRequestClient() {
+ return imageLoader;
+ }
+ };
+ SnoopMetadata snoop = new SnoopMetadata() {
+ @Override
+ public boolean snoopMetadata(Metadata meta, ClientContext context) {
+ String mimeType = meta.getMIMEType();
+ boolean cancel = (mimeType == null) || backgroundFetchCallback.shouldCancel(uri, mimeType, meta.dataLength());
+ if (cancel) {
+ backgroundFetchCallback.failed(uri);
+ }
+ return cancel;
+ }
+ };
+ FetchContext fetchContext = client.getFetchContext();
+ try {
+ ClientGetter clientGetter = client.fetch(uri, 2097152, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
+ clientGetter.setMetaSnoop(snoop);
+ clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
+ } catch (FetchException fe) {
+ /* stupid exception that can not actually be thrown! */
+ }
+ }
+
+ public interface BackgroundFetchCallback {
+ boolean shouldCancel(@Nonnull FreenetURI uri, @Nonnull String mimeType, long size);
+ void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
+ void failed(@Nonnull FreenetURI uri);
+ }
+
/**
* Inserts the image data of the given {@link TemporaryImage} and returns
* the given insert token that can be used to add listeners or cancel the
@@ -194,9 +253,9 @@ public class FreenetInterface {
public void registerActiveUsk(FreenetURI requestUri,
USKCallback uskCallback) {
try {
- soneUskCallbacks.put(routingKey(requestUri), uskCallback);
+ soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
node.clientCore.uskManager.subscribe(create(requestUri),
- uskCallback, true, (RequestClient) client);
+ uskCallback, true, requestClient);
} catch (MalformedURLException mue1) {
logger.log(WARNING, format("Could not subscribe USK â%sâ!",
requestUri), mue1);
@@ -206,11 +265,10 @@ public class FreenetInterface {
public void registerPassiveUsk(FreenetURI requestUri,
USKCallback uskCallback) {
try {
- soneUskCallbacks.put(routingKey(requestUri), uskCallback);
+ soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
node.clientCore
.uskManager
- .subscribe(create(requestUri), uskCallback, false,
- (RequestClient) client);
+ .subscribe(create(requestUri), uskCallback, false, requestClient);
} catch (MalformedURLException mue1) {
logger.log(WARNING,
format("Could not subscribe USK â%sâ!", requestUri),
@@ -225,16 +283,19 @@ public class FreenetInterface {
* The Sone to unregister
*/
public void unregisterUsk(Sone sone) {
- USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
- if (uskCallback == null) {
+ Collection uskCallbacks = soneUskCallbacks.removeAll(sone.getId());
+ if (uskCallbacks.isEmpty()) {
return;
}
- try {
- logger.log(Level.FINEST, String.format("Unsubscribing from USK for %sâ¦", sone));
- node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
- } catch (MalformedURLException mue1) {
- logger.log(Level.FINE, String.format("Could not unsubscribe USK â%sâ!", sone.getRequestUri()), mue1);
- }
+ logger.log(Level.FINE, String.format("Unsubscribing %d from USK for %sâ¦", uskCallbacks.size(), sone));
+ logger.log(Level.FINEST, String.format("USKs left: %d", soneUskCallbacks.size()));
+ uskCallbacks.forEach(uskCallback -> {
+ try {
+ node.clientCore.uskManager.unsubscribe(USK.create(soneUriCreator.getRequestUri(sone)), uskCallback);
+ } catch (MalformedURLException mue1) {
+ logger.log(Level.FINE, String.format("Could not unsubscribe USK â%sâ!", soneUriCreator.getRequestUri(sone)), mue1);
+ }
+ });
}
/**
@@ -266,8 +327,8 @@ public class FreenetInterface {
};
try {
- node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
- uriUskCallbacks.put(uri, uskCallback);
+ node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
+ uriUskCallbacks.put(USK.create(uri).clearCopy().getURI(), uskCallback);
} catch (MalformedURLException mue1) {
logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
}
@@ -280,12 +341,12 @@ public class FreenetInterface {
* The URI to unregister the USK watcher for
*/
public void unregisterUsk(FreenetURI uri) {
- USKCallback uskCallback = uriUskCallbacks.remove(uri);
- if (uskCallback == null) {
- logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
- return;
- }
try {
+ USKCallback uskCallback = uriUskCallbacks.remove(USK.create(uri).clearCopy().getURI());
+ if (uskCallback == null) {
+ logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
+ return;
+ }
node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
} catch (MalformedURLException mue1) {
logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
@@ -293,59 +354,7 @@ public class FreenetInterface {
}
/**
- * Container for a fetched URI and the {@link FetchResult}.
- *
- * @author David Roden
- */
- public static class Fetched {
-
- /** The fetched URI. */
- private final FreenetURI freenetUri;
-
- /** The fetch result. */
- private final FetchResult fetchResult;
-
- /**
- * Creates a new fetched URI.
- *
- * @param freenetUri
- * The URI that was fetched
- * @param fetchResult
- * The fetch result
- */
- public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
- this.freenetUri = freenetUri;
- this.fetchResult = fetchResult;
- }
-
- //
- // ACCESSORS
- //
-
- /**
- * Returns the fetched URI.
- *
- * @return The fetched URI
- */
- public FreenetURI getFreenetUri() {
- return freenetUri;
- }
-
- /**
- * Returns the fetch result.
- *
- * @return The fetch result
- */
- public FetchResult getFetchResult() {
- return fetchResult;
- }
-
- }
-
- /**
* Callback for USK watcher events.
- *
- * @author David âBombeâ Roden
*/
public static interface Callback {
@@ -373,7 +382,6 @@ public class FreenetInterface {
* @see ImageInsertStartedEvent
* @see ImageInsertFailedEvent
* @see ImageInsertFinishedEvent
- * @author David âBombeâ Roden
*/
public class InsertToken implements ClientPutCallback {
@@ -496,11 +504,18 @@ public class FreenetInterface {
}
- public class InsertTokenSupplier implements Function {
+ public static class InsertTokenSupplier implements Function {
+
+ private final FreenetInterface freenetInterface;
+
+ @Inject
+ public InsertTokenSupplier(FreenetInterface freenetInterface) {
+ this.freenetInterface = freenetInterface;
+ }
@Override
public InsertToken apply(Image image) {
- return new InsertToken(image);
+ return freenetInterface.new InsertToken(image);
}
}