2 * Sone - FreenetInterface.java - Copyright © 2010–2013 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 net.pterodactylus.sone.freenet.Key.routingKey;
25 import java.net.MalformedURLException;
26 import java.util.Collections;
27 import java.util.HashMap;
29 import java.util.logging.Level;
30 import java.util.logging.Logger;
32 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
33 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
34 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
35 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
36 import net.pterodactylus.sone.data.Image;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.data.TemporaryImage;
39 import net.pterodactylus.util.logging.Logging;
41 import com.db4o.ObjectContainer;
43 import com.google.common.base.Function;
44 import com.google.common.eventbus.EventBus;
45 import com.google.inject.Inject;
46 import com.google.inject.Singleton;
48 import freenet.client.ClientMetadata;
49 import freenet.client.FetchException;
50 import freenet.client.FetchResult;
51 import freenet.client.HighLevelSimpleClient;
52 import freenet.client.InsertBlock;
53 import freenet.client.InsertContext;
54 import freenet.client.InsertException;
55 import freenet.client.async.BaseClientPutter;
56 import freenet.client.async.ClientContext;
57 import freenet.client.async.ClientPutCallback;
58 import freenet.client.async.ClientPutter;
59 import freenet.client.async.USKCallback;
60 import freenet.keys.FreenetURI;
61 import freenet.keys.InsertableClientSSK;
62 import freenet.keys.USK;
63 import freenet.node.Node;
64 import freenet.node.RequestClient;
65 import freenet.node.RequestStarter;
66 import freenet.support.api.Bucket;
67 import freenet.support.io.ArrayBucket;
70 * Contains all necessary functionality for interacting with the Freenet node.
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public class FreenetInterface {
78 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
81 private final EventBus eventBus;
83 /** The node to interact with. */
84 private final Node node;
86 /** The high-level client to use for requests. */
87 private final HighLevelSimpleClient client;
89 /** The USK callbacks. */
90 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
92 /** The not-Sone-related USK callbacks. */
93 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
96 * Creates a new Freenet interface.
101 * The node to interact with
104 public FreenetInterface(EventBus eventBus, Node node) {
105 this.eventBus = eventBus;
107 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
115 * Fetches the given URI.
119 * @return The result of the fetch, or {@code null} if an error occured
121 public Fetched fetchUri(FreenetURI uri) {
122 FreenetURI currentUri = new FreenetURI(uri);
125 FetchResult fetchResult = client.fetch(currentUri);
126 return new Fetched(currentUri, fetchResult);
127 } catch (FetchException fe1) {
128 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
129 currentUri = fe1.newURI;
132 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
139 * Inserts the image data of the given {@link TemporaryImage} and returns
140 * the given insert token that can be used to add listeners or cancel the
143 * @param temporaryImage
144 * The temporary image data
149 * @throws SoneException
150 * if the insert could not be started
152 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
153 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
154 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
155 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
156 InsertContext insertContext = client.getInsertContext(true);
157 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
158 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
159 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
161 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
162 insertToken.setClientPutter(clientPutter);
163 } catch (InsertException ie1) {
164 throw new SoneInsertException("Could not start image insert.", ie1);
169 * Inserts a directory into Freenet.
173 * @param manifestEntries
174 * The directory entries
176 * The name of the default file
177 * @return The generated URI
178 * @throws SoneException
179 * if an insert error occurs
181 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
183 return client.insertManifest(insertUri, manifestEntries, defaultFile);
184 } catch (InsertException ie1) {
185 throw new SoneException(ie1);
189 public void registerActiveUsk(FreenetURI requestUri,
190 USKCallback uskCallback) {
192 soneUskCallbacks.put(routingKey(requestUri), uskCallback);
193 node.clientCore.uskManager.subscribe(create(requestUri),
194 uskCallback, true, (RequestClient) client);
195 } catch (MalformedURLException mue1) {
196 logger.log(WARNING, format("Could not subscribe USK “%s”!",
201 public void registerPassiveUsk(FreenetURI requestUri,
202 USKCallback uskCallback) {
204 soneUskCallbacks.put(routingKey(requestUri), uskCallback);
207 .subscribe(create(requestUri), uskCallback, false,
208 (RequestClient) client);
209 } catch (MalformedURLException mue1) {
211 format("Could not subscribe USK “%s”!", requestUri),
217 * Unsubscribes the request URI of the given Sone.
220 * The Sone to unregister
222 public void unregisterUsk(Sone sone) {
223 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
224 if (uskCallback == null) {
228 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
229 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
230 } catch (MalformedURLException mue1) {
231 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
236 * Registers an arbitrary URI and calls the given callback if a new edition
242 * The callback to call
244 public void registerUsk(FreenetURI uri, final Callback callback) {
245 USKCallback uskCallback = new USKCallback() {
248 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
249 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
253 public short getPollingPriorityNormal() {
254 return RequestStarter.PREFETCH_PRIORITY_CLASS;
258 public short getPollingPriorityProgress() {
259 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
264 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
265 uriUskCallbacks.put(uri, uskCallback);
266 } catch (MalformedURLException mue1) {
267 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
272 * Unregisters the USK watcher for the given URI.
275 * The URI to unregister the USK watcher for
277 public void unregisterUsk(FreenetURI uri) {
278 USKCallback uskCallback = uriUskCallbacks.remove(uri);
279 if (uskCallback == null) {
280 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
284 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
285 } catch (MalformedURLException mue1) {
286 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
291 * Container for a fetched URI and the {@link FetchResult}.
293 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
295 public static class Fetched {
297 /** The fetched URI. */
298 private final FreenetURI freenetUri;
300 /** The fetch result. */
301 private final FetchResult fetchResult;
304 * Creates a new fetched URI.
307 * The URI that was fetched
311 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
312 this.freenetUri = freenetUri;
313 this.fetchResult = fetchResult;
321 * Returns the fetched URI.
323 * @return The fetched URI
325 public FreenetURI getFreenetUri() {
330 * Returns the fetch result.
332 * @return The fetch result
334 public FetchResult getFetchResult() {
341 * Callback for USK watcher events.
343 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
345 public static interface Callback {
348 * Notifies a listener that a new edition was found for a URI.
351 * The URI that a new edition was found for
354 * @param newKnownGood
355 * Whether the found edition was actually fetched
357 * Whether the found edition is higher than all previously
360 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
365 * Insert token that can cancel a running insert and sends events.
367 * @see ImageInsertAbortedEvent
368 * @see ImageInsertStartedEvent
369 * @see ImageInsertFailedEvent
370 * @see ImageInsertFinishedEvent
371 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
373 public class InsertToken implements ClientPutCallback {
375 /** The image being inserted. */
376 private final Image image;
378 /** The client putter. */
379 private ClientPutter clientPutter;
381 /** The final URI. */
382 private volatile FreenetURI resultingUri;
385 * Creates a new insert token for the given image.
388 * The image being inserted
390 public InsertToken(Image image) {
399 * Sets the client putter that is inserting the image. This will also
400 * signal all registered listeners that the image has started.
402 * @param clientPutter
405 @SuppressWarnings("synthetic-access")
406 public void setClientPutter(ClientPutter clientPutter) {
407 this.clientPutter = clientPutter;
408 eventBus.post(new ImageInsertStartedEvent(image));
416 * Cancels the running insert.
418 @SuppressWarnings("synthetic-access")
419 public void cancel() {
420 clientPutter.cancel(null, node.clientCore.clientContext);
421 eventBus.post(new ImageInsertAbortedEvent(image));
425 // INTERFACE ClientPutCallback
432 public void onMajorProgress(ObjectContainer objectContainer) {
433 /* ignore, we don’t care. */
440 @SuppressWarnings("synthetic-access")
441 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
442 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
443 eventBus.post(new ImageInsertAbortedEvent(image));
445 eventBus.post(new ImageInsertFailedEvent(image, insertException));
453 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
454 /* ignore, we don’t care. */
461 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
462 /* ignore, we don’t care. */
469 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
470 resultingUri = generatedUri;
477 @SuppressWarnings("synthetic-access")
478 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
479 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
484 public class InsertTokenSupplier implements Function<Image, InsertToken> {
487 public InsertToken apply(Image image) {
488 return new InsertToken(image);