series.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. 'use strict';
  2. import cheerio = require('cheerio');
  3. import episode from './episode';
  4. import fs = require('fs-extra');
  5. import my_request = require('./my_request');
  6. import path = require('path');
  7. import url = require('url');
  8. import log = require('./log');
  9. import languages = require('./languages');
  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 !== undefined) && (reqErr.syscall))
  45. {
  46. if ((reqErr.syscall === 'getaddrinfo') && (reqErr.errno === 'ENOTFOUND'))
  47. {
  48. log.error('The URL \'' + task.address + '\' is invalid, please check => I\'m ignoring it.');
  49. }
  50. }
  51. return done(errP);
  52. }
  53. let i = 0;
  54. (function next()
  55. {
  56. if (config.debug)
  57. {
  58. log.dumpToDebug('Episode ' + i, JSON.stringify(page.episodes[i]));
  59. }
  60. if (i >= page.episodes.length) return done(null);
  61. download(cache, config, task, page.episodes[i], (errD, ignored) =>
  62. {
  63. if (errD)
  64. {
  65. /* Check if domain is valid */
  66. const reqErr = errD.error;
  67. if ((reqErr !== undefined) && (reqErr.syscall))
  68. {
  69. if ((reqErr.syscall === 'getaddrinfo') && (reqErr.errno === 'ENOTFOUND'))
  70. {
  71. page.episodes[i].retry = 0;
  72. log.error('The URL \'' + task.address + '\' is invalid, please check => I\'m ignoring it.');
  73. }
  74. }
  75. if (page.episodes[i].retry <= 0)
  76. {
  77. log.error(JSON.stringify(errD));
  78. log.error('Cannot fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
  79. '", please rerun later');
  80. /* Go to the next on the list */
  81. i += 1;
  82. }
  83. else
  84. {
  85. if ((config.verbose) || (config.debug))
  86. {
  87. if (config.debug)
  88. {
  89. log.dumpToDebug('series address', task.address);
  90. log.dumpToDebug('series error', JSON.stringify(errD));
  91. log.dumpToDebug('series data', JSON.stringify(page));
  92. }
  93. log.error(errD);
  94. }
  95. log.warn('Retrying to fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
  96. '" - Retry ' + page.episodes[i].retry + ' / ' + config.retry);
  97. page.episodes[i].retry -= 1;
  98. }
  99. next();
  100. }
  101. else
  102. {
  103. if ((ignored === false) || (ignored === undefined))
  104. {
  105. const newCache = JSON.stringify(cache, null, ' ');
  106. fs.writeFile(persistentPath, newCache, (errW: Error) =>
  107. {
  108. if (errW)
  109. {
  110. return done(errW);
  111. }
  112. i += 1;
  113. next();
  114. });
  115. }
  116. else
  117. {
  118. i += 1;
  119. next();
  120. }
  121. }
  122. });
  123. })();
  124. });
  125. });
  126. }
  127. /**
  128. * Downloads the episode.
  129. */
  130. function download(cache: {[address: string]: number}, config: IConfig,
  131. task: IConfigTask, item: ISeriesEpisode,
  132. done: (err: any, ign: boolean) => void)
  133. {
  134. const episodeNumber = parseInt(item.episode, 10);
  135. const seasonNumber = item.volume;
  136. if ( (episodeNumber < task.episode_min.episode) ||
  137. (episodeNumber > task.episode_max.episode) )
  138. {
  139. return done(null, false);
  140. }
  141. const address = url.resolve(task.address, item.address);
  142. if (cache[address])
  143. {
  144. return done(null, false);
  145. }
  146. episode(config, address, (err, ignored) =>
  147. {
  148. if (err)
  149. {
  150. return done(err, false);
  151. }
  152. cache[address] = Date.now();
  153. done(null, ignored);
  154. });
  155. }
  156. /**
  157. * Requests the page and scrapes the episodes and series.
  158. */
  159. function pageScrape(config: IConfig, task: IConfigTask, done: (err: any, result?: ISeries) => void)
  160. {
  161. if (task.address[0] === '@')
  162. {
  163. log.info('Trying to fetch from ' + task.address.substr(1));
  164. const episodes: ISeriesEpisode[] = [];
  165. episodes.push({
  166. address: task.address.substr(1),
  167. episode: '',
  168. seasonName: '',
  169. volume: 0,
  170. retry: config.retry,
  171. });
  172. done(null, {episodes: episodes.reverse(), series: ''});
  173. }
  174. else
  175. {
  176. let episodeCount = 0;
  177. my_request.get(config, task.address, (err, result) => {
  178. if (err)
  179. {
  180. return done(err);
  181. }
  182. const $ = cheerio.load(result);
  183. const title = $('meta[itemprop=name]').attr('content');
  184. if (config.debug)
  185. {
  186. log.dumpToDebug('serie page', $.html());
  187. }
  188. if (!title) {
  189. if (config.debug)
  190. {
  191. log.dumpToDebug('missing title', task.address);
  192. }
  193. return done(new Error('Invalid page.(' + task.address + ')'));
  194. }
  195. log.info('Checking availability for ' + title);
  196. const episodes: ISeriesEpisode[] = [];
  197. if ($('.availability-notes-low').length)
  198. {
  199. log.warn('This serie may have georestriction and some missings episode (like some dubs)' +
  200. ' [Message: ' + $('.availability-notes-low').text() + '].');
  201. }
  202. if ($('.availability-notes-high').length)
  203. {
  204. log.warnMore('This serie probably have georestriction and will miss some episodes' +
  205. ' [Message: ' + $('.availability-notes-high').text() + '].');
  206. }
  207. $('.episode').each((i, el) => {
  208. if ($(el).children('img[src*=coming_soon]').length) {
  209. return;
  210. }
  211. const season_name = $(el).closest('ul').prev('a').text();
  212. const volume = /([0-9]+)\s*$/.exec($(el).closest('ul').prev('a').text());
  213. const regexp = languages.get_epregexp(config);
  214. const episode = regexp.exec($(el).children('.series-title').text());
  215. const url = $(el).attr('href');
  216. const igndub_re = languages.get_diregexp(config);
  217. if (config.ignoredub && (igndub_re.exec(season_name)))
  218. {
  219. return;
  220. }
  221. if ((!url) || (!episode))
  222. {
  223. return;
  224. }
  225. episodeCount += 1;
  226. episodes.push({
  227. address: url,
  228. episode: episode[1],
  229. seasonName: season_name,
  230. volume: volume ? parseInt(volume[0], 10) : 1,
  231. retry: config.retry,
  232. });
  233. });
  234. if (episodeCount === 0)
  235. {
  236. log.warn('No episodes found for ' + title + '. Could it be a movie?');
  237. }
  238. done(null, {episodes: episodes.reverse(), series: title});
  239. });
  240. }
  241. }