2 * Sone - FreenetInterface.java - Copyright © 2010 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.core.SoneException.Type;
30 import net.pterodactylus.sone.data.Image;
31 import net.pterodactylus.sone.data.Sone;
32 import net.pterodactylus.sone.data.TemporaryImage;
33 import net.pterodactylus.util.collection.Pair;
34 import net.pterodactylus.util.logging.Logging;
36 import com.db4o.ObjectContainer;
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
87 public FreenetInterface(Node node) {
89 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
97 * Fetches the given URI.
101 * @return The result of the fetch, or {@code null} if an error occured
103 public Pair<FreenetURI, FetchResult> fetchUri(FreenetURI uri) {
104 FetchResult fetchResult = null;
105 FreenetURI currentUri = new FreenetURI(uri);
108 fetchResult = client.fetch(currentUri);
109 return new Pair<FreenetURI, FetchResult>(currentUri, fetchResult);
110 } catch (FetchException fe1) {
111 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
112 currentUri = fe1.newURI;
115 logger.log(Level.WARNING, "Could not fetch “" + uri + "”!", fe1);
122 * Creates a key pair.
124 * @return The request key at index 0, the insert key at index 1
126 public String[] generateKeyPair() {
127 FreenetURI[] keyPair = client.generateKeyPair("");
128 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
132 * Inserts the image data of the given {@link TemporaryImage} and returns
133 * the given insert token that can be used to add listeners or cancel the
136 * @param temporaryImage
137 * The temporary image data
142 * @throws SoneException
143 * if the insert could not be started
145 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
146 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
147 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
148 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
149 InsertContext insertContext = client.getInsertContext(true);
150 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
151 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
152 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
154 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
155 insertToken.setClientPutter(clientPutter);
156 } catch (InsertException ie1) {
157 throw new SoneException(Type.INSERT_FAILED, "Could not start image insert.", ie1);
162 * Inserts a directory into Freenet.
166 * @param manifestEntries
167 * The directory entries
169 * The name of the default file
170 * @return The generated URI
171 * @throws SoneException
172 * if an insert error occurs
174 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
176 return client.insertManifest(insertUri, manifestEntries, defaultFile);
177 } catch (InsertException ie1) {
178 throw new SoneException(null, ie1);
183 * Registers the USK for the given Sone and notifies the given
184 * {@link SoneDownloader} if an update was found.
188 * @param soneDownloader
189 * The Sone download to notify on updates
191 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
193 logger.log(Level.FINE, "Registering Sone “%s” for USK updates at %s…", new Object[] { sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" }) });
194 USKCallback uskCallback = new USKCallback() {
197 @SuppressWarnings("synthetic-access")
198 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
199 logger.log(Level.FINE, "Found USK update for Sone “%s” at %s, new known good: %s, new slot too: %s.", new Object[] { sone, key, newKnownGood, newSlotToo });
200 if (edition > sone.getLatestEdition()) {
201 sone.setLatestEdition(edition);
202 new Thread(new Runnable() {
206 soneDownloader.fetchSone(sone);
208 }, "Sone Downloader").start();
213 public short getPollingPriorityProgress() {
214 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
218 public short getPollingPriorityNormal() {
219 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
222 soneUskCallbacks.put(sone.getId(), uskCallback);
223 node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, (System.currentTimeMillis() - sone.getTime()) < 7 * 24 * 60 * 60 * 1000, (HighLevelSimpleClientImpl) client);
224 } catch (MalformedURLException mue1) {
225 logger.log(Level.WARNING, "Could not subscribe USK “" + sone.getRequestUri() + "”!", mue1);
230 * Unsubscribes the request URI of the given Sone.
233 * The Sone to unregister
235 public void unregisterUsk(Sone sone) {
236 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
237 if (uskCallback == null) {
241 logger.log(Level.FINEST, "Unsubscribing from USK for %s…", new Object[] { sone });
242 node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
243 } catch (MalformedURLException mue1) {
244 logger.log(Level.FINE, "Could not unsubscribe USK “" + sone.getRequestUri() + "”!", mue1);
249 * Registers an arbitrary URI and calls the given callback if a new edition
255 * The callback to call
257 public void registerUsk(FreenetURI uri, final Callback callback) {
258 USKCallback uskCallback = new USKCallback() {
261 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
262 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
266 public short getPollingPriorityNormal() {
267 return RequestStarter.PREFETCH_PRIORITY_CLASS;
271 public short getPollingPriorityProgress() {
272 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
277 node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (HighLevelSimpleClientImpl) client);
278 uriUskCallbacks.put(uri, uskCallback);
279 } catch (MalformedURLException mue1) {
280 logger.log(Level.WARNING, "Could not subscribe to USK: " + uri, uri);
285 * Unregisters the USK watcher for the given URI.
288 * The URI to unregister the USK watcher for
290 public void unregisterUsk(FreenetURI uri) {
291 USKCallback uskCallback = uriUskCallbacks.remove(uri);
292 if (uskCallback == null) {
293 logger.log(Level.INFO, "Could not unregister unknown USK: " + uri);
297 node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
298 } catch (MalformedURLException mue1) {
299 logger.log(Level.INFO, "Could not unregister invalid USK: " + uri);
304 * Callback for USK watcher events.
306 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
308 public static interface Callback {
311 * Notifies a listener that a new edition was found for a URI.
314 * The URI that a new edition was found for
317 * @param newKnownGood
318 * Whether the found edition was actually fetched
320 * Whether the found edition is higher than all previously
323 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
328 * Insert token that can be used to add {@link ImageInsertListener}s and
329 * cancel a running insert.
331 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
333 public class InsertToken implements ClientPutCallback {
335 /** The image being inserted. */
336 private final Image image;
338 /** The list of registered image insert listeners. */
339 private final List<ImageInsertListener> imageInsertListeners = Collections.synchronizedList(new ArrayList<ImageInsertListener>());
341 /** The client putter. */
342 private ClientPutter clientPutter;
344 /** The final URI. */
345 private volatile FreenetURI resultingUri;
348 * Creates a new insert token for the given image.
351 * The image being inserted
353 public InsertToken(Image image) {
358 // LISTENER MANAGEMENT
362 * Adds the given listener to the list of registered listener.
364 * @param imageInsertListener
365 * The listener to add
367 public void addImageInsertListener(ImageInsertListener imageInsertListener) {
368 imageInsertListeners.add(imageInsertListener);
372 * Removes the given listener from the list of registered listener.
374 * @param imageInsertListener
375 * The listener to remove
377 public void removeImageInsertListener(ImageInsertListener imageInsertListener) {
378 imageInsertListeners.remove(imageInsertListener);
386 * Sets the client putter that is inserting the image. This will also
387 * signal all registered listeners that the image has started.
389 * @see ImageInsertListener#imageInsertStarted(Image)
390 * @param clientPutter
393 public void setClientPutter(ClientPutter clientPutter) {
394 this.clientPutter = clientPutter;
395 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
396 imageInsertListener.imageInsertStarted(image);
405 * Cancels the running insert.
407 * @see ImageInsertListener#imageInsertAborted(Image)
409 @SuppressWarnings("synthetic-access")
410 public void cancel() {
411 clientPutter.cancel(null, node.clientCore.clientContext);
412 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
413 imageInsertListener.imageInsertAborted(image);
418 // INTERFACE ClientPutCallback
425 public void onMajorProgress(ObjectContainer objectContainer) {
426 /* ignore, we don’t care. */
433 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
434 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
435 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
436 imageInsertListener.imageInsertAborted(image);
438 imageInsertListener.imageInsertFailed(image, insertException);
447 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
448 /* ignore, we don’t care. */
455 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
456 resultingUri = generatedUri;
463 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
464 for (ImageInsertListener imageInsertListener : imageInsertListeners) {
465 imageInsertListener.imageInsertFinished(image, resultingUri);