batch.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 series from './series';
  7. /* correspondances between resolution and value CR excpect */
  8. const resol_table: { [id: string]: IResolData; } =
  9. {
  10. 360: {quality: '60', format: '106'},
  11. 480: {quality: '61', format: '106'},
  12. 720: {quality: '62', format: '106'},
  13. 1080: {quality: '80', format: '108'},
  14. };
  15. /**
  16. * Streams the batch of series to disk.
  17. */
  18. export default function(args: string[], done: (err?: Error) => void)
  19. {
  20. const config = parse(args);
  21. const batchPath = path.join(config.output || process.cwd(), config.batch);
  22. // set resolution
  23. if (config.resolution)
  24. {
  25. try
  26. {
  27. config.video_format = resol_table[config.resolution].format;
  28. config.video_quality = resol_table[config.resolution].quality;
  29. }
  30. catch (e)
  31. {
  32. log.warn('Invalid resolution ' + config.resolution + 'p. Setting to 1080p');
  33. config.video_format = resol_table['1080'].format;
  34. config.video_quality = resol_table['1080'].quality;
  35. }
  36. }
  37. else
  38. {
  39. /* 1080 by default */
  40. config.video_format = resol_table['1080'].format;
  41. config.video_quality = resol_table['1080'].quality;
  42. }
  43. if (config.debug)
  44. {
  45. /* Ugly but meh */
  46. const tmp = JSON.parse(JSON.stringify(config));
  47. tmp.pass = 'obfuscated';
  48. tmp.user = 'obfustated';
  49. tmp.rawArgs = undefined;
  50. tmp.options = undefined;
  51. log.dumpToDebug('Config', JSON.stringify(tmp), true);
  52. }
  53. tasks(config, batchPath, (err, tasksArr) =>
  54. {
  55. if (err)
  56. {
  57. return done(err);
  58. }
  59. let i = 0;
  60. (function next()
  61. {
  62. if (i >= tasksArr.length)
  63. {
  64. return done();
  65. }
  66. if (config.debug)
  67. {
  68. log.dumpToDebug('Task ' + i, JSON.stringify(tasksArr[i]));
  69. }
  70. series(config, tasksArr[i], (errin) =>
  71. {
  72. if (errin)
  73. {
  74. if (tasksArr[i].retry <= 0)
  75. {
  76. log.error(errin.stack || errin);
  77. if (config.debug)
  78. {
  79. log.dumpToDebug('BatchGiveUp', errin.stack || errin);
  80. }
  81. log.error('Cannot get episodes from "' + tasksArr[i].address + '", please rerun later');
  82. /* Go to the next on the list */
  83. i += 1;
  84. }
  85. else
  86. {
  87. if (config.verbose)
  88. {
  89. log.error(errin);
  90. }
  91. if (config.debug)
  92. {
  93. log.dumpToDebug('BatchRetry', errin.stack || errin);
  94. }
  95. log.warn('Retrying to fetch episodes list from' + tasksArr[i].retry + ' / ' + config.retry);
  96. tasksArr[i].retry -= 1;
  97. }
  98. }
  99. else
  100. {
  101. i += 1;
  102. }
  103. next();
  104. });
  105. })();
  106. });
  107. }
  108. /**
  109. * Splits the value into arguments.
  110. */
  111. function split(value: string): string[]
  112. {
  113. let inQuote = false;
  114. let i: number;
  115. const pieces: string[] = [];
  116. let previous = 0;
  117. for (i = 0; i < value.length; i += 1)
  118. {
  119. if (value.charAt(i) === '"')
  120. {
  121. inQuote = !inQuote;
  122. }
  123. if (!inQuote && value.charAt(i) === ' ')
  124. {
  125. pieces.push(value.substring(previous, i).match(/^"?(.+?)"?$/)[1]);
  126. previous = i + 1;
  127. }
  128. }
  129. const lastPiece = value.substring(previous, i).match(/^"?(.+?)"?$/);
  130. if (lastPiece)
  131. {
  132. pieces.push(lastPiece[1]);
  133. }
  134. return pieces;
  135. }
  136. function get_min_filter(filter: string): number
  137. {
  138. if (filter !== undefined)
  139. {
  140. const tok = filter.split('-');
  141. if (tok.length > 2)
  142. {
  143. log.error('Invalid episode filter \'' + filter + '\'');
  144. process.exit(-1);
  145. }
  146. if (tok[0] !== '')
  147. {
  148. return parseInt(tok[0], 10);
  149. }
  150. }
  151. return 0;
  152. }
  153. function get_max_filter(filter: string): number
  154. {
  155. if (filter !== undefined)
  156. {
  157. const tok = filter.split('-');
  158. if (tok.length > 2)
  159. {
  160. log.error('Invalid episode filter \'' + filter + '\'');
  161. process.exit(-1);
  162. }
  163. if ((tok.length > 1) && (tok[1] !== ''))
  164. {
  165. /* We have a max value */
  166. return parseInt(tok[1], 10);
  167. }
  168. else if ((tok.length === 1) && (tok[0] !== ''))
  169. {
  170. /* A single episode has been requested */
  171. return parseInt(tok[0], 10);
  172. }
  173. }
  174. return +Infinity;
  175. }
  176. /**
  177. * Parses the configuration or reads the batch-mode file for tasks.
  178. */
  179. function tasks(config: IConfigLine, batchPath: string, done: (err: Error, tasks?: IConfigTask[]) => void)
  180. {
  181. if (config.args.length)
  182. {
  183. return done(null, config.args.map((addressIn) =>
  184. {
  185. return {address: addressIn, retry: config.retry,
  186. episode_min: get_min_filter(config.episodes), episode_max: get_max_filter(config.episodes)};
  187. }));
  188. }
  189. fs.exists(batchPath, (exists) =>
  190. {
  191. if (!exists)
  192. {
  193. return done(null, []);
  194. }
  195. fs.readFile(batchPath, 'utf8', (err, data) =>
  196. {
  197. if (err)
  198. {
  199. return done(err);
  200. }
  201. const map: IConfigTask[] = [];
  202. data.split(/\r?\n/).forEach((line) =>
  203. {
  204. if (/^(\/\/|#)/.test(line))
  205. {
  206. return;
  207. }
  208. const lineConfig = parse(process.argv.concat(split(line)));
  209. lineConfig.args.forEach((addressIn) =>
  210. {
  211. if (!addressIn)
  212. {
  213. return;
  214. }
  215. map.push({address: addressIn, retry: lineConfig.retry,
  216. episode_min: get_min_filter(lineConfig.episodes), episode_max: get_max_filter(lineConfig.episodes)});
  217. });
  218. });
  219. done(null, map);
  220. });
  221. });
  222. }
  223. /**
  224. * Parses the arguments and returns a configuration.
  225. */
  226. function parse(args: string[]): IConfigLine
  227. {
  228. return new commander.Command().version(require('../package').version)
  229. // Authentication
  230. .option('-p, --pass <s>', 'The password.')
  231. .option('-u, --user <s>', 'The e-mail address or username.')
  232. // Disables
  233. .option('-c, --cache', 'Disables the cache.')
  234. .option('-m, --merge', 'Disables merging subtitles and videos.')
  235. // Episode filter
  236. .option('-e, --episodes <s>', 'Episode list. Read documentation on how to use')
  237. // Settings
  238. .option('-f, --format <s>', 'The subtitle format.', 'ass')
  239. .option('-o, --output <s>', 'The output path.')
  240. .option('-s, --series <s>', 'The series name override.')
  241. .option('-n, --nametmpl <s>', 'Output name template', '{SERIES_TITLE} - s{SEASON_NUMBER}e{EPISODE_NUMBER} - [{TAG}]')
  242. .option('-t, --tag <s>', 'The subgroup.', 'CrunchyRoll')
  243. .option('-r, --resolution <s>', 'The video resolution. (valid: 360, 480, 720, 1080)', '1080')
  244. .option('-b, --batch <s>', 'Batch file', 'CrunchyRoll.txt')
  245. .option('--verbose', 'Make tool verbose')
  246. .option('--debug', 'Create a debug file. Use only if requested!')
  247. .option('--rebuildcrp', 'Rebuild the crpersistant file.')
  248. .option('--retry <i>', 'Number or time to retry fetching an episode.', 5)
  249. .parse(args);
  250. }