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=7cb8a9aaec137075f3bd89cfefb7614c19bebbc3;hpb=d525d4ad65878cfd895945512650d978f6a5c034;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 7cb8a9a..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â2013 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,14 +17,22 @@
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.Collections;
import java.util.HashMap;
import java.util.Map;
-import java.util.concurrent.TimeUnit;
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;
@@ -32,30 +40,36 @@ 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.logging.Logging;
+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;
@@ -67,10 +81,11 @@ import freenet.support.io.ResumeFailedException;
*
* @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;
@@ -87,6 +102,9 @@ 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.
*
@@ -114,11 +132,10 @@ public class FreenetInterface {
* @return The result of the fetch, or {@code null} if an error occured
*/
public Fetched fetchUri(FreenetURI uri) {
- FetchResult fetchResult = null;
FreenetURI currentUri = new FreenetURI(uri);
while (true) {
try {
- fetchResult = client.fetch(currentUri);
+ FetchResult fetchResult = client.fetch(currentUri);
return new Fetched(currentUri, fetchResult);
} catch (FetchException fe1) {
if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
@@ -131,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);
}
/**
@@ -161,6 +221,7 @@ public class FreenetInterface {
FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
InsertContext insertContext = client.getInsertContext(true);
RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
+ insertToken.setBucket(bucket);
ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
try {
@@ -192,51 +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, 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);
- boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
- node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (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);
}
}
@@ -288,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);
@@ -404,6 +444,7 @@ public class FreenetInterface {
/** The client putter. */
private ClientPutter clientPutter;
+ private Bucket bucket;
/** The final URI. */
private volatile FreenetURI resultingUri;
@@ -435,6 +476,10 @@ public class FreenetInterface {
eventBus.post(new ImageInsertStartedEvent(image));
}
+ public void setBucket(Bucket bucket) {
+ this.bucket = bucket;
+ }
+
//
// ACTIONS
//
@@ -446,6 +491,7 @@ public class FreenetInterface {
public void cancel() {
clientPutter.cancel(node.clientCore.clientContext);
eventBus.post(new ImageInsertAbortedEvent(image));
+ bucket.free();
}
//
@@ -454,7 +500,7 @@ public class FreenetInterface {
@Override
public RequestClient getRequestClient() {
- return clientPutter.getClient();
+ return imageInserts;
}
@Override
@@ -473,6 +519,7 @@ public class FreenetInterface {
} else {
eventBus.post(new ImageInsertFailedEvent(image, insertException));
}
+ bucket.free();
}
/**
@@ -506,6 +553,16 @@ public class FreenetInterface {
@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);
}
}