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