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