series.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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, address: string, done: (err: Error) => 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. page(config, address, (errP, page) =>
  40. {
  41. if (errP)
  42. {
  43. return done(errP);
  44. }
  45. let i = 0;
  46. (function next()
  47. {
  48. if (i >= page.episodes.length) return done(null);
  49. download(cache, config, address, page.episodes[i], (errD, ignored) =>
  50. {
  51. if (errD)
  52. {
  53. if (page.episodes[i].retry <= 0)
  54. {
  55. log.dispEpisode(config.filename, 'Error...', true);
  56. log.error(errD);
  57. log.error('Cannot fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
  58. '", please rerun later');
  59. /* Go to the next on the list */
  60. i += 1;
  61. }
  62. else
  63. {
  64. log.dispEpisode(config.filename, 'Error...', true);
  65. if ((config.verbose) || (config.debug))
  66. {
  67. if (config.debug)
  68. {
  69. log.dumpToDebug('series address', address);
  70. log.dumpToDebug('series error', errD.stack || errD);
  71. log.dumpToDebug('series data', JSON.stringify(page));
  72. }
  73. log.error(errD);
  74. }
  75. log.warn('Retrying to fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
  76. '" - Retry ' + page.episodes[i].retry + ' / ' + config.retry);
  77. page.episodes[i].retry -= 1;
  78. }
  79. next();
  80. }
  81. else
  82. {
  83. if ((ignored === false) || (ignored === undefined))
  84. {
  85. const newCache = JSON.stringify(cache, null, ' ');
  86. fs.writeFile(persistentPath, newCache, (errW: Error) =>
  87. {
  88. if (errW)
  89. {
  90. return done(errW);
  91. }
  92. i += 1;
  93. next();
  94. });
  95. }
  96. else
  97. {
  98. i += 1;
  99. next();
  100. }
  101. }
  102. });
  103. })();
  104. });
  105. });
  106. }
  107. /**
  108. * Downloads the episode.
  109. */
  110. function download(cache: {[address: string]: number}, config: IConfig,
  111. baseAddress: string, item: ISeriesEpisode,
  112. done: (err: Error, ign: boolean) => void)
  113. {
  114. const address = url.resolve(baseAddress, item.address);
  115. if (cache[address])
  116. {
  117. return done(null, false);
  118. }
  119. episode(config, address, (err, ignored) =>
  120. {
  121. if (err)
  122. {
  123. return done(err, false);
  124. }
  125. cache[address] = Date.now();
  126. done(null, ignored);
  127. });
  128. }
  129. /**
  130. * Requests the page and scrapes the episodes and series.
  131. */
  132. function page(config: IConfig, address: string, done: (err: Error, result?: ISeries) => void)
  133. {
  134. if (address[0] === '@')
  135. {
  136. log.info('Trying to fetch from ' + address.substr(1));
  137. const episodes: ISeriesEpisode[] = [];
  138. episodes.push({
  139. address: address.substr(1),
  140. episode: '',
  141. volume: 0,
  142. retry: config.retry,
  143. });
  144. done(null, {episodes: episodes.reverse(), series: ''});
  145. }
  146. else
  147. {
  148. let episodeCount = 0;
  149. my_request.get(config, address, (err, result) => {
  150. if (err) {
  151. return done(err);
  152. }
  153. const $ = cheerio.load(result);
  154. const title = $('span[itemprop=name]').text();
  155. if (!title) {
  156. if (config.debug)
  157. {
  158. log.dumpToDebug('inval page addr', address);
  159. log.dumpToDebug('inval page data', $);
  160. }
  161. return done(new Error('Invalid page.(' + address + ')'));
  162. }
  163. log.info('Checking availability for ' + title);
  164. const episodes: ISeriesEpisode[] = [];
  165. $('.episode').each((i, el) => {
  166. if ($(el).children('img[src*=coming_soon]').length) {
  167. return;
  168. }
  169. const volume = /([0-9]+)\s*$/.exec($(el).closest('ul').prev('a').text());
  170. const regexp = /Episode\s+((PV )?[S0-9][\-P0-9.]*[a-fA-F]?)\s*$/i;
  171. const episode = regexp.exec($(el).children('.series-title').text());
  172. const url = $(el).attr('href');
  173. if ((!url) || (!episode)) {
  174. return;
  175. }
  176. episodeCount += 1;
  177. episodes.push({
  178. address: url,
  179. episode: episode[1],
  180. volume: volume ? parseInt(volume[0], 10) : 1,
  181. retry: config.retry,
  182. });
  183. });
  184. if (episodeCount === 0)
  185. {
  186. log.warn('No episodes found for ' + title + '. Could it be a movie?');
  187. }
  188. done(null, {episodes: episodes.reverse(), series: title});
  189. });
  190. }
  191. }