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.db4o.ObjectContainer;
39 import com.google.common.base.Function;
40 import com.google.common.eventbus.EventBus;
41 import com.google.inject.Inject;
42 import com.google.inject.Singleton;
44 import freenet.client.ClientMetadata;
45 import freenet.client.FetchException;
46 import freenet.client.FetchResult;
47 import freenet.client.HighLevelSimpleClient;
48 import freenet.client.InsertBlock;
49 import freenet.client.InsertContext;
50 import freenet.client.InsertException;
51 import freenet.client.async.BaseClientPutter;
52 import freenet.client.async.ClientContext;
53 import freenet.client.async.ClientPutCallback;
54 import freenet.client.async.ClientPutter;
55 import freenet.client.async.USKCallback;
56 import freenet.keys.FreenetURI;
57 import freenet.keys.InsertableClientSSK;
58 import freenet.keys.USK;
59 import freenet.node.Node;
60 import freenet.node.RequestClient;
61 import freenet.node.RequestStarter;
62 import freenet.support.api.Bucket;
63 import freenet.support.io.ArrayBucket;
66 * Contains all necessary functionality for interacting with the Freenet node.
68 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public class FreenetInterface {
74 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
77 private final EventBus eventBus;
79 /** The node to interact with. */
80 private final Node node;
82 /** The high-level client to use for requests. */
83 private final HighLevelSimpleClient client;
85 /** The USK callbacks. */
86 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
88 /** The not-Sone-related USK callbacks. */
89 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
92 * Creates a new Freenet interface.
97 * The node to interact with
100 public FreenetInterface(EventBus eventBus, Node node) {
101 this.eventBus = eventBus;
103 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
111 * Fetches the given URI.
115 * @return The result of the fetch, or {@code null} if an error occured
117 public Fetched fetchUri(FreenetURI uri) {
118 FreenetURI currentUri = new FreenetURI(uri);
121 FetchResult fetchResult = client.fetch(currentUri);
122 return new Fetched(currentUri, fetchResult);
123 } catch (FetchException fe1) {
124 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
125 currentUri = fe1.newURI;
128 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
135 * Inserts the image data of the given {@link TemporaryImage} and returns
136 * the given insert token that can be used to add listeners or cancel the
139 * @param temporaryImage
140 * The temporary image data
145 * @throws SoneException
146 * if the insert could not be started
148 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
149 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
150 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
151 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
152 InsertContext insertContext = client.getInsertContext(true);
153 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
154 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
155 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
157 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
158 insertToken.setClientPutter(clientPutter);
159 } catch (InsertException ie1) {
160 throw new SoneInsertException("Could not start image insert.", ie1);
165 * Inserts a directory into Freenet.
169 * @param manifestEntries
170 * The directory entries
172 * The name of the default file
173 * @return The generated URI
174 * @throws SoneException
175 * if an insert error occurs
177 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
179 return client.insertManifest(insertUri, manifestEntries, defaultFile);
180 } catch (InsertException ie1) {
181 throw new SoneException(ie1);
186 * Registers the USK for the given Sone and notifies the given
187 * {@link SoneDownloader} if an update was found.
191 * @param soneDownloader
192 * The Sone download to notify on updates
194 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
196 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
197 USKCallback uskCallback = new USKCallback() {
200 @SuppressWarnings("synthetic-access")
201 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
202 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));
203 if (edition > sone.getLatestEdition()) {
204 sone.setLatestEdition(edition);
205 new Thread(new Runnable() {
209 soneDownloader.fetchSone(sone);
211 }, "Sone Downloader").start();
216 public short getPollingPriorityProgress() {
217 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
221 public short getPollingPriorityNormal() {
222 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
225 soneUskCallbacks.put(sone.getId(), uskCallback);
226 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
227 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (RequestClient) client);
228 } catch (MalformedURLException mue1) {
229 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
234 * Unsubscribes the request URI of the given Sone.
237 * The Sone to unregister
239 public void unregisterUsk(Sone sone) {
240 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
241 if (uskCallback == null) {
245 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
246 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
247 } catch (MalformedURLException mue1) {
248 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
253 * Registers an arbitrary URI and calls the given callback if a new edition
259 * The callback to call
261 public void registerUsk(FreenetURI uri, final Callback callback) {
262 USKCallback uskCallback = new USKCallback() {
265 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
266 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
270 public short getPollingPriorityNormal() {
271 return RequestStarter.PREFETCH_PRIORITY_CLASS;
275 public short getPollingPriorityProgress() {
276 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
281 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
282 uriUskCallbacks.put(uri, uskCallback);
283 } catch (MalformedURLException mue1) {
284 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
289 * Unregisters the USK watcher for the given URI.
292 * The URI to unregister the USK watcher for
294 public void unregisterUsk(FreenetURI uri) {
295 USKCallback uskCallback = uriUskCallbacks.remove(uri);
296 if (uskCallback == null) {
297 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
301 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
302 } catch (MalformedURLException mue1) {
303 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
308 * Container for a fetched URI and the {@link FetchResult}.
310 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
312 public static class Fetched {
314 /** The fetched URI. */
315 private final FreenetURI freenetUri;
317 /** The fetch result. */
318 private final FetchResult fetchResult;
321 * Creates a new fetched URI.
324 * The URI that was fetched
328 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
329 this.freenetUri = freenetUri;
330 this.fetchResult = fetchResult;
338 * Returns the fetched URI.
340 * @return The fetched URI
342 public FreenetURI getFreenetUri() {
347 * Returns the fetch result.
349 * @return The fetch result
351 public FetchResult getFetchResult() {
358 * Callback for USK watcher events.
360 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
362 public static interface Callback {
365 * Notifies a listener that a new edition was found for a URI.
368 * The URI that a new edition was found for
371 * @param newKnownGood
372 * Whether the found edition was actually fetched
374 * Whether the found edition is higher than all previously
377 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
382 * Insert token that can cancel a running insert and sends events.
384 * @see ImageInsertAbortedEvent
385 * @see ImageInsertStartedEvent
386 * @see ImageInsertFailedEvent
387 * @see ImageInsertFinishedEvent
388 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
390 public class InsertToken implements ClientPutCallback {
392 /** The image being inserted. */
393 private final Image image;
395 /** The client putter. */
396 private ClientPutter clientPutter;
398 /** The final URI. */
399 private volatile FreenetURI resultingUri;
402 * Creates a new insert token for the given image.
405 * The image being inserted
407 public InsertToken(Image image) {
416 * Sets the client putter that is inserting the image. This will also
417 * signal all registered listeners that the image has started.
419 * @param clientPutter
422 @SuppressWarnings("synthetic-access")
423 public void setClientPutter(ClientPutter clientPutter) {
424 this.clientPutter = clientPutter;
425 eventBus.post(new ImageInsertStartedEvent(image));
433 * Cancels the running insert.
435 @SuppressWarnings("synthetic-access")
436 public void cancel() {
437 clientPutter.cancel(null, node.clientCore.clientContext);
438 eventBus.post(new ImageInsertAbortedEvent(image));
442 // INTERFACE ClientPutCallback
449 public void onMajorProgress(ObjectContainer objectContainer) {
450 /* ignore, we don’t care. */
457 @SuppressWarnings("synthetic-access")
458 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
459 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
460 eventBus.post(new ImageInsertAbortedEvent(image));
462 eventBus.post(new ImageInsertFailedEvent(image, insertException));
470 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
471 /* ignore, we don’t care. */
478 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
479 /* ignore, we don’t care. */
486 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
487 resultingUri = generatedUri;
494 @SuppressWarnings("synthetic-access")
495 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
496 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
501 public class InsertTokenSupplier implements Function<Image, InsertToken> {
504 public InsertToken apply(Image image) {
505 return new InsertToken(image);