|
| 1 | +#!/usr/bin/env ts-node-script |
| 2 | +import got from 'got' |
| 3 | +import { parseStringPromise } from 'xml2js' |
| 4 | +import { Drawing } from '../explorer/types' |
| 5 | +import fs from 'fs' |
| 6 | +import stream from 'stream' |
| 7 | +import { promisify } from 'util' |
| 8 | + |
| 9 | +const pipeline = promisify(stream.pipeline) |
| 10 | + |
| 11 | +const baseSitemapUrl = 'https://www.buildingaworld.com/sitemap.xml' |
| 12 | +const yearDrawingLists: Record<string, Drawing[]> = {} |
| 13 | + |
| 14 | +type LocUrl = { |
| 15 | + loc: string // e.g. 'https://www.buildingaworld.com/products/crazy-monster-takes-a-walk' |
| 16 | + lastmod: string // e.g. '2020-12-16T15:31:48-05:00' |
| 17 | + changeFreq: string[] |
| 18 | + 'image:image': LocImage[] |
| 19 | +} |
| 20 | + |
| 21 | +type LocImage = { |
| 22 | + 'image:loc': string[] |
| 23 | + 'image:title': string[] |
| 24 | +} |
| 25 | + |
| 26 | +try { |
| 27 | + const response = await got(baseSitemapUrl) |
| 28 | + const data = await parseStringPromise(response.body) |
| 29 | + const productSitemapUrls: string[] = data.sitemapindex.sitemap |
| 30 | + .map((o: any) => o.loc[0]) |
| 31 | + .filter((s: string) => s.match(/sitemap_products_/)) |
| 32 | + |
| 33 | + await productSitemapUrls.forEach(async (url) => { |
| 34 | + const response = await got(url) |
| 35 | + const data = await parseStringPromise(response.body) |
| 36 | + |
| 37 | + console.log('First 5 product locations:', data.urlset.url.slice(0, 5)) |
| 38 | + |
| 39 | + data.urlset.url |
| 40 | + .filter((o: any) => o['image:image'] && !o.loc.includes('/products/any-drawing')) |
| 41 | + .forEach(async (o: LocUrl) => { |
| 42 | + const year = o.lastmod.slice(0, 4) |
| 43 | + if (!yearDrawingLists[year]) yearDrawingLists[year] = [] |
| 44 | + |
| 45 | + const number: string = (yearDrawingLists[year].length + 1).toString() |
| 46 | + const title = o['image:image'][0]['image:title'][0] |
| 47 | + const slugMatch = o.loc[0].match(/\/products\/(.*)/) |
| 48 | + const slug = slugMatch?.[1] ?? '' |
| 49 | + |
| 50 | + const src = o['image:image'][0]['image:loc'][0] |
| 51 | + const srcMatch = src.match(/([^/]+)\?/) |
| 52 | + const srcBase = srcMatch?.[1] |
| 53 | + const srcPath = `./scraped-images/${srcBase}`; |
| 54 | + |
| 55 | + if (fs.existsSync(srcPath)) { |
| 56 | + console.log(`Skipping ${srcBase}, found ${srcPath}`); |
| 57 | + } else { |
| 58 | + await pipeline(got.stream(src), fs.createWriteStream(srcPath)) |
| 59 | + } |
| 60 | + |
| 61 | + const drawing: Drawing = { |
| 62 | + id: `${year}.${number}`, |
| 63 | + year, |
| 64 | + number, |
| 65 | + date: o.lastmod.slice(0, 10), |
| 66 | + title, |
| 67 | + slug, |
| 68 | + image: `shopify/${srcBase}`, |
| 69 | + } |
| 70 | + yearDrawingLists[year].push(drawing) |
| 71 | + }) |
| 72 | + }) |
| 73 | + console.log('yearDrawingLists:', yearDrawingLists) |
| 74 | +} catch (error) { |
| 75 | + console.log(error?.response?.body || error); |
| 76 | +} |
0 commit comments