Add interface between freenet interface and Sone downloader.
[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         public void registerUsk(final Sone sone, final SoneUpdater soneUpdater) {
186                 try {
187                         logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, sone.getRequestUri().setMetaString(new String[] { "sone.xml" })));
188                         USKCallback uskCallback = new USKCallback() {
189
190                                 @Override
191                                 @SuppressWarnings("synthetic-access")
192                                 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
193                                         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));
194                                         soneUpdater.updateSone(sone, edition);
195                                 }
196
197                                 @Override
198                                 public short getPollingPriorityProgress() {
199                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
200                                 }
201
202                                 @Override
203                                 public short getPollingPriorityNormal() {
204                                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
205                                 }
206                         };
207                         soneUskCallbacks.put(sone.getId(), uskCallback);
208                         boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
209                         node.clientCore.uskManager.subscribe(USK.create(sone.getRequestUri()), uskCallback, runBackgroundFetch, (RequestClient) client);
210                 } catch (MalformedURLException mue1) {
211                         logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", sone.getRequestUri()), mue1);
212                 }
213         }
214
215         /**
216          * Unsubscribes the request URI of the given Sone.
217          *
218          * @param sone
219          *            The Sone to unregister
220          */
221         public void unregisterUsk(Sone sone) {
222                 USKCallback uskCallback = soneUskCallbacks.remove(sone.getId());
223                 if (uskCallback == null) {
224                         return;
225                 }
226                 try {
227                         logger.log(Level.FINEST, String.format("Unsubscribing from USK for %s…", sone));
228                         node.clientCore.uskManager.unsubscribe(USK.create(sone.getRequestUri()), uskCallback);
229                 } catch (MalformedURLException mue1) {
230                         logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", sone.getRequestUri()), mue1);
231                 }
232         }
233
234         /**
235          * Registers an arbitrary URI and calls the given callback if a new edition
236          * is found.
237          *
238          * @param uri
239          *            The URI to watch
240          * @param callback
241          *            The callback to call
242          */
243         public void registerUsk(FreenetURI uri, final Callback callback) {
244                 USKCallback uskCallback = new USKCallback() {
245
246                         @Override
247                         public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
248                                 callback.editionFound(key.getURI(), edition, newKnownGood, newSlotToo);
249                         }
250
251                         @Override
252                         public short getPollingPriorityNormal() {
253                                 return RequestStarter.PREFETCH_PRIORITY_CLASS;
254                         }
255
256                         @Override
257                         public short getPollingPriorityProgress() {
258                                 return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
259                         }
260
261                 };
262                 try {
263                         node.clientCore.uskManager.subscribe(USK.create(uri), uskCallback, true, (RequestClient) client);
264                         uriUskCallbacks.put(uri, uskCallback);
265                 } catch (MalformedURLException mue1) {
266                         logger.log(Level.WARNING, String.format("Could not subscribe to USK: %s", uri), mue1);
267                 }
268         }
269
270         /**
271          * Unregisters the USK watcher for the given URI.
272          *
273          * @param uri
274          *            The URI to unregister the USK watcher for
275          */
276         public void unregisterUsk(FreenetURI uri) {
277                 USKCallback uskCallback = uriUskCallbacks.remove(uri);
278                 if (uskCallback == null) {
279                         logger.log(Level.INFO, String.format("Could not unregister unknown USK: %s", uri));
280                         return;
281                 }
282                 try {
283                         node.clientCore.uskManager.unsubscribe(USK.create(uri), uskCallback);
284                 } catch (MalformedURLException mue1) {
285                         logger.log(Level.INFO, String.format("Could not unregister invalid USK: %s", uri), mue1);
286                 }
287         }
288
289         /**
290          * Container for a fetched URI and the {@link FetchResult}.
291          *
292          * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
293          */
294         public static class Fetched {
295
296                 /** The fetched URI. */
297                 private final FreenetURI freenetUri;
298
299                 /** The fetch result. */
300                 private final FetchResult fetchResult;
301
302                 /**
303                  * Creates a new fetched URI.
304                  *
305                  * @param freenetUri
306                  *            The URI that was fetched
307                  * @param fetchResult
308                  *            The fetch result
309                  */
310                 public Fetched(FreenetURI freenetUri, FetchResult fetchResult) {
311                         this.freenetUri = freenetUri;
312                         this.fetchResult = fetchResult;
313                 }
314
315                 //
316                 // ACCESSORS
317                 //
318
319                 /**
320                  * Returns the fetched URI.
321                  *
322                  * @return The fetched URI
323                  */
324                 public FreenetURI getFreenetUri() {
325                         return freenetUri;
326                 }
327
328                 /**
329                  * Returns the fetch result.
330                  *
331                  * @return The fetch result
332                  */
333                 public FetchResult getFetchResult() {
334                         return fetchResult;
335                 }
336
337         }
338
339         /**
340          * Callback for USK watcher events.
341          *
342          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
343          */
344         public static interface Callback {
345
346                 /**
347                  * Notifies a listener that a new edition was found for a URI.
348                  *
349                  * @param uri
350                  *            The URI that a new edition was found for
351                  * @param edition
352                  *            The found edition
353                  * @param newKnownGood
354                  *            Whether the found edition was actually fetched
355                  * @param newSlot
356                  *            Whether the found edition is higher than all previously
357                  *            found editions
358                  */
359                 public void editionFound(FreenetURI uri, long edition, boolean newKnownGood, boolean newSlot);
360
361         }
362
363         /**
364          * Insert token that can cancel a running insert and sends events.
365          *
366          * @see ImageInsertAbortedEvent
367          * @see ImageInsertStartedEvent
368          * @see ImageInsertFailedEvent
369          * @see ImageInsertFinishedEvent
370          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
371          */
372         public class InsertToken implements ClientPutCallback {
373
374                 /** The image being inserted. */
375                 private final Image image;
376
377                 /** The client putter. */
378                 private ClientPutter clientPutter;
379
380                 /** The final URI. */
381                 private volatile FreenetURI resultingUri;
382
383                 /**
384                  * Creates a new insert token for the given image.
385                  *
386                  * @param image
387                  *            The image being inserted
388                  */
389                 public InsertToken(Image image) {
390                         this.image = image;
391                 }
392
393                 //
394                 // ACCESSORS
395                 //
396
397                 /**
398                  * Sets the client putter that is inserting the image. This will also
399                  * signal all registered listeners that the image has started.
400                  *
401                  * @param clientPutter
402                  *            The client putter
403                  */
404                 @SuppressWarnings("synthetic-access")
405                 public void setClientPutter(ClientPutter clientPutter) {
406                         this.clientPutter = clientPutter;
407                         eventBus.post(new ImageInsertStartedEvent(image));
408                 }
409
410                 //
411                 // ACTIONS
412                 //
413
414                 /**
415                  * Cancels the running insert.
416                  */
417                 @SuppressWarnings("synthetic-access")
418                 public void cancel() {
419                         clientPutter.cancel(null, node.clientCore.clientContext);
420                         eventBus.post(new ImageInsertAbortedEvent(image));
421                 }
422
423                 //
424                 // INTERFACE ClientPutCallback
425                 //
426
427                 /**
428                  * {@inheritDoc}
429                  */
430                 @Override
431                 public void onMajorProgress(ObjectContainer objectContainer) {
432                         /* ignore, we don’t care. */
433                 }
434
435                 /**
436                  * {@inheritDoc}
437                  */
438                 @Override
439                 @SuppressWarnings("synthetic-access")
440                 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
441                         if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
442                                 eventBus.post(new ImageInsertAbortedEvent(image));
443                         } else {
444                                 eventBus.post(new ImageInsertFailedEvent(image, insertException));
445                         }
446                 }
447
448                 /**
449                  * {@inheritDoc}
450                  */
451                 @Override
452                 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
453                         /* ignore, we don’t care. */
454                 }
455
456                 /**
457                  * {@inheritDoc}
458                  */
459                 @Override
460                 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
461                         /* ignore, we don’t care. */
462                 }
463
464                 /**
465                  * {@inheritDoc}
466                  */
467                 @Override
468                 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
469                         resultingUri = generatedUri;
470                 }
471
472                 /**
473                  * {@inheritDoc}
474                  */
475                 @Override
476                 @SuppressWarnings("synthetic-access")
477                 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
478                         eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
479                 }
480
481         }
482
483         public class InsertTokenSupplier implements Function<Image, InsertToken> {
484
485                 @Override
486                 public InsertToken apply(Image image) {
487                         return new InsertToken(image);
488                 }
489
490         }
491
492 }