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