episode.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. 'use strict';
  2. export = main;
  3. import cheerio = require('cheerio');
  4. import fs = require('fs');
  5. import mkdirp = require('mkdirp');
  6. import request = require('./request');
  7. import path = require('path');
  8. import subtitle = require('./subtitle/index');
  9. import typings = require('./typings');
  10. import video = require('./video/index');
  11. import xml2js = require('xml2js');
  12. /**
  13. * Streams the episode to disk.
  14. */
  15. function main(config: typings.IConfig, address: string, done: (err: Error) => void) {
  16. scrapePage(config, address, (err, page) => {
  17. if (err) return done(err);
  18. scrapePlayer(config, address, page.id, (err, player) => {
  19. if (err) return done(err);
  20. download(config, page, player, done);
  21. });
  22. });
  23. }
  24. /**
  25. * Completes a download and writes the message with an elapsed time.
  26. */
  27. function complete(message: string, begin: number, done: (err: Error) => void) {
  28. var timeInMs = Date.now() - begin;
  29. var seconds = prefix(Math.floor(timeInMs / 1000) % 60, 2);
  30. var minutes = prefix(Math.floor(timeInMs / 1000 / 60) % 60, 2);
  31. var hours = prefix(Math.floor(timeInMs / 1000 / 60 / 60), 2);
  32. console.log(message + ' (' + hours + ':' + minutes + ':' + seconds + ')');
  33. done(null);
  34. }
  35. /**
  36. * Downloads the subtitle and video.
  37. */
  38. function download(config: typings.IConfig, page: typings.IEpisodePage, player: typings.IEpisodePlayer, done: (err: Error) => void) {
  39. var series = config.series || page.series;
  40. var fileName = name(config, page, series);
  41. var filePath = path.join(config.output || process.cwd(), series, fileName);
  42. mkdirp(path.dirname(filePath), (err: Error) => {
  43. if (err) return done(err);
  44. downloadSubtitle(config, player, filePath, err => {
  45. if (err) return done(err);
  46. var now = Date.now();
  47. console.log('Fetching ' + fileName);
  48. downloadVideo(config, page, player, filePath, err => {
  49. if (err) return done(err);
  50. if (config.merge) return complete('Finished ' + fileName, now, done);
  51. video.merge(config, player.video.file, filePath, err => {
  52. if (err) return done(err);
  53. complete('Finished ' + fileName, now, done);
  54. });
  55. });
  56. });
  57. });
  58. }
  59. /**
  60. * Saves the subtitles to disk.
  61. */
  62. function downloadSubtitle(config: typings.IConfig, player: typings.IEpisodePlayer, filePath: string, done: (err: Error) => void) {
  63. var enc = player.subtitle;
  64. subtitle.decode(enc.id, enc.iv, enc.data, (err, data) => {
  65. if (err) return done(err);
  66. var formats = subtitle.formats;
  67. var format = formats[config.format] ? config.format : 'ass';
  68. formats[format](data, (err: Error, decodedSubtitle: string) => {
  69. if (err) return done(err);
  70. fs.writeFile(filePath + '.' + format, '\ufeff' + decodedSubtitle, done);
  71. });
  72. });
  73. }
  74. /**
  75. * Streams the video to disk.
  76. */
  77. function downloadVideo(config: typings.IConfig, page: typings.IEpisodePage, player: typings.IEpisodePlayer, filePath: string, done: (err: Error) => void) {
  78. video.stream(
  79. player.video.host,
  80. player.video.file,
  81. page.swf,
  82. filePath + path.extname(player.video.file),
  83. done);
  84. }
  85. /**
  86. * Names the file based on the config, page, series and tag.
  87. */
  88. function name(config: typings.IConfig, page: typings.IEpisodePage, series: string) {
  89. var episode = (page.episode < 10 ? '0' : '') + page.episode;
  90. var volume = (page.volume < 10 ? '0' : '') + page.volume;
  91. var tag = config.tag || 'CrunchyRoll';
  92. return series + ' ' + volume + 'x' + episode + ' [' + tag + ']';
  93. }
  94. /**
  95. * Prefixes a value.
  96. */
  97. function prefix(value: number|string, length: number) {
  98. var valueString = typeof value !== 'string' ? String(value) : value;
  99. while (valueString.length < length) valueString = '0' + valueString;
  100. return valueString;
  101. }
  102. /**
  103. * Requests the page data and scrapes the id, episode, series and swf.
  104. */
  105. function scrapePage(config: typings.IConfig, address: string, done: (err: Error, page?: typings.IEpisodePage) => void) {
  106. var id = parseInt((address.match(/[0-9]+$/) || ['0'])[0], 10);
  107. if (!id) return done(new Error('Invalid address.'));
  108. request.get(config, address, (err, result) => {
  109. if (err) return done(err);
  110. var $ = cheerio.load(result);
  111. var swf = /^([^?]+)/.exec($('link[rel=video_src]').attr('href'));
  112. var regexp = /Watch\s+(.+?)(?:\s+Season\s+([0-9]+))?\s+Episode\s+([0-9]+)/;
  113. var data = regexp.exec($('title').text());
  114. if (!swf || !data) return done(new Error('Invalid page.'));
  115. done(null, {
  116. id: id,
  117. episode: parseInt(data[3], 10),
  118. series: data[1],
  119. swf: swf[1],
  120. volume: parseInt(data[2], 10) || 1
  121. });
  122. });
  123. }
  124. /**
  125. * Requests the player data and scrapes the subtitle and video data.
  126. */
  127. function scrapePlayer(config: typings.IConfig, address: string, id: number, done: (err: Error, player?: typings.IEpisodePlayer) => void) {
  128. var url = address.match(/^(https?:\/\/[^\/]+)/);
  129. if (!url) return done(new Error('Invalid address.'));
  130. request.post(config, {
  131. form: {current_page: address},
  132. url: url[1] + '/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=' + id
  133. }, (err, result) => {
  134. if (err) return done(err);
  135. xml2js.parseString(result, {
  136. explicitArray: false,
  137. explicitRoot: false
  138. }, (err: Error, player: typings.IEpisodePlayerConfig) => {
  139. if (err) return done(err);
  140. try {
  141. done(null, {
  142. subtitle: {
  143. id: parseInt(player['default:preload'].subtitle.$.id, 10),
  144. iv: player['default:preload'].subtitle.iv,
  145. data: player['default:preload'].subtitle.data
  146. },
  147. video: {
  148. file: player['default:preload'].stream_info.file,
  149. host: player['default:preload'].stream_info.host
  150. }
  151. });
  152. } catch (parseError) {
  153. done(parseError);
  154. }
  155. });
  156. });
  157. }