-
Notifications
You must be signed in to change notification settings - Fork 8
/
Scoop.js
1532 lines (1321 loc) · 46.3 KB
/
Scoop.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference path="./options.types.js" />
import os from 'os'
import { readFile, rm, readdir, mkdir, mkdtemp, access } from 'fs/promises'
import { constants as fsConstants } from 'node:fs'
import { createHash } from 'crypto'
import log from 'loglevel'
import logPrefix from 'loglevel-plugin-prefix'
import nunjucks from 'nunjucks'
import { Address4, Address6 } from '@laverdet/beaugunderson-ip-address'
import { v4 as uuidv4 } from 'uuid'
import { chromium } from 'playwright'
import { getOSInfo } from 'get-os-info'
import { exec } from './utils/exec.js'
import { ScoopGeneratedExchange } from './exchanges/index.js'
import { castBlocklistMatcher, searchBlocklistFor } from './utils/blocklist.js'
import * as CONSTANTS from './constants.js'
import * as intercepters from './intercepters/index.js'
import * as exporters from './exporters/index.js'
import * as importers from './importers/index.js'
import { filterOptions, defaults } from './options.js'
import { formatErrorMessage } from './utils/formatErrorMessage.js'
nunjucks.configure(CONSTANTS.TEMPLATES_PATH)
/**
* @class Scoop
*
* @classdesc
* Experimental single-page web archiving library using Playwright.
* Uses a proxy to allow for comprehensive and raw network interception.
*
* @example
* import { Scoop } from "scoop";
*
* const myCapture = await Scoop.capture("https://example.com");
* const myArchive = await myCapture.toWARC();
*/
export class Scoop {
/** @type {string} */
id = uuidv4()
/**
* Enum-like states that the capture occupies.
* @readonly
* @enum {number}
*/
static states = {
INIT: 0,
SETUP: 1,
CAPTURE: 2,
COMPLETE: 3,
PARTIAL: 4,
FAILED: 5,
RECONSTRUCTED: 6
}
/**
* Current state of the capture.
* Should only contain states defined in `states`.
* @type {number}
*/
state = Scoop.states.INIT
/**
* URL to capture.
* @type {string}
*/
url = ''
/**
* URL to capture, resolved to account for redirects.
* Populated during non-web content detection step.
* @type {string}
*/
targetUrlResolved = ''
/**
* Is the target url a web page?
* Assumed `true` until detected otherwise.
* @type {boolean}
*/
targetUrlIsWebPage = true
/**
* Content-type of the target url.
* Assumed `text/html` unless detected otherwise.
* @type {string}
*/
targetUrlContentType = 'text/html; charset=utf-8'
/**
* Current settings.
* @type {ScoopOptions}
*/
options = {}
/**
* Returns a copy of Scoop's default settings.
* @type {ScoopOptions}
*/
static get defaults () {
return Object.assign({}, defaults)
}
/**
* Array of HTTP exchanges that constitute the capture.
* Only contains generated exchanged until `teardown()`.
* @type {ScoopExchange[]}
*/
exchanges = []
/**
* Logger.
* Logging level controlled via the `logLevel` option.
* @type {?log.Logger}
*/
log = log
/**
* Path to the capture-specific temporary folder created by `setup()`.
* Will be a child folder of the path defined in `CONSTANTS.TMP_PATH`.
* @type {?string}
*/
captureTmpFolderPath = null
/**
* The time at which the page was crawled.
* @type {Date}
*/
startedAt
/**
* The Playwright browser instance for this capture.
* @type {Browser}
*/
#browser
/**
* Reference to the intercepter chosen for capture.
* @type {intercepters.ScoopIntercepter}
*/
intercepter
/**
* A mirror of options.blocklist with IPs parsed for matching
* @type {Array.<String|RegEx|Address4|Address6>}
*/
blocklist = []
/**
* Captures information about the context of this capture.
* @type {{
* captureIp: ?string,
* userAgent: ?string,
* software: ?string,
* version: ?string,
* osType: ?string,
* osName: ?string,
* osVersion: ?string,
* cpuArchitecture: ?string,
* blockedRequests: Array.<{match: string, rule: string}>,
* certificates: Array.<{host: string, pem: string}>,
* ytDlpHash: string,
* cripHash: string,
* options: ScoopOptions,
* }}
*/
provenanceInfo = {
blockedRequests: [],
certificates: []
}
/**
* Info extracted by the browser about the page on initial load
* @type {{
* title: ?string,
* description: ?string,
* url: ?string,
* faviconUrl: ?string,
* favicon: ?Buffer
* }}
*/
pageInfo = {}
/**
* @param {string} url - Must be a valid HTTP(S) url.
* @param {?ScoopOptions} [options={}] - See {@link ScoopOptions}.
*/
constructor (url, options = {}) {
this.options = filterOptions(options)
this.blocklist = this.options.blocklist.map(castBlocklistMatcher)
this.url = this.filterUrl(url)
this.targetUrlResolved = this.url
// Logging setup (level, output formatting)
logPrefix.reg(this.log)
logPrefix.apply(log, {
format (level, _name, timestamp) {
const timestampColor = CONSTANTS.LOGGING_COLORS.DEFAULT
const msgColor = CONSTANTS.LOGGING_COLORS[level.toUpperCase()]
return `${timestampColor(`[${timestamp}]`)} ${msgColor(level)}`
}
})
this.log.setLevel(this.options.logLevel)
this.intercepter = new intercepters[this.options.intercepter](this)
}
/**
* Instantiates a Scoop instance and runs the capture
*
* @param {string} url - Must be a valid HTTP(S) url.
* @param {ScoopOptions} [options={}] - See {@link ScoopOptions}.
* @returns {Promise<Scoop>}
*/
static async capture (url, options) {
const instance = new Scoop(url, options)
await instance.capture()
return instance
}
/**
* Main capture process (internal).
* @returns {Promise<void>}
* @private
*/
async capture () {
const options = this.options
/**
* @typedef {object} CaptureStep
* @property {string} name
* @property {?function} setup
* @property {?function} main
* @property {?boolean} alwaysRun - If true, this step will run regardless of capture-level time / size constraints.
* @property {?boolean} webPageOnly - If true, this step will only run if the target url is a web page. Takes precedence over `alwaysRun`.
*/
/** @type {CaptureStep[]} */
const steps = []
//
// Prepare capture steps
//
// Push step: early detection of non-web resources
steps.push({
name: 'Out-of-browser detection and capture of non-web resource',
alwaysRun: true,
webPageOnly: false,
main: async (page) => {
await this.#detectAndCaptureNonWebContent(page)
}
})
// Push step: Wait for initial page load
steps.push({
name: 'Wait for initial page load',
alwaysRun: false,
webPageOnly: true,
main: async (page) => {
await page.goto(this.url, { waitUntil: 'load', timeout: options.loadTimeout })
}
})
// Push step: Capture page info
steps.push({
name: 'Capture page info',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: true,
main: async (page) => {
await this.#capturePageInfo(page)
}
})
// Push step: Browser scripts
if (
options.grabSecondaryResources ||
options.autoPlayMedia ||
options.runSiteSpecificBehaviors ||
options.autoScroll
) {
steps.push({
name: 'Browser scripts',
alwaysRun: false,
webPageOnly: true,
setup: async (page) => {
// Determine path of `behaviors.js`
let behaviorsPath = './node_modules/browsertrix-behaviors/dist/behaviors.js'
try {
await access(behaviorsPath)
} catch (_err) {
behaviorsPath = `${CONSTANTS.BASE_PATH}/node_modules/browsertrix-behaviors/dist/behaviors.js`
}
await page.addInitScript({
path: behaviorsPath
})
await page.addInitScript({
content: `
self.__bx_behaviors.init({
autofetch: ${options.grabSecondaryResources},
autoplay: ${options.autoPlayMedia},
autoscroll: ${options.autoScroll},
siteSpecific: ${options.runSiteSpecificBehaviors},
timeout: ${options.behaviorsTimeout}
});`
})
},
main: async (page) => {
await Promise.allSettled(
page.frames().map((frame) => frame.evaluate('self.__bx_behaviors.run()'))
)
}
})
}
// Push step: Wait for network idle
steps.push({
name: 'Wait for network idle',
alwaysRun: false,
webPageOnly: true,
main: async (page) => {
await page.waitForLoadState('networkidle', { timeout: options.networkIdleTimeout })
}
})
// Push step: scroll up
steps.push({
name: 'Scroll-up',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: true,
main: async (page) => {
await Promise.race([
page.evaluate(() => window.scrollTo(0, 0)),
new Promise(resolve => setTimeout(resolve, 2500)) // Only wait for up to 2.5s for scroll up to happen
])
}
})
// Push step: Screenshot
if (options.screenshot) {
steps.push({
name: 'Screenshot',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: true,
main: async (page) => {
const url = 'file:///screenshot.png'
const httpHeaders = new Headers({ 'content-type': 'image/png' })
const body = await page.screenshot({ fullPage: true, timeout: 5000 })
const isEntryPoint = true
const description = `Capture Time Screenshot of ${this.url}`
this.addGeneratedExchange(url, httpHeaders, body, isEntryPoint, description)
}
})
}
// Push step: DOM Snapshot
if (options.domSnapshot) {
steps.push({
name: 'DOM snapshot',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: true,
main: async (page) => {
const url = 'file:///dom-snapshot.html'
const httpHeaders = new Headers({
'content-type': 'text/html',
'content-disposition': 'Attachment'
})
const body = Buffer.from(await page.content())
const isEntryPoint = true
const description = `Capture Time DOM Snapshot of ${this.url}`
this.addGeneratedExchange(url, httpHeaders, body, isEntryPoint, description)
}
})
}
// Push step: PDF Snapshot
if (options.pdfSnapshot) {
steps.push({
name: 'PDF snapshot',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: true,
main: async (page) => {
await this.#takePdfSnapshot(page)
}
})
}
// Push step: Capture of in-page videos as attachment
if (options.captureVideoAsAttachment) {
steps.push({
name: 'Out-of-browser capture of video as attachment (if any)',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: true,
main: async () => {
await this.#captureVideoAsAttachment()
}
})
}
// Push step: certs capture
if (options.captureCertificatesAsAttachment) {
steps.push({
name: 'Capturing certificates info',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: false,
main: async () => {
await this.#captureCertificatesAsAttachment()
}
})
}
// Push step: Provenance summary
if (options.provenanceSummary) {
steps.push({
name: 'Provenance summary',
alwaysRun: options.attachmentsBypassLimits,
webPageOnly: false,
main: async (page) => {
await this.#captureProvenanceInfo(page)
}
})
}
//
// Initialize capture
//
let page
try {
page = await this.setup()
this.log.info(`Scoop ${CONSTANTS.VERSION} was initialized with the following options:`)
this.log.info(options)
this.log.info(`🍨 Starting capture of ${this.url}.`)
this.state = Scoop.states.CAPTURE
} catch (err) {
this.log.error(`An error occurred during capture setup (${formatErrorMessage(err)}).`)
this.log.trace(err)
this.state = Scoop.states.FAILED
return // exit early if the browser and proxy couldn't be launched
}
//
// Call `setup()` method of steps that have one
//
for (const step of steps.filter((step) => step.setup)) {
await step.setup(page)
}
//
// Run capture steps
//
let i = -1
while (i++ < steps.length - 1) {
const step = steps[i]
//
// Edge cases requiring immediate interruption
//
let shouldStop = false
// Page is a web document and is still "about:blank" after step #2
if (this.targetUrlIsWebPage && i > 1 && page.url() === 'about:blank') {
this.log.error('Navigation to page failed (about:blank).')
shouldStop = true
}
// Page was closed
if (this.targetUrlIsWebPage && page.isClosed()) {
this.log.error('Page closed before it could be captured.')
shouldStop = true
}
if (shouldStop) {
this.state = Scoop.states.FAILED
break
}
//
// If capture was not interrupted, run steps
//
try {
// Only if state is `CAPTURE`, unless `alwaysRun` is set for step
let shouldRun = this.state === Scoop.states.CAPTURE || step.alwaysRun === true
// BUT: `webPageOnly` takes precedence - allows for skipping unnecessary steps when capturing non-web content
if (this.targetUrlIsWebPage === false && step.webPageOnly) {
shouldRun = false
}
if (shouldRun === false) {
this.log.warn(`STEP [${i + 1}/${steps.length}]: ${step.name} (skipped)`)
continue
}
this.log.info(`STEP [${i + 1}/${steps.length}]: ${step.name}`)
/** @type {?function} */
let stateCheckInterval = null
await Promise.race([
// Run current step
step.main(page),
// Check capture state every second - so current step can be interrupted if state changes
new Promise(resolve => {
stateCheckInterval = setInterval(() => {
if (this.state !== Scoop.states.CAPTURE && step.alwaysRun !== true) {
resolve(true)
}
}, 1000)
})
])
clearInterval(stateCheckInterval) // Clear "state checker" interval in case it is still running
//
// On error:
// - Only deliver full trace if error is not due to time / size limit reached.
//
} catch (err) {
if (this.state === Scoop.states.PARTIAL) {
this.log.warn(`STEP [${i + 1}/${steps.length}]: ${step.name} - ended due to max time or size reached.`)
} else {
this.log.warn(`STEP [${i + 1}/${steps.length}]: ${step.name} - failed`)
this.log.trace(err)
}
}
}
//
// Post-capture
//
if (this.state === Scoop.states.CAPTURE) {
this.state = Scoop.states.COMPLETE
}
await this.teardown()
}
/**
* Sets up the proxy and Playwright resources, creates capture-specific temporary folder.
*
* @returns {Promise<Page>} Resolves to a Playwright [Page]{@link https://playwright.dev/docs/api/class-page} object
*/
async setup () {
this.startedAt = new Date()
this.state = Scoop.states.SETUP
const options = this.options
// Create "base" temporary folder if it doesn't exist
let tmpDirExists = false
try {
await access(CONSTANTS.TMP_PATH)
tmpDirExists = true
} catch (_err) {
this.log.info(`Base temporary folder ${CONSTANTS.TMP_PATH} does not exist or cannot be accessed. Scoop will attempt to create it.`)
}
if (!tmpDirExists) {
try {
await mkdir(CONSTANTS.TMP_PATH)
await access(CONSTANTS.TMP_PATH, fsConstants.W_OK)
tmpDirExists = true
} catch (err) {
this.log.warn(`Error while creating base temporary folder ${CONSTANTS.TMP_PATH} ((${formatErrorMessage(err)})).`)
this.log.trace(err)
}
}
// Create captures-specific temporary folder under base temporary folder
try {
this.captureTmpFolderPath = await mkdtemp(CONSTANTS.TMP_PATH)
this.captureTmpFolderPath += '/'
await access(this.captureTmpFolderPath, fsConstants.W_OK)
this.log.info(`Capture-specific temporary folder ${this.captureTmpFolderPath} created.`)
} catch (err) {
try {
await rm(this.captureTmpFolderPath)
} catch { /* Ignore: Deletes the capture-specific folder if it was created, if possible. */ }
throw new Error(`Scoop was unable to create a capture-specific temporary folder.\n${err}`)
}
// Initialize intercepter (proxy)
await this.intercepter.setup()
// Playwright init + pass proxy info to Chromium
const userAgent = chromium._playwright.devices['Desktop Chrome'].userAgent + options.userAgentSuffix
this.provenanceInfo.userAgent = userAgent
this.log.info(`User Agent used for capture: ${userAgent}`)
this.#browser = await chromium.launch({
headless: options.headless
})
const context = await this.#browser.newContext({
...this.intercepter.contextOptions,
userAgent,
// NOTE:
// This is a temporary workaround.
// Most browsers now accept zstd, but part of the web archiving stack (indexing, playback ...) is not fully ready to handle it yet.
// This line wants to be removed once the ecosystem is ready for zstd.
// More on zstd: https://datatracker.ietf.org/doc/html/rfc8878
// TODO: Remove whenever possible.
extraHTTPHeaders: {
'Accept-Encoding': 'gzip, compress, deflate, br'
}
})
const page = await context.newPage()
page.setViewportSize({
width: options.captureWindowX,
height: options.captureWindowY
})
// Enforce capture timeout
const captureTimeoutTimer = setTimeout(() => {
this.log.info(`captureTimeout of ${options.captureTimeout}ms reached. Ending further capture.`)
this.state = Scoop.states.PARTIAL
this.intercepter.recordExchanges = false
}, options.captureTimeout)
this.#browser.on('disconnected', () => {
clearTimeout(captureTimeoutTimer)
})
return page
}
/**
* Tears down Playwright, intercepter, and capture-specific temporary folder.
* @returns {Promise<void>}
*/
async teardown () {
this.log.info('Closing browser and intercepter')
await this.intercepter.teardown()
await this.#browser.close()
this.exchanges = this.intercepter.exchanges.concat(this.exchanges)
this.log.info(`Clearing capture-specific temporary folder ${this.captureTmpFolderPath}`)
await rm(this.captureTmpFolderPath, { recursive: true, force: true })
}
/**
* Assesses whether `this.url` leads to a non-web resource and, if so:
* - Captures it via a curl behind our proxy
* - Sets capture state to `PARTIAL`
*
* Populates `this.targetUrlIsWebPage` and `this.targetUrlContentType`.
*
* @param {Page} page - A Playwright [Page]{@link https://playwright.dev/docs/api/class-page} object
* @returns {Promise<void>}
* @private
*/
async #detectAndCaptureNonWebContent (page) {
/** @type {?string} */
let contentType = null
/** @type {?number} */
let contentLength = null
/**
* Time spent on the initial HEAD request, in ms.
* @type {?number}
*/
let headRequestTimeMs = null
//
// Is `this.url` leading to a text/html resource?
//
try {
const before = new Date()
// Timeout = a 10th of captureTimeout if >= 1 second, 1 second otherwise.
let timeout = this.options.captureTimeout / 10
if (timeout < 1000) {
timeout = 1000
}
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), timeout)
const headRequest = await fetch(this.url, {
method: 'HEAD',
signal: controller.signal
})
clearTimeout(timeoutId)
const after = new Date()
headRequestTimeMs = after - before
this.targetUrlResolved = headRequest.url
contentType = headRequest.headers.get('Content-Type')
contentLength = headRequest.headers.get('Content-Length')
} catch (err) {
this.log.trace(err)
this.log.warn('Resource type detection failed - skipping')
return
}
// Capture content-type
if (contentType) {
this.targetUrlContentType = contentType
}
// If text/html or no content-type, bail from non-web content capture process.
// Scoop.capture will go based on the value of `this.targetUrlIsWebPage`.
if (!contentType) {
this.log.info('Requested URL is assumed to be a web page (no content-type found)')
return
}
if (contentType?.startsWith('text/html')) {
this.log.info('Requested URL is a web page')
return
}
this.targetUrlIsWebPage = false
this.log.warn(`Requested URL is not a web page (detected: ${contentType})`)
this.log.info('Scoop will attempt to capture this resource out-of-browser')
//
// Check if curl is present
//
try {
await exec('curl', ['-V'])
} catch (err) {
this.log.trace(err)
this.log.warn('curl is not present on this system - skipping')
return
}
//
// Capture using curl behind proxy
//
try {
const userAgent = this.provenanceInfo.userAgent
let timeout = this.options.captureTimeout - headRequestTimeMs
if (timeout < 1000) {
timeout = 1000
}
const curlOptions = [
this.url,
'--header', `"User-Agent: ${userAgent}"`,
'--output', '/dev/null',
'--proxy', `'http://${this.options.proxyHost}:${this.options.proxyPort}'`,
'--insecure', // TBD: SSL checks are delegated to the proxy
'--location',
// This will be the only capture step running:
// use all available time - time spent on first request
'--max-time', Math.floor(timeout / 1000)
]
await exec('curl', curlOptions, { timeout })
} catch (err) {
this.log.trace(err)
}
//
// Report on results and:
// - Set capture state to PARTIAL if _anything_ was captured.
// - Leave capture state to CAPTURE otherwise.
//
if (this.intercepter.exchanges.length > 0) {
const intercepted = this.intercepter.exchanges[0]?.response?.body?.byteLength
if (intercepted === Number(contentLength)) {
this.log.info(`Resource fully captured (${contentLength} bytes)`)
} else {
this.log.warn(`Resource partially captured (${intercepted} of ${contentLength} bytes)`)
}
this.state = Scoop.states.PARTIAL
} else {
this.log.warn('Resource could not be captured')
}
}
/**
* Tries to populate `this.pageInfo`.
* Captures page title, description, url and favicon url directly from the browser.
* Will attempt to find the favicon in intercepted exchanges if running in headfull mode, and request it out-of-band otherwise.
*
* @param {Page} page - A Playwright [Page]{@link https://playwright.dev/docs/api/class-page} object
* @returns {Promise<void>}
* @private
*/
async #capturePageInfo (page) {
this.pageInfo = await page.evaluate(() => {
return {
title: document.title,
description: document.querySelector("meta[name='description']")?.content,
url: window.location.href,
faviconUrl: document.querySelector("link[rel*='icon']")?.href,
favicon: null
}
})
//
// Favicon processing
//
// Not needed if:
// - No favicon URL found
// - Favicon url is not an http(s) URL
if (!this.pageInfo?.faviconUrl) {
return
}
if (!this.pageInfo.faviconUrl.startsWith('http')) {
return
}
// If `headless`: request the favicon using curl so it's added to the exchanges list.
if (this.options.headless) {
try {
const userAgent = this.provenanceInfo.userAgent
const timeout = 1000
const curlOptions = [
this.pageInfo.faviconUrl,
'--header', `"User-Agent: ${userAgent}"`,
'--output', '/dev/null',
'--proxy', `'http://${this.options.proxyHost}:${this.options.proxyPort}'`,
'--insecure', // TBD: SSL checks are delegated to the proxy
'--max-time', Math.floor(timeout / 1000)
]
await exec('curl', curlOptions, { timeout })
} catch (err) {
this.log.warn(`Could not fetch favicon at url ${this.pageInfo.faviconUrl}.`)
this.log.trace(err)
}
}
// Look for favicon in exchanges
for (const exchange of this.intercepter.exchanges) {
if (exchange?.url && exchange.url === this.pageInfo.faviconUrl && exchange?.response?.body) {
this.pageInfo.favicon = exchange.response.body
}
}
}
/**
* Runs `yt-dlp` on the current url to try and capture:
* - The "main" video(s) of the current page (`file:///video-extracted-x.mp4`)
* - Associated subtitles (`file:///video-extracted-x.LOCALE.vtt`)
* - Associated meta data (`file:///video-extracted-metadata.json`)
*
* These elements are added as "attachments" to the archive, for context / playback fallback purposes.
* A summary file and entry point, `file:///video-extracted-summary.html`, will be generated in the process.
*
* @returns {Promise<void>}
* @private
*/
async #captureVideoAsAttachment () {
const videoFilename = `${this.captureTmpFolderPath}video-extracted-%(autonumber)d.mp4`
const ytDlpPath = this.options.ytDlpPath
let metadataRaw = null
let metadataParsed = null
let videoSaved = false
let metadataSaved = false
let subtitlesSaved = false
/**
* Key: video filename (ex: "video-extracted-1").
* Value: array of subtitle locales (ex: ["en-US", "fr-FR"])
* @type {Object<string, string[]>}
*/
const availableVideosAndSubtitles = {}
//
// yt-dlp health check
//
try {
const version = await exec(ytDlpPath, ['--version']).then((v) => v.trim())
if (!version.match(/^[0-9]{4}\.[0-9]{2}\.[0-9]{2}$/)) {
throw new Error(`Unknown version: ${version}`)
}
} catch (err) {
this.log.trace(err)
throw new Error('"yt-dlp" executable is not available or cannot be executed.')
}
//
// Try and pull video(s) and meta data from url
//
try {
this.intercepter.recordExchanges = false
const dlpOptions = [
'--dump-json', // Will return JSON meta data via stdout
'--no-simulate', // Forces download despite `--dump-json`
'--no-warnings', // Prevents pollution of stdout
'--no-progress', // (Same as above)
'--write-subs', // Try to pull subs
'--sub-langs', 'all',
'--format', 'mp4', // Forces .mp4 format
'--output', `"${videoFilename}"`,
'--no-check-certificate',
'--proxy', `'http://${this.options.proxyHost}:${this.options.proxyPort}'`,
this.url
]
const spawnOptions = {
timeout: this.options.captureVideoAsAttachmentTimeout,
maxBuffer: 1024 * 1024 * 128
}
metadataRaw = await exec(ytDlpPath, dlpOptions, spawnOptions)
} catch (err) {
this.log.trace(err)
throw new Error(`No video found in ${this.url}.`)
} finally {
this.intercepter.recordExchanges = true
}
//
// Add available video(s) and subtitles to exchanges
//
for (const file of await readdir(this.captureTmpFolderPath)) {
// Video
if (file.startsWith('video-extracted-') && file.endsWith('.mp4')) {
try {
const url = `file:///${file}`
const httpHeaders = new Headers({ 'content-type': 'video/mp4' })
const body = await readFile(`${this.captureTmpFolderPath}${file}`)
const isEntryPoint = false // TODO: Reconsider whether this should be an entry point.
this.addGeneratedExchange(url, httpHeaders, body, isEntryPoint)
videoSaved = true
// Push to map of available videos and subtitles
const index = file.replace('.mp4', '')
if (!(index in availableVideosAndSubtitles)) {
availableVideosAndSubtitles[index] = []
}
} catch (err) {
this.log.warn(`Error while creating exchange for ${file}.`)
this.log.trace(err)
}
}
// Subtitles
if (file.startsWith('video-extracted-') && file.endsWith('.vtt')) {
try {
const url = `file:///${file}`
const httpHeaders = new Headers({ 'content-type': 'text/vtt' })
const body = await readFile(`${this.captureTmpFolderPath}${file}`)
const isEntryPoint = false
const locale = file.split('.')[1]
// Example of valid locales: "en", "en-US"
if (!locale.match(/^[a-z]{2}$/) && !locale.match(/[a-z]{2}-[A-Z]{2}/)) {
continue
}
this.addGeneratedExchange(url, httpHeaders, body, isEntryPoint)
subtitlesSaved = true
// Push to map of available videos and subtitles
const index = file.replace('.vtt', '').replace(`.${locale}`, '')
if (!(index in availableVideosAndSubtitles)) {
availableVideosAndSubtitles[index] = []
}
availableVideosAndSubtitles[index].push(locale)
} catch (err) {
this.log.warn(`Error while creating exchange for ${file}.`)
this.log.trace(err)
}
}
}
//
// Try to add metadata to exchanges
//