🌳
pt0/peatsite/updateScreenshotsAI.mjs
1import { chromium } from 'playwright'
2import { mkdirSync, existsSync } from 'fs'
3import { join, relative } from 'path'
6import { ptDir } from '../serverF/ptDirF.mts'
9const getScreenshotUrl = (site, ep) => {
10 if (site.screenshotUrl) return site.screenshotUrl
11 if (site.href) return site.href
12 const hostname = ep.nonWcHostname || ep.wcHostname
13 if (hostname && !hostname.includes('*')) return `https://${hostname}`
14 return null
17const getBasicAuthHeader = (site) => {
18 if (!site.basicAuth) return null
19 const {user, passwordSecretName} = site.basicAuth
20 const password = getPlainSecOpt(passwordSecretName)
21 if (!password) return null
22 return 'Basic ' + Buffer.from(`${user}:${password}`).toString('base64')
25const captureScreenshot = async (page, url, destPath) => {
26 await page.goto(url, {timeout: 30000})
27 await page.waitForLoadState('networkidle', {timeout: 15000}).catch(() => {})
28 await page.screenshot({path: destPath})
31/** @param {{only?: string}} [opts] */
32export const updateScreenshots = async (sites, publicDir, opts = {}) => {
33 const {only} = opts
35 const imagesDir = join(publicDir, 'images')
36 if (!existsSync(imagesDir)) mkdirSync(imagesDir, {recursive: true})
38 const toCapture = sites.map(site => {
39 const epEntry = site.epH && Object.entries(site.epH)[0]
40 if (!epEntry) return null
41 const [key, ep] = epEntry
42 if (site.image !== 'auto') return null
43 if (only && key !== only) return null
44 const url = getScreenshotUrl(site, ep)
45 if (!url) return null
46 const authHeader = getBasicAuthHeader(site)
47 return {key, url, destPath: join(imagesDir, `${key}-tile.png`), authHeader}
48 }).filter(Boolean)
50 if (!toCapture.length) {
51 console.log(only ? `No site found with key: ${only}` : 'No sites with image: "auto" found')
52 return
53 }
55 const browser = await chromium.launch()
56 try {
57 const page = await browser.newPage({viewport: {width: 600, height: 600}, colorScheme: 'dark'})
58 for (const {key, url, destPath, authHeader} of toCapture) {
59 betLog({capturing: key, url})
60 if (authHeader) await page.setExtraHTTPHeaders({Authorization: authHeader})
61 else await page.setExtraHTTPHeaders({})
62 await captureScreenshot(page, url, destPath)
63 console.log(` → ${relative(ptDir, destPath)}`)
64 }
65 } finally {
66 await browser.close()
67 }