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;
43 import freenet.client.ClientMetadata;
44 import freenet.client.FetchException;
45 import freenet.client.FetchResult;
46 import freenet.client.HighLevelSimpleClient;
47 import freenet.client.InsertBlock;
48 import freenet.client.InsertContext;
49 import freenet.client.InsertException;
50 import freenet.client.async.BaseClientPutter;
51 import freenet.client.async.ClientContext;
52 import freenet.client.async.ClientPutCallback;
53 import freenet.client.async.ClientPutter;
54 import freenet.client.async.USKCallback;
55 import freenet.keys.FreenetURI;
56 import freenet.keys.InsertableClientSSK;
57 import freenet.keys.USK;
58 import freenet.node.Node;
59 import freenet.node.RequestClient;
60 import freenet.node.RequestStarter;
61 import freenet.support.api.Bucket;
62 import freenet.support.io.ArrayBucket;
65 * Contains all necessary functionality for interacting with the Freenet node.
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class FreenetInterface {
72 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
75 private final EventBus eventBus;
77 /** The node to interact with. */
78 private final Node node;
80 /** The high-level client to use for requests. */
81 private final HighLevelSimpleClient client;
83 /** The USK callbacks. */
84 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
86 /** The not-Sone-related USK callbacks. */
87 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
90 * Creates a new Freenet interface.
95 * The node to interact with
98 public FreenetInterface(EventBus eventBus, Node node) {
99 this.eventBus = eventBus;
101 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
109 * Fetches the given URI.
113 * @return The result of the fetch, or {@code null} if an error occured
115 public Fetched fetchUri(FreenetURI uri) {
116 FreenetURI currentUri = new FreenetURI(uri);
119 FetchResult fetchResult = client.fetch(currentUri);
120 return new Fetched(currentUri, fetchResult);
121 } catch (FetchException fe1) {
122 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
123 currentUri = fe1.newURI;
126 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
133 * Inserts the image data of the given {@link TemporaryImage} and returns
134 * the given insert token that can be used to add listeners or cancel the
137 * @param temporaryImage
138 * The temporary image data
143 * @throws SoneException
144 * if the insert could not be started
146 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
147 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
148 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
149 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
150 InsertContext insertContext = client.getInsertContext(true);
151 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
152 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
153 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
155 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
156 insertToken.setClientPutter(clientPutter);
157 } catch (InsertException ie1) {
158 throw new SoneInsertException("Could not start image insert.", ie1);
163 * Inserts a directory into Freenet.
167 * @param manifestEntries
168 * The directory entries
170 * The name of the default file
171 * @return The generated URI
172 * @throws SoneException
173 * if an insert error occurs
175 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
177 return client.insertManifest(insertUri, manifestEntries, defaultFile);
178 } catch (InsertException ie1) {
179 throw new SoneException(ie1);
184 * Registers the USK for the given Sone and notifies the given
185 * {@link SoneDownloader} if an update was found.
189 * @param soneDownloader
190 * The Sone download to notify on updates
192 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
194 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
195 USKCallback uskCallback = new USKCallback() {
198 @SuppressWarnings("synthetic-access")
199 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
200 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));
201 if (edition > sone.getLatestEdition()) {
202 sone.setLatestEdition(edition);
203 new Thread(new Runnable() {
207 soneDownloader.fetchSone(sone);
209 }, "Sone Downloader").start();
214 public short getPollingPriorityProgress() {
215 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
219 public short getPollingPriorityNormal() {
220 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
223 soneUskCallbacks.put(sone.getId(), uskCallback);
224 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
225 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (RequestClient) client);
226 } catch (MalformedURLException mue1) {
227 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), 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 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
245 } catch (MalformedURLException mue1) {
246 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), 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 USKCallback() {
263 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
264 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
268 public short getPollingPriorityNormal() {
269 return RequestStarter.PREFETCH_PRIORITY_CLASS;
273 public short getPollingPriorityProgress() {
274 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
279 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
280 uriUskCallbacks.put(uri, uskCallback);
281 } catch (MalformedURLException mue1) {
282 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
287 * Unregisters the USK watcher for the given URI.
290 * The URI to unregister the USK watcher for
292 public void unregisterUsk(FreenetURI uri) {
293 USKCallback uskCallback = uriUskCallbacks.remove(uri);
294 if (uskCallback == null) {
295 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
299 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
300 } catch (MalformedURLException mue1) {
301 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
306 * Container for a fetched URI and the {@link FetchResult}.
308 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
310 public static class Fetched {
312 /** The fetched URI. */
313 private final FreenetURI freenetUri;
315 /** The fetch result. */
316 private final FetchResult fetchResult;
319 * Creates a new fetched URI.
322 * The URI that was fetched
326 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
327 this.freenetUri = freenetUri;
328 this.fetchResult = fetchResult;
336 * Returns the fetched URI.
338 * @return The fetched URI
340 public FreenetURI getFreenetUri() {
345 * Returns the fetch result.
347 * @return The fetch result
349 public FetchResult getFetchResult() {
356 * Callback for USK watcher events.
358 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
360 public static interface Callback {
363 * Notifies a listener that a new edition was found for a URI.
366 * The URI that a new edition was found for
369 * @param newKnownGood
370 * Whether the found edition was actually fetched
372 * Whether the found edition is higher than all previously
375 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
380 * Insert token that can cancel a running insert and sends events.
382 * @see ImageInsertAbortedEvent
383 * @see ImageInsertStartedEvent
384 * @see ImageInsertFailedEvent
385 * @see ImageInsertFinishedEvent
386 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
388 public class InsertToken implements ClientPutCallback {
390 /** The image being inserted. */
391 private final Image image;
393 /** The client putter. */
394 private ClientPutter clientPutter;
396 /** The final URI. */
397 private volatile FreenetURI resultingUri;
400 * Creates a new insert token for the given image.
403 * The image being inserted
405 public InsertToken(Image image) {
414 * Sets the client putter that is inserting the image. This will also
415 * signal all registered listeners that the image has started.
417 * @param clientPutter
420 @SuppressWarnings("synthetic-access")
421 public void setClientPutter(ClientPutter clientPutter) {
422 this.clientPutter = clientPutter;
423 eventBus.post(new ImageInsertStartedEvent(image));
431 * Cancels the running insert.
433 @SuppressWarnings("synthetic-access")
434 public void cancel() {
435 clientPutter.cancel(null, node.clientCore.clientContext);
436 eventBus.post(new ImageInsertAbortedEvent(image));
440 // INTERFACE ClientPutCallback
447 public void onMajorProgress(ObjectContainer objectContainer) {
448 /* ignore, we don’t care. */
455 @SuppressWarnings("synthetic-access")
456 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
457 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
458 eventBus.post(new ImageInsertAbortedEvent(image));
460 eventBus.post(new ImageInsertFailedEvent(image, insertException));
468 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
469 /* ignore, we don’t care. */
476 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
477 /* ignore, we don’t care. */
484 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
485 resultingUri = generatedUri;
492 @SuppressWarnings("synthetic-access")
493 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
494 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
499 public class InsertTokenSupplier implements Function<Image, InsertToken> {
502 public InsertToken apply(Image image) {
503 return new InsertToken(image);