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(soneDownloader.fetchSoneAction(sone), "Sone Downloader").start();
210 public short getPollingPriorityProgress() {
211 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
215 public short getPollingPriorityNormal() {
216 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
219 soneUskCallbacks.put(sone.getId(), uskCallback);
220 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
221 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (RequestClient) client);
222 } catch (MalformedURLException mue1) {
223 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
228 * Unsubscribes the request URI of the given Sone.
231 * The Sone to unregister
233 public void unregisterUsk(Sone sone) {
234 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
235 if (uskCallback == null) {
239 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
240 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
241 } catch (MalformedURLException mue1) {
242 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
247 * Registers an arbitrary URI and calls the given callback if a new edition
253 * The callback to call
255 public void registerUsk(FreenetURI uri, final Callback callback) {
256 USKCallback uskCallback = new USKCallback() {
259 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
260 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
264 public short getPollingPriorityNormal() {
265 return RequestStarter.PREFETCH_PRIORITY_CLASS;
269 public short getPollingPriorityProgress() {
270 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
275 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
276 uriUskCallbacks.put(uri, uskCallback);
277 } catch (MalformedURLException mue1) {
278 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
283 * Unregisters the USK watcher for the given URI.
286 * The URI to unregister the USK watcher for
288 public void unregisterUsk(FreenetURI uri) {
289 USKCallback uskCallback = uriUskCallbacks.remove(uri);
290 if (uskCallback == null) {
291 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
295 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
296 } catch (MalformedURLException mue1) {
297 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
302 * Container for a fetched URI and the {@link FetchResult}.
304 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
306 public static class Fetched {
308 /** The fetched URI. */
309 private final FreenetURI freenetUri;
311 /** The fetch result. */
312 private final FetchResult fetchResult;
315 * Creates a new fetched URI.
318 * The URI that was fetched
322 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
323 this.freenetUri = freenetUri;
324 this.fetchResult = fetchResult;
332 * Returns the fetched URI.
334 * @return The fetched URI
336 public FreenetURI getFreenetUri() {
341 * Returns the fetch result.
343 * @return The fetch result
345 public FetchResult getFetchResult() {
352 * Callback for USK watcher events.
354 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
356 public static interface Callback {
359 * Notifies a listener that a new edition was found for a URI.
362 * The URI that a new edition was found for
365 * @param newKnownGood
366 * Whether the found edition was actually fetched
368 * Whether the found edition is higher than all previously
371 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
376 * Insert token that can cancel a running insert and sends events.
378 * @see ImageInsertAbortedEvent
379 * @see ImageInsertStartedEvent
380 * @see ImageInsertFailedEvent
381 * @see ImageInsertFinishedEvent
382 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
384 public class InsertToken implements ClientPutCallback {
386 /** The image being inserted. */
387 private final Image image;
389 /** The client putter. */
390 private ClientPutter clientPutter;
392 /** The final URI. */
393 private volatile FreenetURI resultingUri;
396 * Creates a new insert token for the given image.
399 * The image being inserted
401 public InsertToken(Image image) {
410 * Sets the client putter that is inserting the image. This will also
411 * signal all registered listeners that the image has started.
413 * @param clientPutter
416 @SuppressWarnings("synthetic-access")
417 public void setClientPutter(ClientPutter clientPutter) {
418 this.clientPutter = clientPutter;
419 eventBus.post(new ImageInsertStartedEvent(image));
427 * Cancels the running insert.
429 @SuppressWarnings("synthetic-access")
430 public void cancel() {
431 clientPutter.cancel(null, node.clientCore.clientContext);
432 eventBus.post(new ImageInsertAbortedEvent(image));
436 // INTERFACE ClientPutCallback
443 public void onMajorProgress(ObjectContainer objectContainer) {
444 /* ignore, we don’t care. */
451 @SuppressWarnings("synthetic-access")
452 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
453 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
454 eventBus.post(new ImageInsertAbortedEvent(image));
456 eventBus.post(new ImageInsertFailedEvent(image, insertException));
464 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
465 /* ignore, we don’t care. */
472 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
473 /* ignore, we don’t care. */
480 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
481 resultingUri = generatedUri;
488 @SuppressWarnings("synthetic-access")
489 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
490 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
495 public class InsertTokenSupplier implements Function<Image, InsertToken> {
498 public InsertToken apply(Image image) {
499 return new InsertToken(image);