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 java.net.MalformedURLException;
21 import java.util.Collections;
22 import java.util.HashMap;
24 import java.util.concurrent.TimeUnit;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
28 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
29 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
30 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
31 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
32 import net.pterodactylus.sone.data.Image;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.data.TemporaryImage;
35 import net.pterodactylus.util.logging.Logging;
37 import com.google.common.eventbus.EventBus;
38 import com.google.inject.Inject;
40 import freenet.client.ClientMetadata;
41 import freenet.client.FetchException;
42 import freenet.client.FetchException.FetchExceptionMode;
43 import freenet.client.FetchResult;
44 import freenet.client.HighLevelSimpleClient;
45 import freenet.client.HighLevelSimpleClientImpl;
46 import freenet.client.InsertBlock;
47 import freenet.client.InsertContext;
48 import freenet.client.InsertException;
49 import freenet.client.async.BaseClientPutter;
50 import freenet.client.async.ClientContext;
51 import freenet.client.async.ClientPutCallback;
52 import freenet.client.async.ClientPutter;
53 import freenet.client.async.USKCallback;
54 import freenet.keys.FreenetURI;
55 import freenet.keys.InsertableClientSSK;
56 import freenet.keys.USK;
57 import freenet.node.Node;
58 import freenet.node.RequestClient;
59 import freenet.node.RequestStarter;
60 import freenet.support.api.Bucket;
61 import freenet.support.api.RandomAccessBucket;
62 import freenet.support.io.ArrayBucket;
63 import freenet.support.io.ResumeFailedException;
66 * Contains all necessary functionality for interacting with the Freenet node.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70 public class FreenetInterface {
73 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
76 private final EventBus eventBus;
78 /** The node to interact with. */
79 private final Node node;
81 /** The high-level client to use for requests. */
82 private final HighLevelSimpleClient client;
84 /** The USK callbacks. */
85 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
87 /** The not-Sone-related USK callbacks. */
88 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
91 * Creates a new Freenet interface.
96 * The node to interact with
99 public FreenetInterface(EventBus eventBus, Node node) {
100 this.eventBus = eventBus;
102 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
110 * Fetches the given URI.
114 * @return The result of the fetch, or {@code null} if an error occured
116 public Fetched fetchUri(FreenetURI uri) {
117 FetchResult fetchResult = null;
118 FreenetURI currentUri = new FreenetURI(uri);
121 fetchResult = client.fetch(currentUri);
122 return new Fetched(currentUri, fetchResult);
123 } catch (FetchException fe1) {
124 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
125 currentUri = fe1.newURI;
128 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
135 * Creates a key pair.
137 * @return The request key at index 0, the insert key at index 1
139 public String[] generateKeyPair() {
140 FreenetURI[] keyPair = client.generateKeyPair("");
141 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
145 * Inserts the image data of the given {@link TemporaryImage} and returns
146 * the given insert token that can be used to add listeners or cancel the
149 * @param temporaryImage
150 * The temporary image data
155 * @throws SoneException
156 * if the insert could not be started
158 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
159 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
160 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
161 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
162 InsertContext insertContext = client.getInsertContext(true);
163 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
164 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
165 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
167 ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
168 insertToken.setClientPutter(clientPutter);
169 } catch (InsertException ie1) {
170 throw new SoneInsertException("Could not start image insert.", ie1);
175 * Inserts a directory into Freenet.
179 * @param manifestEntries
180 * The directory entries
182 * The name of the default file
183 * @return The generated URI
184 * @throws SoneException
185 * if an insert error occurs
187 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
189 return client.insertManifest(insertUri, manifestEntries, defaultFile);
190 } catch (InsertException ie1) {
191 throw new SoneException(ie1);
196 * Registers the USK for the given Sone and notifies the given
197 * {@link SoneDownloader} if an update was found.
201 * @param soneDownloader
202 * The Sone download to notify on updates
204 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
206 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
207 USKCallback uskCallback = new USKCallback() {
210 @SuppressWarnings("synthetic-access")
211 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
212 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));
213 if (edition > sone.getLatestEdition()) {
214 sone.setLatestEdition(edition);
215 new Thread(new Runnable() {
219 soneDownloader.fetchSone(sone);
221 }, "Sone Downloader").start();
226 public short getPollingPriorityProgress() {
227 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
231 public short getPollingPriorityNormal() {
232 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
235 soneUskCallbacks.put(sone.getId(), uskCallback);
236 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
237 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (HighLevelSimpleClientImpl) client);
238 } catch (MalformedURLException mue1) {
239 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
244 * Unsubscribes the request URI of the given Sone.
247 * The Sone to unregister
249 public void unregisterUsk(Sone sone) {
250 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
251 if (uskCallback == null) {
255 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
256 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
257 } catch (MalformedURLException mue1) {
258 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
263 * Registers an arbitrary URI and calls the given callback if a new edition
269 * The callback to call
271 public void registerUsk(FreenetURI uri, final Callback callback) {
272 USKCallback uskCallback = new USKCallback() {
275 public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
276 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
280 public short getPollingPriorityNormal() {
281 return RequestStarter.PREFETCH_PRIORITY_CLASS;
285 public short getPollingPriorityProgress() {
286 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
291 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
292 uriUskCallbacks.put(uri, uskCallback);
293 } catch (MalformedURLException mue1) {
294 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
299 * Unregisters the USK watcher for the given URI.
302 * The URI to unregister the USK watcher for
304 public void unregisterUsk(FreenetURI uri) {
305 USKCallback uskCallback = uriUskCallbacks.remove(uri);
306 if (uskCallback == null) {
307 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
311 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
312 } catch (MalformedURLException mue1) {
313 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
318 * Container for a fetched URI and the {@link FetchResult}.
320 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
322 public static class Fetched {
324 /** The fetched URI. */
325 private final FreenetURI freenetUri;
327 /** The fetch result. */
328 private final FetchResult fetchResult;
331 * Creates a new fetched URI.
334 * The URI that was fetched
338 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
339 this.freenetUri = freenetUri;
340 this.fetchResult = fetchResult;
348 * Returns the fetched URI.
350 * @return The fetched URI
352 public FreenetURI getFreenetUri() {
357 * Returns the fetch result.
359 * @return The fetch result
361 public FetchResult getFetchResult() {
368 * Callback for USK watcher events.
370 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
372 public static interface Callback {
375 * Notifies a listener that a new edition was found for a URI.
378 * The URI that a new edition was found for
381 * @param newKnownGood
382 * Whether the found edition was actually fetched
384 * Whether the found edition is higher than all previously
387 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
392 * Insert token that can cancel a running insert and sends events.
394 * @see ImageInsertAbortedEvent
395 * @see ImageInsertStartedEvent
396 * @see ImageInsertFailedEvent
397 * @see ImageInsertFinishedEvent
398 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
400 public class InsertToken implements ClientPutCallback {
402 /** The image being inserted. */
403 private final Image image;
405 /** The client putter. */
406 private ClientPutter clientPutter;
408 /** The final URI. */
409 private volatile FreenetURI resultingUri;
412 * Creates a new insert token for the given image.
415 * The image being inserted
417 public InsertToken(Image image) {
426 * Sets the client putter that is inserting the image. This will also
427 * signal all registered listeners that the image has started.
429 * @param clientPutter
432 @SuppressWarnings("synthetic-access")
433 public void setClientPutter(ClientPutter clientPutter) {
434 this.clientPutter = clientPutter;
435 eventBus.post(new ImageInsertStartedEvent(image));
443 * Cancels the running insert.
445 @SuppressWarnings("synthetic-access")
446 public void cancel() {
447 clientPutter.cancel(node.clientCore.clientContext);
448 eventBus.post(new ImageInsertAbortedEvent(image));
452 // INTERFACE ClientPutCallback
456 public RequestClient getRequestClient() {
457 return clientPutter.getClient();
461 public void onResume(ClientContext context) throws ResumeFailedException {
469 @SuppressWarnings("synthetic-access")
470 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
471 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
472 eventBus.post(new ImageInsertAbortedEvent(image));
474 eventBus.post(new ImageInsertFailedEvent(image, insertException));
482 public void onFetchable(BaseClientPutter clientPutter) {
483 /* ignore, we don’t care. */
490 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
491 /* ignore, we don’t care. */
498 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
499 resultingUri = generatedUri;
506 @SuppressWarnings("synthetic-access")
507 public void onSuccess(BaseClientPutter clientPutter) {
508 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));