|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import fs from "fs/promises"; |
| 4 | +import path from "path"; |
| 5 | +import { fileURLToPath } from "url"; |
| 6 | + |
| 7 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 8 | +const publicRoot = path.resolve(__dirname, "../public"); |
| 9 | +const sourceOrigin = |
| 10 | + process.env.PREVIEW_DATA_ORIGIN || "https://compbioatberkeley.github.io"; |
| 11 | + |
| 12 | +const currentSemester = () => { |
| 13 | + const now = new Date(); |
| 14 | + const prefix = now.getMonth() <= 6 ? "sp" : "fa"; |
| 15 | + return `${prefix}${String(now.getFullYear()).slice(-2)}`; |
| 16 | +}; |
| 17 | + |
| 18 | +const destinationFor = (urlPath) => { |
| 19 | + const destination = path.resolve(publicRoot, urlPath.replace(/^\/+/, "")); |
| 20 | + if ( |
| 21 | + destination !== publicRoot && |
| 22 | + !destination.startsWith(`${publicRoot}${path.sep}`) |
| 23 | + ) { |
| 24 | + throw new Error(`Refusing to write outside public/: ${urlPath}`); |
| 25 | + } |
| 26 | + return destination; |
| 27 | +}; |
| 28 | + |
| 29 | +const download = async (urlPath) => { |
| 30 | + const response = await fetch(new URL(urlPath, sourceOrigin)); |
| 31 | + if (!response.ok) { |
| 32 | + throw new Error(`Failed to fetch ${urlPath}: ${response.status}`); |
| 33 | + } |
| 34 | + |
| 35 | + const destination = destinationFor(urlPath); |
| 36 | + await fs.mkdir(path.dirname(destination), { recursive: true }); |
| 37 | + const bytes = Buffer.from(await response.arrayBuffer()); |
| 38 | + await fs.writeFile(destination, bytes); |
| 39 | + return bytes; |
| 40 | +}; |
| 41 | + |
| 42 | +const syncSemester = async (semester) => { |
| 43 | + const jsonPath = `/fetched/officers/${semester}/officers-${semester}.json`; |
| 44 | + const jsonBytes = await download(jsonPath); |
| 45 | + const officers = JSON.parse(jsonBytes.toString("utf8")); |
| 46 | + const imagePaths = [ |
| 47 | + ...new Set( |
| 48 | + officers |
| 49 | + .map((officer) => officer.image) |
| 50 | + .filter( |
| 51 | + (image) => |
| 52 | + typeof image === "string" && image.startsWith("/fetched/"), |
| 53 | + ), |
| 54 | + ), |
| 55 | + ]; |
| 56 | + |
| 57 | + await Promise.all(imagePaths.map(download)); |
| 58 | + console.log( |
| 59 | + `Synced ${officers.length} ${semester} officers and ${imagePaths.length} images`, |
| 60 | + ); |
| 61 | +}; |
| 62 | + |
| 63 | +for (const semester of [...new Set(["fa25", currentSemester()])]) { |
| 64 | + await syncSemester(semester); |
| 65 | +} |
0 commit comments