X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;ds=inline;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Fcore%2FFreenetInterface.java;h=946371bcf3b3c6a91e4c43823fad254dadaeb1a0;hb=648e6f419534c315ade5a506e8ec8820872ee7c8;hp=a8f3efa14ba3eaab7055cfd8f3ad4363eaaa6288;hpb=50ce65f69e49ed10abeedaeb6615ffb37a0c0772;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 a8f3efa..946371b 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â2012 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
@@ -17,53 +17,78 @@
package net.pterodactylus.sone.core;
+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.ArrayList;
import java.util.Collections;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.annotation.Nonnull;
+
+import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
+import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
+import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
+import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
import net.pterodactylus.sone.data.Image;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.data.TemporaryImage;
-import net.pterodactylus.util.collection.Pair;
-import net.pterodactylus.util.logging.Logging;
-import com.db4o.ObjectContainer;
+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;
import freenet.client.HighLevelSimpleClient;
-import freenet.client.HighLevelSimpleClientImpl;
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;
import freenet.support.io.ArrayBucket;
+import freenet.support.io.ResumeFailedException;
/**
* Contains all necessary functionality for interacting with the Freenet node.
*
* @author David âBombeâ Roden
*/
+@Singleton
public class FreenetInterface {
/** The logger. */
- private static final Logger logger = Logging.getLogger(FreenetInterface.class);
+ private static final Logger logger = getLogger(FreenetInterface.class.getName());
+
+ /** The event bus. */
+ private final EventBus eventBus;
/** The node to interact with. */
private final Node node;
@@ -77,13 +102,20 @@ public class FreenetInterface {
/** 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
*/
- public FreenetInterface(Node node) {
+ @Inject
+ public FreenetInterface(EventBus eventBus, Node node) {
+ this.eventBus = eventBus;
this.node = node;
this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
}
@@ -99,15 +131,14 @@ public class FreenetInterface {
* The URI to fetch
* @return The result of the fetch, or {@code null} if an error occured
*/
- public Pair fetchUri(FreenetURI uri) {
- FetchResult fetchResult = null;
+ public Fetched fetchUri(FreenetURI uri) {
FreenetURI currentUri = new FreenetURI(uri);
while (true) {
try {
- fetchResult = client.fetch(currentUri);
- return new Pair(currentUri, fetchResult);
+ FetchResult fetchResult = client.fetch(currentUri);
+ return new Fetched(currentUri, fetchResult);
} catch (FetchException fe1) {
- if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
+ if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
currentUri = fe1.newURI;
continue;
}
@@ -117,14 +148,57 @@ public class FreenetInterface {
}
}
- /**
- * Creates a key pair.
- *
- * @return The request key at index 0, the insert key at index 1
- */
- public String[] generateKeyPair() {
- FreenetURI[] keyPair = client.generateKeyPair("");
- return new String[] { keyPair[1].toString(), keyPair[0].toString() };
+ 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);
}
/**
@@ -146,11 +220,12 @@ public class FreenetInterface {
InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
InsertContext insertContext = client.getInsertContext(true);
- Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
+ RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
+ insertToken.setBucket(bucket);
ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
try {
- ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
+ ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
insertToken.setClientPutter(clientPutter);
} catch (InsertException ie1) {
throw new SoneInsertException("Could not start image insert.", ie1);
@@ -178,50 +253,30 @@ public class FreenetInterface {
}
}
- /**
- * Registers the USK for the given Sone and notifies the given
- * {@link SoneDownloader} if an update was found.
- *
- * @param sone
- * The Sone to watch
- * @param soneDownloader
- * The Sone download to notify on updates
- */
- public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
+ public void registerActiveUsk(FreenetURI requestUri,
+ USKCallback uskCallback) {
try {
- logger.log(Level.FINE, String.format("Registering Sone â%sâ for USK updates at %sâ¦", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
- USKCallback uskCallback = new USKCallback() {
-
- @Override
- @SuppressWarnings("synthetic-access")
- public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
- logger.log(Level.FINE, String.format("Found USK update for Sone â%sâ at %s, new known good: %s, new slot too: %s.", sone, key, newKnownGood, newSlotToo));
- if (edition > sone.getLatestEdition()) {
- sone.setLatestEdition(edition);
- new Thread(new Runnable() {
-
- @Override
- public void run() {
- soneDownloader.fetchSone(sone);
- }
- }, "Sone Downloader").start();
- }
- }
-
- @Override
- public short getPollingPriorityProgress() {
- return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
- }
+ soneUskCallbacks.put(routingKey(requestUri), uskCallback);
+ node.clientCore.uskManager.subscribe(create(requestUri),
+ uskCallback, true, (RequestClient) client);
+ } catch (MalformedURLException mue1) {
+ logger.log(WARNING, format("Could not subscribe USK â%sâ!",
+ requestUri), mue1);
+ }
+ }
- @Override
- public short getPollingPriorityNormal() {
- return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
- }
- };
- soneUskCallbacks.put(sone.getId(), uskCallback);
- node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, (System.currentTimeMillis() - sone.getTime()) < 7 * 24 * 60 * 60 * 1000, (HighLevelSimpleClientImpl) client);
+ public void registerPassiveUsk(FreenetURI requestUri,
+ USKCallback uskCallback) {
+ try {
+ soneUskCallbacks.put(routingKey(requestUri), uskCallback);
+ node.clientCore
+ .uskManager
+ .subscribe(create(requestUri), uskCallback, false,
+ (RequestClient) client);
} catch (MalformedURLException mue1) {
- logger.log(Level.WARNING, String.format("Could not subscribe USK â%sâ!", sone.getRequestUri()), mue1);
+ logger.log(WARNING,
+ format("Could not subscribe USK â%sâ!", requestUri),
+ mue1);
}
}
@@ -257,7 +312,7 @@ public class FreenetInterface {
USKCallback uskCallback = new USKCallback() {
@Override
- public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
+ public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
}
@@ -273,7 +328,7 @@ public class FreenetInterface {
};
try {
- node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
+ node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
uriUskCallbacks.put(uri, uskCallback);
} catch (MalformedURLException mue1) {
logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
@@ -300,6 +355,56 @@ 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
@@ -324,9 +429,12 @@ public class FreenetInterface {
}
/**
- * Insert token that can be used to add {@link ImageInsertListener}s and
- * cancel a running insert.
+ * Insert token that can cancel a running insert and sends events.
*
+ * @see ImageInsertAbortedEvent
+ * @see ImageInsertStartedEvent
+ * @see ImageInsertFailedEvent
+ * @see ImageInsertFinishedEvent
* @author David âBombeâ Roden
*/
public class InsertToken implements ClientPutCallback {
@@ -334,11 +442,9 @@ public class FreenetInterface {
/** The image being inserted. */
private final Image image;
- /** The list of registered image insert listeners. */
- private final List imageInsertListeners = Collections.synchronizedList(new ArrayList());
-
/** The client putter. */
private ClientPutter clientPutter;
+ private Bucket bucket;
/** The final URI. */
private volatile FreenetURI resultingUri;
@@ -354,30 +460,6 @@ public class FreenetInterface {
}
//
- // LISTENER MANAGEMENT
- //
-
- /**
- * Adds the given listener to the list of registered listener.
- *
- * @param imageInsertListener
- * The listener to add
- */
- public void addImageInsertListener(ImageInsertListener imageInsertListener) {
- imageInsertListeners.add(imageInsertListener);
- }
-
- /**
- * Removes the given listener from the list of registered listener.
- *
- * @param imageInsertListener
- * The listener to remove
- */
- public void removeImageInsertListener(ImageInsertListener imageInsertListener) {
- imageInsertListeners.remove(imageInsertListener);
- }
-
- //
// ACCESSORS
//
@@ -385,15 +467,17 @@ public class FreenetInterface {
* Sets the client putter that is inserting the image. This will also
* signal all registered listeners that the image has started.
*
- * @see ImageInsertListener#imageInsertStarted(Image)
* @param clientPutter
* The client putter
*/
+ @SuppressWarnings("synthetic-access")
public void setClientPutter(ClientPutter clientPutter) {
this.clientPutter = clientPutter;
- for (ImageInsertListener imageInsertListener : imageInsertListeners) {
- imageInsertListener.imageInsertStarted(image);
- }
+ eventBus.post(new ImageInsertStartedEvent(image));
+ }
+
+ public void setBucket(Bucket bucket) {
+ this.bucket = bucket;
}
//
@@ -402,48 +486,47 @@ public class FreenetInterface {
/**
* Cancels the running insert.
- *
- * @see ImageInsertListener#imageInsertAborted(Image)
*/
@SuppressWarnings("synthetic-access")
public void cancel() {
- clientPutter.cancel(null, node.clientCore.clientContext);
- for (ImageInsertListener imageInsertListener : imageInsertListeners) {
- imageInsertListener.imageInsertAborted(image);
- }
+ clientPutter.cancel(node.clientCore.clientContext);
+ eventBus.post(new ImageInsertAbortedEvent(image));
+ bucket.free();
}
//
// INTERFACE ClientPutCallback
//
- /**
- * {@inheritDoc}
- */
@Override
- public void onMajorProgress(ObjectContainer objectContainer) {
- /* ignore, we donât care. */
+ public RequestClient getRequestClient() {
+ return imageInserts;
+ }
+
+ @Override
+ public void onResume(ClientContext context) throws ResumeFailedException {
+ /* ignore. */
}
/**
* {@inheritDoc}
*/
@Override
- public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
- for (ImageInsertListener imageInsertListener : imageInsertListeners) {
- if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
- imageInsertListener.imageInsertAborted(image);
- } else {
- imageInsertListener.imageInsertFailed(image, insertException);
- }
+ @SuppressWarnings("synthetic-access")
+ public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
+ if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
+ eventBus.post(new ImageInsertAbortedEvent(image));
+ } else {
+ eventBus.post(new ImageInsertFailedEvent(image, insertException));
}
+ bucket.free();
}
/**
* {@inheritDoc}
*/
@Override
- public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
+ public void onFetchable(BaseClientPutter clientPutter) {
/* ignore, we donât care. */
}
@@ -451,7 +534,7 @@ public class FreenetInterface {
* {@inheritDoc}
*/
@Override
- public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
+ public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
/* ignore, we donât care. */
}
@@ -459,7 +542,7 @@ public class FreenetInterface {
* {@inheritDoc}
*/
@Override
- public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
+ public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
resultingUri = generatedUri;
}
@@ -467,10 +550,19 @@ public class FreenetInterface {
* {@inheritDoc}
*/
@Override
- public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
- for (ImageInsertListener imageInsertListener : imageInsertListeners) {
- imageInsertListener.imageInsertFinished(image, resultingUri);
- }
+ @SuppressWarnings("synthetic-access")
+ public void onSuccess(BaseClientPutter clientPutter) {
+ eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
+ bucket.free();
+ }
+
+ }
+
+ public class InsertTokenSupplier implements Function {
+
+ @Override
+ public InsertToken apply(Image image) {
+ return new InsertToken(image);
}
}