episode.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. 'use strict';
  2. import cheerio = require('cheerio');
  3. import fs = require('fs');
  4. import mkdirp = require('mkdirp');
  5. import my_request = require('./my_request');
  6. import path = require('path');
  7. import subtitle from './subtitle/index';
  8. import video from './video/index';
  9. import xml2js = require('xml2js');
  10. import log = require('./log');
  11. /**
  12. * Streams the episode to disk.
  13. */
  14. export default function(config: IConfig, address: string, done: (err: Error, ign: boolean) => void)
  15. {
  16. scrapePage(config, address, (err, page) =>
  17. {
  18. if (err)
  19. {
  20. return done(err, false);
  21. }
  22. scrapePlayer(config, address, page.id, (errS, player) =>
  23. {
  24. if (errS)
  25. {
  26. return done(errS, false);
  27. }
  28. download(config, page, player, done);
  29. });
  30. });
  31. }
  32. /**
  33. * Completes a download and writes the message with an elapsed time.
  34. */
  35. function complete(epName: string, message: string, begin: number, done: (err: Error, ign: boolean) => void)
  36. {
  37. const timeInMs = Date.now() - begin;
  38. const seconds = prefix(Math.floor(timeInMs / 1000) % 60, 2);
  39. const minutes = prefix(Math.floor(timeInMs / 1000 / 60) % 60, 2);
  40. const hours = prefix(Math.floor(timeInMs / 1000 / 60 / 60), 2);
  41. log.dispEpisode(epName, message + ' (' + hours + ':' + minutes + ':' + seconds + ')', true);
  42. done(null, false);
  43. }
  44. /**
  45. * Check if a file exist..
  46. */
  47. function fileExist(path: string)
  48. {
  49. try
  50. {
  51. fs.statSync(path);
  52. return true;
  53. } catch (e)
  54. {
  55. return false;
  56. }
  57. }
  58. function sanitiseFileName(str: string)
  59. {
  60. return str.replace(/[\/':\?\*"<>\.]/g, '_');
  61. }
  62. /**
  63. * Downloads the subtitle and video.
  64. */
  65. function download(config: IConfig, page: IEpisodePage, player: IEpisodePlayer, done: (err: Error, ign: boolean) => void)
  66. {
  67. let series = config.series || page.series;
  68. series = sanitiseFileName(series);
  69. let fileName = sanitiseFileName(name(config, page, series, ''));
  70. let filePath = path.join(config.output || process.cwd(), series, fileName);
  71. if (fileExist(filePath + '.mkv'))
  72. {
  73. let count = 0;
  74. log.warn('File \'' + fileName + '\' already exist...');
  75. do
  76. {
  77. count = count + 1;
  78. fileName = sanitiseFileName(name(config, page, series, '-' + count));
  79. filePath = path.join(config.output || process.cwd(), series, fileName);
  80. } while (fileExist(filePath + '.mkv'));
  81. log.warn('Renaming to \'' + fileName + '\'...');
  82. }
  83. mkdirp(path.dirname(filePath), (errM: Error) =>
  84. {
  85. if (errM)
  86. {
  87. return done(errM, false);
  88. }
  89. log.dispEpisode(fileName, 'Fetching...', false);
  90. downloadSubtitle(config, player, filePath, (errDS) =>
  91. {
  92. if (errDS)
  93. {
  94. return done(errDS, false);
  95. }
  96. const now = Date.now();
  97. if (player.video.file !== undefined)
  98. {
  99. log.dispEpisode(fileName, 'Fetching video...', false);
  100. downloadVideo(config, page, player, filePath, (errDV) =>
  101. {
  102. if (errDV)
  103. {
  104. return done(errDV, false);
  105. }
  106. if (config.merge)
  107. {
  108. return complete(fileName, 'Finished!', now, done);
  109. }
  110. const isSubtited = Boolean(player.subtitle);
  111. log.dispEpisode(fileName, 'Merging...', false);
  112. video.merge(config, isSubtited, player.video.file, filePath, player.video.mode, (errVM) =>
  113. {
  114. if (errVM)
  115. {
  116. return done(errVM, false);
  117. }
  118. complete(fileName, 'Finished!', now, done);
  119. });
  120. });
  121. }
  122. else
  123. {
  124. log.dispEpisode(fileName, 'Ignoring: not released yet', true);
  125. done(null, true);
  126. }
  127. });
  128. });
  129. }
  130. /**
  131. * Saves the subtitles to disk.
  132. */
  133. function downloadSubtitle(config: IConfig, player: IEpisodePlayer, filePath: string, done: (err?: Error) => void)
  134. {
  135. const enc = player.subtitle;
  136. if (!enc)
  137. {
  138. return done();
  139. }
  140. subtitle.decode(enc.id, enc.iv, enc.data, (errSD, data) =>
  141. {
  142. if (errSD)
  143. {
  144. return done(errSD);
  145. }
  146. const formats = subtitle.formats;
  147. const format = formats[config.format] ? config.format : 'ass';
  148. formats[format](data, (errF: Error, decodedSubtitle: string) =>
  149. {
  150. if (errF)
  151. {
  152. return done(errF);
  153. }
  154. fs.writeFile(filePath + '.' + format, '\ufeff' + decodedSubtitle, done);
  155. });
  156. });
  157. }
  158. /**
  159. * Streams the video to disk.
  160. */
  161. function downloadVideo(ignored/*config*/: IConfig, page: IEpisodePage, player: IEpisodePlayer,
  162. filePath: string, done: (err: Error) => void)
  163. {
  164. video.stream(player.video.host, player.video.file, page.swf, filePath,
  165. path.extname(player.video.file), player.video.mode, done);
  166. }
  167. /**
  168. * Names the file based on the config, page, series and tag.
  169. */
  170. function name(config: IConfig, page: IEpisodePage, series: string, extra: string)
  171. {
  172. const episodeNum = parseInt(page.episode, 10);
  173. const volumeNum = parseInt(page.volume, 10);
  174. const episode = (episodeNum < 10 ? '0' : '') + page.episode;
  175. const volume = (volumeNum < 10 ? '0' : '') + page.volume;
  176. const tag = config.tag || 'CrunchyRoll';
  177. if (!config.filename) {
  178. return page.series + ' - s' + volume + 'e' + episode + ' - [' + tag + ']' + extra;
  179. }
  180. return config.filename
  181. .replace(/{EPISODE_ID}/g, page.id.toString())
  182. .replace(/{EPISODE_NUMBER}/g, episode)
  183. .replace(/{SEASON_NUMBER}/g, volume)
  184. .replace(/{VOLUME_NUMBER}/g, volume)
  185. .replace(/{SEASON_TITLE}/g, page.season)
  186. .replace(/{VOLUME_TITLE}/g, page.season)
  187. .replace(/{SERIES_TITLE}/g, series)
  188. .replace(/{EPISODE_TITLE}/g, page.title)
  189. .replace(/{TAG}/g, tag) + extra;
  190. }
  191. /**
  192. * Prefixes a value.
  193. */
  194. function prefix(value: number|string, length: number)
  195. {
  196. let valueString = (typeof value !== 'string') ? String(value) : value;
  197. while (valueString.length < length)
  198. {
  199. valueString = '0' + valueString;
  200. }
  201. return valueString;
  202. }
  203. /**
  204. * Requests the page data and scrapes the id, episode, series and swf.
  205. */
  206. function scrapePage(config: IConfig, address: string, done: (err: Error, page?: IEpisodePage) => void)
  207. {
  208. const epId = parseInt((address.match(/[0-9]+$/) || ['0'])[0], 10);
  209. if (!epId)
  210. {
  211. return done(new Error('Invalid address.'));
  212. }
  213. my_request.get(config, address, (err, result) =>
  214. {
  215. if (err)
  216. {
  217. return done(err);
  218. }
  219. const $ = cheerio.load(result);
  220. const swf = /^([^?]+)/.exec($('link[rel=video_src]').attr('href'));
  221. const regexp = /\s*([^\n\r\t\f]+)\n?\s*[^0-9]*([0-9][\-0-9.]*)?,?\n?\s\s*[^0-9]*((PV )?[S0-9][P0-9.]*[a-fA-F]?)/;
  222. const look = $('#showmedia_about_media').text();
  223. const seasonTitle = $('span[itemprop="title"]').text();
  224. let episodeTitle = $('#showmedia_about_name').text().replace(/[“”]/g, '');
  225. const data = regexp.exec(look);
  226. if (!swf || !data)
  227. {
  228. log.warn('Somethig unexpected in the page at ' + address + ' (data are: ' + look + ')');
  229. log.warn('Setting Season to ’0’ and episode to ’0’...');
  230. done(null, {
  231. episode: '0',
  232. id: epId,
  233. series: seasonTitle,
  234. season: seasonTitle,
  235. title: episodeTitle,
  236. swf: swf[1],
  237. volume: '0',
  238. });
  239. }
  240. else
  241. {
  242. done(null, {
  243. episode: data[3],
  244. id: epId,
  245. series: data[1],
  246. season: seasonTitle,
  247. title: episodeTitle,
  248. swf: swf[1],
  249. volume: data[2] || '1',
  250. });
  251. }
  252. });
  253. }
  254. /**
  255. * Requests the player data and scrapes the subtitle and video data.
  256. */
  257. function scrapePlayer(config: IConfig, address: string, id: number, done: (err: Error, player?: IEpisodePlayer) => void)
  258. {
  259. const url = address.match(/^(https?:\/\/[^\/]+)/);
  260. if (!url)
  261. {
  262. return done(new Error('Invalid address.'));
  263. }
  264. my_request.post(config, {
  265. form: {current_page: address},
  266. url: url[1] + '/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=' + id,
  267. }, (err, result) =>
  268. {
  269. if (err)
  270. {
  271. return done(err);
  272. }
  273. xml2js.parseString(result, {
  274. explicitArray: false,
  275. explicitRoot: false,
  276. }, (errPS: Error, player: IEpisodePlayerConfig) =>
  277. {
  278. if (errPS)
  279. {
  280. return done(errPS);
  281. }
  282. try
  283. {
  284. const isSubtitled = Boolean(player['default:preload'].subtitle);
  285. let streamMode = 'RTMP';
  286. if (player['default:preload'].stream_info.host === '')
  287. {
  288. streamMode = 'HLS';
  289. }
  290. done(null, {
  291. subtitle: isSubtitled ? {
  292. data: player['default:preload'].subtitle.data,
  293. id: parseInt(player['default:preload'].subtitle.$.id, 10),
  294. iv: player['default:preload'].subtitle.iv,
  295. } : null,
  296. video: {
  297. file: player['default:preload'].stream_info.file,
  298. host: player['default:preload'].stream_info.host,
  299. mode: streamMode,
  300. },
  301. });
  302. } catch (parseError)
  303. {
  304. done(parseError);
  305. }
  306. });
  307. });
  308. }