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 static net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
22 import java.net.MalformedURLException;
23 import java.util.Collections;
24 import java.util.HashMap;
26 import java.util.concurrent.TimeUnit;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
30 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
31 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
32 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
33 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
34 import net.pterodactylus.sone.data.Image;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.TemporaryImage;
37 import net.pterodactylus.util.logging.Logging;
39 import com.db4o.ObjectContainer;
40 import com.google.common.annotations.VisibleForTesting;
41 import com.google.common.eventbus.EventBus;
42 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.HighLevelSimpleClientImpl;
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.client.async.USKManager;
57 import freenet.keys.FreenetURI;
58 import freenet.keys.InsertableClientSSK;
59 import freenet.keys.USK;
60 import freenet.node.Node;
61 import freenet.node.RequestClient;
62 import freenet.node.RequestStarter;
63 import freenet.support.api.Bucket;
64 import freenet.support.io.ArrayBucket;
67 * Contains all necessary functionality for interacting with the Freenet node.
69 * @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;
84 private final RequestClient requestClient;
86 /** The USK callbacks. */
87 private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
89 /** The not-Sone-related USK callbacks. */
90 private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
91 private USKManager uskManager;
94 * Creates a new Freenet interface.
99 * The node to interact with
102 public FreenetInterface(EventBus eventBus, Node node) {
103 this.eventBus = eventBus;
105 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
106 this.requestClient = (HighLevelSimpleClientImpl) client;
107 this.uskManager = node.clientCore.uskManager;
111 public FreenetInterface(EventBus eventBus, Node node, HighLevelSimpleClient highLevelSimpleClient, RequestClient requestClient, USKManager uskManager) {
112 this.eventBus = eventBus;
114 this.client = highLevelSimpleClient;
115 this.requestClient = requestClient;
116 this.uskManager = uskManager;
124 * Fetches the given URI.
128 * @return The result of the fetch, or {@code null} if an error occured
130 public Fetched fetchUri(FreenetURI uri) {
131 FetchResult fetchResult = null;
132 FreenetURI currentUri = new FreenetURI(uri);
135 fetchResult = client.fetch(currentUri);
136 return new Fetched(currentUri, fetchResult);
137 } catch (FetchException fe1) {
138 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
139 currentUri = fe1.newURI;
142 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
149 * Creates a key pair.
151 * @return The request key at index 0, the insert key at index 1
153 public String[] generateKeyPair() {
154 FreenetURI[] keyPair = client.generateKeyPair("");
155 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
159 * Inserts the image data of the given {@link TemporaryImage} and returns
160 * the given insert token that can be used to add listeners or cancel the
163 * @param temporaryImage
164 * The temporary image data
169 * @throws SoneException
170 * if the insert could not be started
172 public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
173 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
174 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
175 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
176 InsertContext insertContext = client.getInsertContext(true);
177 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
178 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
179 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
181 ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
182 insertToken.setClientPutter(clientPutter);
183 } catch (InsertException ie1) {
184 throw new SoneInsertException("Could not start image insert.", ie1);
189 * Inserts a directory into Freenet.
193 * @param manifestEntries
194 * The directory entries
196 * The name of the default file
197 * @return The generated URI
198 * @throws SoneException
199 * if an insert error occurs
201 public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
203 return client.insertManifest(insertUri, manifestEntries, defaultFile);
204 } catch (InsertException ie1) {
205 throw new SoneException(ie1);
210 * Registers the USK for the given Sone and notifies the given
211 * {@link SoneDownloader} if an update was found.
215 * @param soneDownloader
216 * The Sone download to notify on updates
218 public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
220 logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, TO_FREENET_URI.apply(sone).setMetaString(new String[]{"sone.xml"})));
221 USKCallback uskCallback = new USKCallback() {
224 @SuppressWarnings("synthetic-access")
225 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
226 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));
227 if (edition > sone.getLatestEdition()) {
228 sone.modify().setLatestEdition(edition).update();
229 new Thread(new Runnable() {
233 soneDownloader.fetchSone(sone);
235 }, "Sone Downloader").start();
240 public short getPollingPriorityProgress() {
241 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
245 public short getPollingPriorityNormal() {
246 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
249 soneUskCallbacks.put(sone.getId(), uskCallback);
250 boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
251 uskManager.subscribe(USK.create(TO_FREENET_URI.apply(sone)), uskCallback, runBackgroundFetch, requestClient);
252 } catch (MalformedURLException mue1) {
253 logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", TO_FREENET_URI.apply(sone)), mue1);
258 * Unsubscribes the request URI of the given Sone.
261 * The Sone to unregister
263 public void unregisterUsk(Sone sone) {
264 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
265 if (uskCallback == null) {
269 logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
270 uskManager.unsubscribe(USK.create(TO_FREENET_URI.apply(sone)), uskCallback);
271 } catch (MalformedURLException mue1) {
272 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", TO_FREENET_URI.apply(sone)), mue1);
277 * Registers an arbitrary URI and calls the given callback if a new edition
283 * The callback to call
285 public void registerUsk(FreenetURI uri, final Callback callback) {
286 USKCallback uskCallback = new USKCallback() {
289 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
290 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
294 public short getPollingPriorityNormal() {
295 return RequestStarter.PREFETCH_PRIORITY_CLASS;
299 public short getPollingPriorityProgress() {
300 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
305 uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
306 uriUskCallbacks.put(uri, uskCallback);
307 } catch (MalformedURLException mue1) {
308 logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
313 * Unregisters the USK watcher for the given URI.
316 * The URI to unregister the USK watcher for
318 public void unregisterUsk(FreenetURI uri) {
319 USKCallback uskCallback = uriUskCallbacks.remove(uri);
320 if (uskCallback == null) {
321 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
325 uskManager.unsubscribe(USK.create(uri), uskCallback);
326 } catch (MalformedURLException mue1) {
327 logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
332 * Container for a fetched URI and the {@link FetchResult}.
334 * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
336 public static class Fetched {
338 /** The fetched URI. */
339 private final FreenetURI freenetUri;
341 /** The fetch result. */
342 private final FetchResult fetchResult;
345 * Creates a new fetched URI.
348 * The URI that was fetched
352 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
353 this.freenetUri = freenetUri;
354 this.fetchResult = fetchResult;
362 * Returns the fetched URI.
364 * @return The fetched URI
366 public FreenetURI getFreenetUri() {
371 * Returns the fetch result.
373 * @return The fetch result
375 public FetchResult getFetchResult() {
382 * Callback for USK watcher events.
384 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
386 public static interface Callback {
389 * Notifies a listener that a new edition was found for a URI.
392 * The URI that a new edition was found for
395 * @param newKnownGood
396 * Whether the found edition was actually fetched
398 * Whether the found edition is higher than all previously
401 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
406 * Insert token that can cancel a running insert and sends events.
408 * @see ImageInsertAbortedEvent
409 * @see ImageInsertStartedEvent
410 * @see ImageInsertFailedEvent
411 * @see ImageInsertFinishedEvent
412 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
414 public class InsertToken implements ClientPutCallback {
416 /** The image being inserted. */
417 private final Image image;
419 /** The client putter. */
420 private ClientPutter clientPutter;
422 /** The final URI. */
423 private volatile FreenetURI resultingUri;
426 * Creates a new insert token for the given image.
429 * The image being inserted
431 public InsertToken(Image image) {
440 * Sets the client putter that is inserting the image. This will also
441 * signal all registered listeners that the image has started.
443 * @param clientPutter
446 @SuppressWarnings("synthetic-access")
447 public void setClientPutter(ClientPutter clientPutter) {
448 this.clientPutter = clientPutter;
449 eventBus.post(new ImageInsertStartedEvent(image));
457 * Cancels the running insert.
459 @SuppressWarnings("synthetic-access")
460 public void cancel() {
461 clientPutter.cancel(null, node.clientCore.clientContext);
462 eventBus.post(new ImageInsertAbortedEvent(image));
466 // INTERFACE ClientPutCallback
470 public void onMajorProgress(ObjectContainer objectContainer) {
471 /* ignore, we don’t care. */
475 @SuppressWarnings("synthetic-access")
476 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
477 if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
478 eventBus.post(new ImageInsertAbortedEvent(image));
480 eventBus.post(new ImageInsertFailedEvent(image, insertException));
485 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
486 /* ignore, we don’t care. */
490 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
491 /* ignore, we don’t care. */
495 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
496 resultingUri = generatedUri;
500 @SuppressWarnings("synthetic-access")
501 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
502 eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));