Use a real RequestClient instead of casting the HLSC
[Sone.git] / src / main / java / net / pterodactylus / sone / core / FreenetInterface.java
index 219377d..f2cbec6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Sone - FreenetInterface.java - Copyright © 2010–2015 David Roden
+ * Sone - FreenetInterface.java - Copyright © 2010–2016 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
@@ -23,6 +23,7 @@ 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.Collections;
 import java.util.HashMap;
@@ -30,6 +31,9 @@ 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;
@@ -40,10 +44,10 @@ import net.pterodactylus.sone.data.TemporaryImage;
 
 import com.google.common.base.Function;
 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,16 +55,21 @@ 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;
 import freenet.keys.USK;
 import freenet.node.Node;
 import freenet.node.RequestClient;
+import freenet.node.RequestClientBuilder;
 import freenet.node.RequestStarter;
 import freenet.support.api.Bucket;
 import freenet.support.api.RandomAccessBucket;
@@ -69,8 +78,6 @@ import freenet.support.io.ResumeFailedException;
 
 /**
  * Contains all necessary functionality for interacting with the Freenet node.
- *
- * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
 @Singleton
 public class FreenetInterface {
@@ -86,6 +93,7 @@ public class FreenetInterface {
 
        /** 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<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
@@ -93,17 +101,8 @@ public class FreenetInterface {
        /** The not-Sone-related USK callbacks. */
        private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
 
-       private final RequestClient imageInserts = new RequestClient() {
-               @Override
-               public boolean persistent() {
-                       return false;
-               }
-
-               @Override
-               public boolean realTimeFlag() {
-                       return true;
-               }
-       };
+       private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
+       private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
 
        /**
         * Creates a new Freenet interface.
@@ -148,6 +147,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
@@ -205,7 +257,7 @@ public class FreenetInterface {
                try {
                        soneUskCallbacks.put(routingKey(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);
@@ -218,8 +270,7 @@ public class FreenetInterface {
                        soneUskCallbacks.put(routingKey(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),
@@ -275,7 +326,7 @@ public class FreenetInterface {
 
                };
                try {
-                       node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
+                       node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
                        uriUskCallbacks.put(uri, uskCallback);
                } catch (MalformedURLException mue1) {
                        logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
@@ -302,59 +353,7 @@ public class FreenetInterface {
        }
 
        /**
-        * Container for a fetched URI and the {@link FetchResult}.
-        *
-        * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
-        */
-       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 <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
         */
        public static interface Callback {
 
@@ -382,7 +381,6 @@ public class FreenetInterface {
         * @see ImageInsertStartedEvent
         * @see ImageInsertFailedEvent
         * @see ImageInsertFinishedEvent
-        * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
         */
        public class InsertToken implements ClientPutCallback {
 
@@ -505,11 +503,18 @@ public class FreenetInterface {
 
        }
 
-       public class InsertTokenSupplier implements Function<Image, InsertToken> {
+       public static class InsertTokenSupplier implements Function<Image, InsertToken> {
+
+               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);
                }
 
        }