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 java.lang.String.format;
21 import static net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
23 import java.net.MalformedURLException;
24 import java.util.Collections;
25 import java.util.HashMap;
27 import java.util.concurrent.TimeUnit;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
32 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
33 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
34 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
35 import net.pterodactylus.sone.data.Image;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.data.TemporaryImage;
38 import net.pterodactylus.util.logging.Logging;
40 import com.db4o.ObjectContainer;
41 import com.google.common.annotations.VisibleForTesting;
42 import com.google.common.eventbus.EventBus;
43 import com.google.inject.Inject;
44 import freenet.client.ClientMetadata;
45 import freenet.client.FetchException;
46 import freenet.client.FetchResult;
47 import freenet.client.HighLevelSimpleClient;
48 import freenet.client.HighLevelSimpleClientImpl;
49 import freenet.client.InsertBlock;
50 import freenet.client.InsertContext;
51 import freenet.client.InsertException;
52 import freenet.client.async.BaseClientPutter;
53 import freenet.client.async.ClientContext;
54 import freenet.client.async.ClientPutCallback;
55 import freenet.client.async.ClientPutter;
56 import freenet.client.async.USKCallback;
57 import freenet.client.async.USKManager;
58 import freenet.keys.FreenetURI;
59 import freenet.keys.InsertableClientSSK;
60 import freenet.keys.USK;
61 import freenet.node.Node;
62 import freenet.node.RequestClient;
63 import freenet.node.RequestStarter;
64 import freenet.support.api.Bucket;
65 import freenet.support.io.ArrayBucket;
68 * Contains all necessary functionality for interacting with the Freenet node.
70 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
72 public class FreenetInterface {
75 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
78 private final EventBus eventBus;
80 /** The node to interact with. */
81 private final Node node;
83 /** The high-level client to use for requests. */
84 private final HighLevelSimpleClient client;
85 private final RequestClient requestClient;
87 /** The USK callbacks. */
88 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
90 /** The not-Sone-related USK callbacks. */
91 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
92 private USKManager uskManager;
95 * Creates a new Freenet interface.
100 * The node to interact with
103 public FreenetInterface(EventBus eventBus, Node node) {
104 this.eventBus = eventBus;
106 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
107 this.requestClient = (HighLevelSimpleClientImpl) client;
108 this.uskManager = node.clientCore.uskManager;
112 public FreenetInterface(EventBus eventBus, Node node, HighLevelSimpleClient highLevelSimpleClient, RequestClient requestClient, USKManager uskManager) {
113 this.eventBus = eventBus;
115 this.client = highLevelSimpleClient;
116 this.requestClient = requestClient;
117 this.uskManager = uskManager;
125 * Fetches the given URI.
129 * @return The result of the fetch, or {@code null} if an error occured
131 public Fetched fetchUri(FreenetURI uri) {
132 FetchResult fetchResult = null;
133 FreenetURI currentUri = new FreenetURI(uri);
136 fetchResult = client.fetch(currentUri);
137 return new Fetched(currentUri, fetchResult);
138 } catch (FetchException fe1) {
139 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
140 currentUri = fe1.newURI;
143 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
150 * Creates a key pair.
152 * @return The request key at index 0, the insert key at index 1
154 public String[] generateKeyPair() {
155 FreenetURI[] keyPair = client.generateKeyPair("");
156 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
160 * Inserts the image data of the given {@link TemporaryImage} and returns
161 * the given insert token that can be used to add listeners or cancel the
164 * @param temporaryImage
165 * The temporary image data
170 * @throws SoneException
171 * if the insert could not be started
173 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
174 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
175 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
176 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
177 InsertContext insertContext = client.getInsertContext(true);
178 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
179 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
180 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
182 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
183 insertToken.setClientPutter(clientPutter);
184 } catch (InsertException ie1) {
185 throw new SoneInsertException("Could not start image insert.", ie1);
190 * Inserts a directory into Freenet.
194 * @param manifestEntries
195 * The directory entries
197 * The name of the default file
198 * @return The generated URI
199 * @throws SoneException
200 * if an insert error occurs
202 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
204 return client.insertManifest(insertUri, manifestEntries, defaultFile);
205 } catch (InsertException ie1) {
206 throw new SoneException(ie1);
211 * Registers the USK for the given Sone and notifies the given
212 * {@link SoneDownloader} if an update was found.
216 * @param soneDownloader
217 * The Sone download to notify on updates
219 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
221 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, TO_FREENET_URI.apply(sone).setMetaString(new String[]{"sone.xml"})));
222 USKCallback uskCallback = new NewEditionFound(sone, soneDownloader);
223 soneUskCallbacks.put(sone.getId(), uskCallback);
224 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
225 uskManager.subscribe(USK.create(TO_FREENET_URI.apply(sone)), uskCallback, runBackgroundFetch, requestClient);
226 } catch (MalformedURLException mue1) {
227 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", TO_FREENET_URI.apply(sone)), mue1);
232 * Unsubscribes the request URI of the given Sone.
235 * The Sone to unregister
237 public void unregisterUsk(Sone sone) {
238 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
239 if (uskCallback == null) {
243 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
244 uskManager.unsubscribe(USK.create(TO_FREENET_URI.apply(sone)), uskCallback);
245 } catch (MalformedURLException mue1) {
246 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", TO_FREENET_URI.apply(sone)), mue1);
251 * Registers an arbitrary URI and calls the given callback if a new edition
257 * The callback to call
259 public void registerUsk(FreenetURI uri, final Callback callback) {
260 USKCallback uskCallback = new CallbackWrapper(callback);
262 uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
263 uriUskCallbacks.put(uri, uskCallback);
264 } catch (MalformedURLException mue1) {
265 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
270 * Unregisters the USK watcher for the given URI.
273 * The URI to unregister the USK watcher for
275 public void unregisterUsk(FreenetURI uri) {
276 USKCallback uskCallback = uriUskCallbacks.remove(uri);
277 if (uskCallback == null) {
278 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
282 uskManager.unsubscribe(USK.create(uri), uskCallback);
283 } catch (MalformedURLException mue1) {
284 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
289 * Container for a fetched URI and the {@link FetchResult}.
291 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
293 public static class Fetched {
295 /** The fetched URI. */
296 private final FreenetURI freenetUri;
298 /** The fetch result. */
299 private final FetchResult fetchResult;
302 * Creates a new fetched URI.
305 * The URI that was fetched
309 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
310 this.freenetUri = freenetUri;
311 this.fetchResult = fetchResult;
319 * Returns the fetched URI.
321 * @return The fetched URI
323 public FreenetURI getFreenetUri() {
328 * Returns the fetch result.
330 * @return The fetch result
332 public FetchResult getFetchResult() {
339 * Callback for USK watcher events.
341 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
343 public static interface Callback {
346 * Notifies a listener that a new edition was found for a URI.
349 * The URI that a new edition was found for
352 * @param newKnownGood
353 * Whether the found edition was actually fetched
355 * Whether the found edition is higher than all previously
358 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
362 private static class NewEditionFound implements USKCallback {
364 private final Sone sone;
365 private final SoneDownloader soneDownloader;
367 public NewEditionFound(Sone sone, SoneDownloader soneDownloader) {
369 this.soneDownloader = soneDownloader;
373 @SuppressWarnings("synthetic-access")
374 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
375 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));
376 if (edition > sone.getLatestEdition()) {
377 sone.modify().setLatestEdition(edition).update();
378 new Thread(new Runnable() {
382 soneDownloader.fetchSone(sone);
384 }, format("Sone Downloader for %s", sone.getId())).start();
389 public short getPollingPriorityProgress() {
390 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
394 public short getPollingPriorityNormal() {
395 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
399 private static class CallbackWrapper implements USKCallback {
401 private final Callback callback;
403 public CallbackWrapper(Callback callback) {
404 this.callback = callback;
408 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
409 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
413 public short getPollingPriorityNormal() {
414 return RequestStarter.PREFETCH_PRIORITY_CLASS;
418 public short getPollingPriorityProgress() {
419 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
425 * Insert token that can cancel a running insert and sends events.
427 * @see ImageInsertAbortedEvent
428 * @see ImageInsertStartedEvent
429 * @see ImageInsertFailedEvent
430 * @see ImageInsertFinishedEvent
431 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
433 public class InsertToken implements ClientPutCallback {
435 /** The image being inserted. */
436 private final Image image;
438 /** The client putter. */
439 private ClientPutter clientPutter;
441 /** The final URI. */
442 private volatile FreenetURI resultingUri;
445 * Creates a new insert token for the given image.
448 * The image being inserted
450 public InsertToken(Image image) {
459 * Sets the client putter that is inserting the image. This will also
460 * signal all registered listeners that the image has started.
462 * @param clientPutter
465 @SuppressWarnings("synthetic-access")
466 public void setClientPutter(ClientPutter clientPutter) {
467 this.clientPutter = clientPutter;
468 eventBus.post(new ImageInsertStartedEvent(image));
476 * Cancels the running insert.
478 @SuppressWarnings("synthetic-access")
479 public void cancel() {
480 clientPutter.cancel(null, node.clientCore.clientContext);
481 eventBus.post(new ImageInsertAbortedEvent(image));
485 // INTERFACE ClientPutCallback
489 public void onMajorProgress(ObjectContainer objectContainer) {
490 /* ignore, we don’t care. */
494 @SuppressWarnings("synthetic-access")
495 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
496 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
497 eventBus.post(new ImageInsertAbortedEvent(image));
499 eventBus.post(new ImageInsertFailedEvent(image, insertException));
504 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
505 /* ignore, we don’t care. */
509 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
510 /* ignore, we don’t care. */
514 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
515 resultingUri = generatedUri;
519 @SuppressWarnings("synthetic-access")
520 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
521 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));