series.ts 5.0 KB

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