Move USK callback to inner class.
[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 net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
21
22 import java.net.MalformedURLException;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.concurrent.TimeUnit;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
31 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
32 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
33 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
34 import net.pterodactylus.sone.data.Image;
35 import net.pterodactylus.sone.data.Sone;
36 import net.pterodactylus.sone.data.TemporaryImage;
37 import net.pterodactylus.util.logging.Logging;
38
39 import com.db4o.ObjectContainer;
40 import com.google.common.annotations.VisibleForTesting;
41 import com.google.common.eventbus.EventBus;
42 import com.google.inject.Inject;
43 import freenet.client.ClientMetadata;
44 import freenet.client.FetchException;
45 import freenet.client.FetchResult;
46 import freenet.client.HighLevelSimpleClient;
47 import freenet.client.HighLevelSimpleClientImpl;
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.client.async.USKManager;
57 import freenet.keys.FreenetURI;
58 import freenet.keys.InsertableClientSSK;
59 import freenet.keys.USK;
60 import freenet.node.Node;
61 import freenet.node.RequestClient;
62 import freenet.node.RequestStarter;
63 import freenet.support.api.Bucket;
64 import freenet.support.io.ArrayBucket;
65
66 /**
67  * Contains all necessary functionality for interacting with the Freenet node.
68  *
69  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
70  */
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         private final RequestClient requestClient;
85
86         /** The USK callbacks. */
87         private final Map<String, USKCallback> soneUskCallbacks = new HashMap<String, USKCallback>();
88
89         /** The not-Sone-related USK callbacks. */
90         private final Map<FreenetURI, USKCallback> uriUskCallbacks = Collections.synchronizedMap(new HashMap<FreenetURI, USKCallback>());
91         private USKManager uskManager;
92
93         /**
94          * Creates a new Freenet interface.
95          *
96          * @param eventBus
97          *            The event bus
98          * @param node
99          *            The node to interact with
100          */
101         @Inject
102         public FreenetInterface(EventBus eventBus, Node node) {
103                 this.eventBus = eventBus;
104                 this.node = node;
105                 this.client = node.clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS, false, true);
106                 this.requestClient = (HighLevelSimpleClientImpl) client;
107                 this.uskManager = node.clientCore.uskManager;
108         }
109
110         @VisibleForTesting
111         public FreenetInterface(EventBus eventBus, Node node, HighLevelSimpleClient highLevelSimpleClient, RequestClient requestClient, USKManager uskManager) {
112                 this.eventBus = eventBus;
113                 this.node = node;
114                 this.client = highLevelSimpleClient;
115                 this.requestClient = requestClient;
116                 this.uskManager = uskManager;
117         }
118
119         //
120         // ACTIONS
121         //
122
123         /**
124          * Fetches the given URI.
125          *
126          * @param uri
127          *            The URI to fetch
128          * @return The result of the fetch, or {@code null} if an error occured
129          */
130         public Fetched fetchUri(FreenetURI uri) {
131                 FetchResult fetchResult = null;
132                 FreenetURI currentUri = new FreenetURI(uri);
133                 while (true) {
134                         try {
135                                 fetchResult = client.fetch(currentUri);
136                                 return new Fetched(currentUri, fetchResult);
137                         } catch (FetchException fe1) {
138                                 if (fe1.getMode() == FetchException.PERMANENT_REDIRECT) {
139                                         currentUri = fe1.newURI;
140                                         continue;
141                                 }
142                                 logger.log(Level.WARNING, String.format("Could not fetch “%s”!", uri), fe1);
143                                 return null;
144                         }
145                 }
146         }
147
148         /**
149          * Creates a key pair.
150          *
151          * @return The request key at index 0, the insert key at index 1
152          */
153         public String[] generateKeyPair() {
154                 FreenetURI[] keyPair = client.generateKeyPair("");
155                 return new String[] { keyPair[1].toString(), keyPair[0].toString() };
156         }
157
158         /**
159          * Inserts the image data of the given {@link TemporaryImage} and returns
160          * the given insert token that can be used to add listeners or cancel the
161          * insert.
162          *
163          * @param temporaryImage
164          *            The temporary image data
165          * @param image
166          *            The image
167          * @param insertToken
168          *            The insert token
169          * @throws SoneException
170          *             if the insert could not be started
171          */
172         public void insertImage(TemporaryImage temporaryImage, Image image, InsertToken insertToken) throws SoneException {
173                 String filenameHint = image.getId() + "." + temporaryImage.getMimeType().substring(temporaryImage.getMimeType().lastIndexOf("/") + 1);
174                 InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, "");
175                 FreenetURI targetUri = key.getInsertURI().setDocName(filenameHint);
176                 InsertContext insertContext = client.getInsertContext(true);
177                 Bucket bucket = new ArrayBucket(temporaryImage.getImageData());
178                 ClientMetadata metadata = new ClientMetadata(temporaryImage.getMimeType());
179                 InsertBlock insertBlock = new InsertBlock(bucket, metadata, targetUri);
180                 try {
181                         ClientPutter clientPutter = client.insert(insertBlock, false, null, false, insertContext, insertToken, RequestStarter.INTERACTIVE_PRIORITY_CLASS);
182                         insertToken.setClientPutter(clientPutter);
183                 } catch (InsertException ie1) {
184                         throw new SoneInsertException("Could not start image insert.", ie1);
185                 }
186         }
187
188         /**
189          * Inserts a directory into Freenet.
190          *
191          * @param insertUri
192          *            The insert URI
193          * @param manifestEntries
194          *            The directory entries
195          * @param defaultFile
196          *            The name of the default file
197          * @return The generated URI
198          * @throws SoneException
199          *             if an insert error occurs
200          */
201         public FreenetURI insertDirectory(FreenetURI insertUri, HashMap<String, Object> manifestEntries, String defaultFile) throws SoneException {
202                 try {
203                         return client.insertManifest(insertUri, manifestEntries, defaultFile);
204                 } catch (InsertException ie1) {
205                         throw new SoneException(ie1);
206                 }
207         }
208
209         /**
210          * Registers the USK for the given Sone and notifies the given
211          * {@link SoneDownloader} if an update was found.
212          *
213          * @param sone
214          *            The Sone to watch
215          * @param soneDownloader
216          *            The Sone download to notify on updates
217          */
218         public void registerUsk(final Sone sone, final SoneDownloader soneDownloader) {
219                 try {
220                         logger.log(Level.FINE, String.format("Registering Sone “%s” for USK updates at %s…", sone, TO_FREENET_URI.apply(sone).setMetaString(new String[]{"sone.xml"})));
221                         USKCallback uskCallback = new NewEditionFound(sone, soneDownloader);
222                         soneUskCallbacks.put(sone.getId(), uskCallback);
223                         boolean runBackgroundFetch = (System.currentTimeMillis() - sone.getTime()) < TimeUnit.DAYS.toMillis(7);
224                         uskManager.subscribe(USK.create(TO_FREENET_URI.apply(sone)), uskCallback, runBackgroundFetch, requestClient);
225                 } catch (MalformedURLException mue1) {
226                         logger.log(Level.WARNING, String.format("Could not subscribe USK “%s”!", TO_FREENET_URI.apply(sone)), 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                         uskManager.unsubscribe(USK.create(TO_FREENET_URI.apply(sone)), uskCallback);
244                 } catch (MalformedURLException mue1) {
245                         logger.log(Level.FINE, String.format("Could not unsubscribe USK “%s”!", TO_FREENET_URI.apply(sone)), 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, ObjectContainer objectContainer, 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                         uskManager.subscribe(USK.create(uri), uskCallback, true, requestClient);
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                         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         private static class NewEditionFound implements USKCallback {
379
380                 private final Sone sone;
381                 private final SoneDownloader soneDownloader;
382
383                 public NewEditionFound(Sone sone, SoneDownloader soneDownloader) {
384                         this.sone = sone;
385                         this.soneDownloader = soneDownloader;
386                 }
387
388                 @Override
389                 @SuppressWarnings("synthetic-access")
390                 public void onFoundEdition(long edition, USK key, ObjectContainer objectContainer, ClientContext clientContext, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) {
391                         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));
392                         if (edition > sone.getLatestEdition()) {
393                                 sone.modify().setLatestEdition(edition).update();
394                                 new Thread(new Runnable() {
395
396                                         @Override
397                                         public void run() {
398                                                 soneDownloader.fetchSone(sone);
399                                         }
400                                 }, "Sone Downloader").start();
401                         }
402                 }
403
404                 @Override
405                 public short getPollingPriorityProgress() {
406                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
407                 }
408
409                 @Override
410                 public short getPollingPriorityNormal() {
411                         return RequestStarter.INTERACTIVE_PRIORITY_CLASS;
412                 }
413         }
414
415         /**
416          * Insert token that can cancel a running insert and sends events.
417          *
418          * @see ImageInsertAbortedEvent
419          * @see ImageInsertStartedEvent
420          * @see ImageInsertFailedEvent
421          * @see ImageInsertFinishedEvent
422          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
423          */
424         public class InsertToken implements ClientPutCallback {
425
426                 /** The image being inserted. */
427                 private final Image image;
428
429                 /** The client putter. */
430                 private ClientPutter clientPutter;
431
432                 /** The final URI. */
433                 private volatile FreenetURI resultingUri;
434
435                 /**
436                  * Creates a new insert token for the given image.
437                  *
438                  * @param image
439                  *            The image being inserted
440                  */
441                 public InsertToken(Image image) {
442                         this.image = image;
443                 }
444
445                 //
446                 // ACCESSORS
447                 //
448
449                 /**
450                  * Sets the client putter that is inserting the image. This will also
451                  * signal all registered listeners that the image has started.
452                  *
453                  * @param clientPutter
454                  *            The client putter
455                  */
456                 @SuppressWarnings("synthetic-access")
457                 public void setClientPutter(ClientPutter clientPutter) {
458                         this.clientPutter = clientPutter;
459                         eventBus.post(new ImageInsertStartedEvent(image));
460                 }
461
462                 //
463                 // ACTIONS
464                 //
465
466                 /**
467                  * Cancels the running insert.
468                  */
469                 @SuppressWarnings("synthetic-access")
470                 public void cancel() {
471                         clientPutter.cancel(null, node.clientCore.clientContext);
472                         eventBus.post(new ImageInsertAbortedEvent(image));
473                 }
474
475                 //
476                 // INTERFACE ClientPutCallback
477                 //
478
479                 @Override
480                 public void onMajorProgress(ObjectContainer objectContainer) {
481                         /* ignore, we don’t care. */
482                 }
483
484                 @Override
485                 @SuppressWarnings("synthetic-access")
486                 public void onFailure(InsertException insertException, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
487                         if ((insertException != null) && ("Cancelled by user".equals(insertException.getMessage()))) {
488                                 eventBus.post(new ImageInsertAbortedEvent(image));
489                         } else {
490                                 eventBus.post(new ImageInsertFailedEvent(image, insertException));
491                         }
492                 }
493
494                 @Override
495                 public void onFetchable(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
496                         /* ignore, we don’t care. */
497                 }
498
499                 @Override
500                 public void onGeneratedMetadata(Bucket metadata, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
501                         /* ignore, we don’t care. */
502                 }
503
504                 @Override
505                 public void onGeneratedURI(FreenetURI generatedUri, BaseClientPutter clientPutter, ObjectContainer objectContainer) {
506                         resultingUri = generatedUri;
507                 }
508
509                 @Override
510                 @SuppressWarnings("synthetic-access")
511                 public void onSuccess(BaseClientPutter clientPutter, ObjectContainer objectContainer) {
512                         eventBus.post(new ImageInsertFinishedEvent(image, resultingUri));
513                 }
514
515         }
516
517 }