series.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. 'use strict';
  2. import cheerio = require('cheerio');
  3. import episode from './episode';
  4. // import fs = require('fs');
  5. import fs = require('fs-extra');
  6. import my_request = require('./my_request');
  7. import path = require('path');
  8. import url = require('url');
  9. import log = require('./log');
  10. const persistent = '.crpersistent';
  11. /**
  12. * Check if a file exist..
  13. */
  14. function fileExist(path: string)
  15. {
  16. try
  17. {
  18. fs.statSync(path);
  19. return true;
  20. } catch (e)
  21. {
  22. return false;
  23. }
  24. }
  25. /**
  26. * Streams the series to disk.
  27. */
  28. export default function(config: IConfig, task: IConfigTask, done: (err: any) => void)
  29. {
  30. const persistentPath = path.join(config.output || process.cwd(), persistent);
  31. /* Make a backup of the persistent file in case of */
  32. if (fileExist(persistentPath))
  33. {
  34. fs.copySync(persistentPath, persistentPath + '.backup');
  35. }
  36. fs.readFile(persistentPath, 'utf8', (err: Error, contents: string) =>
  37. {
  38. const cache = config.cache ? {} : JSON.parse(contents || '{}');
  39. pageScrape(config, task, (errP, page) =>
  40. {
  41. if (errP)
  42. {
  43. const reqErr = errP.error;
  44. if ((reqErr.syscall === 'getaddrinfo') && (reqErr.errno === 'ENOTFOUND'))
  45. {
  46. log.error('The URL \'' + task.address + '\' is invalid, please check => I\'m ignoring it.');
  47. }
  48. return done(errP);
  49. }
  50. let i = 0;
  51. (function next()
  52. {
  53. if (config.debug)
  54. {
  55. log.dumpToDebug('Episode ' + i, JSON.stringify(page.episodes[i]));
  56. }
  57. if (i >= page.episodes.length) return done(null);
  58. download(cache, config, task, page.episodes[i], (errD, ignored) =>
  59. {
  60. if (errD)
  61. {
  62. /* Check if domain is valid */
  63. const reqErr = errD.error;
  64. if ((reqErr.syscall === 'getaddrinfo') && (reqErr.errno === 'ENOTFOUND'))
  65. {
  66. page.episodes[i].retry = 0;
  67. log.error('The URL \'' + task.address + '\' is invalid, please check => I\'m ignoring it.');
  68. }
  69. if (page.episodes[i].retry <= 0)
  70. {
  71. log.error(JSON.stringify(errD));
  72. log.error('Cannot fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
  73. '", please rerun later');
  74. /* Go to the next on the list */
  75. i += 1;
  76. }
  77. else
  78. {
  79. if ((config.verbose) || (config.debug))
  80. {
  81. if (config.debug)
  82. {
  83. log.dumpToDebug('series address', task.address);
  84. log.dumpToDebug('series error', JSON.stringify(errD));
  85. log.dumpToDebug('series data', JSON.stringify(page));
  86. }
  87. log.error(errD);
  88. }
  89. log.warn('Retrying to fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
  90. '" - Retry ' + page.episodes[i].retry + ' / ' + config.retry);
  91. page.episodes[i].retry -= 1;
  92. }
  93. next();
  94. }
  95. else
  96. {
  97. if ((ignored === false) || (ignored === undefined))
  98. {
  99. const newCache = JSON.stringify(cache, null, ' ');
  100. fs.writeFile(persistentPath, newCache, (errW: Error) =>
  101. {
  102. if (errW)
  103. {
  104. return done(errW);
  105. }
  106. i += 1;
  107. next();
  108. });
  109. }
  110. else
  111. {
  112. i += 1;
  113. next();
  114. }
  115. }
  116. });
  117. })();
  118. });
  119. });
  120. }
  121. /**
  122. * Downloads the episode.
  123. */
  124. function download(cache: {[address: string]: number}, config: IConfig,
  125. task: IConfigTask, item: ISeriesEpisode,
  126. done: (err: any, ign: boolean) => void)
  127. {
  128. const episodeNumber = parseInt(item.episode, 10);
  129. if ( (episodeNumber < task.episode_min) ||
  130. (episodeNumber > task.episode_max) )
  131. {
  132. return done(null, false);
  133. }
  134. const address = url.resolve(task.address, item.address);
  135. if (cache[address])
  136. {
  137. return done(null, false);
  138. }
  139. episode(config, address, (err, ignored) =>
  140. {
  141. if (err)
  142. {
  143. return done(err, false);
  144. }
  145. cache[address] = Date.now();
  146. done(null, ignored);
  147. });
  148. }
  149. /**
  150. * Requests the page and scrapes the episodes and series.
  151. */
  152. function pageScrape(config: IConfig, task: IConfigTask, done: (err: any, result?: ISeries) => void)
  153. {
  154. if (task.address[0] === '@')
  155. {
  156. log.info('Trying to fetch from ' + task.address.substr(1));
  157. const episodes: ISeriesEpisode[] = [];
  158. episodes.push({
  159. address: task.address.substr(1),
  160. episode: '',
  161. volume: 0,
  162. retry: config.retry,
  163. });
  164. done(null, {episodes: episodes.reverse(), series: ''});
  165. }
  166. else
  167. {
  168. let episodeCount = 0;
  169. my_request.get(config, task.address, (err, result) => {
  170. if (err)
  171. {
  172. return done(err);
  173. }
  174. const $ = cheerio.load(result);
  175. const title = $('span[itemprop=name]').text();
  176. if (config.debug)
  177. {
  178. log.dumpToDebug('serie page', $.html());
  179. }
  180. if (!title) {
  181. if (config.debug)
  182. {
  183. log.dumpToDebug('missing title', task.address);
  184. }
  185. return done(new Error('Invalid page.(' + task.address + ')'));
  186. }
  187. log.info('Checking availability for ' + title);
  188. const episodes: ISeriesEpisode[] = [];
  189. $('.episode').each((i, el) => {
  190. if ($(el).children('img[src*=coming_soon]').length) {
  191. return;
  192. }
  193. const volume = /([0-9]+)\s*$/.exec($(el).closest('ul').prev('a').text());
  194. const regexp = /Episode\s+((PV )?[S0-9][\-P0-9.]*[a-fA-F]?)\s*$/i;
  195. const episode = regexp.exec($(el).children('.series-title').text());
  196. const url = $(el).attr('href');
  197. if ((!url) || (!episode)) {
  198. return;
  199. }
  200. episodeCount += 1;
  201. episodes.push({
  202. address: url,
  203. episode: episode[1],
  204. volume: volume ? parseInt(volume[0], 10) : 1,
  205. retry: config.retry,
  206. });
  207. });
  208. if (episodeCount === 0)
  209. {
  210. log.warn('No episodes found for ' + title + '. Could it be a movie?');
  211. }
  212. done(null, {episodes: episodes.reverse(), series: title});
  213. });
  214. }
  215. }