batch.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. 'use strict';
  2. import commander = require('commander');
  3. import fs = require('fs');
  4. import path = require('path');
  5. import log = require('./log');
  6. import my_request = require('./my_request');
  7. import cfg = require('./config');
  8. import series from './series';
  9. /* correspondances between resolution and value CR excpect */
  10. const resol_table: { [id: string]: IResolData; } =
  11. {
  12. 360: {quality: '60', format: '106'},
  13. 480: {quality: '61', format: '106'},
  14. 720: {quality: '62', format: '106'},
  15. 1080: {quality: '80', format: '108'},
  16. };
  17. /**
  18. * Streams the batch of series to disk.
  19. */
  20. export default function(args: string[], done: (err?: Error) => void)
  21. {
  22. const config = Object.assign(cfg.load(), parse(args));
  23. let batchPath;
  24. if (path.isAbsolute(config.batch))
  25. {
  26. batchPath = path.normalize(config.batch);
  27. }
  28. else
  29. {
  30. batchPath = path.normalize(path.join(process.cwd(), config.batch));
  31. }
  32. if (config.nametmpl === undefined)
  33. {
  34. config.nametmpl = '{SERIES_TITLE} - s{SEASON_NUMBER}e{EPISODE_NUMBER} - {EPISODE_TITLE} - [{TAG}]';
  35. }
  36. if (config.tag === undefined)
  37. {
  38. config.tag = 'CrunchyRoll';
  39. }
  40. if (config.sublang === undefined)
  41. {
  42. config.sublang = [ 'enUS' ];
  43. }
  44. // set resolution
  45. if (config.resolution)
  46. {
  47. try
  48. {
  49. config.video_format = resol_table[config.resolution].format;
  50. config.video_quality = resol_table[config.resolution].quality;
  51. }
  52. catch (e)
  53. {
  54. log.warn('Invalid resolution ' + config.resolution + 'p. Setting to 1080p');
  55. config.video_format = resol_table['1080'].format;
  56. config.video_quality = resol_table['1080'].quality;
  57. }
  58. }
  59. else
  60. {
  61. /* 1080 by default */
  62. config.video_format = resol_table['1080'].format;
  63. config.video_quality = resol_table['1080'].quality;
  64. }
  65. // Update the config file with new parameters
  66. cfg.save(config);
  67. if (config.unlog)
  68. {
  69. config.crDeviceId = undefined;
  70. config.user = undefined;
  71. config.pass = undefined;
  72. my_request.eatCookies(config);
  73. cfg.save(config);
  74. log.info('Unlogged!');
  75. process.exit(0);
  76. }
  77. if (config.debug)
  78. {
  79. /* Ugly but meh */
  80. const tmp = JSON.parse(JSON.stringify(config));
  81. tmp.pass = 'obfuscated';
  82. tmp.user = 'obfustated';
  83. tmp.rawArgs = undefined;
  84. tmp.options = undefined;
  85. log.dumpToDebug('Config', JSON.stringify(tmp), true);
  86. }
  87. tasks(config, batchPath, (err, tasksArr) =>
  88. {
  89. if (err)
  90. {
  91. return done(err);
  92. }
  93. if (!tasksArr || !tasksArr[0] || (tasksArr[0].address === ''))
  94. {
  95. return done();
  96. }
  97. let i = 0;
  98. (function next()
  99. {
  100. if (i >= tasksArr.length)
  101. {
  102. // Save configuration before leaving (should store info like session & other)
  103. cfg.save(config);
  104. return done();
  105. }
  106. if (config.debug)
  107. {
  108. log.dumpToDebug('Task ' + i, JSON.stringify(tasksArr[i]));
  109. }
  110. series(config, tasksArr[i], (errin) =>
  111. {
  112. if (errin)
  113. {
  114. if (errin.error)
  115. {
  116. /* Error from the request, so ignore it */
  117. tasksArr[i].retry = 0;
  118. }
  119. if (errin.authError)
  120. {
  121. /* Force a graceful exit */
  122. log.error(errin.message);
  123. i = tasksArr.length;
  124. }
  125. else if (tasksArr[i].retry <= 0)
  126. {
  127. log.error(JSON.stringify(errin));
  128. if (config.debug)
  129. {
  130. log.dumpToDebug('BatchGiveUp', JSON.stringify(errin));
  131. }
  132. log.error('Cannot get episodes from "' + tasksArr[i].address + '", please rerun later');
  133. /* Go to the next on the list */
  134. i += 1;
  135. }
  136. else
  137. {
  138. if (config.verbose)
  139. {
  140. log.error(JSON.stringify(errin));
  141. }
  142. if (config.debug)
  143. {
  144. log.dumpToDebug('BatchRetry', JSON.stringify(errin));
  145. }
  146. log.warn('Retrying to fetch episodes list from' + tasksArr[i].retry + ' / ' + config.retry);
  147. tasksArr[i].retry -= 1;
  148. }
  149. }
  150. else
  151. {
  152. i += 1;
  153. }
  154. setTimeout(next, config.sleepTime);
  155. });
  156. })();
  157. });
  158. }
  159. /**
  160. * Splits the value into arguments.
  161. */
  162. function split(value: string): string[]
  163. {
  164. let inQuote = false;
  165. let i: number;
  166. const pieces: string[] = [];
  167. let previous = 0;
  168. for (i = 0; i < value.length; i += 1)
  169. {
  170. if (value.charAt(i) === '"')
  171. {
  172. inQuote = !inQuote;
  173. }
  174. if (!inQuote && value.charAt(i) === ' ')
  175. {
  176. pieces.push(value.substring(previous, i).match(/^"?(.+?)"?$/)[1]);
  177. previous = i + 1;
  178. }
  179. }
  180. const lastPiece = value.substring(previous, i).match(/^"?(.+?)"?$/);
  181. if (lastPiece)
  182. {
  183. pieces.push(lastPiece[1]);
  184. }
  185. return pieces;
  186. }
  187. function get_min_filter(filter: string): IEpisodeNumber
  188. {
  189. if (filter !== undefined)
  190. {
  191. const tok = filter.split('-');
  192. if (tok.length > 2)
  193. {
  194. log.error('Invalid episode filter \'' + filter + '\'');
  195. process.exit(-1);
  196. }
  197. if (tok[0] !== '')
  198. {
  199. /* If first item is not empty, ie '10-20' */
  200. if (tok[0].includes('e'))
  201. {
  202. /* include a e so we probably have something like 5e10
  203. aka season 5 episode 10
  204. */
  205. const tok2 = tok[0].split('else');
  206. if (tok2.length > 2)
  207. {
  208. log.error('Invalid episode filter \'' + filter + '\'');
  209. process.exit(-1);
  210. }
  211. if (tok[0] !== '')
  212. {
  213. /* So season is properly filled */
  214. return {season: parseInt(tok2[0], 10), episode: parseInt(tok2[1], 10)};
  215. }
  216. else
  217. {
  218. /* we have 'e10' */
  219. return {season: 0, episode: parseInt(tok2[1], 10)};
  220. }
  221. }
  222. else
  223. {
  224. return {season: 0, episode: parseInt(tok[0], 10)};
  225. }
  226. }
  227. }
  228. /* First item is empty, ie '-20' */
  229. return {season: 0, episode: 0};
  230. }
  231. function get_max_filter(filter: string): IEpisodeNumber
  232. {
  233. if (filter !== undefined)
  234. {
  235. const tok = filter.split('-');
  236. if (tok.length > 2)
  237. {
  238. log.error('Invalid episode filter \'' + filter + '\'');
  239. process.exit(-1);
  240. }
  241. if ((tok.length > 1) && (tok[1] !== ''))
  242. {
  243. /* We have a max value */
  244. return {season: +Infinity, episode: parseInt(tok[1], 10)};
  245. }
  246. else if ((tok.length === 1) && (tok[0] !== ''))
  247. {
  248. /* A single episode has been requested */
  249. return {season: +Infinity, episode: parseInt(tok[0], 10) + 1};
  250. }
  251. }
  252. return {season: +Infinity, episode: +Infinity};
  253. }
  254. /**
  255. * Check that URL start with http:// or https://
  256. * As for some reason request just return an error but a useless one when that happen so check it
  257. * soon enough.
  258. */
  259. function checkURL(address: string): boolean
  260. {
  261. if (address.startsWith('http:\/\/'))
  262. {
  263. return true;
  264. }
  265. if (address.startsWith('https:\/\/'))
  266. {
  267. return true;
  268. }
  269. if (address.startsWith('@http:\/\/'))
  270. {
  271. return true;
  272. }
  273. if (address.startsWith('@https:\/\/'))
  274. {
  275. return true;
  276. }
  277. log.error('URL ' + address + ' miss \'http:\/\/\' or \'https:\/\/\' => will be ignored');
  278. return false;
  279. }
  280. /**
  281. * Parses the configuration or reads the batch-mode file for tasks.
  282. */
  283. function tasks(config: IConfigLine, batchPath: string, done: (err: Error, tasks?: IConfigTask[]) => void)
  284. {
  285. if (config.args.length)
  286. {
  287. return done(null, config.args.map((addressIn) =>
  288. {
  289. if (checkURL(addressIn))
  290. {
  291. return {address: addressIn, retry: config.retry,
  292. episode_min: get_min_filter(config.episodes), episode_max: get_max_filter(config.episodes)};
  293. }
  294. return {address: '', retry: 0, episode_min: {season: 0, episode: 0}, episode_max: {season: 0, episode: 0}};
  295. }));
  296. }
  297. fs.exists(batchPath, (exists) =>
  298. {
  299. if (!exists)
  300. {
  301. return done(null, []);
  302. }
  303. fs.readFile(batchPath, 'utf8', (err, data) =>
  304. {
  305. if (err)
  306. {
  307. return done(err);
  308. }
  309. const map: IConfigTask[] = [];
  310. data.split(/\r?\n/).forEach((line) =>
  311. {
  312. if (/^(\/\/|#)/.test(line))
  313. {
  314. return;
  315. }
  316. const lineConfig = parse(process.argv.concat(split(line)));
  317. lineConfig.args.forEach((addressIn) =>
  318. {
  319. if (!addressIn)
  320. {
  321. return;
  322. }
  323. if (checkURL(addressIn))
  324. {
  325. map.push({address: addressIn, retry: lineConfig.retry,
  326. episode_min: get_min_filter(lineConfig.episodes), episode_max: get_max_filter(lineConfig.episodes)});
  327. }
  328. });
  329. });
  330. done(null, map);
  331. });
  332. });
  333. }
  334. /**
  335. * Parses the arguments and returns a configuration.
  336. */
  337. function parse(args: string[]): IConfigLine
  338. {
  339. return new commander.Command().version(require('../package').version)
  340. // Authentication
  341. .option('-p, --pass <s>', 'The password.')
  342. .option('-u, --user <s>', 'The e-mail address or username.')
  343. .option('-d, --unlog', 'Unlog')
  344. // Disables
  345. .option('-c, --cache', 'Disables the cache.')
  346. .option('-m, --merge', 'Disables merging subtitles and videos.')
  347. // Episode filter
  348. .option('-e, --episodes <s>', 'Episode list. Read documentation on how to use')
  349. // Settings
  350. .option('-l, --crlang <s>', 'CR page language (valid: en, fr, es, it, pt, de, ru).')
  351. .option('-f, --format <s>', 'The subtitle format.', 'ass')
  352. .option('-o, --output <s>', 'The output path.')
  353. .option('-s, --series <s>', 'The series name override.')
  354. .option('--ignoredub', 'Experimental: Ignore all seasons where the title end with \'Dub)\'')
  355. .option('-n, --nametmpl <s>', 'Output name template')
  356. .option('-t, --tag <s>', 'The subgroup.')
  357. .option('-r, --resolution <s>', 'The video resolution. (valid: 360, 480, 720, 1080)')
  358. .option('-b, --batch <s>', 'Batch file', 'CrunchyRoll.txt')
  359. .option('--verbose', 'Make tool verbose')
  360. .option('--debug', 'Create a debug file. Use only if requested!')
  361. .option('--rebuildcrp', 'Rebuild the crpersistant file.')
  362. .option('--retry <i>', 'Number or time to retry fetching an episode.', '5')
  363. .option('--sleepTime <i>', 'Minimum wait time between each http requests.')
  364. .parse(args);
  365. }