066747daf49918a724d3ad2853350d50f1a1675d
[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                 fetchContext.dontEnterImplicitArchives = false;
192                 try {
193                         ClientGetter clientGetter = client.fetch(uri, 2097152, callback, fetchContext, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
194                         clientGetter.setMetaSnoop(snoop);
195                         clientGetter.restart(uri, fetchContext.filterData, clientContext);
196                 } catch (FetchException fe) {
197                         /* stupid exception that can not actually be thrown! */
198                 }
199         }
200
201         public interface BackgroundFetchCallback {
202                 boolean shouldCancel(@Nonnull FreenetURI uri, @Nonnull String mimeType, long size);
203                 void loaded(@Nonnull FreenetURI uri, @Nonnull String mimeType, @Nonnull byte[] data);
204                 void failed(@Nonnull FreenetURI uri);
205         }
206
207         /**
208          * Inserts the image data of the given {@link TemporaryImage} and returns
209          * the given insert token that can be used to add listeners or cancel the
210          * insert.
211          *
212          * @param temporaryImage
213          *            The temporary image data
214          * @param image
215          *            The image
216          * @param insertToken
217          *            The insert token
218          * @throws SoneException
219          *             if the insert could not be started
220          */
221         public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
222                 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
223                 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
224                 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
225                 InsertContext insertContext = client.getInsertContext(true);
226                 RandomAccessBucket bucket = new ArrayBucket(temporaryImage.getImageData());
227                 insertToken.setBucket(bucket);
228                 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
229                 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
230                 try {
231                         ClientPutter clientPutter = client.insert(insertBlock, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
232                         insertToken.setClientPutter(clientPutter);
233                 } catch (InsertException ie1) {
234                         throw new SoneInsertException("Could not start image insert.", ie1);
235                 }
236         }
237
238         /**
239          * Inserts a directory into Freenet.
240          *
241          * @param insertUri
242          *            The insert URI
243          * @param manifestEntries
244          *            The directory entries
245          * @param defaultFile
246          *            The name of the default file
247          * @return The generated URI
248          * @throws SoneException
249          *             if an insert error occurs
250          */
251         public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
252                 try {
253                         return client.insertManifest(insertUri, manifestEntries, defaultFile);
254                 } catch (InsertException ie1) {
255                         throw new SoneException(ie1);
256                 }
257         }
258
259         public void registerActiveUsk(FreenetURI requestUri,
260                         USKCallback uskCallback) {
261                 try {
262                         soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
263                         uskManager.subscribe(create(requestUri),
264                                         uskCallback, true, requestClient);
265                 } catch (MalformedURLException mue1) {
266                         logger.log(WARNING, format("Could not subscribe USK “%s”!",
267                                         requestUri), mue1);
268                 }
269         }
270
271         public void registerPassiveUsk(FreenetURI requestUri,
272                         USKCallback uskCallback) {
273                 try {
274                         soneUskCallbacks.put(FreenetURIsKt.getRoutingKeyString(requestUri), uskCallback);
275                         uskManager.subscribe(create(requestUri), uskCallback, false, requestClient);
276                 } catch (MalformedURLException mue1) {
277                         logger.log(WARNING,
278                                         format("Could not subscribe USK “%s”!", requestUri),
279                                         mue1);
280                 }
281         }
282
283         /**
284          * Unsubscribes the request URI of the given Sone.
285          *
286          * @param sone
287          *            The Sone to unregister
288          */
289         public void unregisterUsk(Sone sone) {
290                 Collection<USKCallback> uskCallbacks = soneUskCallbacks.removeAll(sone.getId());
291                 if (uskCallbacks.isEmpty()) {
292                         return;
293                 }
294                 logger.log(Level.FINE, String.format("Unsubscribing %d from USK for %s…", uskCallbacks.size(), sone));
295                 logger.log(Level.FINEST, String.format("USKs left: %d", soneUskCallbacks.size()));
296                 uskCallbacks.forEach(uskCallback -> {
297                         try {
298                                 uskManager.unsubscribe(USK.create(soneUriCreator.getRequestUri(sone)), uskCallback);
299                         } catch (MalformedURLException mue1) {
300                                 logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", soneUriCreator.getRequestUri(sone)), mue1);
301                         }
302                 });
303         }
304
305         /**
306          * Registers an arbitrary URI and calls the given callback if a new edition
307          * is found.
308          *
309          * @param uri
310          *            The URI to watch
311          * @param callback
312          *            The callback to call
313          */
314         public void registerUsk(FreenetURI uri, final Callback callback) {
315                 USKCallback uskCallback = new USKCallback() {
316
317                         @Override
318                         public void onFoundEdition(long edition, USK key, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
319                                 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
320                         }
321
322                         @Override
323                         public short getPollingPriorityNormal() {
324                                 return RequestStarter.PREFETCH_PRIORITY_CLASS;
325                         }
326
327                         @Override
328                         public short getPollingPriorityProgress() {
329                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
330                         }
331
332                 };
333                 try {
334                         uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
335                         uriUskCallbacks.put(USK.create(uri).clearCopy().getURI(), uskCallback);
336                 } catch (MalformedURLException mue1) {
337                         logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
338                 }
339         }
340
341         /**
342          * Unregisters the USK watcher for the given URI.
343          *
344          * @param uri
345          *            The URI to unregister the USK watcher for
346          */
347         public void unregisterUsk(FreenetURI uri) {
348                 try {
349                         USKCallback uskCallback = uriUskCallbacks.remove(USK.create(uri).clearCopy().getURI());
350                         if (uskCallback == null) {
351                                 logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
352                                 return;
353                         }
354                         uskManager.unsubscribe(USK.create(uri), uskCallback);
355                 } catch (MalformedURLException mue1) {
356                         logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
357                 }
358         }
359
360         /**
361          * Callback for USK watcher events.
362          */
363         public static interface Callback {
364
365                 /**
366                  * Notifies a listener that a new edition was found for a URI.
367                  *
368                  * @param uri
369                  *            The URI that a new edition was found for
370                  * @param edition
371                  *            The found edition
372                  * @param newKnownGood
373                  *            Whether the found edition was actually fetched
374                  * @param newSlot
375                  *            Whether the found edition is higher than all previously
376                  *            found editions
377                  */
378                 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
379
380         }
381
382         /**
383          * Insert token that can cancel a running insert and sends events.
384          *
385          * @see ImageInsertAbortedEvent
386          * @see ImageInsertStartedEvent
387          * @see ImageInsertFailedEvent
388          * @see ImageInsertFinishedEvent
389          */
390         public class InsertToken implements ClientPutCallback {
391
392                 /** The image being inserted. */
393                 private final Image image;
394
395                 /** The client putter. */
396                 private ClientPutter clientPutter;
397                 private Bucket bucket;
398
399                 /** The final URI. */
400                 private volatile FreenetURI resultingUri;
401
402                 /**
403                  * Creates a new insert token for the given image.
404                  *
405                  * @param image
406                  *            The image being inserted
407                  */
408                 public InsertToken(Image image) {
409                         this.image = image;
410                 }
411
412                 //
413                 // ACCESSORS
414                 //
415
416                 /**
417                  * Sets the client putter that is inserting the image. This will also
418                  * signal all registered listeners that the image has started.
419                  *
420                  * @param clientPutter
421                  *            The client putter
422                  */
423                 @SuppressWarnings("synthetic-access")
424                 public void setClientPutter(ClientPutter clientPutter) {
425                         this.clientPutter = clientPutter;
426                         eventBus.post(new ImageInsertStartedEvent(image));
427                 }
428
429                 public void setBucket(Bucket bucket) {
430                         this.bucket = bucket;
431                 }
432
433                 //
434                 // ACTIONS
435                 //
436
437                 /**
438                  * Cancels the running insert.
439                  */
440                 @SuppressWarnings("synthetic-access")
441                 public void cancel() {
442                         clientPutter.cancel(clientContext);
443                         eventBus.post(new ImageInsertAbortedEvent(image));
444                         bucket.free();
445                 }
446
447                 //
448                 // INTERFACE ClientPutCallback
449                 //
450
451                 @Override
452                 public RequestClient getRequestClient() {
453                         return imageInserts;
454                 }
455
456                 @Override
457                 public void onResume(ClientContext context) throws ResumeFailedException {
458                         /* ignore. */
459                 }
460
461                 /**
462                  * {@inheritDoc}
463                  */
464                 @Override
465                 @SuppressWarnings("synthetic-access")
466                 public void onFailure(InsertException insertException, BaseClientPutter clientPutter) {
467                         if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
468                                 eventBus.post(new ImageInsertAbortedEvent(image));
469                         } else {
470                                 eventBus.post(new ImageInsertFailedEvent(image, insertException));
471                         }
472                         bucket.free();
473                 }
474
475                 /**
476                  * {@inheritDoc}
477                  */
478                 @Override
479                 public void onFetchable(BaseClientPutter clientPutter) {
480                         /* ignore, we don’t care. */
481                 }
482
483                 /**
484                  * {@inheritDoc}
485                  */
486                 @Override
487                 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter) {
488                         /* ignore, we don’t care. */
489                 }
490
491                 /**
492                  * {@inheritDoc}
493                  */
494                 @Override
495                 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter) {
496                         resultingUri = generatedUri;
497                 }
498
499                 /**
500                  * {@inheritDoc}
501                  */
502                 @Override
503                 @SuppressWarnings("synthetic-access")
504                 public void onSuccess(BaseClientPutter clientPutter) {
505                         eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
506                         bucket.free();
507                 }
508
509         }
510
511         public static class InsertTokenSupplier implements Function<Image, InsertToken> {
512
513                 private final FreenetInterface freenetInterface;
514
515                 @Inject
516                 public InsertTokenSupplier(FreenetInterface freenetInterface) {
517                         this.freenetInterface = freenetInterface;
518                 }
519
520                 @Override
521                 public InsertToken apply(Image image) {
522                         return freenetInterface.new InsertToken(image);
523                 }
524
525         }
526
527 }