nock.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var path = require('path');
  2. var url = require('url');
  3. var nock = require('nock');
  4. var YT_HOST = 'https://www.youtube.com';
  5. var VIDEO_PATH = '/watch?v=';
  6. var MANIFEST_HOST = 'https://manifest.googlevideo.com';
  7. var EMBED_PATH = '/embed/';
  8. var INFO_PATH = '/get_video_info?';
  9. module.exports = function(id, opts) {
  10. opts = opts || {};
  11. var scopes = [];
  12. scopes.push(nock(YT_HOST)
  13. .get(VIDEO_PATH + id)
  14. .replyWithFile(200,
  15. path.resolve(__dirname, 'files/' + id + '/watch.html')));
  16. if (opts.dashmpd) {
  17. scopes.push(nock(MANIFEST_HOST)
  18. .filteringPath(function() { return '/api/manifest/dash/'; })
  19. .get('/api/manifest/dash/')
  20. .replyWithFile(200,
  21. path.resolve(__dirname, 'files/' + id + '/dashmpd.xml')));
  22. }
  23. if (opts.player) {
  24. scopes.push(nock('http://s.ytimg.com')
  25. .get('/yts/jsbin/html5player-' + opts.player +
  26. (opts.player.indexOf('new-') > -1 ? '/html5player-new.js' : '.js'))
  27. .replyWithFile(200,
  28. path.resolve(__dirname, 'files/html5player/' + opts.player + '.js')));
  29. }
  30. if (opts.embed) {
  31. scopes.push(nock(YT_HOST)
  32. .get(EMBED_PATH + id)
  33. .replyWithFile(200,
  34. path.resolve(__dirname, 'files/' + id + '/embed.html')));
  35. }
  36. if (opts.get_video_info) {
  37. scopes.push(nock(YT_HOST)
  38. .filteringPath(function(path) {
  39. var regexp = /\?video_id=([a-zA-Z0-9_-]+)&(.+)$/;
  40. return path.replace(regexp, function(_, r) {
  41. return '?video_id=' + r;
  42. });
  43. })
  44. .get(INFO_PATH + 'video_id=' + id)
  45. .replyWithFile(200,
  46. path.resolve(__dirname, 'files/' + id + '/get_video_info')));
  47. }
  48. return {
  49. done: function() {
  50. scopes.forEach(function(scope) {
  51. scope.done();
  52. });
  53. }
  54. };
  55. };
  56. module.exports.url = function(uri) {
  57. var parsed = url.parse(uri);
  58. return nock(parsed.protocol + '//' + parsed.host)
  59. .get(parsed.path);
  60. };