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