on_Snapshot__26_staticfile.bg.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #!/usr/bin/env node
  2. /**
  3. * Detect and download static files using CDP during initial request.
  4. *
  5. * This hook sets up CDP listeners BEFORE chrome_navigate to capture the
  6. * Content-Type from the initial response. If it's a static file (PDF, image, etc.),
  7. * it downloads the content directly using CDP.
  8. *
  9. * Usage: on_Snapshot__26_staticfile.bg.js --url=<url> --snapshot-id=<uuid>
  10. * Output: Downloads static file
  11. */
  12. const fs = require('fs');
  13. const path = require('path');
  14. // Add NODE_MODULES_DIR to module resolution paths if set
  15. if (process.env.NODE_MODULES_DIR) module.paths.unshift(process.env.NODE_MODULES_DIR);
  16. const puppeteer = require('puppeteer-core');
  17. // Import shared utilities from chrome_utils.js
  18. const {
  19. getEnvBool,
  20. getEnvInt,
  21. parseArgs,
  22. connectToPage,
  23. waitForPageLoaded,
  24. } = require('../chrome/chrome_utils.js');
  25. const PLUGIN_NAME = 'staticfile';
  26. const OUTPUT_DIR = '.';
  27. const CHROME_SESSION_DIR = '../chrome';
  28. // Content-Types that indicate static files
  29. const STATIC_CONTENT_TYPES = new Set([
  30. // Documents
  31. 'application/pdf',
  32. 'application/msword',
  33. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  34. 'application/vnd.ms-excel',
  35. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  36. 'application/vnd.ms-powerpoint',
  37. 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  38. 'application/rtf',
  39. 'application/epub+zip',
  40. // Images
  41. 'image/png',
  42. 'image/jpeg',
  43. 'image/gif',
  44. 'image/webp',
  45. 'image/svg+xml',
  46. 'image/x-icon',
  47. 'image/bmp',
  48. 'image/tiff',
  49. 'image/avif',
  50. 'image/heic',
  51. 'image/heif',
  52. // Audio
  53. 'audio/mpeg',
  54. 'audio/mp3',
  55. 'audio/wav',
  56. 'audio/flac',
  57. 'audio/aac',
  58. 'audio/ogg',
  59. 'audio/webm',
  60. 'audio/m4a',
  61. 'audio/opus',
  62. // Video
  63. 'video/mp4',
  64. 'video/webm',
  65. 'video/x-matroska',
  66. 'video/avi',
  67. 'video/quicktime',
  68. 'video/x-ms-wmv',
  69. 'video/x-flv',
  70. // Archives
  71. 'application/zip',
  72. 'application/x-tar',
  73. 'application/gzip',
  74. 'application/x-bzip2',
  75. 'application/x-xz',
  76. 'application/x-7z-compressed',
  77. 'application/x-rar-compressed',
  78. 'application/vnd.rar',
  79. // Data
  80. 'application/json',
  81. 'application/xml',
  82. 'text/csv',
  83. 'text/xml',
  84. 'application/x-yaml',
  85. // Executables/Binaries
  86. 'application/octet-stream',
  87. 'application/x-executable',
  88. 'application/x-msdos-program',
  89. 'application/x-apple-diskimage',
  90. 'application/vnd.debian.binary-package',
  91. 'application/x-rpm',
  92. // Other
  93. 'application/x-bittorrent',
  94. 'application/wasm',
  95. ]);
  96. const STATIC_CONTENT_TYPE_PREFIXES = [
  97. 'image/',
  98. 'audio/',
  99. 'video/',
  100. 'application/zip',
  101. 'application/x-',
  102. ];
  103. // Global state
  104. let originalUrl = '';
  105. let detectedContentType = null;
  106. let isStaticFile = false;
  107. let downloadedFilePath = null;
  108. let downloadError = null;
  109. let page = null;
  110. let browser = null;
  111. function isStaticContentType(contentType) {
  112. if (!contentType) return false;
  113. const ct = contentType.split(';')[0].trim().toLowerCase();
  114. // Check exact match
  115. if (STATIC_CONTENT_TYPES.has(ct)) return true;
  116. // Check prefixes
  117. for (const prefix of STATIC_CONTENT_TYPE_PREFIXES) {
  118. if (ct.startsWith(prefix)) return true;
  119. }
  120. return false;
  121. }
  122. function sanitizeFilename(str, maxLen = 200) {
  123. return str
  124. .replace(/[^a-zA-Z0-9._-]/g, '_')
  125. .slice(0, maxLen);
  126. }
  127. function getFilenameFromUrl(url) {
  128. try {
  129. const pathname = new URL(url).pathname;
  130. const filename = path.basename(pathname) || 'downloaded_file';
  131. return sanitizeFilename(filename);
  132. } catch (e) {
  133. return 'downloaded_file';
  134. }
  135. }
  136. function normalizeUrl(url) {
  137. try {
  138. const parsed = new URL(url);
  139. let path = parsed.pathname || '';
  140. if (path === '/') path = '';
  141. return `${parsed.origin}${path}`;
  142. } catch (e) {
  143. return url;
  144. }
  145. }
  146. async function setupStaticFileListener() {
  147. const timeout = getEnvInt('STATICFILE_TIMEOUT', 30) * 1000;
  148. // Connect to Chrome page using shared utility
  149. const connection = await connectToPage({
  150. chromeSessionDir: CHROME_SESSION_DIR,
  151. timeoutMs: timeout,
  152. puppeteer,
  153. });
  154. browser = connection.browser;
  155. page = connection.page;
  156. // Track the first response to check Content-Type
  157. let firstResponseHandled = false;
  158. page.on('response', async (response) => {
  159. if (firstResponseHandled) return;
  160. try {
  161. const url = response.url();
  162. const headers = response.headers();
  163. const contentType = headers['content-type'] || '';
  164. const status = response.status();
  165. // Only process the main document response
  166. if (normalizeUrl(url) !== normalizeUrl(originalUrl)) return;
  167. if (status < 200 || status >= 300) return;
  168. firstResponseHandled = true;
  169. detectedContentType = contentType.split(';')[0].trim();
  170. console.error(`Detected Content-Type: ${detectedContentType}`);
  171. // Check if it's a static file
  172. if (!isStaticContentType(detectedContentType)) {
  173. console.error('Not a static file, skipping download');
  174. return;
  175. }
  176. isStaticFile = true;
  177. console.error('Static file detected, downloading...');
  178. // Download the file
  179. const maxSize = getEnvInt('STATICFILE_MAX_SIZE', 1024 * 1024 * 1024); // 1GB default
  180. const buffer = await response.buffer();
  181. if (buffer.length > maxSize) {
  182. downloadError = `File too large: ${buffer.length} bytes > ${maxSize} max`;
  183. return;
  184. }
  185. // Determine filename
  186. let filename = getFilenameFromUrl(url);
  187. // Check content-disposition header for better filename
  188. const contentDisp = headers['content-disposition'] || '';
  189. if (contentDisp.includes('filename=')) {
  190. const match = contentDisp.match(/filename[*]?=["']?([^"';\n]+)/);
  191. if (match) {
  192. filename = sanitizeFilename(match[1].trim());
  193. }
  194. }
  195. const outputPath = path.join(OUTPUT_DIR, filename);
  196. fs.writeFileSync(outputPath, buffer);
  197. downloadedFilePath = filename;
  198. console.error(`Static file downloaded (${buffer.length} bytes): ${filename}`);
  199. } catch (e) {
  200. downloadError = `${e.name}: ${e.message}`;
  201. console.error(`Error downloading static file: ${downloadError}`);
  202. }
  203. });
  204. return { browser, page };
  205. }
  206. function handleShutdown(signal) {
  207. console.error(`\nReceived ${signal}, emitting final results...`);
  208. let result;
  209. if (!detectedContentType) {
  210. // No Content-Type detected (shouldn't happen, but handle it)
  211. result = {
  212. type: 'ArchiveResult',
  213. status: 'skipped',
  214. output_str: 'No Content-Type detected',
  215. plugin: PLUGIN_NAME,
  216. };
  217. } else if (!isStaticFile) {
  218. // Not a static file (normal case for HTML pages)
  219. result = {
  220. type: 'ArchiveResult',
  221. status: 'skipped',
  222. output_str: `Not a static file (Content-Type: ${detectedContentType})`,
  223. plugin: PLUGIN_NAME,
  224. content_type: detectedContentType,
  225. };
  226. } else if (downloadError) {
  227. // Static file but download failed
  228. result = {
  229. type: 'ArchiveResult',
  230. status: 'failed',
  231. output_str: downloadError,
  232. plugin: PLUGIN_NAME,
  233. content_type: detectedContentType,
  234. };
  235. } else if (downloadedFilePath) {
  236. // Static file downloaded successfully
  237. result = {
  238. type: 'ArchiveResult',
  239. status: 'succeeded',
  240. output_str: downloadedFilePath,
  241. plugin: PLUGIN_NAME,
  242. content_type: detectedContentType,
  243. };
  244. } else {
  245. // Static file detected but no download happened (unexpected)
  246. result = {
  247. type: 'ArchiveResult',
  248. status: 'failed',
  249. output_str: 'Static file detected but download did not complete',
  250. plugin: PLUGIN_NAME,
  251. content_type: detectedContentType,
  252. };
  253. }
  254. console.log(JSON.stringify(result));
  255. process.exit(0);
  256. }
  257. async function main() {
  258. const args = parseArgs();
  259. const url = args.url;
  260. const snapshotId = args.snapshot_id;
  261. if (!url || !snapshotId) {
  262. console.error('Usage: on_Snapshot__26_staticfile.bg.js --url=<url> --snapshot-id=<uuid>');
  263. process.exit(1);
  264. }
  265. originalUrl = url;
  266. if (!getEnvBool('STATICFILE_ENABLED', true)) {
  267. console.error('Skipping (STATICFILE_ENABLED=False)');
  268. console.log(JSON.stringify({type: 'ArchiveResult', status: 'skipped', output_str: 'STATICFILE_ENABLED=False'}));
  269. process.exit(0);
  270. }
  271. const timeout = getEnvInt('STATICFILE_TIMEOUT', 30) * 1000;
  272. // Register signal handlers for graceful shutdown
  273. process.on('SIGTERM', () => handleShutdown('SIGTERM'));
  274. process.on('SIGINT', () => handleShutdown('SIGINT'));
  275. try {
  276. // Set up static file listener BEFORE navigation
  277. await setupStaticFileListener();
  278. // Wait for chrome_navigate to complete (non-fatal)
  279. try {
  280. await waitForPageLoaded(CHROME_SESSION_DIR, timeout * 4, 500);
  281. if (!detectedContentType && page) {
  282. try {
  283. const inferred = await page.evaluate(() => document.contentType || '');
  284. if (inferred) {
  285. detectedContentType = inferred.split(';')[0].trim();
  286. if (isStaticContentType(detectedContentType)) {
  287. isStaticFile = true;
  288. }
  289. }
  290. } catch (e) {
  291. // Best-effort only
  292. }
  293. }
  294. } catch (e) {
  295. console.error(`WARN: ${e.message}`);
  296. }
  297. // Keep process alive until killed by cleanup
  298. // console.error('Static file detection complete, waiting for cleanup signal...');
  299. // Keep the process alive indefinitely
  300. await new Promise(() => {}); // Never resolves
  301. } catch (e) {
  302. const error = `${e.name}: ${e.message}`;
  303. console.error(`ERROR: ${error}`);
  304. console.log(JSON.stringify({
  305. type: 'ArchiveResult',
  306. status: 'failed',
  307. output_str: error,
  308. }));
  309. process.exit(1);
  310. }
  311. }
  312. main().catch(e => {
  313. console.error(`Fatal error: ${e.message}`);
  314. process.exit(1);
  315. });