2 * Sone - FreenetInterface.java - Copyright © 2010–2012 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.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import net.pterodactylus.sone.data.Image;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.data.TemporaryImage;
32 import net.pterodactylus.util.collection.Pair;
33 import net.pterodactylus.util.logging.Logging;
35 import com.db4o.ObjectContainer;
36 import com.google.inject.Inject;
38 import freenet.client.ClientMetadata;
39 import freenet.client.FetchException;
40 import freenet.client.FetchResult;
41 import freenet.client.HighLevelSimpleClient;
42 import freenet.client.HighLevelSimpleClientImpl;
43 import freenet.client.InsertBlock;
44 import freenet.client.InsertContext;
45 import freenet.client.InsertException;
46 import freenet.client.async.BaseClientPutter;
47 import freenet.client.async.ClientContext;
48 import freenet.client.async.ClientPutCallback;
49 import freenet.client.async.ClientPutter;
50 import freenet.client.async.USKCallback;
51 import freenet.keys.FreenetURI;
52 import freenet.keys.InsertableClientSSK;
53 import freenet.keys.USK;
54 import freenet.node.Node;
55 import freenet.node.RequestStarter;
56 import freenet.support.api.Bucket;
57 import freenet.support.io.ArrayBucket;
60 * Contains all necessary functionality for interacting with the Freenet node.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public class FreenetInterface {
67 private static final Logger logger = Logging.getLogger(FreenetInterface.class);
69 /** The node to interact with. */
70 private final Node node;
72 /** The high-level client to use for requests. */
73 private final HighLevelSimpleClient client;
75 /** The USK callbacks. */
76 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
78 /** The not-Sone-related USK callbacks. */
79 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
82 * Creates a new Freenet interface.
85 * The node to interact with
88 public FreenetInterface(Node node) {
90 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
98 * Fetches the given URI.
102 * @return The result of the fetch, or {@code null} if an error occured
104 public Pair<FreenetURI, FetchResult> fetchUri(FreenetURI uri) {
105 FetchResult fetchResult = null;
106 FreenetURI currentUri = new FreenetURI(uri);
109 fetchResult = client.fetch(currentUri);
110 return new Pair<FreenetURI, FetchResult>(currentUri, fetchResult);
111 } catch (FetchException fe1) {
112 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
113 currentUri = fe1.newURI;
116 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
123 * Creates a key pair.
125 * @return The request key at index 0, the insert key at index 1
127 public String[] generateKeyPair() {
128 FreenetURI[] keyPair = client.generateKeyPair("");
129 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
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 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, (System.currentTimeMillis() - sone.getTime()) < 7 * 24 * 60 * 60 * 1000, (HighLevelSimpleClientImpl) client);
225 } catch (MalformedURLException mue1) {
226 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
231 * Unsubscribes the request URI of the given Sone.
234 * The Sone to unregister
236 public void unregisterUsk(Sone sone) {
237 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
238 if (uskCallback == null) {
242 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
243 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
244 } catch (MalformedURLException mue1) {
245 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
250 * Registers an arbitrary URI and calls the given callback if a new edition
256 * The callback to call
258 public void registerUsk(FreenetURI uri, final Callback callback) {
259 USKCallback uskCallback = new USKCallback() {
262 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
263 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
267 public short getPollingPriorityNormal() {
268 return RequestStarter.PREFETCH_PRIORITY_CLASS;
272 public short getPollingPriorityProgress() {
273 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
278 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
279 uriUskCallbacks.put(uri, uskCallback);
280 } catch (MalformedURLException mue1) {
281 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
286 * Unregisters the USK watcher for the given URI.
289 * The URI to unregister the USK watcher for
291 public void unregisterUsk(FreenetURI uri) {
292 USKCallback uskCallback = uriUskCallbacks.remove(uri);
293 if (uskCallback == null) {
294 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
298 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
299 } catch (MalformedURLException mue1) {
300 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
305 * Callback for USK watcher events.
307 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
309 public static interface Callback {
312 * Notifies a listener that a new edition was found for a URI.
315 * The URI that a new edition was found for
318 * @param newKnownGood
319 * Whether the found edition was actually fetched
321 * Whether the found edition is higher than all previously
324 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
329 * Insert token that can be used to add {@link ImageInsertListener}s and
330 * cancel a running insert.
332 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
334 public class InsertToken implements ClientPutCallback {
336 /** The image being inserted. */
337 private final Image image;
339 /** The list of registered image insert listeners. */
340 private final List<ImageInsertListener> imageInsertListeners = Collections.synchronizedList(new ArrayList<ImageInsertListener>());
342 /** The client putter. */
343 private ClientPutter clientPutter;
345 /** The final URI. */
346 private volatile FreenetURI resultingUri;
349 * Creates a new insert token for the given image.
352 * The image being inserted
354 public InsertToken(Image image) {
359 // LISTENER MANAGEMENT
363 * Adds the given listener to the list of registered listener.
365 * @param imageInsertListener
366 * The listener to add
368 public void addImageInsertListener(ImageInsertListener imageInsertListener) {
369 imageInsertListeners.add(imageInsertListener);
373 * Removes the given listener from the list of registered listener.
375 * @param imageInsertListener
376 * The listener to remove
378 public void removeImageInsertListener(ImageInsertListener imageInsertListener) {
379 imageInsertListeners.remove(imageInsertListener);
387 * Sets the client putter that is inserting the image. This will also
388 * signal all registered listeners that the image has started.
390 * @see ImageInsertListener#imageInsertStarted(Image)
391 * @param clientPutter
394 public void setClientPutter(ClientPutter clientPutter) {
395 this.clientPutter = clientPutter;
396 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
397 imageInsertListener.imageInsertStarted(image);
406 * Cancels the running insert.
408 * @see ImageInsertListener#imageInsertAborted(Image)
410 @SuppressWarnings("synthetic-access")
411 public void cancel() {
412 clientPutter.cancel(null, node.clientCore.clientContext);
413 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
414 imageInsertListener.imageInsertAborted(image);
419 // INTERFACE ClientPutCallback
426 public void onMajorProgress(ObjectContainer objectContainer) {
427 /* ignore, we don’t care. */
434 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
435 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
436 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
437 imageInsertListener.imageInsertAborted(image);
439 imageInsertListener.imageInsertFailed(image, insertException);
448 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
449 /* ignore, we don’t care. */
456 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
457 /* ignore, we don’t care. */
464 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
465 resultingUri = generatedUri;
472 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
473 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
474 imageInsertListener.imageInsertFinished(image, resultingUri);