From d3a5e99e8a32134289cd7adeab8bd61121e66902 Mon Sep 17 00:00:00 2001 From: yaosanqi137 Date: Sun, 1 Nov 2026 20:37:13 +0800 Subject: [PATCH] feat: serve styled mirror directories with nginx fancyindex --- README.md | 8 ++ deploy/README.md | 12 ++- deploy/install-preview.sh | 7 ++ deploy/nginx-preview.conf | 51 ++++++++++- deploy/test_nginx_directory.py | 151 +++++++++++++++++++++++++++++++ directory.html | 58 ++++++++++++ package.json | 5 +- public/assets/directory-theme.js | 7 ++ scripts/build-directory.ts | 38 ++++++++ scripts/check-directory.ts | 16 ++++ scripts/check-locales.ts | 6 +- src/directory/main.ts | 144 +++++++++++++++++++++++++++++ src/directory/messages.ts | 10 ++ src/directory/style.css | 58 ++++++++++++ src/locales/en-US/directory.ts | 7 ++ src/locales/index.ts | 6 +- src/locales/zh-CN/directory.ts | 7 ++ vite.config.ts | 20 +++- 18 files changed, 597 insertions(+), 14 deletions(-) create mode 100644 deploy/test_nginx_directory.py create mode 100644 directory.html create mode 100644 public/assets/directory-theme.js create mode 100644 scripts/build-directory.ts create mode 100644 scripts/check-directory.ts create mode 100644 src/directory/main.ts create mode 100644 src/directory/messages.ts create mode 100644 src/directory/style.css create mode 100644 src/locales/en-US/directory.ts create mode 100644 src/locales/zh-CN/directory.ts diff --git a/README.md b/README.md index a9c7b17..553e628 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ npm run dev ```sh npm run check:i18n # 检查中英文语言键与插值参数 npm run check:monitoring # 检查监控图表的数据夹具与资源总量约束 +npm run check:directory # 构建后检查 Nginx 目录模板、翻译和资源 npm run build # TypeScript 检查与生产构建 npm run preview # 预览 dist 中的构建结果 ``` @@ -40,6 +41,8 @@ Vue 3 + TypeScript + Vite,使用 vue-i18n 管理界面文案。当前首页支 操作记录按时间倒序,每页 10 条;超过一页时显示分页控制,可查看全部历史记录。接口 `/api/v1/admin/audit?page=1` 返回当前页、总条数和总页数,未带 `page` 的旧版请求继续返回最近 200 条数组。 +`/mirrors//` 采用与 TUNA 同类的 Nginx Fancyindex 方案,服务端直接返回包含完整文件列表、页头和页脚的 HTML。禁用 JavaScript 也可浏览目录、按名称/大小/修改时间排序和下载文件,不再请求目录 JSON。JavaScript 仅增强面包屑、当前目录搜索、每页 100 项、主题和语言选择;另有一次可选的站点设置请求,用于应用后台配置的品牌和页脚内容,失败不影响文件浏览。目录优先排列,隐藏项不展示,时间明确使用 UTC;文件保留原 URL、HEAD 和 Range 支持。在仓库根目录返回上级会回到首页。模板和表头文案从语言文件生成,默认中文,增强脚本支持语言切换。 + ## 后端与部署 后端使用 Go 标准库 HTTP、SQLite 和 TOML 解析器,不依赖数据库外部服务。详细部署、权限、备份和回退操作见 [deploy/README.md](deploy/README.md)。 @@ -59,11 +62,16 @@ go build -o mirrorouc . 生产构建通过 `-static ../dist` 或 `MIRROROUC_STATIC` 指定静态目录;`MIRROROUC_WORKER_CONFIG`、`MIRROROUC_LOGS`、`MIRROROUC_METRICS` 分别指定 Worker 配置、日志根目录和采样历史。缺少配置时,对应管理功能会显示不可用,不会启动假的同步引擎。管理页复用站点的明暗主题和语言选择。 +镜像根目录通过 `deploy/nginx-preview.conf` 中两个 `alias /data/mirrors/` 配置。Go 不枚举镜像目录,也不代理文件内容。符号链接沿用 Nginx 和文件系统的访问规则,与镜像下载服务保持一致。 + +本地开发时,在被忽略的 `.env.local` 中设置 `MIRROROUC_NGINX_ORIGIN=http://100.69.2.2:8080`,再运行 Vite。目录 HTML、下载和其构建资源代理到该 Nginx;其他管理 API 继续代理到本地 Go 的 8081 端口。目录模板修改后需重新构建并更新 Nginx 使用的 `dist/`。未设置时,Nginx 地址默认为 `http://127.0.0.1:8080`。 + 当前服务器预览地址为 `http://100.69.2.2:8080`,管理入口 `/admin`,原有 80 端口下载服务保留。预览仅监听该 Tailnet 地址,正式域名与 HTTPS 尚未配置。 ## 源码约定 - `src/App.vue`:首页与弹窗交互。 +- `directory.html`、`src/directory/`、`scripts/build-directory.ts`:服务端目录的 HTML 模板、渐进增强与构建,产物位于 `dist/fancy-index/`。 - `src/style.css`:爱特官网同款明暗配色、布局、动画和移动端样式;色值来源与映射见 [DESIGN.md](DESIGN.md)。 - `src/locales/zh-CN/`、`src/locales/en-US/`:界面文案及数据夹具文案;新增文案通过语言键引用。 - 各语言的 `mirrors.ts` 定义表头、状态、相对时间、容量与公告日期模板,`formats.ts` 定义日期和数字格式;组件通过 `t`、`d`、`n` 使用,不自行生成界面文案。 diff --git a/deploy/README.md b/deploy/README.md index 5717664..288fb3a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -73,7 +73,15 @@ HTTPS/rsync 使用 TCP 443/873 的 IPv4、IPv6 收发字节计数,双向 NFS I/O 来自 `/proc/self/mountstats` 的 `/data` 挂载,磁盘容量来自 statvfs;CPU、内存来自 `/proc`。采样历史仅覆盖采集器启用后的时间,不补造旧数据。图表最多展示 241 个采样点,均值、当前值、峰值从当前窗口全部原始有效采样计算。 -镜像文件由 Nginx 直接提供,API 不读取整个仓库;镜像目录响应设置 CSP sandbox 和 nosniff,避免仓库中的 HTML/脚本获得管理页面同源权限。 +目录 HTML、静态资源和文件下载全部由 Nginx 提供,Go 不参与目录遍历或文件传输。需要与当前 Nginx ABI 匹配的 Fancyindex 模块及内置 addition、sub_filter 模块;当前 Debian 13 使用 `apt-get install libnginx-mod-http-fancyindex`,安装后执行 `nginx -t`。自编译 Nginx 必须安装匹配模块,不要用包管理器覆盖现有二进制。主配置须加载模块(Debian 的 `/etc/nginx/modules-enabled/*.conf`)。 + +`npm run build` 使用独立 Vite 入口 `directory.html`,随后生成 `dist/fancy-index/header.html`、`footer.html` 和 `labels.conf`。Fancyindex 内部子请求插入页头和页脚,`sub_filter` 用语言文件生成的文案替换四个原生英文标签。浏览器首次响应已经包含全部文件条目;无需 JavaScript、Go 或 JSON 即可导航和下载。JS 只增加搜索、每页 100 条、面包屑、主题、语言和一次可选的站点设置加载。无 JS 时默认中文,显示全部条目。目录 GET/HEAD 只读、目录优先、隐藏项省略,时间显示 UTC;表头的排序链接由 Fancyindex 在服务端处理。 + +目录正则 location 的 `alias /data/mirrors/$mirror_directory` 与下载 location 的 `alias /data/mirrors/` 指向同一镜像树;符号链接遵循 Nginx 和文件系统访问规则,镜像树应仅包含可公开分发的内容。`/mirrors/` 重定向首页,因此仓库根目录的原生上级链接也会返回首页。目录仍需读取当前层文件元数据,不递归扫描;服务端 HTML 不会消除 NFS 元数据开销,大目录首访延迟仍需单独监测。 + +文件响应继续设置 CSP sandbox 和 nosniff,避免仓库中的 HTML/脚本获得管理页面同源权限。目录 HTML 使用主站 CSP,两个模板子请求入口为 `internal`,不能直接访问。仓库中的 `index.html` 不会替代目录列表;显式访问它仍走文件下载 location,保留 sandbox、HEAD 和 Range。 + +发布时同时更新整个 `dist/` 和 `nginx-preview.conf`,保证 `labels.conf` 在 `nginx -t` 时已经存在。执行检查后 reload Nginx;只有前端和目录变化时不必重启 Go 或 tunasync。旧 `/api/v1/directory/` 已移除,原 `MIRROROUC_MIRRORS` 环境变量不再使用。不重新初始化数据库或修改同步任务,原有 80 端口站点保持原配置。回退时同时恢复站点配置与发布目录软链接,并重新检查、reload。 ## 备份与回退 @@ -89,6 +97,8 @@ NFS I/O 来自 `/proc/self/mountstats` 的 `/data` 挂载,磁盘容量来自 s 本次部署核验真实 API、镜像目录、日志、监控与后台草稿保存。没有为验证效果而停止、重启仓库,或应用修改后的生产同步参数。 +先运行 `npm run build && npm run check:directory`,再在安装 Fancyindex 的 Linux 上运行 `python3 deploy/test_nginx_directory.py`。测试使用临时文件与独立本地端口,Go 上游故意不可用,验证原始 HTML 包含条目、中英文标签模板、排序、特殊文件名转义、空/不存在目录、仓库 index.html、HEAD/Range、只读限制、内部模板隔离和路径边界;不停止真实服务或修改真实镜像目录。 + ## 统一中文内容升级 公告的 title/body 和镜像的 help 已改为单个字符串,所有界面语言共用中文内容。旧版本的语言映射在服务启动时以事务迁移:优先保留 zh-CN,其次 zh;没有中文键的历史记录保留原内容供管理员整理。原始 JSON 保存在 SQLite 的 shared_content_backups 表,迁移会递增记录 revision,避免旧编辑页面覆盖新内容;重复启动不会重复迁移。 diff --git a/deploy/install-preview.sh b/deploy/install-preview.sh index bb68b4f..371cf05 100644 --- a/deploy/install-preview.sh +++ b/deploy/install-preview.sh @@ -5,6 +5,13 @@ release=$(readlink -f "$1") case "$release" in /opt/mirrorouc/releases/*) ;; *) echo 'Invalid release path' >&2; exit 1;; esac test -x "$release/mirrorouc" test -f "$release/dist/index.html" +test -f "$release/dist/fancy-index/header.html" +test -f "$release/dist/fancy-index/footer.html" +# The module must match the installed Nginx ABI; do not replace a custom build. +if ! nginx -T 2>&1 | grep -q 'load_module.*ngx_http_fancyindex_module'; then + echo 'Install and enable a matching Nginx Fancyindex module first (Debian: apt-get install libnginx-mod-http-fancyindex).' >&2 + exit 1 +fi deploy="$release/deploy" id mirrorouc >/dev/null 2>&1 || useradd --system --home-dir /var/lib/mirrorouc --shell /usr/sbin/nologin mirrorouc install -d -m 0700 -o mirrorouc -g mirrorouc /var/lib/mirrorouc diff --git a/deploy/nginx-preview.conf b/deploy/nginx-preview.conf index 465c1c1..928b09d 100644 --- a/deploy/nginx-preview.conf +++ b/deploy/nginx-preview.conf @@ -3,11 +3,56 @@ server { server_name 100.69.2.2; client_max_body_size 5m; + location = /mirrors { + return 302 /; + } + location = /mirrors/ { + return 302 /; + } + + location /assets/ { + root /opt/mirrorouc/current/dist; + try_files $uri =404; + add_header X-Content-Type-Options nosniff always; + } + + # Fancyindex renders the complete directory on the server. No Go/JSON hop. + location ~ ^/mirrors/(?.+/)$ { + alias /data/mirrors/$mirror_directory; + index .mirrorouc-autoindex-only; + fancyindex on; + fancyindex_header /_directory/header.html; + fancyindex_footer /_directory/footer.html; + fancyindex_show_path off; + fancyindex_name_length 256; + fancyindex_exact_size off; + fancyindex_directories_first on; + fancyindex_show_dotfiles off; + fancyindex_localtime off; + fancyindex_time_format "%Y-%m-%d %H:%M:%S UTC"; + include /opt/mirrorouc/current/dist/fancy-index/labels.conf; + charset utf-8; + limit_except GET { deny all; } + add_header Cache-Control no-cache; + add_header X-Content-Type-Options nosniff always; + add_header X-Frame-Options DENY always; + add_header Referrer-Policy same-origin always; + add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" always; + } + + # Only Fancyindex subrequests may read the generated fragments. + location = /_directory/header.html { + internal; + alias /opt/mirrorouc/current/dist/fancy-index/header.html; + } + location = /_directory/footer.html { + internal; + alias /opt/mirrorouc/current/dist/fancy-index/footer.html; + } + location /mirrors/ { alias /data/mirrors/; - autoindex on; - autoindex_exact_size off; - autoindex_localtime on; + autoindex off; add_header X-Content-Type-Options nosniff always; add_header Content-Security-Policy "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:" always; } diff --git a/deploy/test_nginx_directory.py b/deploy/test_nginx_directory.py new file mode 100644 index 0000000..71a62cd --- /dev/null +++ b/deploy/test_nginx_directory.py @@ -0,0 +1,151 @@ +"""Exercise the shipped Nginx routes using disposable files and an isolated port.""" +from html.parser import HTMLParser +from pathlib import Path +import shutil +import socket +import subprocess +import tempfile +import time +import unittest +import urllib.error +import urllib.parse +import urllib.request + + +class NginxDirectoryTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + nginx = shutil.which('nginx') + if not nginx: + raise unittest.SkipTest('Nginx is required for the integration fixture') + cls.temp = tempfile.TemporaryDirectory(prefix='mirrorouc-nginx-test-') + cls.root = Path(cls.temp.name) + cls.mirrors = cls.root / 'mirrors' + cls.dist = cls.root / 'dist' + (cls.mirrors / 'repo' / 'sub').mkdir(parents=True) + (cls.mirrors / 'repo' / 'empty').mkdir() + build = Path(__file__).resolve().parent.parent / 'dist' + if not (build / 'fancy-index' / 'header.html').is_file(): + raise RuntimeError('Run npm run build before the Nginx integration fixture') + shutil.copytree(build, cls.dist) + (cls.dist / 'assets' / 'test.js').write_text('window.fixture = true', encoding='utf-8') + (cls.mirrors / 'repo' / 'index.html').write_text('repository index must not replace listing', encoding='utf-8') + (cls.mirrors / 'repo' / '中文 #+%.txt').write_bytes(b'0123456789abcdef') + (cls.mirrors / 'repo' / 'zero').write_bytes(b'') + (cls.mirrors / 'repo' / '.hidden').write_text('hidden', encoding='utf-8') + (cls.mirrors / 'repo' / '\">.txt').write_text('escaped name', encoding='utf-8') + (cls.root / 'private-secret').write_text('outside-secret', encoding='utf-8') + with socket.socket() as available: + available.bind(('127.0.0.1', 0)) + port = available.getsockname()[1] + cls.base = f'http://127.0.0.1:{port}' + server = Path(__file__).with_name('nginx-preview.conf').read_text(encoding='utf-8') + server = server.replace('listen 100.69.2.2:8080;', f'listen 127.0.0.1:{port};') + server = server.replace('/data/mirrors/', cls.mirrors.as_posix() + '/') + server = server.replace('/opt/mirrorouc/current/dist', cls.dist.as_posix()) + # The Go upstream is deliberately unavailable throughout these tests. + server = server.replace('http://127.0.0.1:8081', 'http://127.0.0.1:9') + config = cls.root / 'nginx.conf' + config.write_text(f'load_module /usr/lib/nginx/modules/ngx_http_fancyindex_module.so;\nworker_processes 1;\npid {cls.root}/nginx.pid;\nerror_log {cls.root}/error.log;\nevents {{ worker_connections 32; }}\nhttp {{ access_log off; types {{ text/html html; text/plain txt; application/javascript js; }}\n{server}\n}}\n', encoding='utf-8') + validation = subprocess.run([nginx, '-p', str(cls.root), '-c', str(config), '-t'], capture_output=True, text=True) + if validation.returncode: + raise RuntimeError(validation.stderr) + cls.process = subprocess.Popen([nginx, '-p', str(cls.root), '-c', str(config), '-g', 'daemon off; master_process off;'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(100): + if cls.process.poll() is not None: + raise RuntimeError((cls.root / 'error.log').read_text()) + try: + with urllib.request.urlopen(cls.base + '/assets/test.js', timeout=1): + return + except (OSError, urllib.error.URLError): + time.sleep(0.03) + cls.process.terminate() + raise RuntimeError('Isolated Nginx did not become ready') + + @classmethod + def tearDownClass(cls): + cls.process.terminate() + cls.process.wait(timeout=5) + cls.temp.cleanup() + + def request(self, path, method='GET', headers=None): + request = urllib.request.Request(self.base + path, method=method, headers=headers or {}) + try: + response = urllib.request.build_opener(NoRedirect).open(request, timeout=5) + except urllib.error.HTTPError as response: + return response.code, response.headers, response.read() + with response: + return response.status, response.headers, response.read() + + def test_complete_server_html_without_go_or_javascript(self): + code, headers, body = self.request('/mirrors/repo/') + self.assertEqual(code, 200) + self.assertIn('text/html', headers['Content-Type']) + html = body.decode('utf-8') + self.assertIn('', html) + self.assertIn('href="sub/"', html) + self.assertIn('href="index.html"', html) + self.assertIn('中文 #+%.txt', html) + self.assertIn('data-i18n="directory.name">文件名', html) + self.assertIn('data-i18n="directory.parent">返回上级', html) + self.assertIn('UTC', html) + self.assertIn('', html) + self.assertNotIn('{{', html) + self.assertNotIn('repository index must not replace listing', html) + self.assertNotIn('.hidden', html) + parsed = Tags(); parsed.feed(html) + self.assertFalse(any(tag == 'img' and attrs.get('onerror') for tag, attrs in parsed.tags)) + self.assertNotIn('sandbox', headers['Content-Security-Policy']) + self.assertEqual(self.request('/assets/test.js')[0], 200) + self.assertEqual(self.request('/')[0], 502) + + def test_files_still_support_range_and_head(self): + url = '/mirrors/repo/' + urllib.parse.quote('中文 #+%.txt', safe='') + code, headers, body = self.request(url, headers={'Range': 'bytes=1-4'}) + self.assertEqual((code, body), (206, b'1234')) + self.assertEqual(headers['Content-Range'], 'bytes 1-4/16') + self.assertIn('sandbox', headers['Content-Security-Policy']) + self.assertEqual(headers['X-Content-Type-Options'], 'nosniff') + code, headers, body = self.request(url, method='HEAD') + self.assertEqual((code, int(headers['Content-Length']), body), (200, 16, b'')) + + def test_empty_missing_internal_and_parent(self): + code, _, body = self.request('/mirrors/repo/empty/') + self.assertEqual(code, 200) + self.assertIn(b'
', body) + self.assertEqual(self.request('/mirrors/missing/')[0], 404) + self.assertEqual(self.request('/mirrors/repo/', method='POST')[0], 403) + self.assertEqual(self.request('/_directory/header.html')[0], 404) + self.assertEqual(self.request('/_directory/footer.html')[0], 404) + code, headers, _ = self.request('/mirrors/') + self.assertEqual(code, 302) + self.assertTrue(headers['Location'].endswith('/')) + code, _, body = self.request('/mirrors/%2e%2e/private-secret/') + self.assertNotEqual(code, 200) + self.assertNotIn(b'outside-secret', body) + + def test_native_sort_links_and_head(self): + code, _, body = self.request('/mirrors/repo/?C=N&O=D') + self.assertEqual(code, 200) + html = body.decode('utf-8') + self.assertLess(html.index('href="sub/'), html.index('href="empty/')) + code, _, body = self.request('/mirrors/repo/', method='HEAD') + self.assertEqual((code, body), (200, b'')) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +class Tags(HTMLParser): + def __init__(self): + super().__init__() + self.tags = [] + + def handle_starttag(self, tag, attrs): + self.tags.append((tag, dict(attrs))) + + +if __name__ == '__main__': + unittest.main() diff --git a/directory.html b/directory.html new file mode 100644 index 0000000..6880812 --- /dev/null +++ b/directory.html @@ -0,0 +1,58 @@ + + + + + + + + {{directory.title}} · MirrorOUC + + + + + + +
+ + + + +
+ + + + diff --git a/package.json b/package.json index 04eda08..a895cd9 100644 --- a/package.json +++ b/package.json @@ -8,10 +8,11 @@ }, "scripts": { "dev": "vite --host 127.0.0.1", - "build": "vue-tsc -b && vite build", + "build": "vue-tsc -b && vite build && node scripts/build-directory.ts", "preview": "vite preview --host 127.0.0.1", "check:i18n": "node scripts/check-locales.ts", - "check:monitoring": "node scripts/check-monitoring.ts" + "check:monitoring": "node scripts/check-monitoring.ts", + "check:directory": "node scripts/check-directory.ts" }, "dependencies": { "dompurify": "^3.4.17", diff --git a/public/assets/directory-theme.js b/public/assets/directory-theme.js new file mode 100644 index 0000000..a78be8d --- /dev/null +++ b/public/assets/directory-theme.js @@ -0,0 +1,7 @@ +// Run before the stylesheet so the directory shares the main site's preference. +try { + var preference = localStorage.getItem('mirrorouc.theme'); + document.documentElement.dataset.theme = preference === 'dark' || (preference !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; +} catch (_) { + document.documentElement.dataset.theme = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; +} diff --git a/scripts/build-directory.ts b/scripts/build-directory.ts new file mode 100644 index 0000000..de2022e --- /dev/null +++ b/scripts/build-directory.ts @@ -0,0 +1,38 @@ +import { mkdir, readFile, writeFile, unlink } from 'node:fs/promises' +import { createI18n } from 'vue-i18n' +import { directoryMessages } from '../src/directory/messages.ts' + +const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: directoryMessages }) +const t = (key: string) => i18n.global.t(key) +const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]!) +const text = (key: string) => `${escape(t(key))}` +const navigation = [ + ['mirrors', '/'], ['news', 'https://www.itouc.cn/announcements/'], ['status', '/status'], + ['feedback', 'https://git.itouc.cn/ITStudio_OUC/OUCMirror-WebUI/issues'], +].map(([key, href]) => `${text(`common.nav.${key}`)}`).join('') +const languages = Object.entries(directoryMessages).map(([locale, messages]) => ``).join('') +const themes = ['light', 'dark', 'system'].map(theme => ``).join('') +const specials: Record = { navigation, languages, themes } +const html = (await readFile('dist/directory.html', 'utf8')).replace(/\{\{([\w.]+)\}\}/g, (_, key) => { + if (key in specials) return specials[key]! + if (!i18n.global.te(key)) throw new Error(`Missing directory template message: ${key}`) + return escape(t(key)) +}) +const parts = html.split('') +if (parts.length !== 2) throw new Error('Expected exactly one Nginx directory insertion point') +await mkdir('dist/fancy-index', { recursive: true }) +await writeFile('dist/fancy-index/header.html', parts[0]!) +await writeFile('dist/fancy-index/footer.html', parts[1]!) +// Translate the four native Fancyindex labels on the server as well, so the +// default Chinese listing is complete and accessible even without JavaScript. +const replacements = [ + ['File Name', `${text('directory.name')}`], + ['File Size', `${text('directory.size')}`], + ['Date', `${text('directory.modified')}`], + ['Parent directory/', `${text('directory.parent')}`], +] +const quote = (value: string) => '"' + value.replace(/\\/g, '\\\\').replace(/\$/g, '\\$').replace(/"/g, '\\"') + '"' +await writeFile('dist/fancy-index/labels.conf', 'sub_filter_once on;\n' + replacements.map(([before, after]) => `sub_filter ${quote(before!)} ${quote(after!)};`).join('\n') + '\n') +// Only the two internal fragments are served; Nginx inserts the table between them. +await unlink('dist/directory.html') +console.log('Built Nginx directory header, footer and locale labels.') diff --git a/scripts/check-directory.ts b/scripts/check-directory.ts new file mode 100644 index 0000000..4dcca5a --- /dev/null +++ b/scripts/check-directory.ts @@ -0,0 +1,16 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' + +// Run after the build to check the actual Nginx fragments and hashed assets. +const header = await readFile('dist/fancy-index/header.html', 'utf8') +const footer = await readFile('dist/fancy-index/footer.html', 'utf8') +const labels = await readFile('dist/fancy-index/labels.conf', 'utf8') +assert.ok(!header.includes('directory-path')) +assert.ok(footer.includes('')) +assert.ok(labels.includes('data-i18n=\\"directory.parent\\"')) +assert.ok(!/\{\{[\w.]+\}\}/.test(header + footer)) +assert.ok(!header.includes('/src/')) +for (const [, url] of [...header.matchAll(/(?:src|href)="(\/assets\/[^"?]+)"/g)]) await readFile('dist' + url) +assert.ok(header.includes('data-locale="zh-CN"') && header.includes('data-locale="en-US"')) +assert.ok(header.includes('data-theme-choice="system"')) +console.log('Nginx directory fragments, locale substitution and referenced assets passed.') diff --git a/scripts/check-locales.ts b/scripts/check-locales.ts index 150b51a..d8147ae 100644 --- a/scripts/check-locales.ts +++ b/scripts/check-locales.ts @@ -10,6 +10,8 @@ import { datetimeFormats as datetimeZh, numberFormats as numbersZh } from '../sr import { datetimeFormats as datetimeEn, numberFormats as numbersEn } from '../src/locales/en-US/formats.ts' import { createI18n } from 'vue-i18n' import { adminZh, adminEn } from '../src/locales/admin-messages.ts' +import directoryZh from '../src/locales/zh-CN/directory.ts' +import directoryEn from '../src/locales/en-US/directory.ts' function flatten(value: Record, prefix = ''): Record { return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => { @@ -18,8 +20,8 @@ function flatten(value: Record, prefix = ''): Record { try { return localStorage.getItem(key) } catch { return null } } +const save = (key: string, value: string) => { try { localStorage.setItem(key, value) } catch { /* Optional preference. */ } } +const savedLocale = read('mirrorouc.locale') +const preferredLocale = navigator.languages.map(value => locales.find(locale => locale.toLowerCase() === value.toLowerCase()) ?? locales.find(locale => locale.split('-')[0] === value.split('-')[0])).find(Boolean) +let locale: Locale = locales.includes(savedLocale as Locale) ? savedLocale as Locale : preferredLocale || 'zh-CN' +const i18n = createI18n({ legacy: false, locale, fallbackLocale: 'zh-CN', messages: directoryMessages }) +const t = (key: string, params: Record = {}) => i18n.global.t(key, params) +const system = matchMedia('(prefers-color-scheme: dark)') +const savedTheme = read('mirrorouc.theme') +let theme: Theme = savedTheme === 'light' || savedTheme === 'dark' ? savedTheme : 'system' +let site: SiteSettings | undefined +const table = document.querySelector('#list')! +const segments = location.pathname.split('/').filter(Boolean).slice(1).map(segment => { + try { return decodeURIComponent(segment) } catch { return segment } +}) +const path = '/mirrors/' + segments.join('/') + '/' +const parent = table.tBodies[0]?.rows[0]?.querySelector('a[href^="../"]') +if (parent && segments.length <= 1) parent.href = '/' +const rows = [...table.tBodies[0]!.rows].filter(row => !row.contains(parent || null)).map(row => ({ row, name: row.querySelector('a')?.textContent?.toLocaleLowerCase() || '', directory: row.querySelector('a')?.getAttribute('href')?.split('?')[0]?.endsWith('/') || false })) +const input = document.querySelector('#directory-search')! +const pagination = document.querySelector('.directory-pagination')! +const previous = document.querySelector('#directory-previous')! +const next = document.querySelector('#directory-next')! +const empty = document.querySelector('#directory-empty')! +let matches = rows +let visible: typeof rows = [] +let page = 1 +const pageSize = 100 +for (const { row } of rows) row.hidden = true + +function renderPage() { + for (const { row } of visible) row.hidden = true + visible = matches.slice((page - 1) * pageSize, page * pageSize) + for (const { row } of visible) row.hidden = false + const pages = Math.max(1, Math.ceil(matches.length / pageSize)) + previous.disabled = page === 1 + next.disabled = page === pages + pagination.hidden = matches.length === 0 + pagination.querySelector('div')!.hidden = pages <= 1 + empty.hidden = matches.length > 0 + empty.textContent = t(rows.length ? 'directory.noResults' : 'directory.empty') + document.querySelector('#directory-page')!.textContent = t('directory.page', { page, pages }) + const folders = rows.filter(row => row.directory).length + document.querySelector('#directory-summary')!.textContent = input.value.trim() + ? t('directory.filtered', { count: matches.length }) + : t('directory.summary', { folders, files: rows.length - folders }) +} + +function safeURL(value: string) { + try { const url = new URL(value, location.origin); return ['http:', 'https:'].includes(url.protocol) ? url.href : '' } catch { return '' } +} +function localized(value: Record | undefined) { return value?.[locale] || value?.['zh-CN'] || Object.values(value || {}).find(Boolean) || '' } +function applySite() { + const dark = document.documentElement.dataset.theme === 'dark' + const logo = site && safeURL(dark ? site.logoDark : site.logoLight) + for (const image of document.querySelectorAll('.directory-logo')) image.src = logo || (dark ? '/assets/mirrorOUC.png' : '/assets/mirrorOUC_dark.png') + if (!site) return + document.querySelector('#directory-description')!.textContent = localized(site.description) || t('common.footer') + document.querySelector('#directory-address')!.textContent = localized(site.address) || t('common.studioAddress') + const email = document.querySelector('#directory-email')! + email.textContent = site.email || t('common.contactEmail') + email.href = `mailto:${site.email || t('common.contactEmail')}` + const favicon = safeURL(site.favicon) + if (favicon) document.querySelector('link[rel="icon"]')!.href = favicon + const links = document.querySelector('#directory-footer-links')! + links.replaceChildren(...(site.links || []).flatMap(link => { + const url = safeURL(link.url) + if (!url) return [] + const li = document.createElement('li'), a = document.createElement('a') + a.href = url; a.textContent = localized(link.title); a.rel = 'noopener noreferrer' + li.append(a) + return [li] + })) +} +function applyTheme() { + const dark = theme === 'dark' || (theme === 'system' && system.matches) + document.documentElement.dataset.theme = dark ? 'dark' : 'light' + document.querySelector('meta[name="theme-color"]')!.setAttribute('content', dark ? '#0d1117' : '#ffffff') + for (const button of document.querySelectorAll('[data-theme-choice]')) button.setAttribute('aria-pressed', String(button.dataset.themeChoice === theme)) + applySite() +} +function applyLocale() { + i18n.global.locale.value = locale + document.documentElement.lang = locale + document.title = `${path} · ${t('directory.title')} · MirrorOUC` + for (const element of document.querySelectorAll('[data-i18n]')) element.textContent = t(element.dataset.i18n!) + for (const [attribute, data] of [['aria-label', 'i18nAria'], ['placeholder', 'i18nPlaceholder']] as const) { + for (const element of document.querySelectorAll(`[data-${data === 'i18nAria' ? 'i18n-aria' : 'i18n-placeholder'}]`)) element.setAttribute(attribute, t(element.dataset[data]!)) + } + document.querySelector('[data-current-language]')!.textContent = directoryMessages[locale].common.languageName + for (const button of document.querySelectorAll('[data-locale]')) button.setAttribute('aria-pressed', String(button.dataset.locale === locale)) + renderPage() + applySite() +} + +// Build breadcrumbs using text nodes, never HTML from a repository path. +const breadcrumbs = document.querySelector('.directory-breadcrumbs')! +segments.forEach((segment, index) => { + const slash = document.createElement('span'); slash.textContent = '/'; slash.setAttribute('aria-hidden', 'true') + const a = document.createElement('a'); a.textContent = segment + a.href = '/mirrors/' + segments.slice(0, index + 1).map(encodeURIComponent).join('/') + '/' + if (index === segments.length - 1) a.setAttribute('aria-current', 'page') + breadcrumbs.append(slash, a) +}) +let searchTimer: ReturnType +input.addEventListener('input', () => { + clearTimeout(searchTimer) + searchTimer = setTimeout(() => { const query = input.value.trim().toLocaleLowerCase(); matches = rows.filter(row => row.name.includes(query)); page = 1; renderPage() }, 120) +}) +previous.addEventListener('click', () => { page--; renderPage(); table.scrollIntoView({ block: 'start' }) }) +next.addEventListener('click', () => { page++; renderPage(); table.scrollIntoView({ block: 'start' }) }) +for (const button of document.querySelectorAll('[data-locale]')) button.addEventListener('click', () => { + locale = button.dataset.locale as Locale; save('mirrorouc.locale', locale); applyLocale(); button.closest('details')!.open = false +}) +for (const button of document.querySelectorAll('[data-theme-choice]')) button.addEventListener('click', () => { + theme = button.dataset.themeChoice as Theme; save('mirrorouc.theme', theme); applyTheme(); button.closest('details')!.open = false +}) +const details = [...document.querySelectorAll('details')] +for (const detail of details) detail.addEventListener('toggle', () => { if (detail.open) for (const other of details) if (other !== detail) other.open = false }) +document.addEventListener('click', event => { for (const detail of details) if (!detail.contains(event.target as Node)) detail.open = false }) +document.addEventListener('keydown', event => { + if (event.key === 'Escape') for (const detail of details) { if (detail.open) { detail.open = false; detail.querySelector('summary')?.focus() } } + const target = event.target as HTMLElement + if ((event.key === '/' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) && !target.isContentEditable) || (event.key === 'k' && (event.ctrlKey || event.metaKey))) { event.preventDefault(); input.focus() } +}) +system.addEventListener('change', applyTheme) +document.body.classList.add('directory-enhanced') +applyTheme(); applyLocale() +// Optional branding/settings only. A failed Go API cannot prevent browsing. +fetch('/api/v1/public', { signal: AbortSignal.timeout(3000) }).then(response => { + if (!response.ok) throw new Error('Settings unavailable') + return response.json() +}).then(data => { site = data.site; applySite() }).catch(() => {}) diff --git a/src/directory/messages.ts b/src/directory/messages.ts new file mode 100644 index 0000000..34b36f0 --- /dev/null +++ b/src/directory/messages.ts @@ -0,0 +1,10 @@ +import commonZh from '../locales/zh-CN/common.ts' +import commonEn from '../locales/en-US/common.ts' +import directoryZh from '../locales/zh-CN/directory.ts' +import directoryEn from '../locales/en-US/directory.ts' + +// Shared by the build-time Nginx templates and optional browser enhancements. +export const directoryMessages = { + 'zh-CN': { common: commonZh, directory: directoryZh }, + 'en-US': { common: commonEn, directory: directoryEn }, +} diff --git a/src/directory/style.css b/src/directory/style.css new file mode 100644 index 0000000..ccd9cab --- /dev/null +++ b/src/directory/style.css @@ -0,0 +1,58 @@ +.directory-page [hidden] { display: none !important; } +.directory-page:not(.directory-enhanced) .enhanced-control { display: none; } +.directory-page summary { list-style: none; cursor: pointer; } +.directory-page summary::-webkit-details-marker { display: none; } +.directory-page .language-option[aria-pressed='true'], .directory-page .theme-options button[aria-pressed='true'] { color: var(--blue); background: var(--blue-soft); } +.directory-page .theme-options button { color: var(--ink); } +.directory-main { min-height: 45vh; padding-top: 30px; padding-bottom: 70px; } +.directory-controls { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 20px; min-height: 48px; margin-bottom: 26px; } +.directory-breadcrumbs { display: flex; align-items: baseline; flex-wrap: wrap; gap: 10px; min-width: 0; color: var(--blue); font-size: 20px; font-weight: 600; } +.directory-breadcrumbs a { overflow-wrap: anywhere; } +.directory-breadcrumbs > span { color: var(--ink-2); } +.directory-breadcrumbs a:hover, .directory-refresh:hover { text-decoration: underline; text-underline-offset: 4px; } +.directory-actions { display: flex; align-items: center; gap: 16px; } +#directory-search { width: 280px; max-width: 100%; height: 44px; padding: 9px 13px; border: 1px solid var(--line); border-radius: 5px; background: var(--paper); font-size: 15px; } +.directory-refresh { flex-shrink: 0; color: var(--blue); font-size: 15px; } +:root[data-theme='dark'] #list th { color: #fff; } +#list { width: 100%; table-layout: fixed; border-collapse: collapse; font-size: 15px; } +#list th { padding: 13px 10px; border-bottom: 2px solid var(--line); text-align: left; font-size: 17px; font-weight: 700; } +#list th:first-child { width: 57% !important; } +#list th:nth-child(2) { width: 14% !important; } +#list th:nth-child(3) { width: 29% !important; } +#list td { padding: 11px 10px; border-bottom: 1px solid var(--line-soft); vertical-align: middle; } +#list td.link { overflow-wrap: anywhere; } +#list td.link a { display: inline-block; padding: 2px 0; color: var(--blue); } +#list td.link a:hover { text-decoration: underline; text-underline-offset: 3px; } +#list td.size, #list td.date { color: var(--ink); font-size: 13px; font-variant-numeric: tabular-nums; } +#list tr:hover td { background: var(--blue-soft); } +#list thead a + a { color: var(--blue); } +#directory-empty { padding: 28px 10px; color: var(--ink-2); } +.directory-pagination { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; padding-top: 22px; color: var(--ink-2); font-size: 13px; } +.directory-pagination > div { display: flex; align-items: center; gap: 15px; } +.directory-pagination button { min-height: 36px; padding: 5px 10px; color: var(--blue); } +.directory-pagination button:disabled { color: var(--ink-2); opacity: .5; cursor: default; } +.directory-mobile { display: none; } +.directory-mobile-nav { position: absolute; top: calc(100% - 10px); left: 16px; right: 16px; padding: 8px 14px; border: 1px solid var(--line); border-radius: 7px; background: var(--panel); box-shadow: var(--shadow); } +.directory-mobile-nav .nav-link { display: block; border: 0; min-height: 44px; padding: 11px 0; } +.directory-page :focus-visible { outline: 2px solid var(--blue); outline-offset: 3px; } +@media (max-width: 700px) { + .directory-mobile { display: block; } + .directory-page .brand-logo { width: min(180px, 100%); } + .directory-page .brand { max-width: calc(100% - 165px); } + .directory-main { padding-top: 16px; padding-bottom: 44px; } + .directory-controls { align-items: stretch; gap: 16px; margin-bottom: 20px; } + .directory-breadcrumbs { font-size: 18px; gap: 8px; } + .directory-actions { width: 100%; gap: 14px; } + #directory-search { flex: 1; min-width: 0; height: 44px; font-size: 16px; } + #list { font-size: 14px; } + #list th { padding: 10px 4px; font-size: 14px; } + #list th:first-child { width: 52% !important; } + #list th:nth-child(2) { width: 17% !important; } + #list th:nth-child(3) { width: 31% !important; } + #list th a + a { display: none; } + #list td { padding: 10px 4px; } + #list td.size, #list td.date { font-size: 11px; } + #list td.date { overflow-wrap: anywhere; } + .directory-pagination { font-size: 12px; } + .directory-pagination button { min-height: 44px; } +} diff --git a/src/locales/en-US/directory.ts b/src/locales/en-US/directory.ts new file mode 100644 index 0000000..b6fa466 --- /dev/null +++ b/src/locales/en-US/directory.ts @@ -0,0 +1,7 @@ +export default { + title: 'Files', root: 'Mirrors', breadcrumb: 'Directory path', parent: 'Parent directory', skip: 'Skip to file list', + name: 'File name', size: 'Size', modified: 'Last modified', + search: 'Search this directory…', refresh: 'Refresh', empty: 'This directory is empty', noResults: 'No matching files or directories', + summary: 'Directories: {folders} · Files: {files}', filtered: '{count} matching entries', + pagination: 'File list pagination', previous: 'Previous', next: 'Next', page: 'Page {page} of {pages}', +} diff --git a/src/locales/index.ts b/src/locales/index.ts index 91ef5a6..a7ee4f8 100644 --- a/src/locales/index.ts +++ b/src/locales/index.ts @@ -8,12 +8,14 @@ import announcementsEn from './en-US/announcements' import monitorZh from './zh-CN/monitor' import monitorEn from './en-US/monitor' import { adminZh, adminEn } from './admin-messages' +import directoryZh from './zh-CN/directory' +import directoryEn from './en-US/directory' import { datetimeFormats as datetimeZh, numberFormats as numbersZh } from './zh-CN/formats' import { datetimeFormats as datetimeEn, numberFormats as numbersEn } from './en-US/formats' export const messages = { - 'zh-CN': { common: commonZh, mirrors: mirrorsZh, announcements: announcementsZh, monitor: monitorZh, admin: adminZh }, - 'en-US': { common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn }, + 'zh-CN': { common: commonZh, mirrors: mirrorsZh, announcements: announcementsZh, monitor: monitorZh, admin: adminZh, directory: directoryZh }, + 'en-US': { common: commonEn, mirrors: mirrorsEn, announcements: announcementsEn, monitor: monitorEn, admin: adminEn, directory: directoryEn }, } export type Locale = keyof typeof messages export const supportedLocales = Object.keys(messages) as Locale[] diff --git a/src/locales/zh-CN/directory.ts b/src/locales/zh-CN/directory.ts new file mode 100644 index 0000000..69beacf --- /dev/null +++ b/src/locales/zh-CN/directory.ts @@ -0,0 +1,7 @@ +export default { + title: '文件目录', root: '镜像目录', breadcrumb: '目录路径', parent: '返回上级', skip: '跳转到文件列表', + name: '文件名', size: '大小', modified: '修改时间', + search: '搜索当前目录…', refresh: '刷新', empty: '此目录暂无文件', noResults: '没有找到匹配的文件或目录', + summary: '{folders} 个目录 · {files} 个文件', filtered: '找到 {count} 项', + pagination: '文件列表分页', previous: '上一页', next: '下一页', page: '第 {page} / {pages} 页', +} diff --git a/vite.config.ts b/vite.config.ts index 25b4d50..e76a0fb 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,7 +1,19 @@ -import { defineConfig } from 'vite' +import { defineConfig, loadEnv } from 'vite' import vue from '@vitejs/plugin-vue' -export default defineConfig({ - plugins: [vue()], - server: { port: 5173, strictPort: true, proxy: { '/api': 'http://127.0.0.1:8081', '/uploads': 'http://127.0.0.1:8081', '/mirrors/': 'http://127.0.0.1:8081' } }, +export default defineConfig(({ mode }) => { + const nginx = loadEnv(mode, '.', 'MIRROROUC_').MIRROROUC_NGINX_ORIGIN || 'http://127.0.0.1:8080' + return { + plugins: [vue()], + build: { rollupOptions: { input: { main: 'index.html', directory: 'directory.html' } } }, + server: { + port: 5173, strictPort: true, + proxy: { + '/api': 'http://127.0.0.1:8081', '/uploads': 'http://127.0.0.1:8081', + '/mirrors': nginx, + // The server-rendered directory references its own built asset hashes. + '/assets/': nginx, + }, + }, + } })