${escape(current.title)}
${summary ? `${escape(summary)}
` : ''} ${updated ? `` : ''}'use strict'; const fs = require('fs'); const path = require('path'); const { Service } = require('egg'); const markdown = require('../lib/markdown'); const SITE_NAME = '云仓视频溯源'; /** 目录 / 文件名只允许安全的 ASCII:分类 code、文章 slug 都按这个校验 */ const SAFE_SEGMENT = /^[a-z0-9][a-z0-9_-]{0,63}$/; function ensureDir(dir) { fs.mkdirSync(dir, { recursive: true }); } function writeFile(file, content) { ensureDir(path.dirname(file)); fs.writeFileSync(file, content, 'utf8'); } function escape(value) { return markdown.escapeHtml(value); } /** 日期只留 YYYY-MM-DD */ function dateOnly(value) { if (!value) return ''; const date = value instanceof Date ? value : new Date(value); if (Number.isNaN(date.getTime())) return ''; return date.toISOString().slice(0, 10); } /** * 文档站生成器(`/doc/**` 的静态 HTML + `/sitemap.txt`) * * 设计取舍: * - **静态优先**:每次内容变更(增删改分类 / 栏目 / 文章)整站重写一遍,文章量级小(几十篇)足够快; * - 首次访问 / 部署后文件不存在时 **按需生成**(`ensureSite`),不依赖启动钩子; * - 生成目录放在 `run/doc-site`(不进仓库),由 `controller/web/doc.js` 直接读文件返回。 */ class DocSiteService extends Service { get siteDir() { return this.app.config.docSite.dir; } get indexPath() { return path.join(this.siteDir, 'index.html'); } get sitemapPath() { return path.join(this.siteDir, 'sitemap.txt'); } /** 站点根地址(sitemap 用绝对地址):优先配置,其次当前请求的 origin */ baseUrl(ctx) { const configured = (this.app.config.docSite && this.app.config.docSite.baseUrl) || ''; if (configured) return String(configured).replace(/\/+$/, ''); const origin = ctx && ctx.origin ? String(ctx.origin) : ''; return origin.replace(/\/+$/, ''); } /** 已发布的分类 → 栏目 → 文章(仅 status=1,按 sort 排序) */ async loadModel() { const { DocCategory, DocSection, DocArticle } = this.app.model; const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ]; const [ categories, sections, articles ] = await Promise.all([ DocCategory.findAll({ where: { status: 1 }, order }), DocSection.findAll({ where: { status: 1 }, order }), DocArticle.findAll({ where: { status: 1 }, order }), ]); const articlesBySection = new Map(); for (const article of articles) { const key = String(article.sectionId); if (!articlesBySection.has(key)) articlesBySection.set(key, []); articlesBySection.get(key).push(article); } const sectionsByCategory = new Map(); for (const section of sections) { const key = String(section.categoryId); if (!sectionsByCategory.has(key)) sectionsByCategory.set(key, []); sectionsByCategory.get(key).push(section); } return categories.map(category => { const ownSections = sectionsByCategory.get(String(category.id)) || []; const groups = ownSections.map(section => ({ id: Number(section.id), name: section.name, articles: articlesBySection.get(String(section.id)) || [], })).filter(group => group.articles.length > 0); return { id: Number(category.id), code: category.code, name: category.name, description: category.description || '', groups, articles: groups.reduce((all, group) => all.concat(group.articles), []), }; }).filter(category => SAFE_SEGMENT.test(category.code)); } /** 生成整站(页面 + sitemap),返回生成的文件相对路径列表 */ async generate(ctx) { const model = await this.loadModel(); const base = this.baseUrl(ctx); ensureDir(this.siteDir); const written = []; const firstCategory = model[0] || null; // `/doc/`:默认展示第一个分类(没有分类就展示空态) writeFile(this.indexPath, this.renderPage({ model, base, active: firstCategory, article: null })); written.push('index.html'); for (const category of model) { writeFile( path.join(this.siteDir, category.code, 'index.html'), this.renderPage({ model, base, active: category, article: null }), ); written.push(`${category.code}/index.html`); for (const article of category.articles) { writeFile( path.join(this.siteDir, category.code, `${article.slug}.html`), this.renderPage({ model, base, active: category, article }), ); written.push(`${category.code}/${article.slug}.html`); } } this.prune(model); this.writeSitemap(this.buildSitemapUrls(model, base)); return written; } /** 文件不存在就生成(部署后第一次访问 / 清缓存后) */ async ensureSite(ctx) { if (fs.existsSync(this.indexPath)) return; await this.generate(ctx); } /** 删掉已经不该存在的目录 / 页面(分类改名、文章下架后不留旧链接) */ prune(model) { const codes = new Set(model.map(category => category.code)); const slugsByCode = new Map(model.map(category => [ category.code, new Set(category.articles.map(article => `${article.slug}.html`)) ])); for (const entry of fs.readdirSync(this.siteDir, { withFileTypes: true })) { if (!entry.isDirectory()) continue; if (!codes.has(entry.name)) { fs.rmSync(path.join(this.siteDir, entry.name), { recursive: true, force: true }); continue; } const allow = slugsByCode.get(entry.name) || new Set(); for (const file of fs.readdirSync(path.join(this.siteDir, entry.name))) { if (file === 'index.html') continue; if (!allow.has(file)) fs.rmSync(path.join(this.siteDir, entry.name, file), { force: true }); } } } /** 全站 URL:站点首页 + 文档站各级页面(顺序稳定,新增的排在最后) */ buildSitemapUrls(model, base) { const urls = [ `${base}/`, `${base}/doc/` ]; for (const category of model) { urls.push(`${base}/doc/${category.code}/`); for (const article of category.articles) { urls.push(`${base}/doc/${category.code}/${article.slug}.html`); } } return urls; } /** * 写 sitemap.txt:**已有顺序保持不变,新链接追加到末尾**(文章新增即"在尾部加入")。 * 已经不存在的 URL 会被清掉(下架 / 删除的文章不给搜索引擎留着)。 */ writeSitemap(urls) { const wanted = new Set(urls); let existing = []; try { existing = fs.readFileSync(this.sitemapPath, 'utf8') .split(/\r?\n/) .map(line => line.trim()) .filter(Boolean); } catch { existing = []; } const kept = []; const keptSet = new Set(); for (const url of existing) { if (!wanted.has(url) || keptSet.has(url)) continue; kept.push(url); keptSet.add(url); } const appended = urls.filter(url => !keptSet.has(url)); writeFile(this.sitemapPath, `${kept.concat(appended).join('\n')}\n`); } /** 单个文件在磁盘上的位置(拒绝 `..` 越界) */ resolveFile(relative) { const clean = String(relative || '').replace(/^\/+/, '').replace(/\\/g, '/'); const target = path.resolve(this.siteDir, clean); const root = path.resolve(this.siteDir); if (target !== root && !target.startsWith(`${root}${path.sep}`)) return null; return target; } // ---------------- 渲染 ---------------- /** 顶部 tab(分类全量展示,全局可切换) */ renderTabs(model, active) { return model.map(category => { const isActive = active && category.code === active.code; return `${escape(category.name)}`; }).join(''); } /** 侧边栏:当前分类下的「栏目 → 内容页」 */ renderSidebar(active, article) { if (!active) return '
还没有文档分类。
'; if (!active.groups.length) return '这个分类下还没有内容。
'; return active.groups.map(group => `文档站还没有内容。平台管理员可以在「平台管理 → 文档管理」里新建分类与内容页。
${escape(active.description || '这个分类下还没有已发布的内容。')}
${escape(summary)}
` : ''} ${updated ? `` : ''}