Cancel request early if it’s not an image
[Sone.git] / src / main / java / net / pterodactylus / sone / core / FreenetInterface.java
1 /*
2  * Sone - FreenetInterface.java - Copyright © 2010–2016 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import static freenet.keys.USK.create;
21 import static java.lang.String.format;
22 import static java.util.logging.Level.WARNING;
23 import static java.util.logging.Logger.getLogger;
24 import static net.pterodactylus.sone.freenet.Key.routingKey;
25
26 import java.io.IOException;
27 import java.net.MalformedURLException;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.Map;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
33
34 import javax.annotation.Nonnull;
35
36 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
37 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
38 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.TemporaryImage;
43
44 import com.google.common.base.Function;
45 import com.google.common.eventbus.EventBus;
46 import com.google.inject.Inject;
47 import com.google.inject.Singleton;
48
49 import freenet.client.ClientMetadata;
50 import freenet.client.FetchContext;
51 import freenet.client.FetchException;
52 import freenet.client.FetchException.FetchExceptionMode;
53 import freenet.client.FetchResult;
54 import freenet.client.HighLevelSimpleClient;
55 import freenet.client.InsertBlock;
56 import freenet.client.InsertContext;
57 import freenet.client.InsertException;
58 import freenet.client.Metadata;
59 import freenet.client.async.BaseClientPutter;
60 import freenet.client.async.ClientContext;
61 import freenet.client.async.ClientGetCallback;
62 import freenet.client.async.ClientGetter;
63 import freenet.client.async.ClientPutCallback;
64 import freenet.client.async.ClientPutter;
65 import freenet.client.async.SnoopMetadata;
66 import freenet.client.async.USKCallback;
67 import freenet.keys.FreenetURI;
68 import freenet.keys.InsertableClientSSK;
69 import freenet.keys.USK;
70 import freenet.node.Node;
71 import freenet.node.RequestClient;
72 import freenet.node.RequestClientBuilder;
73 import freenet.node.RequestStarter;
74 import freenet.support.api.Bucket;
75 import freenet.support.api.RandomAccessBucket;
76 import freenet.support.io.ArrayBucket;
77 import freenet.support.io.ResumeFailedException;
78
79 /**
80  * Contains all necessary functionality for interacting with the Freenet node.
81  *
82  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
83  */
84 @Singleton
85 public class FreenetInterface {
86
87         /** The logger. */
88         private static final Logger logger = getLogger(FreenetInterface.class.getName());
89
90         /** The event bus. */
91         private final EventBus eventBus;
92
93         /** The node to interact with. */
94         private final Node node;
95
96         /** The high-level client to use for requests. */
97         private final HighLevelSimpleClient client;
98
99         /** The USK callbacks. */
100         private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
101
102         /** The not-Sone-related USK callbacks. */
103         private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
104
105         private final RequestClient imageInserts = new RequestClientBuilder().realTime().build();
106         private final RequestClient imageLoader = new RequestClientBuilder().realTime().build();
107
108         /**
109          * Creates a new Freenet interface.
110          *
111          * @param eventBus
112          *            The event bus
113          * @param node
114          *            The node to interact with
115          */
116         @Inject
117         public FreenetInterface(EventBus eventBus, Node node) {
118                 this.eventBus = eventBus;
119                 this.node = node;
120                 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
121         }
122
123         //
124         // ACTIONS
125         //
126
127         /**
128          * Fetches the given URI.
129          *
130          * @param uri
131          *            The URI to fetch
132          * @return The result of the fetch, or {@code null} if an error occured
133          */
134         public Fetched fetchUri(FreenetURI uri) {
135                 FreenetURI currentUri = new FreenetURI(uri);
136                 while (true) {
137                         try {
138                                 FetchResult fetchResult = client.fetch(currentUri);
139                                 return new Fetched(currentUri, fetchResult);
140                         } catch (FetchException fe1) {
141                                 if (fe1.getMode() == FetchExceptionMode.PERMANENT_REDIRECT) {
142                                         currentUri = fe1.newURI;
143                                         continue;
144                                 }
145                                 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
146                                 return null;
147                         }
148                 }
149         }
150
151         public void startFetch(final FreenetURI uri, final BackgroundFetchCallback backgroundFetchCallback) {
152                 ClientGetCallback callback = new ClientGetCallback() {
153                         @Override
154                         public void onSuccess(FetchResult result, ClientGetter state) {
155                                 try {
156                                         backgroundFetchCallback.loaded(uri, result.getMimeType(), result.asByteArray());
157                                 } catch (IOException e) {
158                                         backgroundFetchCallback.failed(uri);
159                                 }
160                         }
161
162                         @Override
163                         public void onFailure(FetchException e, ClientGetter state) {
164                                 backgroundFetchCallback.failed(uri);
165                         }
166
167                         @Override
168                         public void onResume(ClientContext context) throws ResumeFailedException {
169                                 /* do nothing. */
170                         }
171
172                         @Override
173                         public RequestClient getRequestClient() {
174                                 return imageLoader;
175                         }
176                 };
177                 SnoopMetadata snoop = new SnoopMetadata() {
178                         @Override
179                         public boolean snoopMetadata(Metadata meta, ClientContext context) {
180                                 String mimeType = meta.getMIMEType();
181                                 return (mimeType == null) || backgroundFetchCallback.cancelForMimeType(uri, mimeType);
182                         }
183                 };
184                 FetchContext fetchContext = client.getFetchContext();
185                 try {
186                         ClientGetter clientGetter = client.fetch(uri, 1048576, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
187                         clientGetter.setMetaSnoop(snoop);
188                         clientGetter.restart(uri, fetchContext.filterData, node.clientCore.clientContext);
189                 } catch (FetchException fe) {
190                         /* stupid exception that can not actually be thrown! */
191                 }
192         }
193
194         public interface BackgroundFetchCallback {
195                 boolean cancelForMimeType(@Nonnull FreenetURI uri, @Nonnull String mimeType);
196                 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
197                 void failed(@Nonnull FreenetURI uri);
198         }
199
200         /**
201          * Inserts the image data of the given {@link TemporaryImage} and returns
202          * the given insert token that can be used to add listeners or cancel the
203          * insert.
204          *
205          * @param temporaryImage
206          *            The temporary image data
207          * @param image
208          *            The image
209          * @param insertToken
210          *            The insert token
211          * @throws SoneException
212          *             if the insert could not be started
213          */
214         public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
215                 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
216                 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
217                 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
218                 InsertContext insertContext = client.getInsertContext(true);
219                 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
220                 insertToken.setBucket(bucket);
221                 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
222                 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
223                 try {
224                         ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
225                         insertToken.setClientPutter(clientPutter);
226                 } catch (InsertException ie1) {
227                         throw new SoneInsertException("Could not start image insert.", ie1);
228                 }
229         }
230
231         /**
232          * Inserts a directory into Freenet.
233          *
234          * @param insertUri
235          *            The insert URI
236          * @param manifestEntries
237          *            The directory entries
238          * @param defaultFile
239          *            The name of the default file
240          * @return The generated URI
241          * @throws SoneException
242          *             if an insert error occurs
243          */
244         public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
245                 try {
246                         return client.insertManifest(insertUri, manifestEntries, defaultFile);
247                 } catch (InsertException ie1) {
248                         throw new SoneException(ie1);
249                 }
250         }
251
252         public void registerActiveUsk(FreenetURI requestUri,
253                         USKCallback uskCallback) {
254                 try {
255                         soneUskCallbacks.put(routingKey(requestUri), uskCallback);
256                         node.clientCore.uskManager.subscribe(create(requestUri),
257                                         uskCallback, true, (RequestClient) client);
258                 } catch (MalformedURLException mue1) {
259                         logger.log(WARNING, format("Could not subscribe USK “%s”!",
260                                         requestUri), mue1);
261                 }
262         }
263
264         public void registerPassiveUsk(FreenetURI requestUri,
265                         USKCallback uskCallback) {
266                 try {
267                         soneUskCallbacks.put(routingKey(requestUri), uskCallback);
268                         node.clientCore
269                                         .uskManager
270                                         .subscribe(create(requestUri), uskCallback, false,
271                                                         (RequestClient) client);
272                 } catch (MalformedURLException mue1) {
273                         logger.log(WARNING,
274                                         format("Could not subscribe USK “%s”!", requestUri),
275                                         mue1);
276                 }
277         }
278
279         /**
280          * Unsubscribes the request URI of the given Sone.
281          *
282          * @param sone
283          *            The Sone to unregister
284          */
285         public void unregisterUsk(Sone sone) {
286                 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
287                 if (uskCallback == null) {
288                         return;
289                 }
290                 try {
291                         logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
292                         node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
293                 } catch (MalformedURLException mue1) {
294                         logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
295                 }
296         }
297
298         /**
299          * Registers an arbitrary URI and calls the given callback if a new edition
300          * is found.
301          *
302          * @param uri
303          *            The URI to watch
304          * @param callback
305          *            The callback to call
306          */
307         public void registerUsk(FreenetURI uri, final Callback callback) {
308                 USKCallback uskCallback = new USKCallback() {
309
310                         @Override
311                         public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
312                                 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
313                         }
314
315                         @Override
316                         public short getPollingPriorityNormal() {
317                                 return RequestStarter.PREFETCH_PRIORITY_CLASS;
318                         }
319
320                         @Override
321                         public short getPollingPriorityProgress() {
322                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
323                         }
324
325                 };
326                 try {
327                         node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
328                         uriUskCallbacks.put(uri, uskCallback);
329                 } catch (MalformedURLException mue1) {
330                         logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
331                 }
332         }
333
334         /**
335          * Unregisters the USK watcher for the given URI.
336          *
337          * @param uri
338          *            The URI to unregister the USK watcher for
339          */
340         public void unregisterUsk(FreenetURI uri) {
341                 USKCallback uskCallback = uriUskCallbacks.remove(uri);
342                 if (uskCallback == null) {
343                         logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
344                         return;
345                 }
346                 try {
347                         node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
348                 } catch (MalformedURLException mue1) {
349                         logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
350                 }
351         }
352
353         /**
354          * Container for a fetched URI and the {@link FetchResult}.
355          *
356          * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
357          */
358         public static class Fetched {
359
360                 /** The fetched URI. */
361                 private final FreenetURI freenetUri;
362
363                 /** The fetch result. */
364                 private final FetchResult fetchResult;
365
366                 /**
367                  * Creates a new fetched URI.
368                  *
369                  * @param freenetUri
370                  *            The URI that was fetched
371                  * @param fetchResult
372                  *            The fetch result
373                  */
374                 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
375                         this.freenetUri = freenetUri;
376                         this.fetchResult = fetchResult;
377                 }
378
379                 //
380                 // ACCESSORS
381                 //
382
383                 /**
384                  * Returns the fetched URI.
385                  *
386                  * @return The fetched URI
387                  */
388                 public FreenetURI getFreenetUri() {
389                         return freenetUri;
390                 }
391
392                 /**
393                  * Returns the fetch result.
394                  *
395                  * @return The fetch result
396                  */
397                 public FetchResult getFetchResult() {
398                         return fetchResult;
399                 }
400
401         }
402
403         /**
404          * Callback for USK watcher events.
405          *
406          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
407          */
408         public static interface Callback {
409
410                 /**
411                  * Notifies a listener that a new edition was found for a URI.
412                  *
413                  * @param uri
414                  *            The URI that a new edition was found for
415                  * @param edition
416                  *            The found edition
417                  * @param newKnownGood
418                  *            Whether the found edition was actually fetched
419                  * @param newSlot
420                  *            Whether the found edition is higher than all previously
421                  *            found editions
422                  */
423                 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
424
425         }
426
427         /**
428          * Insert token that can cancel a running insert and sends events.
429          *
430          * @see ImageInsertAbortedEvent
431          * @see ImageInsertStartedEvent
432          * @see ImageInsertFailedEvent
433          * @see ImageInsertFinishedEvent
434          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
435          */
436         public class InsertToken implements ClientPutCallback {
437
438                 /** The image being inserted. */
439                 private final Image image;
440
441                 /** The client putter. */
442                 private ClientPutter clientPutter;
443                 private Bucket bucket;
444
445                 /** The final URI. */
446                 private volatile FreenetURI resultingUri;
447
448                 /**
449                  * Creates a new insert token for the given image.
450                  *
451                  * @param image
452                  *            The image being inserted
453                  */
454                 public InsertToken(Image image) {
455                         this.image = image;
456                 }
457
458                 //
459                 // ACCESSORS
460                 //
461
462                 /**
463                  * Sets the client putter that is inserting the image. This will also
464                  * signal all registered listeners that the image has started.
465                  *
466                  * @param clientPutter
467                  *            The client putter
468                  */
469                 @SuppressWarnings("synthetic-access")
470                 public void setClientPutter(ClientPutter clientPutter) {
471                         this.clientPutter = clientPutter;
472                         eventBus.post(new ImageInsertStartedEvent(image));
473                 }
474
475                 public void setBucket(Bucket bucket) {
476                         this.bucket = bucket;
477                 }
478
479                 //
480                 // ACTIONS
481                 //
482
483                 /**
484                  * Cancels the running insert.
485                  */
486                 @SuppressWarnings("synthetic-access")
487                 public void cancel() {
488                         clientPutter.cancel(node.clientCore.clientContext);
489                         eventBus.post(new ImageInsertAbortedEvent(image));
490                         bucket.free();
491                 }
492
493                 //
494                 // INTERFACE ClientPutCallback
495                 //
496
497                 @Override
498                 public RequestClient getRequestClient() {
499                         return imageInserts;
500                 }
501
502                 @Override
503                 public void onResume(ClientContext context) throws ResumeFailedException {
504                         /* ignore. */
505                 }
506
507                 /**
508                  * {@inheritDoc}
509                  */
510                 @Override
511                 @SuppressWarnings("synthetic-access")
512                 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
513                         if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
514                                 eventBus.post(new ImageInsertAbortedEvent(image));
515                         } else {
516                                 eventBus.post(new ImageInsertFailedEvent(image, insertException));
517                         }
518                         bucket.free();
519                 }
520
521                 /**
522                  * {@inheritDoc}
523                  */
524                 @Override
525                 public void onFetchable(BaseClientPutter clientPutter) {
526                         /* ignore, we don’t care. */
527                 }
528
529                 /**
530                  * {@inheritDoc}
531                  */
532                 @Override
533                 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
534                         /* ignore, we don’t care. */
535                 }
536
537                 /**
538                  * {@inheritDoc}
539                  */
540                 @Override
541                 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
542                         resultingUri = generatedUri;
543                 }
544
545                 /**
546                  * {@inheritDoc}
547                  */
548                 @Override
549                 @SuppressWarnings("synthetic-access")
550                 public void onSuccess(BaseClientPutter clientPutter) {
551                         eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
552                         bucket.free();
553                 }
554
555         }
556
557         public class InsertTokenSupplier implements Function<Image, InsertToken> {
558
559                 @Override
560                 public InsertToken apply(Image image) {
561                         return new InsertToken(image);
562                 }
563
564         }
565
566 }