series.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. 'use strict';
  2. import cheerio = require('cheerio');
  3. import episode from './episode';
  4. import fs = require('fs');
  5. const fse = 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. fse.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. return done(errD);
  54. }
  55. if ((ignored === false) || (ignored === undefined))
  56. {
  57. const newCache = JSON.stringify(cache, null, ' ');
  58. fs.writeFile(persistentPath, newCache, (errW: Error) =>
  59. {
  60. if (errW)
  61. {
  62. return done(errW);
  63. }
  64. i += 1;
  65. next();
  66. });
  67. }
  68. else
  69. {
  70. i += 1;
  71. next();
  72. }
  73. });
  74. })();
  75. });
  76. });
  77. }
  78. /**
  79. * Downloads the episode.
  80. */
  81. function download(cache: {[address: string]: number}, config: IConfig,
  82. baseAddress: string, item: ISeriesEpisode,
  83. done: (err: Error, ign: boolean) => void)
  84. {
  85. if (!filter(config, item))
  86. {
  87. return done(null, false);
  88. }
  89. const address = url.resolve(baseAddress, item.address);
  90. if (cache[address])
  91. {
  92. return done(null, false);
  93. }
  94. episode(config, address, (err, ignored) =>
  95. {
  96. if (err)
  97. {
  98. return done(err, false);
  99. }
  100. cache[address] = Date.now();
  101. done(null, ignored);
  102. });
  103. }
  104. /**
  105. * Filters the item based on the configuration.
  106. */
  107. function filter(config: IConfig, item: ISeriesEpisode)
  108. {
  109. // Filter on chapter.
  110. const episodeFilter = config.episode;
  111. // Filter on volume.
  112. const volumeFilter = config.volume;
  113. const currentEpisode = parseInt(item.episode, 10);
  114. const currentVolume = item.volume;
  115. if ( ( (episodeFilter > 0) && (currentEpisode <= episodeFilter) ) ||
  116. ( (episodeFilter < 0) && (currentEpisode >= -episodeFilter) ) ||
  117. ( (volumeFilter > 0) && (currentVolume <= volumeFilter ) ) ||
  118. ( (volumeFilter < 0) && (currentVolume >= -volumeFilter ) ) )
  119. {
  120. return false;
  121. }
  122. return true;
  123. }
  124. /**
  125. * Requests the page and scrapes the episodes and series.
  126. */
  127. function page(config: IConfig, address: string, done: (err: Error, result?: ISeries) => void)
  128. {
  129. if (address[0] === '@')
  130. {
  131. log.info('Trying to fetch from ' + address.substr(1));
  132. const episodes: ISeriesEpisode[] = [];
  133. episodes.push({
  134. address: address.substr(1),
  135. episode: '',
  136. volume: 0,
  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. });
  171. });
  172. if (episodeCount === 0)
  173. {
  174. log.warn("No episodes found for " + title + ". Could it be a movie?");
  175. }
  176. done(null, {episodes: episodes.reverse(), series: title});
  177. });
  178. }
  179. }