/**
* One-shot import of MST «شبکه اساتید» from a browser-saved folder.
*
* Usage:
* node scripts/import-faculty-from-local.mjs
* node scripts/import-faculty-from-local.mjs "C:\Users\...\شبکه اساتید"
*
* Reads DATABASE_URL from .env.local. Copies avatars into public/images/faculty.
*/
import { existsSync, readFileSync, readdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
if (!process.env.DATABASE_URL) {
const envPath = path.join(root, ".env.local");
if (existsSync(envPath)) {
for (const line of readFileSync(envPath, "utf8").split(/\r?\n/)) {
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
if (match && !(match[1] in process.env)) {
process.env[match[1]] = match[2];
}
}
}
}
if (!process.env.DATABASE_URL) {
console.error("DATABASE_URL is not set.");
process.exit(1);
}
function findDefaultFolder() {
const downloads = path.join(process.env.USERPROFILE || "", "Downloads");
if (!existsSync(downloads)) return null;
const hit = readdirSync(downloads, { withFileTypes: true }).find(
(d) => d.isDirectory() && d.name.includes("شبکه"),
);
return hit ? path.join(downloads, hit.name) : null;
}
function findHtmlAndFiles(folder) {
const entries = readdirSync(folder, { withFileTypes: true });
const html = entries.find((e) => e.isFile() && e.name.endsWith(".html"));
const filesDir = entries.find(
(e) => e.isDirectory() && e.name.includes("_files"),
);
if (!html) throw new Error(`No .html in ${folder}`);
return {
htmlPath: path.join(folder, html.name),
filesDir: filesDir ? path.join(folder, filesDir.name) : undefined,
};
}
// Dynamic import of TS modules via Node + project ts runner is awkward;
// re-implement a minimal upsert here mirroring sync-mst-network.ts.
function decodeEntities(s) {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/ /g, " ")
.trim();
}
function stripTags(s) {
return decodeEntities(s.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim());
}
function pickHref(block, classToken) {
const re = new RegExp(
`class="[^"]*${classToken}[^"]*"[^>]*href="([^"]+)"|href="([^"]+)"[^>]*class="[^"]*${classToken}[^"]*"`,
"i",
);
const m = block.match(re);
const href = m?.[1] || m?.[2] || "";
if (!href || href.endsWith("orcid.org/")) return "";
return decodeEntities(href);
}
function formatPhone(tel) {
let local = tel.replace(/\D/g, "");
if (local.startsWith("98")) local = "0" + local.slice(2);
if (local.length === 11 && local.startsWith("021")) {
return `${local.slice(0, 3)}-${local.slice(3)}`;
}
return local || tel;
}
function parseHtml(html) {
const cardRe =
/
\s*<\/div>/g;
const out = [];
let m;
while ((m = cardRe.exec(html))) {
const classExtra = m[1] ?? "";
const body = m[0];
const name = stripTags(body.match(/mstf-name">([^<]+)/)?.[1] ?? "");
if (!name) continue;
const pill =
stripTags(body.match(/mstf-pill">([^<]+)/)?.[1] ?? "") ||
"عضو هیئت علمی";
const department = stripTags(
body.match(/mstf-dept">([\s\S]*?)<\/div>/)?.[1] ?? "",
);
const focus = stripTags(
body.match(/mstf-int">
[^<]*<\/b>\s*([^<]+)/)?.[1] ?? "",
);
const email = decodeEntities(
body.match(/mailto:([^"'>\s]+)/)?.[1] ?? "",
);
const telRaw = body.match(/tel:(\+?[\d]+)/)?.[1] ?? "";
const imageSrc = decodeEntities(
body.match(/mstf-avatar">
]+src="([^"]+)"/)?.[1] ?? "",
);
const visiting =
classExtra.includes("mstf-visiting") || pill.includes("مدعو");
out.push({
name,
title: pill,
department,
focus: focus || (visiting ? "استاد مدعو" : "—"),
email,
phone: telRaw ? formatPhone(telRaw) : "",
linkedinUrl: pickHref(body, "mstf-i-linkedin"),
scholarUrl: pickHref(body, "mstf-i-scholar"),
imageSrc,
visiting,
});
}
return out;
}
function facultyId(p) {
if (p.email) {
const local = p.email
.split("@")[0]
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
if (local) return `fac-${local}`;
}
let h = 0;
for (let i = 0; i < p.name.length; i++) {
h = (h * 31 + p.name.charCodeAt(i)) >>> 0;
}
return `fac-${h.toString(36)}`;
}
async function main() {
const folder = process.argv[2] || findDefaultFolder();
if (!folder || !existsSync(folder)) {
console.error("Faculty folder not found. Pass the path as argv[2].");
process.exit(1);
}
const { htmlPath, filesDir } = findHtmlAndFiles(folder);
const html = readFileSync(htmlPath, "utf8");
const list = parseHtml(html);
console.log(`Parsed ${list.length} faculty from ${htmlPath}`);
// Use the TS sync via next-compatible dynamic import when available;
// otherwise upsert with pg directly (this script).
const { copyFileSync, mkdirSync } = await import("node:fs");
const publicFaculty = path.join(root, "public", "images", "faculty");
mkdirSync(publicFaculty, { recursive: true });
if (filesDir && existsSync(path.join(filesDir, "johndoe.png"))) {
copyFileSync(
path.join(filesDir, "johndoe.png"),
path.join(publicFaculty, "placeholder.png"),
);
}
const { Client } = pg;
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
try {
const existing = await client.query(`SELECT * FROM faculty_members`);
const byEmail = new Map();
const byName = new Map();
for (const row of existing.rows) {
if (row.email) byEmail.set(row.email.toLowerCase(), row);
byName.set(row.name.replace(/\s+/g, " ").trim().toLowerCase(), row);
}
let inserted = 0;
let updated = 0;
let images = 0;
for (const p of list) {
const match =
(p.email && byEmail.get(p.email.toLowerCase())) ||
byName.get(p.name.replace(/\s+/g, " ").trim().toLowerCase());
const id = match?.id ?? facultyId(p);
let imageUrl = match?.image_url || "/images/faculty/placeholder.png";
const fileBase = p.imageSrc.split(/[/\\]/).pop() || "";
const isPlaceholder =
!fileBase ||
fileBase.toLowerCase() === "johndoe.png" ||
fileBase.includes("placeholder");
if (filesDir && fileBase && !isPlaceholder) {
const from = path.join(filesDir, fileBase);
if (existsSync(from)) {
const destName = `${id}.png`;
copyFileSync(from, path.join(publicFaculty, destName));
imageUrl = `/images/faculty/${destName}`;
images += 1;
}
} else if (isPlaceholder && match?.image_url && !match.image_url.includes("placeholder")) {
imageUrl = match.image_url;
}
const title =
match?.title && !/هیئت علمی|مدعو/.test(match.title)
? match.title
: p.title;
const bio =
match?.bio?.trim() ||
[p.title, p.department].filter(Boolean).join(" — ");
if (match) {
await client.query(
`UPDATE faculty_members SET
name=$2, title=$3, focus=$4, bio=$5, image_url=$6,
email=$7, phone=$8, department=$9,
linkedin_url=$10, scholar_url=$11, updated_at=now()
WHERE id=$1`,
[
id,
p.name,
title,
p.focus,
bio,
imageUrl,
p.email || null,
p.phone || null,
p.department || null,
p.linkedinUrl || null,
p.scholarUrl || null,
],
);
updated += 1;
} else {
await client.query(
`INSERT INTO faculty_members (
id, name, title, focus, bio, image_url,
email, phone, department, linkedin_url, scholar_url, published
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true)`,
[
id,
p.name,
title,
p.focus,
bio,
imageUrl,
p.email || null,
p.phone || null,
p.department || null,
p.linkedinUrl || null,
p.scholarUrl || null,
],
);
inserted += 1;
}
const row = { id, name: p.name, email: p.email || null };
if (p.email) byEmail.set(p.email.toLowerCase(), row);
byName.set(p.name.replace(/\s+/g, " ").trim().toLowerCase(), row);
}
console.log(
JSON.stringify({ total: list.length, inserted, updated, images }, null, 2),
);
} finally {
await client.end();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});