batch.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. if (config.verbose)
  128. {
  129. log.error(JSON.stringify(errin));
  130. }
  131. if (config.debug)
  132. {
  133. log.dumpToDebug('BatchGiveUp', JSON.stringify(errin));
  134. }
  135. log.error('Cannot get episodes from "' + tasksArr[i].address + '", please rerun later');
  136. /* Go to the next on the list */
  137. i += 1;
  138. }
  139. else
  140. {
  141. if (config.verbose)
  142. {
  143. log.error(JSON.stringify(errin));
  144. }
  145. if (config.debug)
  146. {
  147. log.dumpToDebug('BatchRetry', JSON.stringify(errin));
  148. }
  149. log.warn('Retrying to fetch episodes list from' + tasksArr[i].retry + ' / ' + config.retry);
  150. tasksArr[i].retry -= 1;
  151. }
  152. }
  153. else
  154. {
  155. i += 1;
  156. }
  157. setTimeout(next, config.sleepTime);
  158. });
  159. })();
  160. });
  161. }
  162. /**
  163. * Splits the value into arguments.
  164. */
  165. function split(value: string): string[]
  166. {
  167. let inQuote = false;
  168. let i: number;
  169. const pieces: string[] = [];
  170. let previous = 0;
  171. for (i = 0; i < value.length; i += 1)
  172. {
  173. if (value.charAt(i) === '"')
  174. {
  175. inQuote = !inQuote;
  176. }
  177. if (!inQuote && value.charAt(i) === ' ')
  178. {
  179. pieces.push(value.substring(previous, i).match(/^"?(.+?)"?$/)[1]);
  180. previous = i + 1;
  181. }
  182. }
  183. const lastPiece = value.substring(previous, i).match(/^"?(.+?)"?$/);
  184. if (lastPiece)
  185. {
  186. pieces.push(lastPiece[1]);
  187. }
  188. return pieces;
  189. }
  190. function get_min_filter(filter: string): IEpisodeNumber
  191. {
  192. if (filter !== undefined)
  193. {
  194. const tok = filter.split('-');
  195. if (tok.length > 2)
  196. {
  197. log.error('Invalid episode filter \'' + filter + '\'');
  198. process.exit(-1);
  199. }
  200. if (tok[0] !== '')
  201. {
  202. /* If first item is not empty, ie '10-20' */
  203. if (tok[0].includes('e'))
  204. {
  205. /* include a e so we probably have something like 5e10
  206. aka season 5 episode 10
  207. */
  208. const tok2 = tok[0].split('else');
  209. if (tok2.length > 2)
  210. {
  211. log.error('Invalid episode filter \'' + filter + '\'');
  212. process.exit(-1);
  213. }
  214. if (tok[0] !== '')
  215. {
  216. /* So season is properly filled */
  217. return {season: parseInt(tok2[0], 10), episode: parseInt(tok2[1], 10)};
  218. }
  219. else
  220. {
  221. /* we have 'e10' */
  222. return {season: 0, episode: parseInt(tok2[1], 10)};
  223. }
  224. }
  225. else
  226. {
  227. return {season: 0, episode: parseInt(tok[0], 10)};
  228. }
  229. }
  230. }
  231. /* First item is empty, ie '-20' */
  232. return {season: 0, episode: 0};
  233. }
  234. function get_max_filter(filter: string): IEpisodeNumber
  235. {
  236. if (filter !== undefined)
  237. {
  238. const tok = filter.split('-');
  239. if (tok.length > 2)
  240. {
  241. log.error('Invalid episode filter \'' + filter + '\'');
  242. process.exit(-1);
  243. }
  244. if ((tok.length > 1) && (tok[1] !== ''))
  245. {
  246. /* We have a max value */
  247. return {season: +Infinity, episode: parseInt(tok[1], 10)};
  248. }
  249. else if ((tok.length === 1) && (tok[0] !== ''))
  250. {
  251. /* A single episode has been requested */
  252. return {season: +Infinity, episode: parseInt(tok[0], 10) + 1};
  253. }
  254. }
  255. return {season: +Infinity, episode: +Infinity};
  256. }
  257. /**
  258. * Check that URL start with http:// or https://
  259. * As for some reason request just return an error but a useless one when that happen so check it
  260. * soon enough.
  261. */
  262. function checkURL(address: string): boolean
  263. {
  264. if (address.startsWith('http:\/\/'))
  265. {
  266. return true;
  267. }
  268. if (address.startsWith('https:\/\/'))
  269. {
  270. return true;
  271. }
  272. if (address.startsWith('@http:\/\/'))
  273. {
  274. return true;
  275. }
  276. if (address.startsWith('@https:\/\/'))
  277. {
  278. return true;
  279. }
  280. log.error('URL ' + address + ' miss \'http:\/\/\' or \'https:\/\/\' => will be ignored');
  281. return false;
  282. }
  283. /**
  284. * Parses the configuration or reads the batch-mode file for tasks.
  285. */
  286. function tasks(config: IConfigLine, batchPath: string, done: (err: Error, tasks?: IConfigTask[]) => void)
  287. {
  288. if (config.args.length)
  289. {
  290. return done(null, config.args.map((addressIn) =>
  291. {
  292. if (checkURL(addressIn))
  293. {
  294. return {address: addressIn, retry: config.retry,
  295. episode_min: get_min_filter(config.episodes), episode_max: get_max_filter(config.episodes)};
  296. }
  297. return {address: '', retry: 0, episode_min: {season: 0, episode: 0}, episode_max: {season: 0, episode: 0}};
  298. }));
  299. }
  300. fs.exists(batchPath, (exists) =>
  301. {
  302. if (!exists)
  303. {
  304. return done(null, []);
  305. }
  306. fs.readFile(batchPath, 'utf8', (err, data) =>
  307. {
  308. if (err)
  309. {
  310. return done(err);
  311. }
  312. const map: IConfigTask[] = [];
  313. data.split(/\r?\n/).forEach((line) =>
  314. {
  315. if (/^(\/\/|#)/.test(line))
  316. {
  317. return;
  318. }
  319. const lineConfig = parse(process.argv.concat(split(line)));
  320. lineConfig.args.forEach((addressIn) =>
  321. {
  322. if (!addressIn)
  323. {
  324. return;
  325. }
  326. if (checkURL(addressIn))
  327. {
  328. map.push({address: addressIn, retry: lineConfig.retry,
  329. episode_min: get_min_filter(lineConfig.episodes), episode_max: get_max_filter(lineConfig.episodes)});
  330. }
  331. });
  332. });
  333. done(null, map);
  334. });
  335. });
  336. }
  337. /**
  338. * Parses the arguments and returns a configuration.
  339. */
  340. function parse(args: string[]): IConfigLine
  341. {
  342. return new commander.Command().version(require('../package').version)
  343. // Authentication
  344. .option('-p, --pass <s>', 'The password.')
  345. .option('-u, --user <s>', 'The e-mail address or username.')
  346. .option('-d, --unlog', 'Unlog')
  347. // Disables
  348. .option('-c, --cache', 'Disables the cache.')
  349. .option('-m, --merge', 'Disables merging subtitles and videos.')
  350. // Episode filter
  351. .option('-e, --episodes <s>', 'Episode list. Read documentation on how to use')
  352. // Settings
  353. .option('-l, --crlang <s>', 'CR page language (valid: en, fr, es, it, pt, de, ru).')
  354. .option('-f, --format <s>', 'The subtitle format.', 'ass')
  355. .option('-o, --output <s>', 'The output path.')
  356. .option('-s, --series <s>', 'The series name override.')
  357. .option('--ignoredub', 'Experimental: Ignore all seasons where the title end with \'Dub)\'')
  358. .option('-n, --nametmpl <s>', 'Output name template')
  359. .option('-t, --tag <s>', 'The subgroup.')
  360. .option('-r, --resolution <s>', 'The video resolution. (valid: 360, 480, 720, 1080)')
  361. .option('-b, --batch <s>', 'Batch file', 'CrunchyRoll.txt')
  362. .option('--verbose', 'Make tool verbose')
  363. .option('--debug', 'Create a debug file. Use only if requested!')
  364. .option('--rebuildcrp', 'Rebuild the crpersistant file.')
  365. .option('--retry <i>', 'Number or time to retry fetching an episode.', '5')
  366. .option('--sleepTime <i>', 'Minimum wait time between each http requests.')
  367. .parse(args);
  368. }