episode.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. }
  54. catch (e)
  55. {
  56. return false;
  57. }
  58. }
  59. function sanitiseFileName(str: string)
  60. {
  61. return str.replace(/[\/':\?\*"<>\\\.\|]/g, '_');
  62. }
  63. /**
  64. * Downloads the subtitle and video.
  65. */
  66. function download(config: IConfig, page: IEpisodePage, player: IEpisodePlayer, done: (err: Error | string, ign: boolean) => void)
  67. {
  68. const serieFolder = sanitiseFileName(config.series || page.series);
  69. let fileName = sanitiseFileName(generateName(config, page));
  70. let filePath = path.join(config.output || process.cwd(), serieFolder, fileName);
  71. if (fileExist(filePath + '.mkv'))
  72. {
  73. let count = 0;
  74. if (config.rebuildcrp)
  75. {
  76. log.warn('Adding \'' + fileName + '\' to the DB...');
  77. return done(null, false);
  78. }
  79. log.warn('File \'' + fileName + '\' already exist...');
  80. do
  81. {
  82. count = count + 1;
  83. fileName = sanitiseFileName(generateName(config, page, '-' + count));
  84. filePath = path.join(config.output || process.cwd(), serieFolder, fileName);
  85. } while (fileExist(filePath + '.mkv'));
  86. log.warn('Renaming to \'' + fileName + '\'...');
  87. page.filename = fileName;
  88. }
  89. if (config.rebuildcrp)
  90. {
  91. log.warn('Ignoring \'' + fileName + '\' as it does not exist...');
  92. return done(null, true);
  93. }
  94. const ret = mkdirp(path.dirname(filePath));
  95. if (ret)
  96. {
  97. log.dispEpisode(fileName, 'Fetching...', false);
  98. downloadSubtitle(config, player, filePath, (errDS) =>
  99. {
  100. if (errDS)
  101. {
  102. log.dispEpisode(fileName, 'Error...', true);
  103. return done(errDS, false);
  104. }
  105. const now = Date.now();
  106. if (player.video.file !== undefined)
  107. {
  108. log.dispEpisode(fileName, 'Fetching video...', false);
  109. downloadVideo(config, page, player, filePath, (errDV) =>
  110. {
  111. if (errDV)
  112. {
  113. log.dispEpisode(fileName, 'Error...', true);
  114. return done(errDV, false);
  115. }
  116. if (config.merge)
  117. {
  118. return complete(fileName, 'Finished!', now, done);
  119. }
  120. const isSubtited = Boolean(player.subtitle);
  121. log.dispEpisode(fileName, 'Merging...', false);
  122. video.merge(config, isSubtited, player.video.file, filePath, player.video.mode, config.verbose, (errVM) =>
  123. {
  124. if (errVM)
  125. {
  126. log.dispEpisode(fileName, 'Error...', true);
  127. return done(errVM, false);
  128. }
  129. complete(fileName, 'Finished!', now, done);
  130. });
  131. });
  132. }
  133. else
  134. {
  135. log.dispEpisode(fileName, 'Ignoring: not released yet', true);
  136. done(null, true);
  137. }
  138. });
  139. }
  140. else
  141. {
  142. log.dispEpisode(fileName, 'Error creating folder \'" + filePath + "\'...', true);
  143. return done('Cannot create folder', false);
  144. }
  145. }
  146. /**
  147. * Saves the subtitles to disk.
  148. */
  149. function downloadSubtitle(config: IConfig, player: IEpisodePlayer, filePath: string, done: (err?: Error | string) => void)
  150. {
  151. const enc = player.subtitle;
  152. if (!enc)
  153. {
  154. return done();
  155. }
  156. subtitle.decode(enc.id, enc.iv, enc.data, (errSD, data) =>
  157. {
  158. if (errSD)
  159. {
  160. return done(errSD);
  161. }
  162. if (config.debug)
  163. {
  164. log.dumpToDebug('SubtitlesXML', data);
  165. }
  166. const formats = subtitle.formats;
  167. const format = formats[config.format] ? config.format : 'ass';
  168. formats[format](config, data, (errF: Error, decodedSubtitle: string) =>
  169. {
  170. if (errF)
  171. {
  172. return done(errF);
  173. }
  174. fs.writeFile(filePath + '.' + format, '\ufeff' + decodedSubtitle, done);
  175. });
  176. });
  177. }
  178. /**
  179. * Streams the video to disk.
  180. */
  181. function downloadVideo(config: IConfig, page: IEpisodePage, player: IEpisodePlayer,
  182. filePath: string, done: (err: Error) => void)
  183. {
  184. video.stream(player.video.host, player.video.file, page.swf, filePath,
  185. path.extname(player.video.file), player.video.mode, config.verbose, done);
  186. }
  187. /**
  188. * Names the file based on the config, page, series and tag.
  189. */
  190. function generateName(config: IConfig, page: IEpisodePage, extra = '')
  191. {
  192. const episodeNum = parseInt(page.episode, 10);
  193. const volumeNum = parseInt(page.volume, 10);
  194. const episode = (episodeNum < 10 ? '0' : '') + page.episode;
  195. const volume = (volumeNum < 10 ? '0' : '') + page.volume;
  196. const tag = config.tag || 'CrunchyRoll';
  197. const series = config.series || page.series;
  198. return config.nametmpl
  199. .replace(/{EPISODE_ID}/g, page.id.toString())
  200. .replace(/{EPISODE_NUMBER}/g, episode)
  201. .replace(/{SEASON_NUMBER}/g, volume)
  202. .replace(/{VOLUME_NUMBER}/g, volume)
  203. .replace(/{SEASON_TITLE}/g, page.season)
  204. .replace(/{VOLUME_TITLE}/g, page.season)
  205. .replace(/{SERIES_TITLE}/g, series)
  206. .replace(/{EPISODE_TITLE}/g, page.title)
  207. .replace(/{TAG}/g, tag) + extra;
  208. }
  209. /**
  210. * Prefixes a value.
  211. */
  212. function prefix(value: number|string, length: number)
  213. {
  214. let valueString = (typeof value !== 'string') ? String(value) : value;
  215. while (valueString.length < length)
  216. {
  217. valueString = '0' + valueString;
  218. }
  219. return valueString;
  220. }
  221. /**
  222. * Requests the page data and scrapes the id, episode, series and swf.
  223. */
  224. function scrapePage(config: IConfig, address: string, done: (err: Error, page?: IEpisodePage) => void)
  225. {
  226. const epId = parseInt((address.match(/[0-9]+$/) || ['0'])[0], 10);
  227. if (!epId)
  228. {
  229. return done(new Error('Invalid address.'));
  230. }
  231. my_request.get(config, address, (err, result) =>
  232. {
  233. if (err)
  234. {
  235. return done(err);
  236. }
  237. const $ = cheerio.load(result);
  238. const swf = /^([^?]+)/.exec($('link[rel=video_src]').attr('href'));
  239. 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]?)/;
  240. const look = $('#showmedia_about_media').text();
  241. const seasonTitle = $('span[itemprop="title"]').text();
  242. const episodeTitle = $('#showmedia_about_name').text().replace(/[“”]/g, '');
  243. const data = regexp.exec(look);
  244. if (config.debug)
  245. {
  246. log.dumpToDebug('episode page', $.html());
  247. }
  248. if (!swf || !data)
  249. {
  250. log.warn('Somethig unexpected in the page at ' + address + ' (data are: ' + look + ')');
  251. log.warn('Setting Season to ’0’ and episode to ’0’...');
  252. if (config.debug)
  253. {
  254. log.dumpToDebug('episode unexpected', look);
  255. }
  256. done(null, {
  257. episode: '0',
  258. id: epId,
  259. series: seasonTitle,
  260. season: seasonTitle,
  261. title: episodeTitle,
  262. swf: swf[1],
  263. volume: '0',
  264. filename: '',
  265. });
  266. }
  267. else
  268. {
  269. done(null, {
  270. episode: data[3],
  271. id: epId,
  272. series: data[1],
  273. season: seasonTitle,
  274. title: episodeTitle,
  275. swf: swf[1],
  276. volume: data[2] || '1',
  277. filename: '',
  278. });
  279. }
  280. });
  281. }
  282. /**
  283. * Requests the player data and scrapes the subtitle and video data.
  284. */
  285. function scrapePlayer(config: IConfig, address: string, id: number, done: (err: Error, player?: IEpisodePlayer) => void)
  286. {
  287. const url = address.match(/^(https?:\/\/[^\/]+)/);
  288. if (!url)
  289. {
  290. return done(new Error('Invalid address.'));
  291. }
  292. const postForm = {
  293. current_page: address,
  294. video_format: config.video_format,
  295. video_quality: config.video_quality,
  296. media_id: id
  297. };
  298. my_request.post(config, url[1] + '/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id=' + id, postForm,
  299. (err, result) =>
  300. {
  301. if (err)
  302. {
  303. return done(err);
  304. }
  305. xml2js.parseString(result, {
  306. explicitArray: false,
  307. explicitRoot: false,
  308. }, (errPS: Error, player: IEpisodePlayerConfig) =>
  309. {
  310. if (errPS)
  311. {
  312. return done(errPS);
  313. }
  314. try
  315. {
  316. const isSubtitled = Boolean(player['default:preload'].subtitle);
  317. let streamMode = 'RTMP';
  318. if (player['default:preload'].stream_info.host === '')
  319. {
  320. streamMode = 'HLS';
  321. }
  322. done(null, {
  323. subtitle: isSubtitled ? {
  324. data: player['default:preload'].subtitle.data,
  325. id: parseInt(player['default:preload'].subtitle.$.id, 10),
  326. iv: player['default:preload'].subtitle.iv,
  327. } : null,
  328. video: {
  329. file: player['default:preload'].stream_info.file,
  330. host: player['default:preload'].stream_info.host,
  331. mode: streamMode,
  332. },
  333. });
  334. } catch (parseError)
  335. {
  336. if (config.debug)
  337. {
  338. log.dumpToDebug('player scrape', parseError);
  339. }
  340. done(parseError);
  341. }
  342. });
  343. });
  344. }