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