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