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.logging.Level;
25 import java.util.logging.Logger;
27 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
28 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
29 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
30 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
31 import net.pterodactylus.sone.data.Image;
32 import net.pterodactylus.sone.data.Sone;
33 import net.pterodactylus.sone.data.TemporaryImage;
34 import net.pterodactylus.util.logging.Logging;
36 import com.db4o.ObjectContainer;
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.FetchResult;
43 import freenet.client.HighLevelSimpleClient;
44 import freenet.client.HighLevelSimpleClientImpl;
45 import freenet.client.InsertBlock;
46 import freenet.client.InsertContext;
47 import freenet.client.InsertException;
48 import freenet.client.async.BaseClientPutter;
49 import freenet.client.async.ClientContext;
50 import freenet.client.async.ClientPutCallback;
51 import freenet.client.async.ClientPutter;
52 import freenet.client.async.USKCallback;
53 import freenet.keys.FreenetURI;
54 import freenet.keys.InsertableClientSSK;
55 import freenet.keys.USK;
56 import freenet.node.Node;
57 import freenet.node.RequestStarter;
58 import freenet.support.api.Bucket;
59 import freenet.support.io.ArrayBucket;
62 * Contains all necessary functionality for interacting with the Freenet node.
64 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
66 public class FreenetInterface {
69 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
72 private final EventBus eventBus;
74 /** The node to interact with. */
75 private final Node node;
77 /** The high-level client to use for requests. */
78 private final HighLevelSimpleClient client;
80 /** The USK callbacks. */
81 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
83 /** The not-Sone-related USK callbacks. */
84 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
87 * Creates a new Freenet interface.
92 * The node to interact with
95 public FreenetInterface(EventBus eventBus, Node node) {
96 this.eventBus = eventBus;
98 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
106 * Fetches the given URI.
110 * @return The result of the fetch, or {@code null} if an error occured
112 public Fetched fetchUri(FreenetURI uri) {
113 FetchResult fetchResult = null;
114 FreenetURI currentUri = new FreenetURI(uri);
117 fetchResult = client.fetch(currentUri);
118 return new Fetched(currentUri, fetchResult);
119 } catch (FetchException fe1) {
120 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
121 currentUri = fe1.newURI;
124 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
131 * Creates a key pair.
133 * @return The request key at index 0, the insert key at index 1
135 public String[] generateKeyPair() {
136 FreenetURI[] keyPair = client.generateKeyPair("");
137 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
141 * Inserts the image data of the given {@link TemporaryImage} and returns
142 * the given insert token that can be used to add listeners or cancel the
145 * @param temporaryImage
146 * The temporary image data
151 * @throws SoneException
152 * if the insert could not be started
154 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
155 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
156 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
157 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
158 InsertContext insertContext = client.getInsertContext(true);
159 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
160 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
161 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
163 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
164 insertToken.setClientPutter(clientPutter);
165 } catch (InsertException ie1) {
166 throw new SoneInsertException("Could not start image insert.", ie1);
171 * Inserts a directory into Freenet.
175 * @param manifestEntries
176 * The directory entries
178 * The name of the default file
179 * @return The generated URI
180 * @throws SoneException
181 * if an insert error occurs
183 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
185 return client.insertManifest(insertUri, manifestEntries, defaultFile);
186 } catch (InsertException ie1) {
187 throw new SoneException(ie1);
192 * Registers the USK for the given Sone and notifies the given
193 * {@link SoneDownloader} if an update was found.
197 * @param soneDownloader
198 * The Sone download to notify on updates
200 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
202 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
203 USKCallback uskCallback = new USKCallback() {
206 @SuppressWarnings("synthetic-access")
207 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
208 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));
209 if (edition > sone.getLatestEdition()) {
210 sone.setLatestEdition(edition);
211 new Thread(new Runnable() {
215 soneDownloader.fetchSone(sone);
217 }, "Sone Downloader").start();
222 public short getPollingPriorityProgress() {
223 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
227 public short getPollingPriorityNormal() {
228 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
231 soneUskCallbacks.put(sone.getId(), uskCallback);
232 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, (System.currentTimeMillis() - sone.getTime()) < 7 * 24 * 60 * 60 * 1000, (HighLevelSimpleClientImpl) client);
233 } catch (MalformedURLException mue1) {
234 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
239 * Unsubscribes the request URI of the given Sone.
242 * The Sone to unregister
244 public void unregisterUsk(Sone sone) {
245 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
246 if (uskCallback == null) {
250 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
251 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
252 } catch (MalformedURLException mue1) {
253 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
258 * Registers an arbitrary URI and calls the given callback if a new edition
264 * The callback to call
266 public void registerUsk(FreenetURI uri, final Callback callback) {
267 USKCallback uskCallback = new USKCallback() {
270 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
271 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
275 public short getPollingPriorityNormal() {
276 return RequestStarter.PREFETCH_PRIORITY_CLASS;
280 public short getPollingPriorityProgress() {
281 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
286 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
287 uriUskCallbacks.put(uri, uskCallback);
288 } catch (MalformedURLException mue1) {
289 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
294 * Unregisters the USK watcher for the given URI.
297 * The URI to unregister the USK watcher for
299 public void unregisterUsk(FreenetURI uri) {
300 USKCallback uskCallback = uriUskCallbacks.remove(uri);
301 if (uskCallback == null) {
302 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
306 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
307 } catch (MalformedURLException mue1) {
308 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
313 * Container for a fetched URI and the {@link FetchResult}.
315 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
317 public static class Fetched {
319 /** The fetched URI. */
320 private final FreenetURI freenetUri;
322 /** The fetch result. */
323 private final FetchResult fetchResult;
326 * Creates a new fetched URI.
329 * The URI that was fetched
333 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
334 this.freenetUri = freenetUri;
335 this.fetchResult = fetchResult;
343 * Returns the fetched URI.
345 * @return The fetched URI
347 public FreenetURI getFreenetUri() {
352 * Returns the fetch result.
354 * @return The fetch result
356 public FetchResult getFetchResult() {
363 * Callback for USK watcher events.
365 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
367 public static interface Callback {
370 * Notifies a listener that a new edition was found for a URI.
373 * The URI that a new edition was found for
376 * @param newKnownGood
377 * Whether the found edition was actually fetched
379 * Whether the found edition is higher than all previously
382 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
387 * Insert token that can cancel a running insert and sends events.
389 * @see ImageInsertAbortedEvent
390 * @see ImageInsertStartedEvent
391 * @see ImageInsertFailedEvent
392 * @see ImageInsertFinishedEvent
393 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
395 public class InsertToken implements ClientPutCallback {
397 /** The image being inserted. */
398 private final Image image;
400 /** The client putter. */
401 private ClientPutter clientPutter;
403 /** The final URI. */
404 private volatile FreenetURI resultingUri;
407 * Creates a new insert token for the given image.
410 * The image being inserted
412 public InsertToken(Image image) {
421 * Sets the client putter that is inserting the image. This will also
422 * signal all registered listeners that the image has started.
424 * @param clientPutter
427 @SuppressWarnings("synthetic-access")
428 public void setClientPutter(ClientPutter clientPutter) {
429 this.clientPutter = clientPutter;
430 eventBus.post(new ImageInsertStartedEvent(image));
438 * Cancels the running insert.
440 @SuppressWarnings("synthetic-access")
441 public void cancel() {
442 clientPutter.cancel(null, node.clientCore.clientContext);
443 eventBus.post(new ImageInsertAbortedEvent(image));
447 // INTERFACE ClientPutCallback
454 public void onMajorProgress(ObjectContainer objectContainer) {
455 /* ignore, we don’t care. */
462 @SuppressWarnings("synthetic-access")
463 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
464 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
465 eventBus.post(new ImageInsertAbortedEvent(image));
467 eventBus.post(new ImageInsertFailedEvent(image, insertException));
475 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
476 /* ignore, we don’t care. */
483 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
484 /* ignore, we don’t care. */
491 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
492 resultingUri = generatedUri;
499 @SuppressWarnings("synthetic-access")
500 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
501 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));