Compare commits
29
Commits
v1.0.2-beta8
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf95d715a4 | ||
|
|
1838afce56 | ||
|
|
7f3a1cdf5c | ||
|
|
2d7683b0bb | ||
|
|
6edc44fe26 | ||
|
|
f81a588dc1 | ||
|
|
be3a1eda8c | ||
|
|
0098e9eb07 | ||
|
|
629fe9c26a | ||
|
|
159f9e3f38 | ||
|
|
598fb5c679 | ||
|
|
aaf394f790 | ||
|
|
3c8ac04269 | ||
|
|
71b8d111fb | ||
|
|
febbd84ae7 | ||
|
|
667c1a0900 | ||
|
|
ac38c98203 | ||
|
|
ef1435bd31 | ||
|
|
87de306245 | ||
|
|
fbcbb803ac | ||
|
|
7b3a5212e6 | ||
|
|
8d73689356 | ||
|
|
4a3b4268b9 | ||
|
|
64f2f85607 | ||
|
|
ede28e0062 | ||
|
|
b0178c046f | ||
|
|
57ff974d79 | ||
|
|
ac9373ddae | ||
|
|
47c4a3973d |
No files matched your search
@@ -51,6 +51,7 @@ jobs:
|
||||
node scripts/axolotl/check-migrations.mjs --release
|
||||
node scripts/axolotl/brand-guard.mjs
|
||||
node scripts/axolotl/i18n-check.mjs
|
||||
node --test scripts/axolotl/publish-skin-site.test.mjs
|
||||
cargo fmt --all --check
|
||||
|
||||
- name: Check updater signing configuration
|
||||
@@ -286,6 +287,9 @@ jobs:
|
||||
name: Verify and publish
|
||||
needs: build
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: skin-site-${{ github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}
|
||||
UPDATE_SERVER_WEBHOOK_SECRET: ${{ secrets.UPDATE_SERVER_WEBHOOK_SECRET }}
|
||||
@@ -298,6 +302,11 @@ jobs:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
- name: Download updater signatures
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -374,6 +383,16 @@ jobs:
|
||||
)
|
||||
gh release upload "${GITHUB_REF_NAME}" "release-check/${bundle_name}" --clobber
|
||||
|
||||
- name: Publish to skin site
|
||||
env:
|
||||
SKIN_SITE_TOKEN: ${{ secrets.SKIN_SITE_CI_UPLOAD_TOKEN }}
|
||||
SKIN_SITE_URL: ${{ vars.SKIN_SITE_URL || 'https://skin.starlight.cool' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#v}"
|
||||
bundle="release-check/Starlight_Launcher_${version}_skin-site-update.zip"
|
||||
node scripts/axolotl/publish-skin-site.mjs "${bundle}" "${GITHUB_REF_NAME}"
|
||||
|
||||
- name: Notify Update Server to publish release assets
|
||||
if: ${{ env.UPDATE_SERVER_URL != '' && env.UPDATE_SERVER_WEBHOOK_SECRET != '' }}
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
name: Diagnose skin site CI authentication
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
diagnose:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Inspect token format without revealing credentials
|
||||
env:
|
||||
SKIN_SITE_TOKEN: ${{ secrets.SKIN_SITE_CI_UPLOAD_TOKEN }}
|
||||
SKIN_SITE_URL: ${{ vars.SKIN_SITE_URL || 'https://skin.starlight.cool' }}
|
||||
run: |
|
||||
node --input-type=module <<'NODE'
|
||||
const token = process.env.SKIN_SITE_TOKEN || ''
|
||||
const checks = {
|
||||
configured: token.length > 0,
|
||||
containsWhitespace: /\s/.test(token),
|
||||
containsComma: token.includes(','),
|
||||
containsQuotes: /["']/.test(token),
|
||||
containsBearerPrefix: /^Bearer\s/i.test(token),
|
||||
bearerTokenFormatValid: /^[A-Za-z0-9._~+/-]+=*$/.test(token),
|
||||
}
|
||||
console.log(JSON.stringify(checks))
|
||||
if (!checks.bearerTokenFormatValid) {
|
||||
console.error('::error::CI secret is not a valid Bearer token. No credential value has been logged.')
|
||||
process.exitCode = 1
|
||||
} else {
|
||||
const base = process.env.SKIN_SITE_URL.replace(/\/$/, '')
|
||||
if (new URL(base).protocol !== 'https:') throw new Error('HTTPS is required')
|
||||
try {
|
||||
const response = await fetch(base + '/starlight/launcher/admin', {
|
||||
headers: { Authorization: 'Bearer ' + token, Accept: 'application/json' },
|
||||
redirect: 'error', signal: AbortSignal.timeout(30000),
|
||||
})
|
||||
console.log('Read-only CI authentication HTTP status: ' + response.status)
|
||||
await response.body?.cancel()
|
||||
if (!response.ok) process.exitCode = 1
|
||||
} catch {
|
||||
console.error('::error::Read-only CI authentication request failed; credentials have not been logged.')
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
NODE
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Sync release to skin site
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Existing GitHub release tag to sync (for example v1.0.2-beta10)
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: skin-site-${{ inputs.tag }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Upload and activate existing release
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- name: Check out publisher
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
- name: Download complete update package
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "${RELEASE_TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error::Expected a semantic version tag beginning with v'
|
||||
exit 1
|
||||
fi
|
||||
version="${RELEASE_TAG#v}"
|
||||
gh release download "${RELEASE_TAG}" \
|
||||
--pattern "Starlight_Launcher_${version}_skin-site-update.zip" \
|
||||
--dir release-check
|
||||
|
||||
- name: Publish to skin site
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.tag }}
|
||||
SKIN_SITE_TOKEN: ${{ secrets.SKIN_SITE_CI_UPLOAD_TOKEN }}
|
||||
SKIN_SITE_URL: ${{ vars.SKIN_SITE_URL || 'https://skin.starlight.cool' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${RELEASE_TAG#v}"
|
||||
node scripts/axolotl/publish-skin-site.mjs \
|
||||
"release-check/Starlight_Launcher_${version}_skin-site-update.zip" "${RELEASE_TAG}"
|
||||
Generated
+2
-2
@@ -6841,7 +6841,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "theseus"
|
||||
version = "1.0.2-beta7"
|
||||
version = "1.0.2-beta11"
|
||||
dependencies = [
|
||||
"ariadne",
|
||||
"async-minecraft-ping",
|
||||
@@ -6945,7 +6945,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "theseus_gui"
|
||||
version = "1.0.2-beta7"
|
||||
version = "1.0.2-beta11"
|
||||
dependencies = [
|
||||
"ashpd",
|
||||
"async_zip",
|
||||
|
||||
@@ -1,76 +1,77 @@
|
||||
{
|
||||
"name": "@modrinth/app-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.2-beta8",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"tsc:check": "vue-tsc --noEmit",
|
||||
"lint": "eslint . && prettier --check .",
|
||||
"fix": "eslint . --fix && prettier --write .",
|
||||
"intl:extract": "formatjs extract \"src/**/*.{vue,ts,tsx,js,jsx,mts,cts,mjs,cjs}\" --ignore \"**/*.d.ts\" --ignore node_modules --out-file src/locales/en-US/index.json --format crowdin --preserve-whitespace",
|
||||
"intl:prune-local": "pnpm -w scripts i18n-icu-contract prune-local --scope apps/app-frontend",
|
||||
"test": "vue-tsc --noEmit && node --test \"src/**/*.test.ts\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "6.3.1",
|
||||
"@dnd-kit/utilities": "3.2.2",
|
||||
"@dnd-kit/vue": "^0.5.0",
|
||||
"@lobehub/icons-static-svg": "1.94.0",
|
||||
"@modrinth/api-client": "workspace:^",
|
||||
"@modrinth/assets": "workspace:*",
|
||||
"@modrinth/server": "workspace:*",
|
||||
"@modrinth/ui": "workspace:*",
|
||||
"@modrinth/utils": "workspace:*",
|
||||
"@sfirew/minecraft-motd-parser": "^1.1.6",
|
||||
"@tanstack/vue-query": "5.90.7",
|
||||
"@tauri-apps/api": "^2.5.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.2.1",
|
||||
"@tauri-apps/plugin-fs": "^2.4.5",
|
||||
"@tauri-apps/plugin-http": "~2.5.7",
|
||||
"@tauri-apps/plugin-opener": "^2.2.6",
|
||||
"@tauri-apps/plugin-os": "^2.2.1",
|
||||
"@tauri-apps/plugin-updater": "^2.7.1",
|
||||
"@tauri-apps/plugin-window-state": "^2.2.2",
|
||||
"@types/three": "^0.172.0",
|
||||
"@vueuse/core": "^11.1.0",
|
||||
"dayjs": "^1.11.10",
|
||||
"deepslate": "0.26.0",
|
||||
"fflate": "0.8.2",
|
||||
"floating-vue": "^5.2.2",
|
||||
"fuse.js": "^6.6.2",
|
||||
"intl-messageformat": "^10.7.7",
|
||||
"monaco-editor": "^0.56.0",
|
||||
"ofetch": "^1.3.4",
|
||||
"overlayscrollbars": "^2.15.1",
|
||||
"pinia": "^3.0.0",
|
||||
"three": "^0.172.0",
|
||||
"vite-svg-loader": "^5.1.0",
|
||||
"vue": "^3.5.13",
|
||||
"vue-i18n": "^10.0.0",
|
||||
"vue-router": "^4.6.0",
|
||||
"vuedraggable": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^1.1.1",
|
||||
"@formatjs/cli": "^6.2.12",
|
||||
"@modrinth/tooling-config": "workspace:*",
|
||||
"@nuxt/eslint-config": "^0.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"eslint": "^9.9.1",
|
||||
"eslint-plugin-turbo": "^2.5.4",
|
||||
"postcss": "^8.4.39",
|
||||
"prettier": "^3.2.5",
|
||||
"sass": "^1.74.1",
|
||||
"tailwindcss": "^3.4.4",
|
||||
"typescript": "^5.5.4",
|
||||
"vite": "^8.0.0",
|
||||
"vite-plugin-vue-devtools": "^8.2.1",
|
||||
"vue-component-type-helpers": "^3.1.8",
|
||||
"vue-tsc": "^2.1.6"
|
||||
},
|
||||
"packageManager": "pnpm@9.4.0",
|
||||
"web-types": "../../web-types.json"
|
||||
"name": "@modrinth/app-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.2-beta11",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"tsc:check": "vue-tsc --noEmit",
|
||||
"lint": "eslint . && prettier --check .",
|
||||
"fix": "eslint . --fix && prettier --write .",
|
||||
"intl:extract": "formatjs extract \"src/**/*.{vue,ts,tsx,js,jsx,mts,cts,mjs,cjs}\" --ignore \"**/*.d.ts\" --ignore node_modules --out-file src/locales/en-US/index.json --format crowdin --preserve-whitespace",
|
||||
"intl:prune-local": "pnpm -w scripts i18n-icu-contract prune-local --scope apps/app-frontend",
|
||||
"test": "vue-tsc --noEmit && node --test \"src/**/*.test.ts\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "6.3.1",
|
||||
"@dnd-kit/utilities": "3.2.2",
|
||||
"@dnd-kit/vue": "^0.5.0",
|
||||
"@lobehub/icons-static-svg": "1.94.0",
|
||||
"@modrinth/api-client": "workspace:^",
|
||||
"@modrinth/assets": "workspace:*",
|
||||
"@modrinth/server": "workspace:*",
|
||||
"@modrinth/ui": "workspace:*",
|
||||
"@modrinth/utils": "workspace:*",
|
||||
"@sfirew/minecraft-motd-parser": "^1.1.6",
|
||||
"@tanstack/vue-query": "5.90.7",
|
||||
"@tauri-apps/api": "^2.5.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.2.1",
|
||||
"@tauri-apps/plugin-fs": "^2.4.5",
|
||||
"@tauri-apps/plugin-http": "~2.5.7",
|
||||
"@tauri-apps/plugin-opener": "^2.2.6",
|
||||
"@tauri-apps/plugin-os": "^2.2.1",
|
||||
"@tauri-apps/plugin-updater": "^2.7.1",
|
||||
"@tauri-apps/plugin-window-state": "^2.2.2",
|
||||
"@types/three": "^0.172.0",
|
||||
"@vueuse/core": "^11.1.0",
|
||||
"dayjs": "^1.11.10",
|
||||
"deepslate": "0.26.0",
|
||||
"fflate": "0.8.2",
|
||||
"floating-vue": "^5.2.2",
|
||||
"fuse.js": "^6.6.2",
|
||||
"intl-messageformat": "^10.7.7",
|
||||
"monaco-editor": "^0.56.0",
|
||||
"ofetch": "^1.3.4",
|
||||
"overlayscrollbars": "^2.15.1",
|
||||
"pinia": "^3.0.0",
|
||||
"three": "^0.172.0",
|
||||
"vite-svg-loader": "^5.1.0",
|
||||
"vue": "^3.5.13",
|
||||
"vue-i18n": "^10.0.0",
|
||||
"vue-router": "^4.6.0",
|
||||
"vuedraggable": "^4.1.0",
|
||||
"xxhash-wasm": "1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^1.1.1",
|
||||
"@formatjs/cli": "^6.2.12",
|
||||
"@modrinth/tooling-config": "workspace:*",
|
||||
"@nuxt/eslint-config": "^0.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"eslint": "^9.9.1",
|
||||
"eslint-plugin-turbo": "^2.5.4",
|
||||
"postcss": "^8.4.39",
|
||||
"prettier": "^3.2.5",
|
||||
"sass": "^1.74.1",
|
||||
"tailwindcss": "^3.4.4",
|
||||
"typescript": "^5.5.4",
|
||||
"vite": "^8.0.0",
|
||||
"vite-plugin-vue-devtools": "^8.2.1",
|
||||
"vue-component-type-helpers": "^3.1.8",
|
||||
"vue-tsc": "^2.1.6"
|
||||
},
|
||||
"packageManager": "pnpm@9.4.0",
|
||||
"web-types": "../../web-types.json"
|
||||
}
|
||||
@@ -32,6 +32,130 @@ export const ANNOUNCEMENT_CHANGE_TYPES: readonly AnnouncementChangeType[] = [
|
||||
]
|
||||
|
||||
export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
{
|
||||
id: 'launcher-1.0.2-beta11',
|
||||
version: '1.0.2-beta11',
|
||||
publishedAt: '2026-10-20',
|
||||
title: {
|
||||
'en-US': 'Starlight Launcher 1.0.2-beta11',
|
||||
'zh-CN': 'Starlight Launcher 1.0.2-beta11',
|
||||
},
|
||||
changes: {
|
||||
fixed: [
|
||||
{
|
||||
'en-US':
|
||||
'Filled missing Chinese translations across skin site sign-in, announcements, verification, registration, account settings, downloads and maps, and localized remaining user and Wiki labels.',
|
||||
'zh-CN':
|
||||
'补齐皮肤站登录、公告、验证、注册、账号设置、下载和地图等界面的中文翻译,并修复用户信息与维基权限选项中的英文标签。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Renew the saved skin site JWT on launcher startup before loading the user and announcements. Fixed overlapping refresh, sign-in and sign-out requests that could leave the account in an incorrect state.',
|
||||
'zh-CN':
|
||||
'启动启动器时先刷新已保存的皮肤站 JWT,再加载用户与公告;修复刷新、登录和退出请求交错时可能导致的账号状态异常。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Announcements now reload after sign-in, show a sign-in hint when signed out, and offer a retry action after a loading failure.',
|
||||
'zh-CN': '公告在登录后自动重新加载,未登录时显示登录提示,加载失败时可直接重试。',
|
||||
},
|
||||
],
|
||||
changed: [
|
||||
{
|
||||
'en-US':
|
||||
'Skin site release publishing now uses chunked uploads and reports synchronization failures explicitly. Localization checks also scan message IDs used in source to catch missing catalog entries.',
|
||||
'zh-CN':
|
||||
'皮肤站自动发布改用分片上传,同步失败会明确报错;国际化检查新增源码词条扫描,防止再次遗漏语言包内容。',
|
||||
},
|
||||
],
|
||||
},
|
||||
notes: {
|
||||
'en-US':
|
||||
'If the previously saved JWT has already expired, sign in again once to restore the session.',
|
||||
'zh-CN': '如果此前保存的 JWT 已经过期,需要重新登录一次以恢复会话。',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'launcher-1.0.2-beta10',
|
||||
version: '1.0.2-beta10',
|
||||
publishedAt: '2026-10-20',
|
||||
title: {
|
||||
'en-US': 'Starlight Launcher 1.0.2-beta10',
|
||||
'zh-CN': 'Starlight Launcher 1.0.2-beta10',
|
||||
},
|
||||
changes: {
|
||||
security: [
|
||||
{
|
||||
'en-US':
|
||||
'Backported the upstream Axolotl modpack path traversal fix to prevent malicious modpacks from writing files outside the intended installation directory.',
|
||||
'zh-CN':
|
||||
'合入上游 Axolotl 整合包路径穿越安全补丁,阻止恶意整合包向安装目录之外写入文件。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Strengthened path validation for Modrinth and CurseForge modpacks, server installations, cached files and modpack uninstall cleanup, including unsafe Windows path aliases.',
|
||||
'zh-CN':
|
||||
'加强 Modrinth 与 CurseForge 整合包、服务端安装、缓存文件及整合包卸载清理的路径校验,拦截不安全的 Windows 路径别名。',
|
||||
},
|
||||
],
|
||||
},
|
||||
notes: {
|
||||
'en-US':
|
||||
'Users of earlier versions should update promptly, especially before installing modpacks from untrusted sources.',
|
||||
'zh-CN': '建议旧版本用户尽快更新,尤其是在安装来源不明的整合包之前。',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'launcher-1.0.2-beta9',
|
||||
version: '1.0.2-beta9',
|
||||
publishedAt: '2026-10-19',
|
||||
title: {
|
||||
'en-US': 'Starlight Launcher 1.0.2-beta9',
|
||||
'zh-CN': 'Starlight Launcher 1.0.2-beta9',
|
||||
},
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US':
|
||||
'Finished the skin site admin console: system overview, announcements, user and player management, review paper editor, mod upload with batch operations, chat room management with real-time voice, servers, audit log, resource downloads, donations and launcher releases.',
|
||||
'zh-CN':
|
||||
'补全皮肤站管理台:系统概览、公告、用户与玩家管理、审核试卷编辑器、Mod 上传与批量操作、聊天室房间管理与实时语音、服务器、审计日志、资源下载、捐赠与启动器版本管理。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Added Wiki management to the admin console, including a MediaWiki migration center that imports pages from an existing wiki and lets you review, publish or roll back the result.',
|
||||
'zh-CN':
|
||||
'管理台新增维基管理,包含 MediaWiki 迁移中心:可从现有 Wiki 导入页面,并对结果进行审核、发布或回滚。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Added a read-only Wiki reader in the launcher: render pages, follow links between entries, and keep a back stack while browsing.',
|
||||
'zh-CN': '启动器新增维基阅读页:渲染词条正文、跟随词条链接跳转,并在浏览时保留返回栈。',
|
||||
},
|
||||
],
|
||||
changed: [
|
||||
{
|
||||
'en-US':
|
||||
'Releases are now published to the skin site automatically when a tag is pushed, so the download page stays in sync without a manual upload.',
|
||||
'zh-CN': '推送 tag 发版时会自动把版本同步到皮肤站,下载页无需再手动上传即可保持同步。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Server management pages are only shown to web administrators.',
|
||||
'zh-CN': '服务器管理页仅对网页管理员展示。',
|
||||
},
|
||||
],
|
||||
fixed: [
|
||||
{
|
||||
'en-US': 'Fixed the Chinese and English text on the skin site home navigation cards.',
|
||||
'zh-CN': '修复皮肤站主页导航卡片的中英文案。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Renamed the public download and map endpoints to resolve a duplicate export.',
|
||||
'zh-CN': '重命名公开下载与地图接口,解决导出冲突。',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'launcher-1.0.2-beta8',
|
||||
version: '1.0.2-beta8',
|
||||
@@ -43,27 +167,35 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'The skin site is now fully native inside the launcher: sign-in, registration, password reset, account settings, players, downloads, world map and player review all run through the launcher UI instead of an embedded web page.',
|
||||
'zh-CN': '皮肤站全面改为启动器原生界面:登录、注册、找回密码、账号设置、角色管理、资源下载、服务器地图与玩家审核均不再依赖内嵌网页。',
|
||||
'en-US':
|
||||
'The skin site is now fully native inside the launcher: sign-in, registration, password reset, account settings, players, downloads, world map and player review all run through the launcher UI instead of an embedded web page.',
|
||||
'zh-CN':
|
||||
'皮肤站全面改为启动器原生界面:登录、注册、找回密码、账号设置、角色管理、资源下载、服务器地图与玩家审核均不再依赖内嵌网页。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Added a bug tracker: browse and filter issues, read details and comments, post replies, create new issues and follow notifications.',
|
||||
'zh-CN': '新增问题追踪:可浏览与筛选问题、查看详情与评论、发表回复、提交新问题并接收通知。',
|
||||
'en-US':
|
||||
'Added a bug tracker: browse and filter issues, read details and comments, post replies, create new issues and follow notifications.',
|
||||
'zh-CN':
|
||||
'新增问题追踪:可浏览与筛选问题、查看详情与评论、发表回复、提交新问题并接收通知。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Added an admin console with a permission gate: system overview, announcements, users, players, player review and launcher releases.',
|
||||
'zh-CN': '新增管理控制台(带权限校验):系统概览、公告管理、用户管理、玩家管理、玩家审核与启动器版本管理。',
|
||||
'en-US':
|
||||
'Added an admin console with a permission gate: system overview, announcements, users, players, player review and launcher releases.',
|
||||
'zh-CN':
|
||||
'新增管理控制台(带权限校验):系统概览、公告管理、用户管理、玩家管理、玩家审核与启动器版本管理。',
|
||||
},
|
||||
],
|
||||
changed: [
|
||||
{
|
||||
'en-US': 'Hosted modpack downloads now go through the dedicated download server, keeping large downloads off the main API host.',
|
||||
'en-US':
|
||||
'Hosted modpack downloads now go through the dedicated download server, keeping large downloads off the main API host.',
|
||||
'zh-CN': '整合包下载改为走独立的下载服务器,避免大文件下载挤占主 API 服务。',
|
||||
},
|
||||
],
|
||||
fixed: [
|
||||
{
|
||||
'en-US': 'LogShare now collects logs with a lightweight reader, fixing crash log uploads that previously failed.',
|
||||
'en-US':
|
||||
'LogShare now collects logs with a lightweight reader, fixing crash log uploads that previously failed.',
|
||||
'zh-CN': 'LogShare 改用轻量日志收集,修复崩溃日志上传失败的问题。',
|
||||
},
|
||||
{
|
||||
@@ -92,12 +224,16 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
'zh-CN': '修复实时日志积压导致控制台卡顿的问题。',
|
||||
},
|
||||
{
|
||||
'en-US': 'The update channel now defaults to the build type: installing a Beta build starts on the Beta channel instead of Release.',
|
||||
'zh-CN': '更新通道默认值改为跟随安装包版本:安装 Beta 版后默认使用 Beta 通道,不再回落为 Release。',
|
||||
'en-US':
|
||||
'The update channel now defaults to the build type: installing a Beta build starts on the Beta channel instead of Release.',
|
||||
'zh-CN':
|
||||
'更新通道默认值改为跟随安装包版本:安装 Beta 版后默认使用 Beta 通道,不再回落为 Release。',
|
||||
},
|
||||
{
|
||||
'en-US': 'On Linux, the default game directory for StarLight instances no longer points at the system install path (e.g. /usr/bin); it falls back to the home directory.',
|
||||
'zh-CN': 'Linux 上 StarLight 实例的默认游戏目录不再指向系统安装路径(如 /usr/bin),改为回退到用户主目录。',
|
||||
'en-US':
|
||||
'On Linux, the default game directory for StarLight instances no longer points at the system install path (e.g. /usr/bin); it falls back to the home directory.',
|
||||
'zh-CN':
|
||||
'Linux 上 StarLight 实例的默认游戏目录不再指向系统安装路径(如 /usr/bin),改为回退到用户主目录。',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -113,15 +249,19 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'Added keyboard shortcut settings: enable and rebind navigation and quick-scrolling shortcuts.',
|
||||
'en-US':
|
||||
'Added keyboard shortcut settings: enable and rebind navigation and quick-scrolling shortcuts.',
|
||||
'zh-CN': '新增键盘快捷键设置:可启用并自定义导航与快速滚动快捷键。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Added crash log sharing and AI analysis: share crash diagnostics to LogShare for a structured summary and optional AI analysis, with a rebuilt crash window that browses log files and streams the analysis.',
|
||||
'zh-CN': '新增崩溃日志分享与 AI 分析:可将崩溃诊断分享到 LogShare 获取结构化摘要与 AI 分析;崩溃窗口重做为双栏布局,可浏览日志文件并流式查看分析结果。',
|
||||
'en-US':
|
||||
'Added crash log sharing and AI analysis: share crash diagnostics to LogShare for a structured summary and optional AI analysis, with a rebuilt crash window that browses log files and streams the analysis.',
|
||||
'zh-CN':
|
||||
'新增崩溃日志分享与 AI 分析:可将崩溃诊断分享到 LogShare 获取结构化摘要与 AI 分析;崩溃窗口重做为双栏布局,可浏览日志文件并流式查看分析结果。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Crash logs now also collect JVM crash reports (hs_err_pid*.log) and launcher logs.',
|
||||
'en-US':
|
||||
'Crash logs now also collect JVM crash reports (hs_err_pid*.log) and launcher logs.',
|
||||
'zh-CN': '崩溃日志现在也会收集 JVM 崩溃报告(hs_err_pid*.log)与启动器日志。',
|
||||
},
|
||||
{
|
||||
@@ -162,12 +302,16 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'Added a remote announcements center: a bell in the top bar opens a panel listing launcher announcements fetched from the Starlight skin site.',
|
||||
'zh-CN': '新增远程公告中心:顶栏的铃铛可打开公告面板,展示从 Starlight 皮肤站拉取的启动器公告。',
|
||||
'en-US':
|
||||
'Added a remote announcements center: a bell in the top bar opens a panel listing launcher announcements fetched from the Starlight skin site.',
|
||||
'zh-CN':
|
||||
'新增远程公告中心:顶栏的铃铛可打开公告面板,展示从 Starlight 皮肤站拉取的启动器公告。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Added a custom Minecraft window title option: set a global toggle and default title, and let each instance override it. The game window is renamed on Windows.',
|
||||
'zh-CN': '新增自定义 Minecraft 窗口标题:可设置全局开关与默认标题,并允许各实例单独覆盖;Windows 下会重命名游戏窗口。',
|
||||
'en-US':
|
||||
'Added a custom Minecraft window title option: set a global toggle and default title, and let each instance override it. The game window is renamed on Windows.',
|
||||
'zh-CN':
|
||||
'新增自定义 Minecraft 窗口标题:可设置全局开关与默认标题,并允许各实例单独覆盖;Windows 下会重命名游戏窗口。',
|
||||
},
|
||||
],
|
||||
fixed: [
|
||||
@@ -189,24 +333,31 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'Added armor and armor-trim rendering to the skin preview, letting you try on armor pieces and trim patterns directly in the skin editor.',
|
||||
'zh-CN': '皮肤预览新增盔甲与盔甲纹饰渲染,可在皮肤编辑器内直接试穿各部位盔甲并调整纹饰图案。',
|
||||
'en-US':
|
||||
'Added armor and armor-trim rendering to the skin preview, letting you try on armor pieces and trim patterns directly in the skin editor.',
|
||||
'zh-CN':
|
||||
'皮肤预览新增盔甲与盔甲纹饰渲染,可在皮肤编辑器内直接试穿各部位盔甲并调整纹饰图案。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Armor preview selections in the skin editor are now saved locally, so they persist across sessions.',
|
||||
'en-US':
|
||||
'Armor preview selections in the skin editor are now saved locally, so they persist across sessions.',
|
||||
'zh-CN': '皮肤编辑器中的盔甲预览选择现在会保存在本地,跨会话保留。',
|
||||
},
|
||||
],
|
||||
changed: [
|
||||
{
|
||||
'en-US': 'Improved download scheduling to reduce concurrency automatically when tasks are waiting for capacity, making large Minecraft installations more reliable on constrained connections.',
|
||||
'zh-CN': '优化下载任务调度:任务因容量不足排队时会自动降低并发,提升大型 Minecraft 版本在受限网络环境下的安装稳定性。',
|
||||
'en-US':
|
||||
'Improved download scheduling to reduce concurrency automatically when tasks are waiting for capacity, making large Minecraft installations more reliable on constrained connections.',
|
||||
'zh-CN':
|
||||
'优化下载任务调度:任务因容量不足排队时会自动降低并发,提升大型 Minecraft 版本在受限网络环境下的安装稳定性。',
|
||||
},
|
||||
],
|
||||
fixed: [
|
||||
{
|
||||
'en-US': 'Fixed downloads timing out while waiting for internal connection capacity, which could cause Minecraft installations to fail even when the network was available.',
|
||||
'zh-CN': '修复下载任务等待内部连接容量时过早超时,导致网络正常的情况下 Minecraft 安装仍可能失败的问题。',
|
||||
'en-US':
|
||||
'Fixed downloads timing out while waiting for internal connection capacity, which could cause Minecraft installations to fail even when the network was available.',
|
||||
'zh-CN':
|
||||
'修复下载任务等待内部连接容量时过早超时,导致网络正常的情况下 Minecraft 安装仍可能失败的问题。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Fixed instance group changes not saving for some instances.',
|
||||
@@ -226,8 +377,10 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
fixed: [
|
||||
{
|
||||
'en-US': 'Fixed the anniversary celebration banner not showing above the window title bar, and made the banner background semi-transparent so the content behind it stays visible.',
|
||||
'zh-CN': '修复周年庆庆祝横幅被窗口标题栏遮挡、无法显示的问题,并将横幅背景改为半透明,避免遮住下方内容。',
|
||||
'en-US':
|
||||
'Fixed the anniversary celebration banner not showing above the window title bar, and made the banner background semi-transparent so the content behind it stays visible.',
|
||||
'zh-CN':
|
||||
'修复周年庆庆祝横幅被窗口标题栏遮挡、无法显示的问题,并将横幅背景改为半透明,避免遮住下方内容。',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -243,8 +396,10 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
fixed: [
|
||||
{
|
||||
'en-US': 'Fixed the launcher failing to start with "no such table: synced_pack_catalog": the cross-instance sync migration was missing the synced_pack_catalog and synced_pack_instances tables.',
|
||||
'zh-CN': '修复启动器因 "no such table: synced_pack_catalog" 无法启动的问题:跨实例同步迁移遗漏了 synced_pack_catalog 与 synced_pack_instances 两张表。',
|
||||
'en-US':
|
||||
'Fixed the launcher failing to start with "no such table: synced_pack_catalog": the cross-instance sync migration was missing the synced_pack_catalog and synced_pack_instances tables.',
|
||||
'zh-CN':
|
||||
'修复启动器因 "no such table: synced_pack_catalog" 无法启动的问题:跨实例同步迁移遗漏了 synced_pack_catalog 与 synced_pack_instances 两张表。',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -260,15 +415,20 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'Cross-instance sync: share game options, resource packs, data packs, multiplayer servers, command history, and creative hotbars across instances, with per-option toggles and a fine-grained game-settings editor.',
|
||||
'zh-CN': '跨实例同步:可跨实例共享游戏选项、资源包、数据包、多人服务器、命令历史与创造模式快捷栏,支持逐项开关与精细的游戏设置编辑器。',
|
||||
'en-US':
|
||||
'Cross-instance sync: share game options, resource packs, data packs, multiplayer servers, command history, and creative hotbars across instances, with per-option toggles and a fine-grained game-settings editor.',
|
||||
'zh-CN':
|
||||
'跨实例同步:可跨实例共享游戏选项、资源包、数据包、多人服务器、命令历史与创造模式快捷栏,支持逐项开关与精细的游戏设置编辑器。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Starlight turns 12! On October 4th every year the launcher now shows a celebration banner and falling confetti. The anniversary number is computed from 2014.',
|
||||
'zh-CN': 'Starlight 十二周年!每年 10 月 4 日,启动器会显示庆祝横幅与飘落的彩带、蛋糕,周年数按 2014 年起算。',
|
||||
'en-US':
|
||||
'Starlight turns 12! On October 4th every year the launcher now shows a celebration banner and falling confetti. The anniversary number is computed from 2014.',
|
||||
'zh-CN':
|
||||
'Starlight 十二周年!每年 10 月 4 日,启动器会显示庆祝横幅与飘落的彩带、蛋糕,周年数按 2014 年起算。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Added a developer feature flag to preview the anniversary celebration at any time.',
|
||||
'en-US':
|
||||
'Added a developer feature flag to preview the anniversary celebration at any time.',
|
||||
'zh-CN': '新增开发者功能开关,可随时预览周年庆效果。',
|
||||
},
|
||||
],
|
||||
@@ -285,8 +445,10 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'Instance backups: create deduplicated snapshots of an instance while it is closed, preview and restore them, exclude specific files or folders, and move the backup repository.',
|
||||
'zh-CN': '实例备份:在实例关闭时创建去重快照,可预览与恢复,支持排除指定文件或文件夹,并可迁移备份仓库。',
|
||||
'en-US':
|
||||
'Instance backups: create deduplicated snapshots of an instance while it is closed, preview and restore them, exclude specific files or folders, and move the backup repository.',
|
||||
'zh-CN':
|
||||
'实例备份:在实例关闭时创建去重快照,可预览与恢复,支持排除指定文件或文件夹,并可迁移备份仓库。',
|
||||
},
|
||||
{
|
||||
'en-US': "Customize the launcher's UI font and monospace font in appearance settings.",
|
||||
@@ -295,12 +457,16 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
],
|
||||
fixed: [
|
||||
{
|
||||
'en-US': 'Fixed beta builds not auto-updating from beta9 to beta10 (prerelease versions were compared as text instead of by number).',
|
||||
'zh-CN': '修复 beta 版本无法从 beta9 自动更新到 beta10 的问题(预发布版本此前按文本而非数字比较)。',
|
||||
'en-US':
|
||||
'Fixed beta builds not auto-updating from beta9 to beta10 (prerelease versions were compared as text instead of by number).',
|
||||
'zh-CN':
|
||||
'修复 beta 版本无法从 beta9 自动更新到 beta10 的问题(预发布版本此前按文本而非数字比较)。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Fixed a cross-crate visibility issue that prevented the launcher from compiling with the ignore-SSL-errors option.',
|
||||
'zh-CN': '修复因跨 crate 可见性导致的编译失败,此前启用“忽略 SSL 证书错误”选项时无法编译。',
|
||||
'en-US':
|
||||
'Fixed a cross-crate visibility issue that prevented the launcher from compiling with the ignore-SSL-errors option.',
|
||||
'zh-CN':
|
||||
'修复因跨 crate 可见性导致的编译失败,此前启用“忽略 SSL 证书错误”选项时无法编译。',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -316,11 +482,13 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US': 'Reworked the instance-page tour into four steps covering content, files, worlds, and logs.',
|
||||
'en-US':
|
||||
'Reworked the instance-page tour into four steps covering content, files, worlds, and logs.',
|
||||
'zh-CN': '重做实例页导览,分为内容、文件、世界、日志四步。',
|
||||
},
|
||||
{
|
||||
'en-US': 'When the install location is a drive root, the installer now creates a Starlight subfolder automatically.',
|
||||
'en-US':
|
||||
'When the install location is a drive root, the installer now creates a Starlight subfolder automatically.',
|
||||
'zh-CN': '安装位置选到盘符根目录时,安装器会自动创建 Starlight 子文件夹。',
|
||||
},
|
||||
],
|
||||
@@ -334,11 +502,13 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
'zh-CN': '修复开发者功能开关无法保存的问题。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Fixed instance group edits not saving for instances without an applied content set.',
|
||||
'en-US':
|
||||
'Fixed instance group edits not saving for instances without an applied content set.',
|
||||
'zh-CN': '修复没有应用内容集的实例无法保存分组修改的问题。',
|
||||
},
|
||||
{
|
||||
'en-US': 'Fixed the launcher crashing on startup when feature flags were out of sync between the frontend and backend.',
|
||||
'en-US':
|
||||
'Fixed the launcher crashing on startup when feature flags were out of sync between the frontend and backend.',
|
||||
'zh-CN': '修复前后端功能开关不同步导致启动器启动崩溃的问题。',
|
||||
},
|
||||
{
|
||||
@@ -455,12 +625,10 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
{
|
||||
'en-US':
|
||||
'Fixed the onboarding tour skipping steps automatically, getting stuck, or not navigating between steps; the tour bubble no longer covers the left navigation bar.',
|
||||
'zh-CN':
|
||||
'修复新手导览自动跳过、卡住或不跳转的问题;导览气泡不再遮挡左侧导航栏。',
|
||||
'zh-CN': '修复新手导览自动跳过、卡住或不跳转的问题;导览气泡不再遮挡左侧导航栏。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Fixed the onboarding tour target on the minimal home layout.',
|
||||
'en-US': 'Fixed the onboarding tour target on the minimal home layout.',
|
||||
'zh-CN': '修复精简主页下导览目标找不到的问题。',
|
||||
},
|
||||
],
|
||||
@@ -491,13 +659,11 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
],
|
||||
fixed: [
|
||||
{
|
||||
'en-US':
|
||||
'Fixed the developer feature flags page rendering blank.',
|
||||
'en-US': 'Fixed the developer feature flags page rendering blank.',
|
||||
'zh-CN': '修复开发者“功能开关”页面空白的问题。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Fixed a build error that prevented the launcher from compiling.',
|
||||
'en-US': 'Fixed a build error that prevented the launcher from compiling.',
|
||||
'zh-CN': '修复导致启动器无法编译的构建错误。',
|
||||
},
|
||||
],
|
||||
@@ -514,8 +680,7 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
fixed: [
|
||||
{
|
||||
'en-US':
|
||||
'Fixed a build error in 1.0.1-beta3 that prevented the launcher from compiling.',
|
||||
'en-US': 'Fixed a build error in 1.0.1-beta3 that prevented the launcher from compiling.',
|
||||
'zh-CN': '修复 1.0.1-beta3 中导致启动器无法编译的构建错误。',
|
||||
},
|
||||
],
|
||||
@@ -574,8 +739,7 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
],
|
||||
fixed: [
|
||||
{
|
||||
'en-US':
|
||||
'Improved the reliability of live logs and database switching.',
|
||||
'en-US': 'Improved the reliability of live logs and database switching.',
|
||||
'zh-CN': '提高实时日志与数据库切换的可靠性。',
|
||||
},
|
||||
],
|
||||
@@ -667,15 +831,13 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
'zh-CN': '修复更新清单的下载地址与发布顺序,更新检查现在可以成功。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Updated the signing key pair used to sign update packages.',
|
||||
'en-US': 'Updated the signing key pair used to sign update packages.',
|
||||
'zh-CN': '更新了用于签名更新包的密钥对。',
|
||||
},
|
||||
],
|
||||
changed: [
|
||||
{
|
||||
'en-US':
|
||||
'Removed upstream release announcements prior to 1.0.0-beta1.',
|
||||
'en-US': 'Removed upstream release announcements prior to 1.0.0-beta1.',
|
||||
'zh-CN': '移除了 1.0.0-beta1 之前的上游版本公告。',
|
||||
},
|
||||
],
|
||||
@@ -692,13 +854,11 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
changes: {
|
||||
added: [
|
||||
{
|
||||
'en-US':
|
||||
'Installing a modpack now lets you choose the game directory.',
|
||||
'en-US': 'Installing a modpack now lets you choose the game directory.',
|
||||
'zh-CN': '一键安装整合包时现在可以选择游戏目录。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Approved (hosted) modpack sync and StarLight instance mode were added.',
|
||||
'en-US': 'Approved (hosted) modpack sync and StarLight instance mode were added.',
|
||||
'zh-CN': '新增获批整合包同步与 StarLight 实例模式。',
|
||||
},
|
||||
{
|
||||
@@ -709,8 +869,7 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
],
|
||||
changed: [
|
||||
{
|
||||
'en-US':
|
||||
'The about page now plays a looping wither victory animation.',
|
||||
'en-US': 'The about page now plays a looping wither victory animation.',
|
||||
'zh-CN': '关于页现在会播放循环的凋灵胜利动画。',
|
||||
},
|
||||
],
|
||||
@@ -722,8 +881,7 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
'修复从 .minecraft 文件夹导入实例的多项问题(内容复制、版本隔离、符号链接、加载器版本识别等)。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Fixed the instance log view stopping updates and overlapping log lines.',
|
||||
'en-US': 'Fixed the instance log view stopping updates and overlapping log lines.',
|
||||
'zh-CN': '修复实例日志窗口停更与日志行重叠的问题。',
|
||||
},
|
||||
{
|
||||
@@ -742,8 +900,7 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
'zh-CN': '修复未登录皮肤站时启动卡住且不再弹出玩家选择的问题。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
'Fixed various skin site login, player list sync, and display issues.',
|
||||
'en-US': 'Fixed various skin site login, player list sync, and display issues.',
|
||||
'zh-CN': '修复皮肤站登录、玩家列表同步及若干显示问题。',
|
||||
},
|
||||
],
|
||||
@@ -762,7 +919,8 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
{
|
||||
'en-US':
|
||||
'The launcher has been rebranded from Axolotl Launcher to Starlight Launcher, with a new icon and a refreshed about page.',
|
||||
'zh-CN': '启动器已从 Axolotl Launcher 更名为 Starlight Launcher,并更换了全新图标与关于页。',
|
||||
'zh-CN':
|
||||
'启动器已从 Axolotl Launcher 更名为 Starlight Launcher,并更换了全新图标与关于页。',
|
||||
},
|
||||
{
|
||||
'en-US':
|
||||
@@ -776,7 +934,8 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
],
|
||||
added: [
|
||||
{
|
||||
'en-US': 'A "Starlight" entry was added to the sidebar, which embeds the StarLight skin site.',
|
||||
'en-US':
|
||||
'A "Starlight" entry was added to the sidebar, which embeds the StarLight skin site.',
|
||||
'zh-CN': '侧边栏新增「斯达莱特」入口,内嵌 StarLight 皮肤站。',
|
||||
},
|
||||
{
|
||||
@@ -795,10 +954,12 @@ export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
|
||||
{
|
||||
'en-US':
|
||||
'The hard-coded Starlight official server was removed from "Pinned servers"; only servers you favorite yourself are shown now.',
|
||||
'zh-CN': '移除了「固定的服务器」中写死的 Starlight 官方服务器,现在只显示你自己收藏的服务器。',
|
||||
'zh-CN':
|
||||
'移除了「固定的服务器」中写死的 Starlight 官方服务器,现在只显示你自己收藏的服务器。',
|
||||
},
|
||||
{
|
||||
'en-US': 'The swimming axolotl animation on the about page was replaced with a static nether star.',
|
||||
'en-US':
|
||||
'The swimming axolotl animation on the about page was replaced with a static nether star.',
|
||||
'zh-CN': '关于页中游动的美西螈动画已替换为静止的下界之星。',
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
<script setup lang="ts">
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
|
||||
import { type SkinSiteChatUserInfo, skinSiteChatUserSearch } from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError } = injectNotificationManager()
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
roomId?: number
|
||||
label?: string
|
||||
placeholder?: string
|
||||
excludeUuids?: string[]
|
||||
allowedUuids?: string[]
|
||||
allowedHint?: string
|
||||
}>(),
|
||||
{
|
||||
roomId: undefined,
|
||||
label: undefined,
|
||||
placeholder: undefined,
|
||||
excludeUuids: () => [],
|
||||
allowedUuids: undefined,
|
||||
allowedHint: undefined,
|
||||
},
|
||||
)
|
||||
|
||||
const model = defineModel<SkinSiteChatUserInfo | null>({ required: true })
|
||||
|
||||
const messages = defineMessages({
|
||||
label: { id: 'app.skin-site.chat.user-picker.label', defaultMessage: 'Pick a user' },
|
||||
placeholder: {
|
||||
id: 'app.skin-site.chat.user-picker.placeholder',
|
||||
defaultMessage: 'Search username, email or account ID',
|
||||
},
|
||||
byUser: { id: 'app.skin-site.chat.user-picker.by-user', defaultMessage: 'By user' },
|
||||
byPlayer: { id: 'app.skin-site.chat.user-picker.by-player', defaultMessage: 'By player' },
|
||||
hint: {
|
||||
id: 'app.skin-site.chat.user-picker.hint',
|
||||
defaultMessage: 'Fuzzy search on username and email, or search by account ID.',
|
||||
},
|
||||
playerHint: {
|
||||
id: 'app.skin-site.chat.user-picker.player-hint',
|
||||
defaultMessage: 'Enter a player name to find the bound user.',
|
||||
},
|
||||
empty: {
|
||||
id: 'app.skin-site.chat.user-picker.empty',
|
||||
defaultMessage: 'No matching user.',
|
||||
},
|
||||
banned: {
|
||||
id: 'app.skin-site.chat.user-picker.banned',
|
||||
defaultMessage: 'This account is banned.',
|
||||
},
|
||||
guest: {
|
||||
id: 'app.skin-site.chat.user-picker.guest',
|
||||
defaultMessage: 'Guests cannot become a manager or settlement owner.',
|
||||
},
|
||||
alreadyIn: {
|
||||
id: 'app.skin-site.chat.user-picker.already-in',
|
||||
defaultMessage: 'This user is already in the room.',
|
||||
},
|
||||
notAllowed: {
|
||||
id: 'app.skin-site.chat.user-picker.not-allowed',
|
||||
defaultMessage: 'This user is outside the allowed range.',
|
||||
},
|
||||
select: { id: 'app.skin-site.chat.user-picker.select', defaultMessage: 'Select' },
|
||||
selected: {
|
||||
id: 'app.skin-site.chat.user-picker.selected',
|
||||
defaultMessage: 'Selected',
|
||||
},
|
||||
idLabel: { id: 'app.skin-site.chat.user-picker.id', defaultMessage: 'ID' },
|
||||
emailLabel: { id: 'app.skin-site.chat.user-picker.email', defaultMessage: 'Email' },
|
||||
registeredLabel: {
|
||||
id: 'app.skin-site.chat.user-picker.registered',
|
||||
defaultMessage: 'Registered',
|
||||
},
|
||||
bannedStatus: { id: 'app.skin-site.chat.user-picker.banned-status', defaultMessage: 'Banned' },
|
||||
activeStatus: { id: 'app.skin-site.chat.user-picker.active-status', defaultMessage: 'Active' },
|
||||
})
|
||||
|
||||
const keyword = ref('')
|
||||
const searchMode = ref<'user' | 'player'>('user')
|
||||
const results = ref<SkinSiteChatUserInfo[]>([])
|
||||
const preview = ref<SkinSiteChatUserInfo | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let requestId = 0
|
||||
|
||||
const currentLabel = computed(() => props.label ?? formatMessage(messages.label))
|
||||
const currentPlaceholder = computed(() => props.placeholder ?? formatMessage(messages.placeholder))
|
||||
|
||||
watch([keyword, searchMode], () => {
|
||||
clearTimeout(timer)
|
||||
const query = keyword.value.trim()
|
||||
if (!query) {
|
||||
results.value = []
|
||||
preview.value = null
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
timer = setTimeout(() => void search(query), 300)
|
||||
})
|
||||
|
||||
watch(model, (value) => {
|
||||
if (value) return
|
||||
keyword.value = ''
|
||||
preview.value = null
|
||||
results.value = []
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.roomId,
|
||||
() => {
|
||||
model.value = null
|
||||
},
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => clearTimeout(timer))
|
||||
|
||||
async function search(query: string) {
|
||||
const current = ++requestId
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await skinSiteChatUserSearch(query, props.roomId, searchMode.value)
|
||||
if (current !== requestId) return
|
||||
if (!res.success) throw new Error(res.errorMessage)
|
||||
results.value = res.payload ?? []
|
||||
preview.value = results.value.length === 1 ? results.value[0] : null
|
||||
} catch (error) {
|
||||
if (current === requestId) {
|
||||
results.value = []
|
||||
handleError(error)
|
||||
}
|
||||
} finally {
|
||||
if (current === requestId) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function unavailableReason(user: SkinSiteChatUserInfo): string | null {
|
||||
if (user.banned) return formatMessage(messages.banned)
|
||||
if (user.permissions.includes('GUEST')) return formatMessage(messages.guest)
|
||||
if (props.excludeUuids.includes(user.uuid)) return formatMessage(messages.alreadyIn)
|
||||
if (props.allowedUuids && !props.allowedUuids.includes(user.uuid)) {
|
||||
return props.allowedHint ?? formatMessage(messages.notAllowed)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function selectPreview() {
|
||||
if (preview.value && !unavailableReason(preview.value)) {
|
||||
model.value = preview.value
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(ts: number): string {
|
||||
try {
|
||||
return new Date(ts).toLocaleString()
|
||||
} catch {
|
||||
return '—'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-xs font-semibold text-secondary">{{ currentLabel }}</span>
|
||||
<div class="flex gap-2">
|
||||
<select
|
||||
v-model="searchMode"
|
||||
class="shrink-0 rounded-lg border border-solid border-surface-5 bg-bg-raised px-2 py-1.5 text-xs text-contrast outline-none focus:border-brand"
|
||||
>
|
||||
<option value="user">{{ formatMessage(messages.byUser) }}</option>
|
||||
<option value="player">{{ formatMessage(messages.byPlayer) }}</option>
|
||||
</select>
|
||||
<input
|
||||
v-model.trim="keyword"
|
||||
type="text"
|
||||
maxlength="100"
|
||||
:placeholder="
|
||||
searchMode === 'player' ? formatMessage(messages.playerHint) : currentPlaceholder
|
||||
"
|
||||
class="min-w-0 flex-1 rounded-lg border border-solid border-surface-5 bg-bg-raised px-3 py-1.5 text-xs text-contrast outline-none focus:border-brand"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<span class="text-[11px] text-secondary">
|
||||
{{
|
||||
searchMode === 'player'
|
||||
? formatMessage(messages.playerHint)
|
||||
: formatMessage(messages.hint)
|
||||
}}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="keyword && !loading"
|
||||
class="flex max-h-56 flex-col gap-1.5 overflow-y-auto rounded-lg border border-solid border-surface-5 bg-bg-raised p-2"
|
||||
>
|
||||
<button
|
||||
v-for="user in results"
|
||||
:key="user.uuid"
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between gap-3 rounded-lg border border-solid p-2 text-left transition-colors"
|
||||
:class="
|
||||
preview?.uuid === user.uuid
|
||||
? 'border-brand bg-brand/10'
|
||||
: 'border-transparent bg-bg hover:border-surface-5'
|
||||
"
|
||||
@click="preview = user"
|
||||
>
|
||||
<span class="flex min-w-0 items-center gap-2">
|
||||
<span
|
||||
class="grid size-8 shrink-0 place-items-center rounded-lg bg-brand/15 text-xs font-bold text-brand"
|
||||
>
|
||||
{{ user.username.slice(0, 1).toUpperCase() }}
|
||||
</span>
|
||||
<span class="min-w-0">
|
||||
<strong class="block truncate text-xs text-contrast">{{ user.username }}</strong>
|
||||
<span class="block truncate text-[10px] text-secondary">
|
||||
{{ formatMessage(messages.idLabel) }} {{ user.id }} · {{ user.email }}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="unavailableReason(user)"
|
||||
class="shrink-0 rounded-full bg-red/20 px-2 py-0.5 text-[10px] font-semibold text-red"
|
||||
>
|
||||
{{ unavailableReason(user) }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="model?.uuid === user.uuid"
|
||||
class="shrink-0 rounded-full bg-brand px-2 py-0.5 text-[10px] font-semibold text-contrast"
|
||||
>
|
||||
{{ formatMessage(messages.selected) }}
|
||||
</span>
|
||||
</button>
|
||||
<p v-if="!results.length" class="m-0 py-4 text-center text-xs text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section
|
||||
v-if="preview"
|
||||
class="flex flex-col gap-3 rounded-lg border border-solid border-surface-5 bg-bg-raised p-3"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 class="m-0 text-sm font-bold text-contrast">{{ preview.username }}</h3>
|
||||
<p class="m-0 text-[11px] text-secondary">
|
||||
{{ formatMessage(messages.idLabel) }} {{ preview.id }}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[10px] font-semibold"
|
||||
:class="preview.banned ? 'bg-red text-contrast' : 'bg-green text-contrast'"
|
||||
>
|
||||
{{ formatMessage(preview.banned ? messages.bannedStatus : messages.activeStatus) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="grid gap-2 text-[11px] sm:grid-cols-2">
|
||||
<div class="min-w-0">
|
||||
<span class="block text-secondary">UUID</span>
|
||||
<span class="block break-all font-mono text-contrast">{{ preview.uuid }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-secondary">{{ formatMessage(messages.emailLabel) }}</span>
|
||||
<span class="block break-all text-contrast">{{ preview.email }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-secondary">QQ</span>
|
||||
<span class="block text-contrast">{{ preview.qq ?? '—' }}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-secondary">{{ formatMessage(messages.registeredLabel) }}</span>
|
||||
<span class="block text-contrast">{{ formatTime(preview.registerTime) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span
|
||||
v-for="perm in preview.permissions"
|
||||
:key="perm"
|
||||
class="rounded bg-bg px-2 py-0.5 font-mono text-[10px] text-secondary"
|
||||
>
|
||||
{{ perm }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="unavailableReason(preview)" class="m-0 text-[11px] text-red">
|
||||
{{ unavailableReason(preview) }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full rounded-lg bg-brand px-3 py-2 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="Boolean(unavailableReason(preview))"
|
||||
@click="selectPreview"
|
||||
>
|
||||
{{
|
||||
model?.uuid === preview.uuid
|
||||
? formatMessage(messages.selected)
|
||||
: formatMessage(messages.select)
|
||||
}}
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,63 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import { loadCachedRoomAvatar } from './room-avatar-cache'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
roomId: number
|
||||
avatarAttachmentId?: number | null
|
||||
name: string
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl'
|
||||
}>(),
|
||||
{ avatarAttachmentId: null, size: 'md' },
|
||||
)
|
||||
|
||||
const avatarUrl = ref<string | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
const sizeClass = computed(
|
||||
() =>
|
||||
({
|
||||
sm: 'size-9 rounded-lg text-lg',
|
||||
md: 'size-10 rounded-lg text-xl',
|
||||
lg: 'size-12 rounded-lg text-2xl',
|
||||
xl: 'size-20 rounded-xl text-3xl',
|
||||
})[props.size],
|
||||
)
|
||||
|
||||
watch(
|
||||
() => [props.roomId, props.avatarAttachmentId] as const,
|
||||
async ([roomId, attachmentId]) => {
|
||||
avatarUrl.value = null
|
||||
if (!attachmentId) {
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
const url = await loadCachedRoomAvatar(roomId, attachmentId)
|
||||
if (props.roomId === roomId && props.avatarAttachmentId === attachmentId) {
|
||||
avatarUrl.value = url
|
||||
}
|
||||
loading.value = false
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="grid shrink-0 place-items-center overflow-hidden border border-solid border-surface-5 bg-brand/10 font-bold text-brand"
|
||||
:class="sizeClass"
|
||||
>
|
||||
<img
|
||||
v-if="avatarUrl"
|
||||
:src="avatarUrl"
|
||||
:alt="name"
|
||||
class="h-full w-full object-cover"
|
||||
decoding="async"
|
||||
/>
|
||||
<span v-else-if="loading" class="text-[10px] text-secondary">…</span>
|
||||
<span v-else class="select-none">#</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,161 @@
|
||||
<script setup lang="ts">
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
|
||||
import { skinSiteChatAttachmentUpload } from '@/helpers/skin-site-api'
|
||||
|
||||
import RoomAvatar from './RoomAvatar.vue'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
roomId?: number
|
||||
avatarAttachmentId?: number | null
|
||||
name: string
|
||||
token?: string | null
|
||||
remove?: boolean
|
||||
}>(),
|
||||
{ roomId: 0, avatarAttachmentId: null, token: null, remove: false },
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:token', value: string | null): void
|
||||
(e: 'update:remove', value: boolean): void
|
||||
(e: 'update:uploading', value: boolean): void
|
||||
}>()
|
||||
|
||||
const messages = defineMessages({
|
||||
label: { id: 'app.skin-site.chat.avatar.label', defaultMessage: 'Room avatar' },
|
||||
upload: { id: 'app.skin-site.chat.avatar.upload', defaultMessage: 'Upload avatar' },
|
||||
replace: { id: 'app.skin-site.chat.avatar.replace', defaultMessage: 'Replace avatar' },
|
||||
remove: { id: 'app.skin-site.chat.avatar.remove', defaultMessage: 'Remove avatar' },
|
||||
hint: {
|
||||
id: 'app.skin-site.chat.avatar.hint',
|
||||
defaultMessage: 'PNG, JPEG or WebP, up to 8192 px per side and 5 MB.',
|
||||
},
|
||||
badFormat: {
|
||||
id: 'app.skin-site.chat.avatar.bad-format',
|
||||
defaultMessage: 'Only PNG, JPEG and WebP are supported.',
|
||||
},
|
||||
tooLarge: {
|
||||
id: 'app.skin-site.chat.avatar.too-large',
|
||||
defaultMessage: 'Avatar must not exceed 5 MB.',
|
||||
},
|
||||
notImage: {
|
||||
id: 'app.skin-site.chat.avatar.not-image',
|
||||
defaultMessage: 'Avatar must be an image.',
|
||||
},
|
||||
})
|
||||
|
||||
const MAX_BYTES = 5 * 1024 * 1024
|
||||
const ALLOWED = ['png', 'jpg', 'jpeg', 'webp']
|
||||
|
||||
const uploading = ref(false)
|
||||
const previewUrl = ref<string | null>(null)
|
||||
|
||||
watch(
|
||||
() => props.token,
|
||||
(token) => {
|
||||
if (!token) revokePreview()
|
||||
},
|
||||
)
|
||||
|
||||
function revokePreview() {
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value)
|
||||
previewUrl.value = null
|
||||
}
|
||||
|
||||
async function selectAvatar(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
|
||||
const ext = file.name.split('.').pop()?.toLowerCase()
|
||||
if (!ext || !ALLOWED.includes(ext)) {
|
||||
addNotification({ type: 'error', title: formatMessage(messages.badFormat) })
|
||||
return
|
||||
}
|
||||
if (file.size > MAX_BYTES) {
|
||||
addNotification({ type: 'error', title: formatMessage(messages.tooLarge) })
|
||||
return
|
||||
}
|
||||
|
||||
uploading.value = true
|
||||
emit('update:uploading', true)
|
||||
try {
|
||||
const res = await skinSiteChatAttachmentUpload(file)
|
||||
if (!res.success) throw new Error(res.errorMessage)
|
||||
if (res.payload.attachment.kind !== 'IMAGE') {
|
||||
addNotification({ type: 'error', title: formatMessage(messages.notImage) })
|
||||
return
|
||||
}
|
||||
revokePreview()
|
||||
previewUrl.value = URL.createObjectURL(file)
|
||||
emit('update:token', res.payload.token)
|
||||
emit('update:remove', false)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
uploading.value = false
|
||||
emit('update:uploading', false)
|
||||
}
|
||||
}
|
||||
|
||||
function removeAvatar() {
|
||||
revokePreview()
|
||||
emit('update:token', null)
|
||||
emit('update:remove', true)
|
||||
}
|
||||
|
||||
onBeforeUnmount(revokePreview)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<span class="text-xs font-semibold text-secondary">
|
||||
{{ formatMessage(messages.label) }}
|
||||
</span>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<div
|
||||
v-if="previewUrl"
|
||||
class="size-20 overflow-hidden rounded-xl border border-solid border-surface-5 bg-bg-raised"
|
||||
>
|
||||
<img :src="previewUrl" alt="" class="h-full w-full object-cover" />
|
||||
</div>
|
||||
<RoomAvatar
|
||||
v-else
|
||||
:room-id="roomId"
|
||||
:avatar-attachment-id="remove ? null : avatarAttachmentId"
|
||||
:name="name || 'Room'"
|
||||
size="xl"
|
||||
/>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<label
|
||||
class="cursor-pointer rounded-lg bg-button-bg px-3 py-1.5 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
:class="uploading ? 'pointer-events-none opacity-50' : ''"
|
||||
>
|
||||
{{ uploading ? '…' : (avatarAttachmentId || previewUrl ? formatMessage(messages.replace) : formatMessage(messages.upload)) }}
|
||||
<input
|
||||
type="file"
|
||||
class="hidden"
|
||||
accept=".png,.jpg,.jpeg,.webp"
|
||||
@change="selectAvatar"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
v-if="previewUrl || (avatarAttachmentId && !remove)"
|
||||
type="button"
|
||||
class="rounded-lg bg-red/20 px-3 py-1.5 text-xs font-semibold text-red hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="uploading"
|
||||
@click="removeAvatar"
|
||||
>
|
||||
{{ formatMessage(messages.remove) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="m-0 text-[11px] text-secondary">{{ formatMessage(messages.hint) }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -4,12 +4,19 @@ import { computed, ref } from 'vue'
|
||||
|
||||
import { skinSiteUser } from '@/composables/skin-site-session'
|
||||
|
||||
import AdminAccessAuditPage from './admin/AdminAccessAuditPage.vue'
|
||||
import AdminBroadcastPage from './admin/AdminBroadcastPage.vue'
|
||||
import AdminChatPage from './admin/AdminChatPage.vue'
|
||||
import AdminDonationsPage from './admin/AdminDonationsPage.vue'
|
||||
import AdminDownloadsPage from './admin/AdminDownloadsPage.vue'
|
||||
import AdminLauncherPage from './admin/AdminLauncherPage.vue'
|
||||
import AdminModsPage from './admin/AdminModsPage.vue'
|
||||
import AdminPlayersPage from './admin/AdminPlayersPage.vue'
|
||||
import AdminReviewPage from './admin/AdminReviewPage.vue'
|
||||
import AdminServersPage from './admin/AdminServersPage.vue'
|
||||
import AdminSummaryPage from './admin/AdminSummaryPage.vue'
|
||||
import AdminUsersPage from './admin/AdminUsersPage.vue'
|
||||
import AdminWikiPage from './admin/AdminWikiPage.vue'
|
||||
|
||||
const emit = defineEmits<{ (e: 'back'): void }>()
|
||||
|
||||
@@ -72,7 +79,9 @@ const navGroups = computed<NavGroup[]>(() => [
|
||||
id: 'security',
|
||||
label: formatMessage(messages.groupSecurity),
|
||||
items: [
|
||||
{ key: 'servers', label: formatMessage(messages.itemServers) },
|
||||
...(hasWebAdmin.value
|
||||
? [{ key: 'servers' as AdminKey, label: formatMessage(messages.itemServers) }]
|
||||
: []),
|
||||
{ key: 'summary', label: formatMessage(messages.itemSummary) },
|
||||
{ key: 'access-audit', label: formatMessage(messages.itemAccessAudit) },
|
||||
],
|
||||
@@ -93,7 +102,9 @@ const navGroups = computed<NavGroup[]>(() => [
|
||||
{ key: 'broadcast', label: formatMessage(messages.itemBroadcast) },
|
||||
{ key: 'chat', label: formatMessage(messages.itemChat) },
|
||||
{ key: 'wiki', label: formatMessage(messages.itemWiki) },
|
||||
{ key: 'donations', label: formatMessage(messages.itemDonations) },
|
||||
...(hasWebAdmin.value
|
||||
? [{ key: 'donations' as AdminKey, label: formatMessage(messages.itemDonations) }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -112,6 +123,11 @@ const hasAdminAccess = computed(() => {
|
||||
return permissions.includes('WEB_ADMIN') || permissions.includes('SERVER_ADMIN')
|
||||
})
|
||||
|
||||
const hasWebAdmin = computed(() => {
|
||||
const permissions = skinSiteUser.value?.permissions ?? []
|
||||
return permissions.includes('WEB_ADMIN')
|
||||
})
|
||||
|
||||
const current = ref<AdminKey>('summary')
|
||||
</script>
|
||||
<template>
|
||||
@@ -159,11 +175,18 @@ const current = ref<AdminKey>('summary')
|
||||
class="min-w-0 flex-1 overflow-y-auto rounded-xl border border-solid border-surface-5 bg-bg-raised p-4"
|
||||
>
|
||||
<AdminSummaryPage v-if="current === 'summary'" />
|
||||
<AdminServersPage v-else-if="current === 'servers' && hasWebAdmin" />
|
||||
<AdminAccessAuditPage v-else-if="current === 'access-audit'" />
|
||||
<AdminBroadcastPage v-else-if="current === 'broadcast'" />
|
||||
<AdminChatPage v-else-if="current === 'chat'" />
|
||||
<AdminUsersPage v-else-if="current === 'users'" />
|
||||
<AdminPlayersPage v-else-if="current === 'players'" />
|
||||
<AdminReviewPage v-else-if="current === 'review'" />
|
||||
<AdminLauncherPage v-else-if="current === 'launcher'" />
|
||||
<AdminModsPage v-else-if="current === 'mods'" />
|
||||
<AdminWikiPage v-else-if="current === 'wiki'" />
|
||||
<AdminDownloadsPage v-else-if="current === 'downloads'" />
|
||||
<AdminDonationsPage v-else-if="current === 'donations' && hasWebAdmin" />
|
||||
<p v-else class="m-0 text-sm text-secondary">{{ current }}</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire, registerHooks, stripTypeScriptTypes } from 'node:module'
|
||||
import test from 'node:test'
|
||||
|
||||
import { createRenderer, nextTick, ref } from 'vue'
|
||||
|
||||
const testSession = {
|
||||
skinSiteStatus: ref('checking'),
|
||||
skinSiteUser: ref<{ uuid: string } | null>(null),
|
||||
}
|
||||
const testGlobal = globalThis as unknown as {
|
||||
skinSiteAnnouncementSession: typeof testSession
|
||||
skinSiteAnnouncementFetch: () => Promise<unknown>
|
||||
}
|
||||
testGlobal.skinSiteAnnouncementSession = testSession
|
||||
const require = createRequire(import.meta.url)
|
||||
const { parse, compileScript } = require('vue/compiler-sfc')
|
||||
const componentUrl = new URL('./SkinSiteAnnouncements.vue', import.meta.url).href
|
||||
const stubs: Record<string, string> = {
|
||||
'@modrinth/assets': 'export const SpinnerIcon={}',
|
||||
'@modrinth/ui':
|
||||
'export const commonMessages={retryButton:{defaultMessage:"Retry"}}; export const defineMessages=x=>x; export const useVIntl=()=>({formatMessage:x=>x.defaultMessage})',
|
||||
'@/helpers/skin-site-api':
|
||||
'export const skinSiteAnnouncements=()=>globalThis.skinSiteAnnouncementFetch()',
|
||||
'@/composables/skin-site-session':
|
||||
'export const {skinSiteStatus,skinSiteUser}=globalThis.skinSiteAnnouncementSession; export const reloadSkinSiteSession=async()=>{}',
|
||||
}
|
||||
const hooks = registerHooks({
|
||||
resolve(specifier, context, nextResolve) {
|
||||
if (specifier in stubs)
|
||||
return {
|
||||
url: `data:text/javascript,${encodeURIComponent(stubs[specifier])}`,
|
||||
shortCircuit: true,
|
||||
}
|
||||
return nextResolve(specifier, context)
|
||||
},
|
||||
load(url, context, nextLoad) {
|
||||
if (url !== componentUrl) return nextLoad(url, context)
|
||||
const { descriptor } = parse(readFileSync(new URL(url), 'utf8'))
|
||||
return {
|
||||
format: 'module',
|
||||
source: stripTypeScriptTypes(
|
||||
compileScript(descriptor, { id: 'skin-announcement-test' }).content,
|
||||
),
|
||||
shortCircuit: true,
|
||||
}
|
||||
},
|
||||
})
|
||||
const { default: Announcements } = await import(componentUrl)
|
||||
hooks.deregister()
|
||||
Announcements.render = () => null
|
||||
|
||||
type Node = Record<string, unknown>
|
||||
const renderer = createRenderer<Node, Node>({
|
||||
createElement: () => ({}),
|
||||
createText: () => ({}),
|
||||
createComment: () => ({}),
|
||||
insert() {},
|
||||
remove() {},
|
||||
setText() {},
|
||||
setElementText() {},
|
||||
patchProp() {},
|
||||
parentNode: () => null,
|
||||
nextSibling: () => null,
|
||||
})
|
||||
const flush = async () => {
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
await nextTick()
|
||||
}
|
||||
type State = {
|
||||
announcements: Array<{ id: number }>
|
||||
loading: boolean
|
||||
failed: boolean
|
||||
load: () => Promise<void>
|
||||
}
|
||||
let requests = 0
|
||||
function mount(t: test.TestContext) {
|
||||
const app = renderer.createApp(Announcements)
|
||||
const instance = app.mount({})
|
||||
t.after(() => app.unmount())
|
||||
return instance.$.setupState as State
|
||||
}
|
||||
test.beforeEach(() => {
|
||||
testSession.skinSiteStatus.value = 'checking'
|
||||
testSession.skinSiteUser.value = null
|
||||
requests = 0
|
||||
testGlobal.skinSiteAnnouncementFetch = async () => {
|
||||
requests++
|
||||
return { success: true, payload: [{ id: 1, title: '公告', updateAt: 1, star: false }] }
|
||||
}
|
||||
})
|
||||
|
||||
test('announcements wait for startup renewal and reload when sign-in finishes', async (t) => {
|
||||
const state = mount(t)
|
||||
await flush()
|
||||
assert.equal(requests, 0)
|
||||
assert.equal(state.loading, true)
|
||||
testSession.skinSiteUser.value = { uuid: 'owner' }
|
||||
testSession.skinSiteStatus.value = 'signed-in'
|
||||
await flush()
|
||||
assert.equal(requests, 1)
|
||||
assert.equal(state.announcements.length, 1)
|
||||
})
|
||||
|
||||
test('signed-out users do not request protected announcements or see a load failure', async (t) => {
|
||||
testSession.skinSiteStatus.value = 'signed-out'
|
||||
const state = mount(t)
|
||||
await flush()
|
||||
assert.equal(requests, 0)
|
||||
assert.equal(state.loading, false)
|
||||
assert.equal(state.failed, false)
|
||||
})
|
||||
|
||||
test('signing out clears announcements and ignores an old in-flight response', async (t) => {
|
||||
testSession.skinSiteStatus.value = 'signed-in'
|
||||
let finish!: (value: unknown) => void
|
||||
testGlobal.skinSiteAnnouncementFetch = () =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
const state = mount(t)
|
||||
await flush()
|
||||
testSession.skinSiteStatus.value = 'signed-out'
|
||||
await flush()
|
||||
finish({ success: true, payload: [{ id: 2 }] })
|
||||
await flush()
|
||||
assert.deepEqual(state.announcements, [])
|
||||
assert.equal(state.failed, false)
|
||||
})
|
||||
|
||||
test('a failed announcement request can be retried', async (t) => {
|
||||
testSession.skinSiteStatus.value = 'signed-in'
|
||||
testGlobal.skinSiteAnnouncementFetch = async () => ({ success: false })
|
||||
const state = mount(t)
|
||||
await flush()
|
||||
assert.equal(state.failed, true)
|
||||
testGlobal.skinSiteAnnouncementFetch = async () => ({ success: true, payload: [{ id: 3 }] })
|
||||
await state.load()
|
||||
assert.equal(state.failed, false)
|
||||
assert.equal(state.announcements[0].id, 3)
|
||||
})
|
||||
@@ -1,8 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, useVIntl } from '@modrinth/ui'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { commonMessages, defineMessages, useVIntl } from '@modrinth/ui'
|
||||
import { onUnmounted, ref, watch } from 'vue'
|
||||
|
||||
import {
|
||||
reloadSkinSiteSession,
|
||||
skinSiteStatus,
|
||||
skinSiteUser,
|
||||
} from '@/composables/skin-site-session'
|
||||
import { type SkinSiteAnnouncement, skinSiteAnnouncements } from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
@@ -18,11 +23,16 @@ const messages = defineMessages({
|
||||
id: 'app.skin-site.home.announcements.failed',
|
||||
defaultMessage: 'Could not load announcements.',
|
||||
},
|
||||
signedOut: {
|
||||
id: 'app.skin-site.home.announcements.signed-out',
|
||||
defaultMessage: 'Sign in to view announcements.',
|
||||
},
|
||||
})
|
||||
|
||||
const announcements = ref<SkinSiteAnnouncement[]>([])
|
||||
const loading = ref(true)
|
||||
const failed = ref(false)
|
||||
let requestId = 0
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
try {
|
||||
@@ -32,9 +42,16 @@ function formatDate(ts: number): string {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
async function load() {
|
||||
const currentRequest = ++requestId
|
||||
announcements.value = []
|
||||
failed.value = skinSiteStatus.value === 'error'
|
||||
loading.value = skinSiteStatus.value === 'checking'
|
||||
if (skinSiteStatus.value !== 'signed-in') return
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await skinSiteAnnouncements()
|
||||
if (currentRequest !== requestId) return
|
||||
if (result.success) {
|
||||
announcements.value = [...(result.payload ?? [])]
|
||||
.sort((a, b) => {
|
||||
@@ -46,10 +63,20 @@ onMounted(async () => {
|
||||
failed.value = true
|
||||
}
|
||||
} catch {
|
||||
failed.value = true
|
||||
if (currentRequest === requestId) failed.value = true
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (currentRequest === requestId) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function retry() {
|
||||
if (skinSiteStatus.value === 'error') await reloadSkinSiteSession()
|
||||
else await load()
|
||||
}
|
||||
|
||||
watch([skinSiteStatus, () => skinSiteUser.value?.uuid], load, { immediate: true })
|
||||
onUnmounted(() => {
|
||||
requestId++
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -63,8 +90,14 @@ onMounted(async () => {
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p v-else-if="failed" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.failed) }}
|
||||
<div v-else-if="failed" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<p class="m-0">{{ formatMessage(messages.failed) }}</p>
|
||||
<button type="button" class="text-brand hover:underline" @click="retry">
|
||||
{{ formatMessage(commonMessages.retryButton) }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-else-if="skinSiteStatus === 'signed-out'" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.signedOut) }}
|
||||
</p>
|
||||
<p v-else-if="!announcements.length" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
|
||||
@@ -3,7 +3,10 @@ import { HeartIcon, SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, useVIntl } from '@modrinth/ui'
|
||||
import { onMounted, ref } from 'vue'
|
||||
|
||||
import { type SkinSiteDonationSummary, skinSiteDonationSummary } from '@/helpers/skin-site-api'
|
||||
import {
|
||||
type SkinSitePublicDonationSummary,
|
||||
skinSitePublicDonationSummary,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
|
||||
@@ -18,13 +21,13 @@ const messages = defineMessages({
|
||||
loading: { id: 'app.skin-site.home.donation.loading', defaultMessage: 'Loading…' },
|
||||
})
|
||||
|
||||
const summary = ref<SkinSiteDonationSummary | null>(null)
|
||||
const summary = ref<SkinSitePublicDonationSummary | null>(null)
|
||||
const loading = ref(true)
|
||||
const failed = ref(false)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const result = await skinSiteDonationSummary()
|
||||
const result = await skinSitePublicDonationSummary()
|
||||
if (result.success) summary.value = result.payload
|
||||
else failed.value = true
|
||||
} catch {
|
||||
|
||||
@@ -4,11 +4,11 @@ import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/u
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
skinSiteDownloadCategories,
|
||||
type SkinSiteDownloadCategory,
|
||||
type SkinSiteDownloadItem,
|
||||
skinSiteDownloadList,
|
||||
type SkinSiteDownloadStatus,
|
||||
skinSitePublicDownloadCategories,
|
||||
type SkinSitePublicDownloadCategory,
|
||||
type SkinSitePublicDownloadItem,
|
||||
skinSitePublicDownloadList,
|
||||
type SkinSitePublicDownloadStatus,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
@@ -36,8 +36,8 @@ const messages = defineMessages({
|
||||
|
||||
const emit = defineEmits<{ (e: 'back'): void }>()
|
||||
|
||||
const items = ref<SkinSiteDownloadItem[]>([])
|
||||
const categories = ref<SkinSiteDownloadCategory[]>([])
|
||||
const items = ref<SkinSitePublicDownloadItem[]>([])
|
||||
const categories = ref<SkinSitePublicDownloadCategory[]>([])
|
||||
const selectedCategory = ref<string | null>(null)
|
||||
const loading = ref(true)
|
||||
const failed = ref(false)
|
||||
@@ -48,7 +48,7 @@ const filtered = computed(() =>
|
||||
: items.value,
|
||||
)
|
||||
|
||||
function statusLabel(status: SkinSiteDownloadStatus): string {
|
||||
function statusLabel(status: SkinSitePublicDownloadStatus): string {
|
||||
switch (status) {
|
||||
case 'NEW':
|
||||
return formatMessage(messages.statusNew)
|
||||
@@ -68,7 +68,7 @@ async function openUrl(url: string) {
|
||||
await open(url)
|
||||
}
|
||||
|
||||
function download(item: SkinSiteDownloadItem) {
|
||||
function download(item: SkinSitePublicDownloadItem) {
|
||||
const route = item.routes?.[0]
|
||||
void openUrl(route?.url ?? item.url)
|
||||
}
|
||||
@@ -78,8 +78,8 @@ async function load() {
|
||||
failed.value = false
|
||||
try {
|
||||
const [listResult, categoryResult] = await Promise.all([
|
||||
skinSiteDownloadList(),
|
||||
skinSiteDownloadCategories(),
|
||||
skinSitePublicDownloadList(),
|
||||
skinSitePublicDownloadCategories(),
|
||||
])
|
||||
if (!listResult.success) throw new Error(listResult.errorMessage)
|
||||
items.value = listResult.payload ?? []
|
||||
|
||||
@@ -18,6 +18,7 @@ import SkinSiteNavCards from './SkinSiteNavCards.vue'
|
||||
import SkinSiteProfileModal from './SkinSiteProfileModal.vue'
|
||||
import SkinSiteProfileView from './SkinSiteProfileView.vue'
|
||||
import SkinSiteReviewView from './SkinSiteReviewView.vue'
|
||||
import WikiView from './WikiView.vue'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { addNotification } = injectNotificationManager()
|
||||
@@ -45,6 +46,7 @@ const view = ref<
|
||||
| 'bug-detail'
|
||||
| 'bug-notifications'
|
||||
| 'admin'
|
||||
| 'wiki'
|
||||
>('home')
|
||||
const selectedBugId = ref<number | null>(null)
|
||||
|
||||
@@ -98,6 +100,8 @@ async function copyAddress() {
|
||||
@open="openBug"
|
||||
/>
|
||||
<SkinSiteAdminView v-else-if="view === 'admin'" @back="view = 'home'" />
|
||||
<WikiView v-else-if="view === 'wiki'" />
|
||||
|
||||
<SkinSiteBugDetailView
|
||||
v-else-if="view === 'bug-detail' && selectedBugId !== null"
|
||||
:issue-id="selectedBugId"
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ExternalIcon, SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
|
||||
import { type SkinSiteMapServer, skinSiteMapServers } from '@/helpers/skin-site-api'
|
||||
import { type SkinSitePublicMapServer, skinSitePublicMapServers } from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError } = injectNotificationManager()
|
||||
@@ -23,7 +23,7 @@ const messages = defineMessages({
|
||||
|
||||
const emit = defineEmits<{ (e: 'back'): void }>()
|
||||
|
||||
const servers = ref<SkinSiteMapServer[]>([])
|
||||
const servers = ref<SkinSitePublicMapServer[]>([])
|
||||
const internal = ref(false)
|
||||
const serverIndex = ref(0)
|
||||
const mapIndex = ref(0)
|
||||
@@ -52,7 +52,7 @@ async function load() {
|
||||
loading.value = true
|
||||
failed.value = false
|
||||
try {
|
||||
const result = await skinSiteMapServers()
|
||||
const result = await skinSitePublicMapServers()
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
servers.value = result.payload ?? []
|
||||
if (!servers.value.some((s) => !s.internal)) internal.value = true
|
||||
|
||||
@@ -12,7 +12,9 @@ import type { Component } from 'vue'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
|
||||
const emit = defineEmits<{ (e: 'navigate', view: 'downloads' | 'review' | 'bugs' | 'map'): void }>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'navigate', view: 'downloads' | 'review' | 'bugs' | 'map' | 'wiki'): void
|
||||
}>()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.home.nav.title', defaultMessage: 'Skin site' },
|
||||
@@ -104,8 +106,19 @@ const items: NavItem[] = [
|
||||
]
|
||||
|
||||
function open(item: NavItem) {
|
||||
if (item.id === 'download' || item.id === 'review' || item.id === 'bugs' || item.id === 'map') {
|
||||
emit('navigate', item.id === 'download' ? 'downloads' : item.id)
|
||||
if (
|
||||
item.id === 'download' ||
|
||||
item.id === 'review' ||
|
||||
item.id === 'bugs' ||
|
||||
item.id === 'map' ||
|
||||
item.id === 'wiki'
|
||||
) {
|
||||
emit(
|
||||
'navigate',
|
||||
item.id === 'download'
|
||||
? 'downloads'
|
||||
: (item.id as 'review' | 'bugs' | 'map' | 'wiki'),
|
||||
)
|
||||
return
|
||||
}
|
||||
void import('@tauri-apps/plugin-opener').then(({ openUrl }) => openUrl(item.href))
|
||||
|
||||
@@ -5,8 +5,8 @@ import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
skinSiteReviewCatalog,
|
||||
type SkinSiteReviewPaper,
|
||||
type SkinSiteReviewQuestion,
|
||||
type SkinSiteReviewPublicPaper,
|
||||
type SkinSiteReviewPublicQuestion,
|
||||
type SkinSiteReviewReceipt,
|
||||
skinSiteSubmitReview,
|
||||
} from '@/helpers/skin-site-api'
|
||||
@@ -46,10 +46,10 @@ const messages = defineMessages({
|
||||
|
||||
const emit = defineEmits<{ (e: 'back'): void }>()
|
||||
|
||||
const papers = ref<SkinSiteReviewPaper[]>([])
|
||||
const papers = ref<SkinSiteReviewPublicPaper[]>([])
|
||||
const loading = ref(true)
|
||||
const failed = ref(false)
|
||||
const activePaper = ref<SkinSiteReviewPaper | null>(null)
|
||||
const activePaper = ref<SkinSiteReviewPublicPaper | null>(null)
|
||||
const email = ref('')
|
||||
const inviteCode = ref('')
|
||||
const answers = ref<Record<string, string | string[]>>({})
|
||||
@@ -70,7 +70,7 @@ const requiredAnswered = computed(() => {
|
||||
|
||||
const canSubmit = computed(() => emailValid.value && requiredAnswered.value && !submitting.value)
|
||||
|
||||
function defaultAnswer(q: SkinSiteReviewQuestion): string | string[] {
|
||||
function defaultAnswer(q: SkinSiteReviewPublicQuestion): string | string[] {
|
||||
if (q.type === 'MULTIPLE' || q.type === 'SINGLE') {
|
||||
const preset = (q.options ?? []).filter((o) => o.defaultSelected).map((o) => o.id)
|
||||
return q.type === 'MULTIPLE' ? preset : (preset[0] ?? '')
|
||||
@@ -78,7 +78,7 @@ function defaultAnswer(q: SkinSiteReviewQuestion): string | string[] {
|
||||
return ''
|
||||
}
|
||||
|
||||
function openPaper(paper: SkinSiteReviewPaper) {
|
||||
function openPaper(paper: SkinSiteReviewPublicPaper) {
|
||||
activePaper.value = paper
|
||||
answers.value = {}
|
||||
for (const q of paper.questions) answers.value[q.id] = defaultAnswer(q)
|
||||
@@ -93,7 +93,7 @@ function closePaper() {
|
||||
receipt.value = null
|
||||
}
|
||||
|
||||
function toggleMultiple(q: SkinSiteReviewQuestion, optionId: string, checked: boolean) {
|
||||
function toggleMultiple(q: SkinSiteReviewPublicQuestion, optionId: string, checked: boolean) {
|
||||
const current = Array.isArray(answers.value[q.id]) ? (answers.value[q.id] as string[]) : []
|
||||
answers.value[q.id] = checked
|
||||
? [...current.filter((id) => id !== optionId), optionId]
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
type SkinSiteWikiPageDetail,
|
||||
skinSiteWikiPage,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
import WikiNodeRenderer from './wiki/WikiNodeRenderer.vue'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError } = injectNotificationManager()
|
||||
|
||||
const props = withDefaults(defineProps<{ initialTitle?: string }>(), {
|
||||
initialTitle: '',
|
||||
})
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.wiki.title', defaultMessage: 'StarLight Wiki' },
|
||||
searchPlaceholder: {
|
||||
id: 'app.skin-site.wiki.search-placeholder',
|
||||
defaultMessage: 'Enter a page title',
|
||||
},
|
||||
open: { id: 'app.skin-site.wiki.open', defaultMessage: 'Open' },
|
||||
loading: { id: 'app.skin-site.wiki.loading', defaultMessage: 'Loading…' },
|
||||
notFound: {
|
||||
id: 'app.skin-site.wiki.not-found',
|
||||
defaultMessage: 'Page not found.',
|
||||
},
|
||||
empty: {
|
||||
id: 'app.skin-site.wiki.empty',
|
||||
defaultMessage: 'Enter a page title above to start reading.',
|
||||
},
|
||||
updatedAt: {
|
||||
id: 'app.skin-site.wiki.updated-at',
|
||||
defaultMessage: 'Last edited {date} by {author}',
|
||||
},
|
||||
revision: { id: 'app.skin-site.wiki.revision', defaultMessage: 'Revision #{id}' },
|
||||
categories: { id: 'app.skin-site.wiki.categories', defaultMessage: 'Categories' },
|
||||
back: { id: 'app.skin-site.wiki.back', defaultMessage: 'Back' },
|
||||
})
|
||||
|
||||
const titleInput = ref(props.initialTitle)
|
||||
const page = ref<SkinSiteWikiPageDetail | null>(null)
|
||||
const loading = ref(false)
|
||||
const notFound = ref(false)
|
||||
const history = ref<string[]>([])
|
||||
|
||||
const currentTitle = computed(() => page.value?.title ?? '')
|
||||
|
||||
async function openPage(title: string) {
|
||||
const trimmed = title.trim()
|
||||
if (!trimmed) return
|
||||
titleInput.value = trimmed
|
||||
loading.value = true
|
||||
notFound.value = false
|
||||
try {
|
||||
const res = await skinSiteWikiPage(trimmed)
|
||||
if (!res.success) {
|
||||
notFound.value = true
|
||||
page.value = null
|
||||
return
|
||||
}
|
||||
page.value = res.payload
|
||||
if (currentTitle.value && history.value[history.value.length - 1] !== currentTitle.value) {
|
||||
history.value.push(currentTitle.value)
|
||||
}
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
notFound.value = true
|
||||
page.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
const prev = history.value.pop()
|
||||
if (prev) void openPage(prev)
|
||||
}
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
try {
|
||||
return new Date(ts).toLocaleString()
|
||||
} catch {
|
||||
return '—'
|
||||
}
|
||||
}
|
||||
|
||||
function onNavigate(title: string) {
|
||||
if (title) void openPage(title)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (props.initialTitle) void openPage(props.initialTitle)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex w-full flex-col gap-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
v-if="history.length"
|
||||
type="button"
|
||||
class="rounded-lg bg-button-bg px-3 py-1.5 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="goBack"
|
||||
>
|
||||
← {{ formatMessage(messages.back) }}
|
||||
</button>
|
||||
<h2 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h2>
|
||||
<input
|
||||
v-model="titleInput"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.searchPlaceholder)"
|
||||
class="min-w-0 flex-1 rounded-lg border border-solid border-surface-5 bg-bg-raised px-3 py-1.5 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="openPage(titleInput)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand px-3 py-1.5 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="openPage(titleInput)"
|
||||
>
|
||||
{{ formatMessage(messages.open) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex min-h-48 items-center justify-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p
|
||||
v-else-if="notFound"
|
||||
class="m-0 rounded-lg border border-solid border-surface-5 bg-bg-raised p-4 text-sm text-secondary"
|
||||
>
|
||||
{{ formatMessage(messages.notFound) }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="!page"
|
||||
class="m-0 rounded-lg border border-solid border-surface-5 bg-bg-raised p-4 text-sm text-secondary"
|
||||
>
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap items-baseline justify-between gap-2 border-b border-solid border-surface-5 pb-2">
|
||||
<h1 class="m-0 text-2xl font-bold text-contrast">{{ page.title }}</h1>
|
||||
<span class="text-[11px] text-secondary">
|
||||
{{ formatMessage(messages.revision, { id: page.revisionId }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p class="m-0 text-[11px] text-secondary">
|
||||
{{
|
||||
formatMessage(messages.updatedAt, {
|
||||
date: formatDate(page.updatedAt),
|
||||
author: page.authorName,
|
||||
})
|
||||
}}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="page.redirectTarget"
|
||||
class="rounded-lg border border-solid border-yellow/40 bg-yellow/10 p-3 text-xs text-yellow"
|
||||
>
|
||||
重定向到
|
||||
<button
|
||||
type="button"
|
||||
class="font-semibold underline underline-offset-2"
|
||||
@click="openPage(page.redirectTarget ?? '')"
|
||||
>
|
||||
{{ page.redirectTarget }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<article class="min-w-0 text-sm leading-7 text-contrast">
|
||||
<WikiNodeRenderer :nodes="page.nodes" @navigate="onNavigate" />
|
||||
</article>
|
||||
|
||||
<div v-if="page.categories.length" class="flex flex-wrap items-center gap-2 pt-2">
|
||||
<span class="text-[11px] text-secondary">{{ formatMessage(messages.categories) }}:</span>
|
||||
<span
|
||||
v-for="category in page.categories"
|
||||
:key="category"
|
||||
class="rounded bg-bg-raised px-2 py-0.5 text-[11px] text-secondary"
|
||||
>
|
||||
{{ category }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,273 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
skinSiteAccessAudit,
|
||||
type SkinSiteAccessAuditEntry,
|
||||
skinSiteUpdateAccessAuditSettings,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.admin.audit.title', defaultMessage: 'Access audit' },
|
||||
loading: { id: 'app.skin-site.admin.audit.loading', defaultMessage: 'Loading…' },
|
||||
failed: { id: 'app.skin-site.admin.audit.failed', defaultMessage: 'Could not load audit log.' },
|
||||
empty: { id: 'app.skin-site.admin.audit.empty', defaultMessage: 'No audit entries.' },
|
||||
subject: { id: 'app.skin-site.admin.audit.subject', defaultMessage: 'Subject' },
|
||||
action: { id: 'app.skin-site.admin.audit.action', defaultMessage: 'Action' },
|
||||
sourceIp: { id: 'app.skin-site.admin.audit.source-ip', defaultMessage: 'Source IP' },
|
||||
reportedIp: {
|
||||
id: 'app.skin-site.admin.audit.reported-ip',
|
||||
defaultMessage: 'Reported player IP',
|
||||
},
|
||||
count: { id: 'app.skin-site.admin.audit.count', defaultMessage: 'Count' },
|
||||
firstAt: { id: 'app.skin-site.admin.audit.first-at', defaultMessage: 'First seen' },
|
||||
lastAt: { id: 'app.skin-site.admin.audit.last-at', defaultMessage: 'Last seen' },
|
||||
proxy: { id: 'app.skin-site.admin.audit.proxy', defaultMessage: 'Proxy' },
|
||||
internal: { id: 'app.skin-site.admin.audit.internal', defaultMessage: 'Internal' },
|
||||
searchSubject: {
|
||||
id: 'app.skin-site.admin.audit.search-subject',
|
||||
defaultMessage: 'Subject',
|
||||
},
|
||||
searchIp: { id: 'app.skin-site.admin.audit.search-ip', defaultMessage: 'IP' },
|
||||
searchAction: { id: 'app.skin-site.admin.audit.search-action', defaultMessage: 'Action' },
|
||||
search: { id: 'app.skin-site.admin.audit.search', defaultMessage: 'Search' },
|
||||
clear: { id: 'app.skin-site.admin.audit.clear', defaultMessage: 'Clear' },
|
||||
loadMore: { id: 'app.skin-site.admin.audit.load-more', defaultMessage: 'Load more' },
|
||||
retention: {
|
||||
id: 'app.skin-site.admin.audit.retention',
|
||||
defaultMessage: 'Retention (days)',
|
||||
},
|
||||
recordLimit: { id: 'app.skin-site.admin.audit.record-limit', defaultMessage: 'Record limit' },
|
||||
saveRetention: {
|
||||
id: 'app.skin-site.admin.audit.save-retention',
|
||||
defaultMessage: 'Save',
|
||||
},
|
||||
retentionSaved: {
|
||||
id: 'app.skin-site.admin.audit.retention-saved',
|
||||
defaultMessage: 'Retention updated.',
|
||||
},
|
||||
})
|
||||
|
||||
const items = ref<SkinSiteAccessAuditEntry[]>([])
|
||||
const nextCursor = ref<number | null>(null)
|
||||
const retentionDays = ref(0)
|
||||
const recordLimit = ref(0)
|
||||
const loading = ref(true)
|
||||
const loadingMore = ref(false)
|
||||
const failed = ref(false)
|
||||
|
||||
const subjectFilter = ref('')
|
||||
const ipFilter = ref('')
|
||||
const actionFilter = ref('')
|
||||
|
||||
const retentionDraft = ref(0)
|
||||
const savingRetention = ref(false)
|
||||
|
||||
function formatDateTime(ts: number): string {
|
||||
try {
|
||||
return new Date(ts).toLocaleString()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function load(reset = true) {
|
||||
if (reset) {
|
||||
loading.value = true
|
||||
items.value = []
|
||||
nextCursor.value = null
|
||||
} else {
|
||||
loadingMore.value = true
|
||||
}
|
||||
failed.value = false
|
||||
try {
|
||||
const result = await skinSiteAccessAudit({
|
||||
before: reset ? undefined : (nextCursor.value ?? undefined),
|
||||
subject: subjectFilter.value.trim() || undefined,
|
||||
ip: ipFilter.value.trim() || undefined,
|
||||
action: actionFilter.value.trim() || undefined,
|
||||
})
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
const page = result.payload
|
||||
items.value = reset ? page.items : [...items.value, ...page.items]
|
||||
nextCursor.value = page.nextCursor
|
||||
retentionDays.value = page.retentionDays
|
||||
recordLimit.value = page.recordLimit
|
||||
retentionDraft.value = page.retentionDays
|
||||
} catch (error) {
|
||||
failed.value = true
|
||||
handleError(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
loadingMore.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function clearFilters() {
|
||||
subjectFilter.value = ''
|
||||
ipFilter.value = ''
|
||||
actionFilter.value = ''
|
||||
void load(true)
|
||||
}
|
||||
|
||||
async function saveRetention() {
|
||||
if (savingRetention.value) return
|
||||
savingRetention.value = true
|
||||
try {
|
||||
const result = await skinSiteUpdateAccessAuditSettings(Number(retentionDraft.value) || 0)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
retentionDays.value = result.payload.retentionDays
|
||||
retentionDraft.value = result.payload.retentionDays
|
||||
addNotification({ type: 'success', title: formatMessage(messages.retentionSaved) })
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
savingRetention.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load(true))
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h2 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h2>
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.recordLimit) }}: {{ recordLimit }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-end gap-2">
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.searchSubject) }}</span>
|
||||
<input
|
||||
v-model="subjectFilter"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="load(true)"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.searchIp) }}</span>
|
||||
<input
|
||||
v-model="ipFilter"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="load(true)"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.searchAction) }}</span>
|
||||
<input
|
||||
v-model="actionFilter"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="load(true)"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="load(true)"
|
||||
>
|
||||
{{ formatMessage(messages.search) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-secondary hover:brightness-110"
|
||||
@click="clearFilters"
|
||||
>
|
||||
{{ formatMessage(messages.clear) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-end gap-2 rounded-xl bg-bg-raised p-3">
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.retention) }}</span>
|
||||
<input
|
||||
v-model.number="retentionDraft"
|
||||
type="number"
|
||||
min="1"
|
||||
class="w-24 rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="savingRetention"
|
||||
@click="saveRetention"
|
||||
>
|
||||
{{ formatMessage(messages.saveRetention) }}
|
||||
</button>
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.retention) }}: {{ retentionDays }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p v-else-if="failed" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.failed) }}
|
||||
</p>
|
||||
<p v-else-if="!items.length" class="m-0 rounded-xl bg-bg-raised p-4 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="entry in items"
|
||||
:key="entry.id"
|
||||
class="flex flex-col gap-1.5 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="shrink-0 text-xs text-secondary">#{{ entry.id }}</span>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-semibold text-contrast">
|
||||
{{ entry.subject }}
|
||||
</span>
|
||||
<span
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-0.5 text-[10px] font-semibold text-secondary"
|
||||
>
|
||||
{{ entry.action }}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-secondary">×{{ entry.count }}</span>
|
||||
<span
|
||||
v-if="entry.proxy"
|
||||
class="shrink-0 rounded-full bg-orange px-2 py-0.5 text-[10px] font-semibold text-contrast"
|
||||
>
|
||||
{{ formatMessage(messages.proxy) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="entry.internalServer"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-0.5 text-[10px] font-semibold text-secondary"
|
||||
>
|
||||
{{ formatMessage(messages.internal) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-xs text-secondary">
|
||||
<span>{{ formatMessage(messages.sourceIp) }}: {{ entry.sourceIp }}</span>
|
||||
<span v-if="entry.reportedPlayerIp">
|
||||
{{ formatMessage(messages.reportedIp) }}: {{ entry.reportedPlayerIp }}
|
||||
</span>
|
||||
<span>{{ formatMessage(messages.firstAt) }}: {{ formatDateTime(entry.firstAt) }}</span>
|
||||
<span>{{ formatMessage(messages.lastAt) }}: {{ formatDateTime(entry.lastAt) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="nextCursor !== null"
|
||||
type="button"
|
||||
class="w-fit self-center rounded-full bg-button-bg px-4 py-2 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="loadingMore"
|
||||
@click="load(false)"
|
||||
>
|
||||
{{ formatMessage(messages.loadMore) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,366 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
skinSiteAdminDonations,
|
||||
skinSiteCreateDonation,
|
||||
skinSiteDeleteDonation,
|
||||
type SkinSiteDonationAdminEntry,
|
||||
type SkinSiteDonationSummary,
|
||||
skinSiteUpdateDonation,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.admin.donations.title', defaultMessage: 'Donations' },
|
||||
loading: { id: 'app.skin-site.admin.donations.loading', defaultMessage: 'Loading…' },
|
||||
failed: {
|
||||
id: 'app.skin-site.admin.donations.failed',
|
||||
defaultMessage: 'Could not load donations.',
|
||||
},
|
||||
empty: { id: 'app.skin-site.admin.donations.empty', defaultMessage: 'No donations yet.' },
|
||||
totalAmount: { id: 'app.skin-site.admin.donations.total-amount', defaultMessage: 'Total' },
|
||||
donorCount: { id: 'app.skin-site.admin.donations.donor-count', defaultMessage: 'Donors' },
|
||||
donor: { id: 'app.skin-site.admin.donations.donor', defaultMessage: 'Donor' },
|
||||
amount: { id: 'app.skin-site.admin.donations.amount', defaultMessage: 'Amount' },
|
||||
updatedAt: { id: 'app.skin-site.admin.donations.updated-at', defaultMessage: 'Updated' },
|
||||
external: { id: 'app.skin-site.admin.donations.external', defaultMessage: 'External' },
|
||||
linked: { id: 'app.skin-site.admin.donations.linked', defaultMessage: 'Linked' },
|
||||
create: { id: 'app.skin-site.admin.donations.create', defaultMessage: 'Add donation' },
|
||||
save: { id: 'app.skin-site.admin.donations.save', defaultMessage: 'Save' },
|
||||
cancel: { id: 'app.skin-site.admin.donations.cancel', defaultMessage: 'Cancel' },
|
||||
edit: { id: 'app.skin-site.admin.donations.edit', defaultMessage: 'Edit' },
|
||||
remove: { id: 'app.skin-site.admin.donations.remove', defaultMessage: 'Delete' },
|
||||
amountField: { id: 'app.skin-site.admin.donations.amount-field', defaultMessage: 'Amount' },
|
||||
displayName: {
|
||||
id: 'app.skin-site.admin.donations.display-name',
|
||||
defaultMessage: 'Display name',
|
||||
},
|
||||
userUuid: { id: 'app.skin-site.admin.donations.user-uuid', defaultMessage: 'User UUID' },
|
||||
qq: { id: 'app.skin-site.admin.donations.qq', defaultMessage: 'QQ' },
|
||||
appendMode: {
|
||||
id: 'app.skin-site.admin.donations.append-mode',
|
||||
defaultMessage: 'Append to existing amount',
|
||||
},
|
||||
created: { id: 'app.skin-site.admin.donations.created', defaultMessage: 'Donation created.' },
|
||||
updated: { id: 'app.skin-site.admin.donations.updated', defaultMessage: 'Donation updated.' },
|
||||
deleted: { id: 'app.skin-site.admin.donations.deleted', defaultMessage: 'Donation deleted.' },
|
||||
confirmDelete: {
|
||||
id: 'app.skin-site.admin.donations.confirm-delete',
|
||||
defaultMessage: 'Delete the donation from “{name}”? This cannot be undone.',
|
||||
},
|
||||
loadMore: { id: 'app.skin-site.admin.donations.load-more', defaultMessage: 'Load more' },
|
||||
})
|
||||
|
||||
const items = ref<SkinSiteDonationAdminEntry[]>([])
|
||||
const summary = ref<SkinSiteDonationSummary | null>(null)
|
||||
const hasMore = ref(false)
|
||||
const loading = ref(true)
|
||||
const loadingMore = ref(false)
|
||||
const failed = ref(false)
|
||||
const offset = ref(0)
|
||||
|
||||
const editorOpen = ref(false)
|
||||
const editingId = ref<number | null>(null)
|
||||
const editingVersion = ref(0)
|
||||
const saving = ref(false)
|
||||
const deletingId = ref<number | null>(null)
|
||||
|
||||
const form = ref({
|
||||
amount: '',
|
||||
displayName: '',
|
||||
userUuid: '',
|
||||
qq: '',
|
||||
appendMode: false,
|
||||
})
|
||||
|
||||
const canSave = computed(() => form.value.amount.trim().length > 0 && !saving.value)
|
||||
|
||||
function formatDateTime(ts: number): string {
|
||||
try {
|
||||
return new Date(ts).toLocaleString()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
form.value = { amount: '', displayName: '', userUuid: '', qq: '', appendMode: false }
|
||||
editingId.value = null
|
||||
editingVersion.value = 0
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
resetForm()
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function openEdit(entry: SkinSiteDonationAdminEntry) {
|
||||
form.value = {
|
||||
amount: entry.donor.amount,
|
||||
displayName: entry.donor.username,
|
||||
userUuid: entry.userUuid ?? '',
|
||||
qq: entry.qq ?? '',
|
||||
appendMode: false,
|
||||
}
|
||||
editingId.value = entry.donor.id
|
||||
editingVersion.value = entry.version
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function closeEditor() {
|
||||
editorOpen.value = false
|
||||
resetForm()
|
||||
}
|
||||
|
||||
async function load(reset = true) {
|
||||
if (reset) {
|
||||
loading.value = true
|
||||
items.value = []
|
||||
offset.value = 0
|
||||
} else {
|
||||
loadingMore.value = true
|
||||
}
|
||||
failed.value = false
|
||||
try {
|
||||
const result = await skinSiteAdminDonations(offset.value)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
const page = result.payload
|
||||
items.value = reset ? page.items : [...items.value, ...page.items]
|
||||
summary.value = page.summary
|
||||
hasMore.value = page.hasMore
|
||||
} catch (error) {
|
||||
failed.value = true
|
||||
handleError(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
loadingMore.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
if (!hasMore.value) return
|
||||
offset.value += 20
|
||||
await load(false)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!canSave.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
if (editingId.value === null) {
|
||||
const payload: Parameters<typeof skinSiteCreateDonation>[0] = {
|
||||
amount: form.value.amount.trim(),
|
||||
}
|
||||
if (form.value.userUuid.trim()) payload.userUuid = form.value.userUuid.trim()
|
||||
if (form.value.qq.trim()) payload.qq = form.value.qq.trim()
|
||||
if (form.value.displayName.trim()) payload.displayName = form.value.displayName.trim()
|
||||
const result = await skinSiteCreateDonation(payload)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.created) })
|
||||
} else {
|
||||
const result = await skinSiteUpdateDonation(editingId.value, {
|
||||
amount: form.value.amount.trim(),
|
||||
version: editingVersion.value,
|
||||
displayName: form.value.displayName.trim() || undefined,
|
||||
mode: form.value.appendMode ? 'APPEND' : 'REPLACE',
|
||||
})
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.updated) })
|
||||
}
|
||||
closeEditor()
|
||||
await load(true)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(entry: SkinSiteDonationAdminEntry) {
|
||||
if (deletingId.value !== null) return
|
||||
if (!window.confirm(formatMessage(messages.confirmDelete, { name: entry.donor.username }))) return
|
||||
deletingId.value = entry.donor.id
|
||||
try {
|
||||
const result = await skinSiteDeleteDonation(entry.donor.id, entry.version)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.deleted) })
|
||||
await load(true)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load(true))
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h2 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="openCreate"
|
||||
>
|
||||
{{ formatMessage(messages.create) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="summary" class="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="flex flex-col gap-1 rounded-xl bg-bg-raised p-4">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.totalAmount) }}</span>
|
||||
<span class="text-xl font-bold text-contrast">{{ summary.totalAmount }}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1 rounded-xl bg-bg-raised p-4">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.donorCount) }}</span>
|
||||
<span class="text-xl font-bold text-contrast">{{ summary.donorCount }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p v-else-if="failed" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.failed) }}
|
||||
</p>
|
||||
<p v-else-if="!items.length" class="m-0 rounded-xl bg-bg-raised p-4 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="entry in items"
|
||||
:key="entry.donor.id"
|
||||
class="flex flex-wrap items-center gap-3 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<span class="shrink-0 text-xs text-secondary">#{{ entry.donor.rank }}</span>
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<span class="truncate text-sm font-semibold text-contrast">
|
||||
{{ entry.donor.username }}
|
||||
</span>
|
||||
<span class="truncate text-xs text-secondary">
|
||||
{{ formatMessage(messages.updatedAt) }}:
|
||||
{{ formatDateTime(entry.updatedAt) }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="shrink-0 text-sm font-bold text-contrast">{{ entry.donor.amount }}</span>
|
||||
<span
|
||||
v-if="entry.external"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-0.5 text-[10px] font-semibold text-secondary"
|
||||
>
|
||||
{{ formatMessage(messages.external) }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="shrink-0 rounded-full bg-green px-2 py-0.5 text-[10px] font-semibold text-contrast"
|
||||
>
|
||||
{{ formatMessage(messages.linked) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="openEdit(entry)"
|
||||
>
|
||||
{{ formatMessage(messages.edit) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="deletingId !== null"
|
||||
@click="remove(entry)"
|
||||
>
|
||||
{{ formatMessage(messages.remove) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="hasMore"
|
||||
type="button"
|
||||
class="w-fit self-center rounded-full bg-button-bg px-4 py-2 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="loadingMore"
|
||||
@click="loadMore"
|
||||
>
|
||||
{{ formatMessage(messages.loadMore) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="editorOpen"
|
||||
class="flex flex-col gap-3 rounded-xl border border-solid border-surface-5 bg-bg-raised p-4"
|
||||
>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.amountField) }}
|
||||
</span>
|
||||
<input
|
||||
v-model="form.amount"
|
||||
type="text"
|
||||
inputmode="decimal"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.displayName) }}
|
||||
</span>
|
||||
<input
|
||||
v-model="form.displayName"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<template v-if="editingId === null">
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.userUuid) }}
|
||||
</span>
|
||||
<input
|
||||
v-model="form.userUuid"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.qq) }}
|
||||
</span>
|
||||
<input
|
||||
v-model="form.qq"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
<label v-else class="flex items-center gap-2">
|
||||
<input v-model="form.appendMode" type="checkbox" />
|
||||
<span class="text-sm text-contrast">{{ formatMessage(messages.appendMode) }}</span>
|
||||
</label>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="closeEditor"
|
||||
>
|
||||
{{ formatMessage(messages.cancel) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast disabled:opacity-50"
|
||||
:disabled="!canSave"
|
||||
@click="save"
|
||||
>
|
||||
{{ formatMessage(messages.save) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,576 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
skinSiteAddDownloadCategory,
|
||||
skinSiteAddDownloadItem,
|
||||
skinSiteBindDownloadCategory,
|
||||
skinSiteDeleteDownloadCategory,
|
||||
skinSiteDeleteDownloadItem,
|
||||
skinSiteDownloadCategories,
|
||||
type SkinSiteDownloadCategory,
|
||||
type SkinSiteDownloadItem,
|
||||
skinSiteDownloadItemCount,
|
||||
skinSiteDownloadItems,
|
||||
type SkinSiteDownloadRoute,
|
||||
type SkinSiteDownloadStatus,
|
||||
skinSiteUnbindDownloadCategory,
|
||||
skinSiteUpdateDownloadItem,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.admin.downloads.title', defaultMessage: 'Downloads' },
|
||||
loading: { id: 'app.skin-site.admin.downloads.loading', defaultMessage: 'Loading…' },
|
||||
failed: {
|
||||
id: 'app.skin-site.admin.downloads.failed',
|
||||
defaultMessage: 'Could not load downloads.',
|
||||
},
|
||||
empty: { id: 'app.skin-site.admin.downloads.empty', defaultMessage: 'No download items.' },
|
||||
categories: { id: 'app.skin-site.admin.downloads.categories', defaultMessage: 'Categories' },
|
||||
all: { id: 'app.skin-site.admin.downloads.all', defaultMessage: 'All items' },
|
||||
addCategory: { id: 'app.skin-site.admin.downloads.add-category', defaultMessage: 'Add' },
|
||||
categoryName: {
|
||||
id: 'app.skin-site.admin.downloads.category-name',
|
||||
defaultMessage: 'Category name',
|
||||
},
|
||||
removeCategory: {
|
||||
id: 'app.skin-site.admin.downloads.remove-category',
|
||||
defaultMessage: 'Remove',
|
||||
},
|
||||
total: { id: 'app.skin-site.admin.downloads.total', defaultMessage: '{count} items' },
|
||||
addItem: { id: 'app.skin-site.admin.downloads.add-item', defaultMessage: 'New item' },
|
||||
save: { id: 'app.skin-site.admin.downloads.save', defaultMessage: 'Save' },
|
||||
cancel: { id: 'app.skin-site.admin.downloads.cancel', defaultMessage: 'Cancel' },
|
||||
edit: { id: 'app.skin-site.admin.downloads.edit', defaultMessage: 'Edit' },
|
||||
remove: { id: 'app.skin-site.admin.downloads.remove', defaultMessage: 'Delete' },
|
||||
filename: { id: 'app.skin-site.admin.downloads.filename', defaultMessage: 'File name' },
|
||||
description: {
|
||||
id: 'app.skin-site.admin.downloads.description',
|
||||
defaultMessage: 'Description',
|
||||
},
|
||||
routes: { id: 'app.skin-site.admin.downloads.routes', defaultMessage: 'Download routes' },
|
||||
routeName: { id: 'app.skin-site.admin.downloads.route-name', defaultMessage: 'Name' },
|
||||
routeUrl: { id: 'app.skin-site.admin.downloads.route-url', defaultMessage: 'URL' },
|
||||
addRoute: { id: 'app.skin-site.admin.downloads.add-route', defaultMessage: 'Add route' },
|
||||
removeRoute: { id: 'app.skin-site.admin.downloads.remove-route', defaultMessage: 'Remove' },
|
||||
statuses: { id: 'app.skin-site.admin.downloads.statuses', defaultMessage: 'Statuses' },
|
||||
bindCategory: {
|
||||
id: 'app.skin-site.admin.downloads.bind-category',
|
||||
defaultMessage: 'Categories',
|
||||
},
|
||||
uploader: { id: 'app.skin-site.admin.downloads.uploader', defaultMessage: 'by {name}' },
|
||||
created: { id: 'app.skin-site.admin.downloads.created', defaultMessage: 'Item created.' },
|
||||
updated: { id: 'app.skin-site.admin.downloads.updated', defaultMessage: 'Item updated.' },
|
||||
deleted: { id: 'app.skin-site.admin.downloads.deleted', defaultMessage: 'Item deleted.' },
|
||||
categoryAdded: {
|
||||
id: 'app.skin-site.admin.downloads.category-added',
|
||||
defaultMessage: 'Category added.',
|
||||
},
|
||||
categoryDeleted: {
|
||||
id: 'app.skin-site.admin.downloads.category-deleted',
|
||||
defaultMessage: 'Category deleted.',
|
||||
},
|
||||
confirmDeleteItem: {
|
||||
id: 'app.skin-site.admin.downloads.confirm-delete-item',
|
||||
defaultMessage: 'Delete “{name}”? This cannot be undone.',
|
||||
},
|
||||
confirmDeleteCategory: {
|
||||
id: 'app.skin-site.admin.downloads.confirm-delete-category',
|
||||
defaultMessage: 'Delete category “{name}”?',
|
||||
},
|
||||
})
|
||||
|
||||
const STATUS_OPTIONS: SkinSiteDownloadStatus[] = ['OK', 'NEW', 'LEGACY', 'OUTDATED', 'REMOVAL']
|
||||
|
||||
const items = ref<SkinSiteDownloadItem[]>([])
|
||||
const categories = ref<SkinSiteDownloadCategory[]>([])
|
||||
const total = ref(0)
|
||||
const loading = ref(true)
|
||||
const failed = ref(false)
|
||||
const activeCategory = ref<string>('')
|
||||
|
||||
const newCategoryName = ref('')
|
||||
const categoryWorking = ref(false)
|
||||
|
||||
const editorOpen = ref(false)
|
||||
const editingId = ref<number | null>(null)
|
||||
const saving = ref(false)
|
||||
const deletingId = ref<number | null>(null)
|
||||
|
||||
const form = ref({
|
||||
filename: '',
|
||||
description: '',
|
||||
status: [] as SkinSiteDownloadStatus[],
|
||||
routes: [{ name: '', url: '' }] as Array<{ name: string; url: string }>,
|
||||
selectedCategories: [] as number[],
|
||||
})
|
||||
|
||||
const canSave = computed(
|
||||
() =>
|
||||
form.value.filename.trim().length > 0 &&
|
||||
form.value.routes.some((r) => r.url.trim().length > 0) &&
|
||||
!saving.value,
|
||||
)
|
||||
|
||||
function resetForm() {
|
||||
form.value = {
|
||||
filename: '',
|
||||
description: '',
|
||||
status: [],
|
||||
routes: [{ name: '', url: '' }],
|
||||
selectedCategories: [],
|
||||
}
|
||||
editingId.value = null
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
resetForm()
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function openEdit(item: SkinSiteDownloadItem) {
|
||||
form.value = {
|
||||
filename: item.filename,
|
||||
description: item.description,
|
||||
status: [...item.status],
|
||||
routes: item.routes.length
|
||||
? item.routes.map((r) => ({ name: r.name ?? '', url: r.url }))
|
||||
: [{ name: '', url: '' }],
|
||||
selectedCategories: categories.value
|
||||
.filter((c) => item.category.includes(c.name))
|
||||
.map((c) => c.id),
|
||||
}
|
||||
editingId.value = item.id
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function closeEditor() {
|
||||
editorOpen.value = false
|
||||
resetForm()
|
||||
}
|
||||
|
||||
function addRouteRow() {
|
||||
form.value.routes.push({ name: '', url: '' })
|
||||
}
|
||||
|
||||
function removeRouteRow(index: number) {
|
||||
if (form.value.routes.length <= 1) return
|
||||
form.value.routes.splice(index, 1)
|
||||
}
|
||||
|
||||
function toggleStatus(status: SkinSiteDownloadStatus) {
|
||||
const i = form.value.status.indexOf(status)
|
||||
if (i >= 0) form.value.status.splice(i, 1)
|
||||
else form.value.status.push(status)
|
||||
}
|
||||
|
||||
async function loadCategories() {
|
||||
try {
|
||||
const result = await skinSiteDownloadCategories()
|
||||
if (result.success) categories.value = result.payload ?? []
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadItems() {
|
||||
loading.value = true
|
||||
failed.value = false
|
||||
try {
|
||||
const listResult = await skinSiteDownloadItems({
|
||||
limit: 200,
|
||||
offset: 0,
|
||||
category: activeCategory.value || undefined,
|
||||
})
|
||||
if (!listResult.success) throw new Error(listResult.errorMessage)
|
||||
items.value = listResult.payload ?? []
|
||||
const countResult = await skinSiteDownloadItemCount(activeCategory.value || undefined)
|
||||
if (countResult.success && typeof countResult.payload === 'number') {
|
||||
total.value = countResult.payload
|
||||
}
|
||||
} catch (error) {
|
||||
failed.value = true
|
||||
handleError(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function selectCategory(name: string) {
|
||||
activeCategory.value = name
|
||||
await loadItems()
|
||||
}
|
||||
|
||||
async function addCategory() {
|
||||
const name = newCategoryName.value.trim()
|
||||
if (!name || categoryWorking.value) return
|
||||
categoryWorking.value = true
|
||||
try {
|
||||
const result = await skinSiteAddDownloadCategory(name)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
newCategoryName.value = ''
|
||||
addNotification({ type: 'success', title: formatMessage(messages.categoryAdded) })
|
||||
await loadCategories()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
categoryWorking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeCategory(category: SkinSiteDownloadCategory) {
|
||||
if (categoryWorking.value) return
|
||||
if (!window.confirm(formatMessage(messages.confirmDeleteCategory, { name: category.name })))
|
||||
return
|
||||
categoryWorking.value = true
|
||||
try {
|
||||
const result = await skinSiteDeleteDownloadCategory(category.id)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.categoryDeleted) })
|
||||
if (activeCategory.value === category.name) activeCategory.value = ''
|
||||
await loadCategories()
|
||||
await loadItems()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
categoryWorking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!canSave.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const routes: SkinSiteDownloadRoute[] = form.value.routes
|
||||
.filter((r) => r.url.trim())
|
||||
.map((r) => ({ name: r.name.trim() || null, url: r.url.trim() }))
|
||||
const payload = {
|
||||
routes,
|
||||
filename: form.value.filename.trim(),
|
||||
description: form.value.description,
|
||||
status: form.value.status,
|
||||
}
|
||||
const result =
|
||||
editingId.value === null
|
||||
? await skinSiteAddDownloadItem(payload)
|
||||
: await skinSiteUpdateDownloadItem(editingId.value, payload)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({
|
||||
type: 'success',
|
||||
title: formatMessage(editingId.value === null ? messages.created : messages.updated),
|
||||
})
|
||||
closeEditor()
|
||||
await loadItems()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(item: SkinSiteDownloadItem) {
|
||||
if (deletingId.value !== null) return
|
||||
if (!window.confirm(formatMessage(messages.confirmDeleteItem, { name: item.filename }))) return
|
||||
deletingId.value = item.id
|
||||
try {
|
||||
const result = await skinSiteDeleteDownloadItem(item.id)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.deleted) })
|
||||
await loadItems()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleItemCategory(item: SkinSiteDownloadItem, category: SkinSiteDownloadCategory) {
|
||||
try {
|
||||
const bound = item.category.includes(category.name)
|
||||
const result = bound
|
||||
? await skinSiteUnbindDownloadCategory(item.id, category.id)
|
||||
: await skinSiteBindDownloadCategory(item.id, category.id)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
await loadItems()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadCategories()
|
||||
await loadItems()
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h2 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h2>
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.total, { count: total }) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="openCreate"
|
||||
>
|
||||
{{ formatMessage(messages.addItem) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-0 gap-4">
|
||||
<aside class="flex w-56 shrink-0 flex-col gap-2">
|
||||
<span class="text-xs font-bold tracking-wide text-secondary uppercase">
|
||||
{{ formatMessage(messages.categories) }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg px-2 py-1.5 text-left text-xs font-semibold"
|
||||
:class="
|
||||
activeCategory === ''
|
||||
? 'bg-brand text-contrast'
|
||||
: 'text-secondary hover:bg-button-bg hover:text-contrast'
|
||||
"
|
||||
@click="selectCategory('')"
|
||||
>
|
||||
{{ formatMessage(messages.all) }}
|
||||
</button>
|
||||
<div v-for="category in categories" :key="category.id" class="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="min-w-0 flex-1 truncate rounded-lg px-2 py-1.5 text-left text-xs font-semibold"
|
||||
:class="
|
||||
activeCategory === category.name
|
||||
? 'bg-brand text-contrast'
|
||||
: 'text-secondary hover:bg-button-bg hover:text-contrast'
|
||||
"
|
||||
@click="selectCategory(category.name)"
|
||||
>
|
||||
{{ category.name }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded px-1 text-[10px] text-secondary hover:text-red"
|
||||
:disabled="categoryWorking"
|
||||
@click="removeCategory(category)"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex items-center gap-1 pt-1">
|
||||
<input
|
||||
v-model="newCategoryName"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.categoryName)"
|
||||
class="min-w-0 flex-1 rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="addCategory"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="categoryWorking || !newCategoryName.trim()"
|
||||
@click="addCategory"
|
||||
>
|
||||
{{ formatMessage(messages.addCategory) }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-2">
|
||||
<div v-if="loading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p v-else-if="failed" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.failed) }}
|
||||
</p>
|
||||
<p v-else-if="!items.length" class="m-0 rounded-xl bg-bg-raised p-4 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="item in items"
|
||||
:key="item.id"
|
||||
class="flex flex-col gap-2 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="shrink-0 text-xs text-secondary">#{{ item.id }}</span>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-semibold text-contrast">
|
||||
{{ item.filename }}
|
||||
</span>
|
||||
<span
|
||||
v-for="s in item.status"
|
||||
:key="s"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-0.5 text-[10px] font-semibold text-secondary"
|
||||
>
|
||||
{{ s }}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-secondary">
|
||||
{{ formatMessage(messages.uploader, { name: item.uploader }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="item.description" class="text-xs text-secondary">
|
||||
{{ item.description }}
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<span
|
||||
v-for="route in item.routes"
|
||||
:key="route.url"
|
||||
class="rounded bg-bg px-2 py-0.5 font-mono text-[10px] text-secondary"
|
||||
>
|
||||
{{ route.name ? route.name + ': ' : '' }}{{ route.url }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.bindCategory) }}:
|
||||
</span>
|
||||
<button
|
||||
v-for="category in categories"
|
||||
:key="category.id"
|
||||
type="button"
|
||||
class="rounded-full px-2 py-0.5 text-[10px] font-semibold"
|
||||
:class="
|
||||
item.category.includes(category.name)
|
||||
? 'bg-brand text-contrast'
|
||||
: 'bg-button-bg text-secondary hover:text-contrast'
|
||||
"
|
||||
@click="toggleItemCategory(item, category)"
|
||||
>
|
||||
{{ category.name }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="openEdit(item)"
|
||||
>
|
||||
{{ formatMessage(messages.edit) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="deletingId !== null"
|
||||
@click="remove(item)"
|
||||
>
|
||||
{{ formatMessage(messages.remove) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="editorOpen"
|
||||
class="flex flex-col gap-3 rounded-xl border border-solid border-surface-5 bg-bg-raised p-4"
|
||||
>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.filename) }}
|
||||
</span>
|
||||
<input
|
||||
v-model="form.filename"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.description) }}
|
||||
</span>
|
||||
<textarea
|
||||
v-model="form.description"
|
||||
rows="3"
|
||||
class="w-full resize-y rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.statuses) }}
|
||||
</span>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="status in STATUS_OPTIONS"
|
||||
:key="status"
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1 text-xs font-semibold"
|
||||
:class="
|
||||
form.status.includes(status)
|
||||
? 'bg-brand text-contrast'
|
||||
: 'bg-button-bg text-secondary'
|
||||
"
|
||||
@click="toggleStatus(status)"
|
||||
>
|
||||
{{ status }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.routes) }}
|
||||
</span>
|
||||
<div
|
||||
v-for="(route, idx) in form.routes"
|
||||
:key="idx"
|
||||
class="flex flex-wrap items-center gap-2"
|
||||
>
|
||||
<input
|
||||
v-model="route.name"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.routeName)"
|
||||
class="w-32 rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
<input
|
||||
v-model="route.url"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.routeUrl)"
|
||||
class="min-w-0 flex-1 rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-1 text-[10px] font-semibold text-secondary hover:text-red disabled:opacity-50"
|
||||
:disabled="form.routes.length <= 1"
|
||||
@click="removeRouteRow(idx)"
|
||||
>
|
||||
{{ formatMessage(messages.removeRoute) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="w-fit rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-secondary hover:brightness-110"
|
||||
@click="addRouteRow"
|
||||
>
|
||||
{{ formatMessage(messages.addRoute) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="closeEditor"
|
||||
>
|
||||
{{ formatMessage(messages.cancel) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast disabled:opacity-50"
|
||||
:disabled="!canSave"
|
||||
@click="save"
|
||||
>
|
||||
{{ formatMessage(messages.save) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,982 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
skinSiteActivateModRuntime,
|
||||
skinSiteCreateModRuleTag,
|
||||
skinSiteDeleteModFile,
|
||||
skinSiteDeleteModRuleTag,
|
||||
skinSiteDeleteModRuntime,
|
||||
skinSiteDeleteMultiModFile,
|
||||
skinSiteModCount,
|
||||
type SkinSiteModInfo,
|
||||
skinSiteModList,
|
||||
type SkinSiteModRuleTag,
|
||||
skinSiteModRuleTags,
|
||||
type SkinSiteModRuntimeAdminState,
|
||||
type SkinSiteModRuntimeRelease,
|
||||
skinSiteModRuntimeReleases,
|
||||
skinSiteModSearch,
|
||||
skinSiteUpdateModInfo,
|
||||
skinSiteUpdateModRuleTag,
|
||||
skinSiteUpdateMultiModInfo,
|
||||
skinSiteUploadModRuntime,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
import ModUploadModal from './ModUploadModal.vue'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.admin.mods.title', defaultMessage: 'Mods' },
|
||||
tabMods: { id: 'app.skin-site.admin.mods.tab-mods', defaultMessage: 'Mod files' },
|
||||
tabTags: { id: 'app.skin-site.admin.mods.tab-tags', defaultMessage: 'Rule tags' },
|
||||
tabRuntime: { id: 'app.skin-site.admin.mods.tab-runtime', defaultMessage: 'Runtime' },
|
||||
loading: { id: 'app.skin-site.admin.mods.loading', defaultMessage: 'Loading…' },
|
||||
failed: { id: 'app.skin-site.admin.mods.failed', defaultMessage: 'Could not load mods.' },
|
||||
empty: { id: 'app.skin-site.admin.mods.empty', defaultMessage: 'No mods found.' },
|
||||
total: { id: 'app.skin-site.admin.mods.total', defaultMessage: '{count} mods' },
|
||||
search: { id: 'app.skin-site.admin.mods.search', defaultMessage: 'Search by name' },
|
||||
filterAll: { id: 'app.skin-site.admin.mods.filter-all', defaultMessage: 'All tags' },
|
||||
prev: { id: 'app.skin-site.admin.mods.prev', defaultMessage: 'Previous' },
|
||||
next: { id: 'app.skin-site.admin.mods.next', defaultMessage: 'Next' },
|
||||
page: { id: 'app.skin-site.admin.mods.page', defaultMessage: 'Page {page}' },
|
||||
name: { id: 'app.skin-site.admin.mods.name', defaultMessage: 'Name' },
|
||||
version: { id: 'app.skin-site.admin.mods.version', defaultMessage: 'Version' },
|
||||
modId: { id: 'app.skin-site.admin.mods.mod-id', defaultMessage: 'Mod ID' },
|
||||
size: { id: 'app.skin-site.admin.mods.size', defaultMessage: 'Size' },
|
||||
loaders: { id: 'app.skin-site.admin.mods.loaders', defaultMessage: 'Loaders' },
|
||||
domainRules: { id: 'app.skin-site.admin.mods.domain-rules', defaultMessage: 'Domain rules' },
|
||||
edit: { id: 'app.skin-site.admin.mods.edit', defaultMessage: 'Edit' },
|
||||
save: { id: 'app.skin-site.admin.mods.save', defaultMessage: 'Save' },
|
||||
cancel: { id: 'app.skin-site.admin.mods.cancel', defaultMessage: 'Cancel' },
|
||||
remove: { id: 'app.skin-site.admin.mods.remove', defaultMessage: 'Delete' },
|
||||
updated: { id: 'app.skin-site.admin.mods.updated', defaultMessage: 'Mod updated.' },
|
||||
deleted: { id: 'app.skin-site.admin.mods.deleted', defaultMessage: 'Mod deleted.' },
|
||||
confirmDelete: {
|
||||
id: 'app.skin-site.admin.mods.confirm-delete',
|
||||
defaultMessage: 'Delete mod “{name}”? This cannot be undone.',
|
||||
},
|
||||
ruleTags: { id: 'app.skin-site.admin.mods.rule-tags', defaultMessage: 'Rule tags' },
|
||||
tagName: { id: 'app.skin-site.admin.mods.tag-name', defaultMessage: 'Tag name' },
|
||||
tagRules: { id: 'app.skin-site.admin.mods.tag-rules', defaultMessage: 'Rules' },
|
||||
tagRulesHint: {
|
||||
id: 'app.skin-site.admin.mods.tag-rules-hint',
|
||||
defaultMessage: 'One rule per line.',
|
||||
},
|
||||
newTag: { id: 'app.skin-site.admin.mods.new-tag', defaultMessage: 'New tag' },
|
||||
tagCreated: { id: 'app.skin-site.admin.mods.tag-created', defaultMessage: 'Tag created.' },
|
||||
tagUpdated: { id: 'app.skin-site.admin.mods.tag-updated', defaultMessage: 'Tag updated.' },
|
||||
tagDeleted: { id: 'app.skin-site.admin.mods.tag-deleted', defaultMessage: 'Tag deleted.' },
|
||||
confirmDeleteTag: {
|
||||
id: 'app.skin-site.admin.mods.confirm-delete-tag',
|
||||
defaultMessage: 'Delete tag “{name}”?',
|
||||
},
|
||||
runtime: { id: 'app.skin-site.admin.mods.runtime', defaultMessage: 'Runtime releases' },
|
||||
manifestUrl: { id: 'app.skin-site.admin.mods.manifest-url', defaultMessage: 'Manifest URL' },
|
||||
uploadRuntime: {
|
||||
id: 'app.skin-site.admin.mods.upload-runtime',
|
||||
defaultMessage: 'Upload runtime',
|
||||
},
|
||||
runtimeVersion: {
|
||||
id: 'app.skin-site.admin.mods.runtime-version',
|
||||
defaultMessage: 'Version',
|
||||
},
|
||||
uploading: { id: 'app.skin-site.admin.mods.uploading', defaultMessage: 'Uploading…' },
|
||||
runtimeUploaded: {
|
||||
id: 'app.skin-site.admin.mods.runtime-uploaded',
|
||||
defaultMessage: 'Runtime uploaded.',
|
||||
},
|
||||
activate: { id: 'app.skin-site.admin.mods.activate', defaultMessage: 'Activate' },
|
||||
activated: { id: 'app.skin-site.admin.mods.activated', defaultMessage: 'Runtime activated.' },
|
||||
available: { id: 'app.skin-site.admin.mods.available', defaultMessage: 'Available' },
|
||||
unavailable: { id: 'app.skin-site.admin.mods.unavailable', defaultMessage: 'Unavailable' },
|
||||
active: { id: 'app.skin-site.admin.mods.active', defaultMessage: 'Active' },
|
||||
uploader: { id: 'app.skin-site.admin.mods.uploader', defaultMessage: 'by {name}' },
|
||||
upload: { id: 'app.skin-site.admin.mods.upload', defaultMessage: 'Upload' },
|
||||
selectMode: {
|
||||
id: 'app.skin-site.admin.mods.select-mode',
|
||||
defaultMessage: 'Select multiple',
|
||||
},
|
||||
exitSelect: {
|
||||
id: 'app.skin-site.admin.mods.exit-select',
|
||||
defaultMessage: 'Done selecting',
|
||||
},
|
||||
selectAll: { id: 'app.skin-site.admin.mods.select-all', defaultMessage: 'Select all' },
|
||||
clearSelection: {
|
||||
id: 'app.skin-site.admin.mods.clear-selection',
|
||||
defaultMessage: 'Clear selection',
|
||||
},
|
||||
selectedCount: {
|
||||
id: 'app.skin-site.admin.mods.selected-count',
|
||||
defaultMessage: '{count} selected',
|
||||
},
|
||||
deleteSelected: {
|
||||
id: 'app.skin-site.admin.mods.delete-selected',
|
||||
defaultMessage: 'Delete selected',
|
||||
},
|
||||
confirmDeleteMulti: {
|
||||
id: 'app.skin-site.admin.mods.confirm-delete-multi',
|
||||
defaultMessage: 'Delete {count} selected mods? This cannot be undone.',
|
||||
},
|
||||
deletedMulti: {
|
||||
id: 'app.skin-site.admin.mods.deleted-multi',
|
||||
defaultMessage: 'Selected mods deleted.',
|
||||
},
|
||||
serverAddress: {
|
||||
id: 'app.skin-site.admin.mods.server-address',
|
||||
defaultMessage: 'Server address',
|
||||
},
|
||||
serverAddressHint: {
|
||||
id: 'app.skin-site.admin.mods.server-address-hint',
|
||||
defaultMessage: 'Filter by server address',
|
||||
},
|
||||
apply: { id: 'app.skin-site.admin.mods.apply', defaultMessage: 'Apply' },
|
||||
clear: { id: 'app.skin-site.admin.mods.clear', defaultMessage: 'Clear' },
|
||||
})
|
||||
|
||||
type Tab = 'mods' | 'tags' | 'runtime'
|
||||
const tab = ref<Tab>('mods')
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
const mods = ref<SkinSiteModInfo[]>([])
|
||||
const modTotal = ref(0)
|
||||
const modOffset = ref(0)
|
||||
const modLoading = ref(true)
|
||||
const modFailed = ref(false)
|
||||
const searchKeyword = ref('')
|
||||
const tagFilter = ref<number | null>(null)
|
||||
|
||||
const editingHash = ref<string | null>(null)
|
||||
const editForm = ref({ name: '', modId: '', version: '', domainRules: '' })
|
||||
const savingMod = ref(false)
|
||||
const deletingHash = ref<string | null>(null)
|
||||
|
||||
const selectedHashes = ref<Set<string>>(new Set())
|
||||
const selectionMode = ref(false)
|
||||
const deletingMulti = ref(false)
|
||||
const serverAddressInput = ref('')
|
||||
const serverAddressFilter = ref('')
|
||||
const uploadOpen = ref(false)
|
||||
|
||||
const tags = ref<SkinSiteModRuleTag[]>([])
|
||||
const tagsLoading = ref(false)
|
||||
const tagEditorOpen = ref(false)
|
||||
const editingTagId = ref<number | null>(null)
|
||||
const tagForm = ref({ name: '', rules: '' })
|
||||
const savingTag = ref(false)
|
||||
|
||||
const runtimeState = ref<SkinSiteModRuntimeAdminState | null>(null)
|
||||
const runtimeLoading = ref(false)
|
||||
const runtimeVersion = ref('')
|
||||
const runtimeFile = ref<HTMLInputElement | null>(null)
|
||||
const runtimeUploading = ref(false)
|
||||
const activatingRuntimeId = ref<number | null>(null)
|
||||
const deletingRuntimeId = ref<number | null>(null)
|
||||
|
||||
const modPage = computed(() => Math.floor(modOffset.value / PAGE_SIZE) + 1)
|
||||
const modPageCount = computed(() => Math.max(1, Math.ceil(modTotal.value / PAGE_SIZE)))
|
||||
const hasPrev = computed(() => modOffset.value > 0)
|
||||
const hasNext = computed(() => modOffset.value + PAGE_SIZE < modTotal.value)
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes < 0) return '—'
|
||||
const units = ['B', 'KB', 'MB', 'GB']
|
||||
let v = bytes
|
||||
let i = 0
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024
|
||||
i++
|
||||
}
|
||||
return v.toFixed(i === 0 ? 0 : 2) + ' ' + units[i]
|
||||
}
|
||||
|
||||
function formatDateTime(ts?: number | null): string {
|
||||
if (!ts) return '—'
|
||||
try {
|
||||
return new Date(ts).toLocaleString()
|
||||
} catch {
|
||||
return '—'
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMods(reset = true) {
|
||||
if (reset) {
|
||||
modLoading.value = true
|
||||
mods.value = []
|
||||
modOffset.value = 0
|
||||
}
|
||||
modFailed.value = false
|
||||
try {
|
||||
const kw = searchKeyword.value.trim()
|
||||
if (kw) {
|
||||
const result = await skinSiteModSearch(kw, tagFilter.value)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
mods.value = result.payload ?? []
|
||||
modTotal.value = mods.value.length
|
||||
} else {
|
||||
const [listResult, countResult] = await Promise.all([
|
||||
skinSiteModList({
|
||||
limit: PAGE_SIZE,
|
||||
offset: modOffset.value,
|
||||
ruleTagId: tagFilter.value,
|
||||
serverAddr: serverAddressFilter.value || undefined,
|
||||
}),
|
||||
skinSiteModCount({
|
||||
ruleTagId: tagFilter.value,
|
||||
serverAddr: serverAddressFilter.value || undefined,
|
||||
}),
|
||||
])
|
||||
if (!listResult.success) throw new Error(listResult.errorMessage)
|
||||
mods.value = listResult.payload ?? []
|
||||
if (countResult.success && typeof countResult.payload === 'number') {
|
||||
modTotal.value = countResult.payload
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
modFailed.value = true
|
||||
handleError(error)
|
||||
} finally {
|
||||
modLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function prevPage() {
|
||||
if (hasPrev.value) {
|
||||
modOffset.value = Math.max(0, modOffset.value - PAGE_SIZE)
|
||||
void loadMods(false)
|
||||
}
|
||||
}
|
||||
function nextPage() {
|
||||
if (hasNext.value) {
|
||||
modOffset.value += PAGE_SIZE
|
||||
void loadMods(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTags() {
|
||||
tagsLoading.value = true
|
||||
try {
|
||||
const result = await skinSiteModRuleTags()
|
||||
if (result.success) tags.value = result.payload ?? []
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
tagsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRuntime() {
|
||||
runtimeLoading.value = true
|
||||
try {
|
||||
const result = await skinSiteModRuntimeReleases()
|
||||
if (result.success) runtimeState.value = result.payload
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
runtimeLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function switchTab(next: Tab) {
|
||||
tab.value = next
|
||||
if (next === 'tags' && !tags.value.length) await loadTags()
|
||||
if (next === 'runtime' && !runtimeState.value) await loadRuntime()
|
||||
}
|
||||
|
||||
function startEdit(mod: SkinSiteModInfo) {
|
||||
editingHash.value = mod.hash
|
||||
editForm.value = {
|
||||
name: mod.metadata.name ?? mod.name,
|
||||
modId: mod.metadata.modId ?? '',
|
||||
version: mod.metadata.version ?? '',
|
||||
domainRules: mod.domainRules.join(', '),
|
||||
}
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
editingHash.value = null
|
||||
}
|
||||
|
||||
async function saveMod(mod: SkinSiteModInfo) {
|
||||
if (savingMod.value) return
|
||||
savingMod.value = true
|
||||
try {
|
||||
const payload: SkinSiteModInfo = {
|
||||
...mod,
|
||||
name: editForm.value.name.trim() || mod.name,
|
||||
domainRules: editForm.value.domainRules
|
||||
.split(',')
|
||||
.map((r) => r.trim())
|
||||
.filter(Boolean),
|
||||
metadata: {
|
||||
...mod.metadata,
|
||||
name: editForm.value.name.trim() || undefined,
|
||||
modId: editForm.value.modId.trim() || undefined,
|
||||
version: editForm.value.version.trim() || undefined,
|
||||
},
|
||||
}
|
||||
const result = await skinSiteUpdateModInfo(payload)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.updated) })
|
||||
cancelEdit()
|
||||
await loadMods(false)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
savingMod.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMod(mod: SkinSiteModInfo) {
|
||||
if (deletingHash.value !== null) return
|
||||
if (!window.confirm(formatMessage(messages.confirmDelete, { name: mod.name }))) return
|
||||
deletingHash.value = mod.hash
|
||||
try {
|
||||
const result = await skinSiteDeleteModFile(mod.hash)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.deleted) })
|
||||
await loadMods(false)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
deletingHash.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSelect(hash: string) {
|
||||
const next = new Set(selectedHashes.value)
|
||||
if (next.has(hash)) next.delete(hash)
|
||||
else next.add(hash)
|
||||
selectedHashes.value = next
|
||||
}
|
||||
|
||||
function selectAllVisible() {
|
||||
selectedHashes.value = new Set(mods.value.map((m) => m.hash))
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedHashes.value = new Set()
|
||||
}
|
||||
|
||||
function exitSelectionMode() {
|
||||
selectionMode.value = false
|
||||
clearSelection()
|
||||
}
|
||||
|
||||
async function deleteSelected() {
|
||||
if (deletingMulti.value || !selectedHashes.value.size) return
|
||||
const count = selectedHashes.value.size
|
||||
if (!window.confirm(formatMessage(messages.confirmDeleteMulti, { count }))) return
|
||||
deletingMulti.value = true
|
||||
try {
|
||||
const result = await skinSiteDeleteMultiModFile(Array.from(selectedHashes.value))
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.deletedMulti) })
|
||||
clearSelection()
|
||||
selectionMode.value = false
|
||||
await loadMods(false)
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
deletingMulti.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function applyServerAddress() {
|
||||
serverAddressFilter.value = serverAddressInput.value.trim()
|
||||
void loadMods(true)
|
||||
}
|
||||
|
||||
function clearServerAddress() {
|
||||
serverAddressInput.value = ''
|
||||
serverAddressFilter.value = ''
|
||||
void loadMods(true)
|
||||
}
|
||||
|
||||
function openNewTag() {
|
||||
editingTagId.value = null
|
||||
tagForm.value = { name: '', rules: '' }
|
||||
tagEditorOpen.value = true
|
||||
}
|
||||
|
||||
function openEditTag(tag: SkinSiteModRuleTag) {
|
||||
editingTagId.value = tag.id
|
||||
tagForm.value = { name: tag.name, rules: tag.rules.join('\n') }
|
||||
tagEditorOpen.value = true
|
||||
}
|
||||
|
||||
function closeTagEditor() {
|
||||
tagEditorOpen.value = false
|
||||
tagForm.value = { name: '', rules: '' }
|
||||
editingTagId.value = null
|
||||
}
|
||||
|
||||
async function saveTag() {
|
||||
const name = tagForm.value.name.trim()
|
||||
if (!name || savingTag.value) return
|
||||
savingTag.value = true
|
||||
try {
|
||||
const rules = tagForm.value.rules
|
||||
.split('\n')
|
||||
.map((r) => r.trim())
|
||||
.filter(Boolean)
|
||||
const result =
|
||||
editingTagId.value === null
|
||||
? await skinSiteCreateModRuleTag(name, rules)
|
||||
: await skinSiteUpdateModRuleTag(editingTagId.value, name, rules)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({
|
||||
type: 'success',
|
||||
title: formatMessage(editingTagId.value === null ? messages.tagCreated : messages.tagUpdated),
|
||||
})
|
||||
closeTagEditor()
|
||||
await loadTags()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
savingTag.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeTag(tag: SkinSiteModRuleTag) {
|
||||
if (!window.confirm(formatMessage(messages.confirmDeleteTag, { name: tag.name }))) return
|
||||
try {
|
||||
const result = await skinSiteDeleteModRuleTag(tag.id)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.tagDeleted) })
|
||||
if (tagFilter.value === tag.id) tagFilter.value = null
|
||||
await loadTags()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
}
|
||||
}
|
||||
|
||||
function pickRuntimeFile() {
|
||||
runtimeFile.value?.click()
|
||||
}
|
||||
|
||||
async function onRuntimeFile(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
const version = runtimeVersion.value.trim()
|
||||
if (!file || !version || runtimeUploading.value) return
|
||||
runtimeUploading.value = true
|
||||
try {
|
||||
const result = await skinSiteUploadModRuntime(version, file)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.runtimeUploaded) })
|
||||
runtimeVersion.value = ''
|
||||
await loadRuntime()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
runtimeUploading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function activateRuntime(release: SkinSiteModRuntimeRelease) {
|
||||
if (activatingRuntimeId.value !== null) return
|
||||
activatingRuntimeId.value = release.id
|
||||
try {
|
||||
const result = await skinSiteActivateModRuntime(release.id)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
addNotification({ type: 'success', title: formatMessage(messages.activated) })
|
||||
await loadRuntime()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
activatingRuntimeId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRuntime(release: SkinSiteModRuntimeRelease) {
|
||||
if (deletingRuntimeId.value !== null) return
|
||||
deletingRuntimeId.value = release.id
|
||||
try {
|
||||
const result = await skinSiteDeleteModRuntime(release.id)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
await loadRuntime()
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
deletingRuntimeId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadTags()
|
||||
await loadMods(true)
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h2 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1 text-xs font-semibold"
|
||||
:class="tab === 'mods' ? 'bg-brand text-contrast' : 'bg-button-bg text-secondary'"
|
||||
@click="switchTab('mods')"
|
||||
>
|
||||
{{ formatMessage(messages.tabMods) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1 text-xs font-semibold"
|
||||
:class="tab === 'tags' ? 'bg-brand text-contrast' : 'bg-button-bg text-secondary'"
|
||||
@click="switchTab('tags')"
|
||||
>
|
||||
{{ formatMessage(messages.tabTags) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1 text-xs font-semibold"
|
||||
:class="tab === 'runtime' ? 'bg-brand text-contrast' : 'bg-button-bg text-secondary'"
|
||||
@click="switchTab('runtime')"
|
||||
>
|
||||
{{ formatMessage(messages.tabRuntime) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-if="tab === 'mods'">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
v-model="searchKeyword"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.search)"
|
||||
class="min-w-0 flex-1 rounded-full border border-solid border-surface-5 bg-bg px-3 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="loadMods(true)"
|
||||
/>
|
||||
<select
|
||||
v-model="tagFilter"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast"
|
||||
@change="loadMods(true)"
|
||||
>
|
||||
<option :value="null">{{ formatMessage(messages.filterAll) }}</option>
|
||||
<option v-for="tag in tags" :key="tag.id" :value="tag.id">{{ tag.name }}</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="uploadOpen = true"
|
||||
>
|
||||
{{ formatMessage(messages.upload) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="!selectionMode"
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="selectionMode = true"
|
||||
>
|
||||
{{ formatMessage(messages.selectMode) }}
|
||||
</button>
|
||||
<template v-else>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="selectAllVisible"
|
||||
>
|
||||
{{ formatMessage(messages.selectAll) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="!selectedHashes.size"
|
||||
@click="clearSelection"
|
||||
>
|
||||
{{ formatMessage(messages.clearSelection) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="!selectedHashes.size || deletingMulti"
|
||||
@click="deleteSelected"
|
||||
>
|
||||
{{ formatMessage(messages.deleteSelected) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="exitSelectionMode"
|
||||
>
|
||||
{{ formatMessage(messages.exitSelect) }}
|
||||
</button>
|
||||
</template>
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.total, { count: modTotal }) }}
|
||||
</span>
|
||||
<span v-if="selectionMode && selectedHashes.size" class="text-xs font-semibold text-contrast">
|
||||
{{ formatMessage(messages.selectedCount, { count: selectedHashes.size }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
v-model="serverAddressInput"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.serverAddressHint)"
|
||||
class="min-w-0 flex-1 rounded-full border border-solid border-surface-5 bg-bg px-3 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
@keyup.enter="applyServerAddress"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="applyServerAddress"
|
||||
>
|
||||
{{ formatMessage(messages.apply) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="!serverAddressFilter"
|
||||
@click="clearServerAddress"
|
||||
>
|
||||
{{ formatMessage(messages.clear) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="modLoading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p v-else-if="modFailed" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.failed) }}
|
||||
</p>
|
||||
<p v-else-if="!mods.length" class="m-0 rounded-xl bg-bg-raised p-4 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="mod in mods"
|
||||
:key="mod.hash"
|
||||
class="flex flex-col gap-2 rounded-xl bg-bg-raised p-3"
|
||||
:class="selectionMode && selectedHashes.has(mod.hash) ? 'ring-2 ring-brand' : ''"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
v-if="selectionMode"
|
||||
type="checkbox"
|
||||
class="size-3.5 shrink-0"
|
||||
:checked="selectedHashes.has(mod.hash)"
|
||||
@change="toggleSelect(mod.hash)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-semibold text-contrast">
|
||||
{{ mod.metadata.name || mod.name }}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-secondary">{{ formatSize(mod.size) }}</span>
|
||||
<span
|
||||
v-for="loader in mod.metadata.loaderType"
|
||||
:key="loader"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-0.5 text-[10px] font-semibold text-secondary"
|
||||
>
|
||||
{{ loader }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="truncate font-mono text-[10px] text-secondary">{{ mod.hash }}</span>
|
||||
|
||||
<div v-if="editingHash === mod.hash" class="grid grid-cols-1 gap-2 sm:grid-cols-3">
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.name) }}</span>
|
||||
<input
|
||||
v-model="editForm.name"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.modId) }}</span>
|
||||
<input
|
||||
v-model="editForm.modId"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.version) }}</span>
|
||||
<input
|
||||
v-model="editForm.version"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1 sm:col-span-3">
|
||||
<span class="text-xs text-secondary">{{ formatMessage(messages.domainRules) }}</span>
|
||||
<input
|
||||
v-model="editForm.domainRules"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<template v-if="editingHash === mod.hash">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="cancelEdit"
|
||||
>
|
||||
{{ formatMessage(messages.cancel) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="savingMod"
|
||||
@click="saveMod(mod)"
|
||||
>
|
||||
{{ formatMessage(messages.save) }}
|
||||
</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span
|
||||
v-for="rule in mod.domainRules"
|
||||
:key="rule"
|
||||
class="rounded bg-bg px-2 py-0.5 font-mono text-[10px] text-secondary"
|
||||
>
|
||||
{{ rule }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="startEdit(mod)"
|
||||
>
|
||||
{{ formatMessage(messages.edit) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="deletingHash !== null"
|
||||
@click="removeMod(mod)"
|
||||
>
|
||||
{{ formatMessage(messages.remove) }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-center gap-3 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="!hasPrev"
|
||||
@click="prevPage"
|
||||
>
|
||||
{{ formatMessage(messages.prev) }}
|
||||
</button>
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.page, { page: modPage }) }} / {{ modPageCount }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="!hasNext"
|
||||
@click="nextPage"
|
||||
>
|
||||
{{ formatMessage(messages.next) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="tab === 'tags'">
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="openNewTag"
|
||||
>
|
||||
{{ formatMessage(messages.newTag) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="tagsLoading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<div v-else-if="!tags.length" class="rounded-xl bg-bg-raised p-4 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</div>
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="tag in tags"
|
||||
:key="tag.id"
|
||||
class="flex flex-wrap items-center gap-2 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-sm font-semibold text-contrast">
|
||||
{{ tag.name }}
|
||||
</span>
|
||||
<span class="text-xs text-secondary">×{{ tag.rules.length }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="openEditTag(tag)"
|
||||
>
|
||||
{{ formatMessage(messages.edit) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="removeTag(tag)"
|
||||
>
|
||||
{{ formatMessage(messages.remove) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="tagEditorOpen"
|
||||
class="flex flex-col gap-2 rounded-xl border border-solid border-surface-5 bg-bg-raised p-4"
|
||||
>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.tagName) }}
|
||||
</span>
|
||||
<input
|
||||
v-model="tagForm.name"
|
||||
type="text"
|
||||
class="rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-1">
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.tagRules) }}
|
||||
</span>
|
||||
<textarea
|
||||
v-model="tagForm.rules"
|
||||
rows="5"
|
||||
:placeholder="formatMessage(messages.tagRulesHint)"
|
||||
class="w-full resize-y rounded-lg border border-solid border-surface-5 bg-bg px-3 py-2 font-mono text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
</label>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="closeTagEditor"
|
||||
>
|
||||
{{ formatMessage(messages.cancel) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast disabled:opacity-50"
|
||||
:disabled="savingTag || !tagForm.name.trim()"
|
||||
@click="saveTag"
|
||||
>
|
||||
{{ formatMessage(messages.save) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<input ref="runtimeFile" type="file" class="hidden" @change="onRuntimeFile" />
|
||||
<input
|
||||
v-model="runtimeVersion"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.runtimeVersion)"
|
||||
class="w-40 rounded-lg border border-solid border-surface-5 bg-bg px-3 py-1.5 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="runtimeUploading || !runtimeVersion.trim()"
|
||||
@click="pickRuntimeFile"
|
||||
>
|
||||
{{
|
||||
runtimeUploading
|
||||
? formatMessage(messages.uploading)
|
||||
: formatMessage(messages.uploadRuntime)
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="runtimeState && runtimeState.manifestUrl"
|
||||
class="flex flex-wrap items-center gap-2 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<span class="text-xs font-semibold text-contrast">
|
||||
{{ formatMessage(messages.manifestUrl) }}
|
||||
</span>
|
||||
<code class="min-w-0 flex-1 truncate text-xs text-secondary">
|
||||
{{ runtimeState.manifestUrl }}
|
||||
</code>
|
||||
</div>
|
||||
|
||||
<div v-if="runtimeLoading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p
|
||||
v-else-if="!runtimeState || !runtimeState.releases.length"
|
||||
class="m-0 rounded-xl bg-bg-raised p-4 text-sm text-secondary"
|
||||
>
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<div v-else class="flex flex-col gap-2">
|
||||
<div
|
||||
v-for="release in runtimeState.releases"
|
||||
:key="release.id"
|
||||
class="flex flex-wrap items-center gap-3 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<span class="truncate text-sm font-semibold text-contrast">
|
||||
{{ release.version }}
|
||||
<span class="text-xs font-normal text-secondary">#{{ release.id }}</span>
|
||||
</span>
|
||||
<span class="truncate text-xs text-secondary">
|
||||
{{ formatMessage(messages.uploader, { name: release.uploadedBy }) }} ·
|
||||
{{ formatDateTime(release.uploadedAt) }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="shrink-0 text-xs text-secondary">
|
||||
{{ formatSize(release.fileSize) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="release.active"
|
||||
class="shrink-0 rounded-full bg-green px-2 py-0.5 text-[10px] font-semibold text-contrast"
|
||||
>
|
||||
{{ formatMessage(messages.active) }}
|
||||
</span>
|
||||
<span
|
||||
class="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold"
|
||||
:class="release.available ? 'bg-button-bg text-secondary' : 'bg-orange text-contrast'"
|
||||
>
|
||||
{{
|
||||
release.available
|
||||
? formatMessage(messages.available)
|
||||
: formatMessage(messages.unavailable)
|
||||
}}
|
||||
</span>
|
||||
<button
|
||||
v-if="!release.active"
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-brand px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="activatingRuntimeId !== null"
|
||||
@click="activateRuntime(release)"
|
||||
>
|
||||
{{ formatMessage(messages.activate) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="deletingRuntimeId !== null || release.active"
|
||||
@click="removeRuntime(release)"
|
||||
>
|
||||
{{ formatMessage(messages.remove) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<ModUploadModal
|
||||
v-if="uploadOpen"
|
||||
:rule-tags="tags"
|
||||
@finished="uploadOpen = false"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,188 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
type SkinSiteMapServer,
|
||||
skinSiteMapServers,
|
||||
skinSiteSaveMapServers,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.admin.servers.title', defaultMessage: 'Map servers' },
|
||||
loading: { id: 'app.skin-site.admin.servers.loading', defaultMessage: 'Loading…' },
|
||||
failed: { id: 'app.skin-site.admin.servers.failed', defaultMessage: 'Could not load servers.' },
|
||||
empty: { id: 'app.skin-site.admin.servers.empty', defaultMessage: 'No map servers configured.' },
|
||||
serverName: { id: 'app.skin-site.admin.servers.server-name', defaultMessage: 'Server name' },
|
||||
internal: { id: 'app.skin-site.admin.servers.internal', defaultMessage: 'Internal' },
|
||||
maps: { id: 'app.skin-site.admin.servers.maps', defaultMessage: 'Maps' },
|
||||
mapName: { id: 'app.skin-site.admin.servers.map-name', defaultMessage: 'Map name' },
|
||||
mapUrl: { id: 'app.skin-site.admin.servers.map-url', defaultMessage: 'Map URL' },
|
||||
addMap: { id: 'app.skin-site.admin.servers.add-map', defaultMessage: 'Add map' },
|
||||
removeMap: { id: 'app.skin-site.admin.servers.remove-map', defaultMessage: 'Remove' },
|
||||
addServer: { id: 'app.skin-site.admin.servers.add-server', defaultMessage: 'Add server' },
|
||||
removeServer: {
|
||||
id: 'app.skin-site.admin.servers.remove-server',
|
||||
defaultMessage: 'Remove server',
|
||||
},
|
||||
save: { id: 'app.skin-site.admin.servers.save', defaultMessage: 'Save changes' },
|
||||
saving: { id: 'app.skin-site.admin.servers.saving', defaultMessage: 'Saving…' },
|
||||
saved: { id: 'app.skin-site.admin.servers.saved', defaultMessage: 'Map servers saved.' },
|
||||
})
|
||||
|
||||
const servers = ref<SkinSiteMapServer[]>([])
|
||||
const loading = ref(true)
|
||||
const failed = ref(false)
|
||||
const saving = ref(false)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
failed.value = false
|
||||
try {
|
||||
const result = await skinSiteMapServers()
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
servers.value = result.payload ?? []
|
||||
} catch (error) {
|
||||
failed.value = true
|
||||
handleError(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function addServer() {
|
||||
servers.value.push({ name: '', internal: false, maps: [{ name: '', url: '' }] })
|
||||
}
|
||||
|
||||
function removeServer(index: number) {
|
||||
servers.value.splice(index, 1)
|
||||
}
|
||||
|
||||
function addMap(server: SkinSiteMapServer) {
|
||||
server.maps.push({ name: '', url: '' })
|
||||
}
|
||||
|
||||
function removeMap(server: SkinSiteMapServer, index: number) {
|
||||
server.maps.splice(index, 1)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (saving.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const cleaned = servers.value.map((s) => ({
|
||||
name: s.name.trim(),
|
||||
internal: s.internal,
|
||||
maps: s.maps
|
||||
.filter((m) => m.name.trim() || m.url.trim())
|
||||
.map((m) => ({ name: m.name.trim(), url: m.url.trim() })),
|
||||
}))
|
||||
const result = await skinSiteSaveMapServers(cleaned)
|
||||
if (!result.success) throw new Error(result.errorMessage)
|
||||
servers.value = result.payload ?? cleaned
|
||||
addNotification({ type: 'success', title: formatMessage(messages.saved) })
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h2 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="addServer"
|
||||
>
|
||||
{{ formatMessage(messages.addServer) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto rounded-full bg-brand px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ saving ? formatMessage(messages.saving) : formatMessage(messages.save) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex items-center gap-2 text-sm text-secondary">
|
||||
<SpinnerIcon class="size-4 animate-spin" />
|
||||
{{ formatMessage(messages.loading) }}
|
||||
</div>
|
||||
<p v-else-if="failed" class="m-0 text-sm text-secondary">
|
||||
{{ formatMessage(messages.failed) }}
|
||||
</p>
|
||||
<p v-else-if="!servers.length" class="m-0 rounded-xl bg-bg-raised p-4 text-sm text-secondary">
|
||||
{{ formatMessage(messages.empty) }}
|
||||
</p>
|
||||
<div v-else class="flex flex-col gap-3">
|
||||
<div
|
||||
v-for="(server, si) in servers"
|
||||
:key="si"
|
||||
class="flex flex-col gap-2 rounded-xl bg-bg-raised p-3"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
v-model="server.name"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.serverName)"
|
||||
class="min-w-0 flex-1 rounded-lg border border-solid border-surface-5 bg-bg px-3 py-1.5 text-sm text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
<label class="flex shrink-0 items-center gap-1.5 text-xs text-contrast">
|
||||
<input v-model="server.internal" type="checkbox" />
|
||||
{{ formatMessage(messages.internal) }}
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-red px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110"
|
||||
@click="removeServer(si)"
|
||||
>
|
||||
{{ formatMessage(messages.removeServer) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<span class="text-xs font-semibold text-secondary">
|
||||
{{ formatMessage(messages.maps) }}
|
||||
</span>
|
||||
<div v-for="(map, mi) in server.maps" :key="mi" class="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
v-model="map.name"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.mapName)"
|
||||
class="w-40 rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
<input
|
||||
v-model="map.url"
|
||||
type="text"
|
||||
:placeholder="formatMessage(messages.mapUrl)"
|
||||
class="min-w-0 flex-1 rounded-lg border border-solid border-surface-5 bg-bg px-2 py-1 text-xs text-contrast outline-none focus:border-brand"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-full bg-button-bg px-2 py-1 text-[10px] font-semibold text-secondary hover:text-red"
|
||||
@click="removeMap(server, mi)"
|
||||
>
|
||||
{{ formatMessage(messages.removeMap) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="w-fit rounded-full bg-button-bg px-3 py-1 text-xs font-semibold text-secondary hover:brightness-110"
|
||||
@click="addMap(server)"
|
||||
>
|
||||
{{ formatMessage(messages.addMap) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,440 @@
|
||||
<script setup lang="ts">
|
||||
import { SpinnerIcon } from '@modrinth/assets'
|
||||
import { defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import {
|
||||
type SkinSiteModRuleTag,
|
||||
skinSiteModExistsByHash,
|
||||
skinSiteModExistsByName,
|
||||
skinSiteModHashFromFile,
|
||||
skinSiteUploadMod,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const { formatMessage } = useVIntl()
|
||||
const { handleError, addNotification } = injectNotificationManager()
|
||||
|
||||
defineProps<{ ruleTags: SkinSiteModRuleTag[] }>()
|
||||
const emit = defineEmits<{ (e: 'finished'): void }>()
|
||||
|
||||
const messages = defineMessages({
|
||||
title: { id: 'app.skin-site.admin.mods.upload-title', defaultMessage: 'Upload mods' },
|
||||
dropHint: {
|
||||
id: 'app.skin-site.admin.mods.upload-drop',
|
||||
defaultMessage: 'Drag .jar files here, or click to choose',
|
||||
},
|
||||
dropSub: {
|
||||
id: 'app.skin-site.admin.mods.upload-sub',
|
||||
defaultMessage: 'Multiple files supported, up to {size} MB each',
|
||||
},
|
||||
tagsLabel: {
|
||||
id: 'app.skin-site.admin.mods.upload-tags',
|
||||
defaultMessage: 'Attach rule tags',
|
||||
},
|
||||
queue: { id: 'app.skin-site.admin.mods.upload-queue', defaultMessage: 'Files' },
|
||||
statusPending: {
|
||||
id: 'app.skin-site.admin.mods.upload-pending',
|
||||
defaultMessage: 'Pending',
|
||||
},
|
||||
statusChecking: {
|
||||
id: 'app.skin-site.admin.mods.upload-checking',
|
||||
defaultMessage: 'Checking…',
|
||||
},
|
||||
statusUploading: {
|
||||
id: 'app.skin-site.admin.mods.upload-uploading',
|
||||
defaultMessage: 'Uploading…',
|
||||
},
|
||||
statusConflict: {
|
||||
id: 'app.skin-site.admin.mods.upload-conflict',
|
||||
defaultMessage: 'Name exists',
|
||||
},
|
||||
statusSuccess: {
|
||||
id: 'app.skin-site.admin.mods.upload-success',
|
||||
defaultMessage: 'Done',
|
||||
},
|
||||
statusError: {
|
||||
id: 'app.skin-site.admin.mods.upload-error',
|
||||
defaultMessage: 'Failed',
|
||||
},
|
||||
existsAlready: {
|
||||
id: 'app.skin-site.admin.mods.upload-exists',
|
||||
defaultMessage: 'This file already exists on the server.',
|
||||
},
|
||||
nameConflictTitle: {
|
||||
id: 'app.skin-site.admin.mods.upload-name-conflict',
|
||||
defaultMessage: 'A mod with the same file name already exists',
|
||||
},
|
||||
nameConflictHint: {
|
||||
id: 'app.skin-site.admin.mods.upload-name-conflict-hint',
|
||||
defaultMessage: 'Overwrite the existing mod, or skip this file.',
|
||||
},
|
||||
overwrite: { id: 'app.skin-site.admin.mods.upload-overwrite', defaultMessage: 'Overwrite' },
|
||||
skip: { id: 'app.skin-site.admin.mods.upload-skip', defaultMessage: 'Skip' },
|
||||
close: { id: 'app.skin-site.admin.mods.upload-close', defaultMessage: 'Close' },
|
||||
allDone: {
|
||||
id: 'app.skin-site.admin.mods.upload-all-done',
|
||||
defaultMessage: 'All files processed.',
|
||||
},
|
||||
tooLarge: {
|
||||
id: 'app.skin-site.admin.mods.upload-too-large',
|
||||
defaultMessage: 'File too large: {name}',
|
||||
},
|
||||
})
|
||||
|
||||
const MAX_MOD_SIZE_MB = 200
|
||||
const MAX_RETRIES = 3
|
||||
|
||||
type TaskStatus = 'pending' | 'checking' | 'uploading' | 'conflict' | 'success' | 'error'
|
||||
|
||||
interface Task {
|
||||
file: File
|
||||
status: TaskStatus
|
||||
message?: string
|
||||
attempts: number
|
||||
}
|
||||
|
||||
const queue = ref<Task[]>([])
|
||||
const selectedTagIds = ref<Set<number>>(new Set())
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const busy = ref(false)
|
||||
const conflictTask = ref<Task | null>(null)
|
||||
|
||||
const finishedCount = computed(
|
||||
() => queue.value.filter((t) => t.status === 'success' || t.status === 'error').length,
|
||||
)
|
||||
const allDone = computed(() => queue.value.length > 0 && finishedCount.value === queue.value.length)
|
||||
const hasWork = computed(() => queue.value.length > 0)
|
||||
|
||||
function toggleTag(id: number) {
|
||||
const next = new Set(selectedTagIds.value)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
selectedTagIds.value = next
|
||||
}
|
||||
|
||||
function pickFiles() {
|
||||
if (busy.value) return
|
||||
fileInput.value?.click()
|
||||
}
|
||||
|
||||
function onFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const files = Array.from(input.files ?? [])
|
||||
input.value = ''
|
||||
enqueue(files)
|
||||
}
|
||||
|
||||
function onDrop(event: DragEvent) {
|
||||
event.preventDefault()
|
||||
if (busy.value) return
|
||||
enqueue(Array.from(event.dataTransfer?.files ?? []))
|
||||
}
|
||||
|
||||
function enqueue(files: File[]) {
|
||||
const jars = files.filter((f) => f.name.toLowerCase().endsWith('.jar'))
|
||||
if (!jars.length) return
|
||||
const accepted: Task[] = []
|
||||
for (const file of jars) {
|
||||
if (file.size > MAX_MOD_SIZE_MB * 1024 * 1024) {
|
||||
addNotification({
|
||||
type: 'error',
|
||||
title: formatMessage(messages.tooLarge, { name: file.name }),
|
||||
})
|
||||
continue
|
||||
}
|
||||
accepted.push({ file, status: 'pending', attempts: 0 })
|
||||
}
|
||||
if (!accepted.length) return
|
||||
queue.value = [...queue.value, ...accepted]
|
||||
void runQueue()
|
||||
}
|
||||
|
||||
async function runQueue() {
|
||||
if (busy.value) return
|
||||
busy.value = true
|
||||
try {
|
||||
for (;;) {
|
||||
const task = queue.value.find((t) => t.status === 'pending')
|
||||
if (!task) break
|
||||
await processTask(task)
|
||||
if (task.status === 'conflict') break
|
||||
}
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
if (allDone.value) {
|
||||
addNotification({ type: 'success', title: formatMessage(messages.allDone) })
|
||||
emit('finished')
|
||||
}
|
||||
}
|
||||
|
||||
async function processTask(task: Task) {
|
||||
task.status = 'checking'
|
||||
task.message = undefined
|
||||
try {
|
||||
const hash = await skinSiteModHashFromFile(task.file)
|
||||
const exists = await skinSiteModExistsByHash(hash)
|
||||
if (exists.success) {
|
||||
task.status = 'error'
|
||||
task.message = formatMessage(messages.existsAlready)
|
||||
return
|
||||
}
|
||||
const nameExists = await skinSiteModExistsByName(task.file.name)
|
||||
if (nameExists.success) {
|
||||
task.status = 'conflict'
|
||||
conflictTask.value = task
|
||||
return
|
||||
}
|
||||
await upload(task, false)
|
||||
} catch (error) {
|
||||
task.status = 'error'
|
||||
task.message = error instanceof Error ? error.message : String(error)
|
||||
handleError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function upload(task: Task, overwrite: boolean) {
|
||||
task.status = 'uploading'
|
||||
try {
|
||||
const res = await skinSiteUploadMod(task.file, Array.from(selectedTagIds.value), overwrite)
|
||||
if (res.success) {
|
||||
task.status = 'success'
|
||||
return
|
||||
}
|
||||
if (res.errorCode === 429) {
|
||||
task.attempts++
|
||||
if (task.attempts < MAX_RETRIES) {
|
||||
task.status = 'pending'
|
||||
task.message = 'rate limited, retrying'
|
||||
setTimeout(() => void runQueue(), 1500 * task.attempts)
|
||||
} else {
|
||||
task.status = 'error'
|
||||
task.message = res.errorMessage
|
||||
}
|
||||
return
|
||||
}
|
||||
if (res.errorType === 'HashDiff') {
|
||||
task.attempts++
|
||||
if (task.attempts < MAX_RETRIES) {
|
||||
task.status = 'pending'
|
||||
task.message = 'hash mismatch, retrying'
|
||||
setTimeout(() => void runQueue(), 800)
|
||||
} else {
|
||||
task.status = 'error'
|
||||
task.message = res.errorMessage
|
||||
}
|
||||
return
|
||||
}
|
||||
if (res.errorType === 'ModNameConflict') {
|
||||
task.status = 'conflict'
|
||||
conflictTask.value = task
|
||||
return
|
||||
}
|
||||
task.status = 'error'
|
||||
task.message = res.errorMessage
|
||||
} catch (error) {
|
||||
task.status = 'error'
|
||||
task.message = error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveConflict(overwrite: boolean) {
|
||||
const task = conflictTask.value
|
||||
conflictTask.value = null
|
||||
if (!task) return
|
||||
if (overwrite) {
|
||||
busy.value = true
|
||||
try {
|
||||
await upload(task, true)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
} else {
|
||||
task.status = 'error'
|
||||
task.message = formatMessage(messages.skip)
|
||||
}
|
||||
void runQueue()
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (busy.value) return
|
||||
queue.value = []
|
||||
conflictTask.value = null
|
||||
emit('finished')
|
||||
}
|
||||
|
||||
function statusLabel(status: TaskStatus): string {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return formatMessage(messages.statusPending)
|
||||
case 'checking':
|
||||
return formatMessage(messages.statusChecking)
|
||||
case 'uploading':
|
||||
return formatMessage(messages.statusUploading)
|
||||
case 'conflict':
|
||||
return formatMessage(messages.statusConflict)
|
||||
case 'success':
|
||||
return formatMessage(messages.statusSuccess)
|
||||
default:
|
||||
return formatMessage(messages.statusError)
|
||||
}
|
||||
}
|
||||
|
||||
function statusClass(status: TaskStatus): string {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return 'bg-green text-contrast'
|
||||
case 'error':
|
||||
return 'bg-red text-contrast'
|
||||
case 'conflict':
|
||||
return 'bg-yellow text-contrast'
|
||||
default:
|
||||
return 'bg-button-bg text-secondary'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" @click.self="close">
|
||||
<div class="flex max-h-[88vh] w-full max-w-2xl flex-col gap-4 overflow-y-auto rounded-xl bg-bg p-6">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<h3 class="m-0 text-lg font-bold text-contrast">{{ formatMessage(messages.title) }}</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-lg bg-button-bg px-3 py-1 text-xs font-semibold text-contrast hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
@click="close"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex min-h-40 cursor-pointer flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-surface-5 p-6 text-center transition-colors hover:bg-bg-raised"
|
||||
:class="busy ? 'cursor-not-allowed opacity-60' : ''"
|
||||
@dragover.prevent
|
||||
@dragenter.prevent
|
||||
@drop.prevent="onDrop"
|
||||
@click="pickFiles"
|
||||
>
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
class="hidden"
|
||||
multiple
|
||||
accept=".jar"
|
||||
@change="onFileChange"
|
||||
/>
|
||||
<span class="text-sm font-semibold text-contrast">
|
||||
{{ formatMessage(messages.dropHint) }}
|
||||
</span>
|
||||
<span class="text-xs text-secondary">
|
||||
{{ formatMessage(messages.dropSub, { size: MAX_MOD_SIZE_MB }) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="ruleTags.length" class="flex flex-col gap-2">
|
||||
<span class="text-xs font-semibold text-secondary">
|
||||
{{ formatMessage(messages.tagsLabel) }}
|
||||
</span>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="tag in ruleTags"
|
||||
:key="tag.id"
|
||||
type="button"
|
||||
class="rounded-full px-3 py-1 text-xs font-semibold transition-colors"
|
||||
:class="
|
||||
selectedTagIds.has(tag.id)
|
||||
? 'bg-brand text-contrast'
|
||||
: 'bg-button-bg text-secondary hover:text-contrast'
|
||||
"
|
||||
@click="toggleTag(tag.id)"
|
||||
>
|
||||
{{ tag.name }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasWork" class="flex flex-col gap-2">
|
||||
<span class="text-xs font-semibold text-secondary">
|
||||
{{ formatMessage(messages.queue) }} ({{ finishedCount }}/{{ queue.length }})
|
||||
</span>
|
||||
<div class="flex max-h-64 flex-col gap-1.5 overflow-y-auto">
|
||||
<div
|
||||
v-for="(task, index) in queue"
|
||||
:key="task.file.name + index"
|
||||
class="flex flex-wrap items-center gap-2 rounded-lg bg-bg-raised px-3 py-2"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-xs text-contrast">
|
||||
{{ task.file.name }}
|
||||
</span>
|
||||
<span class="shrink-0 text-[10px] text-secondary">
|
||||
{{ (task.file.size / 1024 / 1024).toFixed(2) }} MB
|
||||
</span>
|
||||
<span
|
||||
class="shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold"
|
||||
:class="statusClass(task.status)"
|
||||
>
|
||||
{{ statusLabel(task.status) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="task.message"
|
||||
class="w-full truncate text-[10px] text-secondary"
|
||||
:title="task.message"
|
||||
>
|
||||
{{ task.message }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="busy"
|
||||
class="flex items-center gap-2 text-xs text-secondary"
|
||||
>
|
||||
<SpinnerIcon class="size-3.5 animate-spin" />
|
||||
{{ formatMessage(messages.statusUploading) }}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 border-t border-solid border-surface-5 pt-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-button-bg px-4 py-2 text-sm font-semibold text-secondary hover:brightness-110 disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
@click="close"
|
||||
>
|
||||
{{ formatMessage(messages.close) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="conflictTask"
|
||||
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4"
|
||||
>
|
||||
<div class="flex w-full max-w-md flex-col gap-3 rounded-xl bg-bg p-6">
|
||||
<h4 class="m-0 text-base font-bold text-contrast">
|
||||
{{ formatMessage(messages.nameConflictTitle) }}
|
||||
</h4>
|
||||
<p class="m-0 text-xs break-all text-secondary">{{ conflictTask.file.name }}</p>
|
||||
<p class="m-0 text-xs text-secondary">{{ formatMessage(messages.nameConflictHint) }}</p>
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-button-bg px-4 py-2 text-sm font-semibold text-secondary hover:brightness-110"
|
||||
@click="resolveConflict(false)"
|
||||
>
|
||||
{{ formatMessage(messages.skip) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-contrast hover:brightness-110"
|
||||
@click="resolveConflict(true)"
|
||||
>
|
||||
{{ formatMessage(messages.overwrite) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,30 @@
|
||||
import { skinSiteChatRoomAvatarFetch } from '@/helpers/skin-site-api'
|
||||
|
||||
const avatarUrls = new Map<number, string>()
|
||||
const pending = new Map<number, Promise<string | null>>()
|
||||
|
||||
export function loadCachedRoomAvatar(
|
||||
roomId: number,
|
||||
attachmentId: number,
|
||||
): Promise<string | null> {
|
||||
const cached = avatarUrls.get(attachmentId)
|
||||
if (cached) return Promise.resolve(cached)
|
||||
const running = pending.get(attachmentId)
|
||||
if (running) return running
|
||||
|
||||
const request = skinSiteChatRoomAvatarFetch(roomId).then((blob) => {
|
||||
pending.delete(attachmentId)
|
||||
if (!blob) return null
|
||||
const url = URL.createObjectURL(blob)
|
||||
avatarUrls.set(attachmentId, url)
|
||||
return url
|
||||
})
|
||||
pending.set(attachmentId, request)
|
||||
return request
|
||||
}
|
||||
|
||||
export function forgetRoomAvatar(attachmentId: number) {
|
||||
const url = avatarUrls.get(attachmentId)
|
||||
if (url) URL.revokeObjectURL(url)
|
||||
avatarUrls.delete(attachmentId)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
type SkinSiteWikiAttachmentInfo,
|
||||
skinSiteWikiAttachment,
|
||||
skinSiteWikiAttachmentUrl,
|
||||
} from '@/helpers/skin-site-api'
|
||||
|
||||
const props = defineProps<{ name: string; caption?: string | null }>()
|
||||
|
||||
const attachment = ref<SkinSiteWikiAttachmentInfo | null>(null)
|
||||
const loading = ref(true)
|
||||
const viewerOpen = ref(false)
|
||||
|
||||
const contentUrl = computed(() =>
|
||||
attachment.value ? skinSiteWikiAttachmentUrl(attachment.value.id) : '#',
|
||||
)
|
||||
const imageCaption = computed(() => {
|
||||
const caption = props.caption?.trim() ?? ''
|
||||
return caption === props.name || caption === attachment.value?.name ? '' : caption
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const res = await skinSiteWikiAttachment(props.name)
|
||||
if (res.success) attachment.value = res.payload
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="loading"
|
||||
class="inline-flex min-h-20 min-w-32 items-center justify-center rounded-lg border border-solid border-surface-5"
|
||||
>
|
||||
<span class="text-xs text-secondary">…</span>
|
||||
</span>
|
||||
<figure v-else-if="attachment?.image" class="my-5 inline-block max-w-full">
|
||||
<button type="button" class="block max-w-full cursor-zoom-in rounded-lg" @click="viewerOpen = true">
|
||||
<img
|
||||
class="max-h-[70vh] max-w-full rounded-lg border border-solid border-surface-5 object-contain shadow-md"
|
||||
:src="contentUrl"
|
||||
:alt="caption || attachment.name"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
</button>
|
||||
<figcaption v-if="imageCaption" class="mt-2 text-center text-sm text-secondary">
|
||||
{{ imageCaption }}
|
||||
</figcaption>
|
||||
</figure>
|
||||
<a
|
||||
v-else-if="attachment"
|
||||
class="inline-flex items-center gap-1 text-brand underline-offset-2 hover:underline"
|
||||
:href="contentUrl"
|
||||
download
|
||||
>
|
||||
{{ caption || attachment.name }}
|
||||
</a>
|
||||
<span v-else class="text-red">附件“{{ name }}”不存在</span>
|
||||
|
||||
<div
|
||||
v-if="viewerOpen"
|
||||
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/80 p-4"
|
||||
@click.self="viewerOpen = false"
|
||||
>
|
||||
<img :src="contentUrl" :alt="caption || attachment?.name" class="max-h-[92vh] max-w-[92vw] object-contain" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
import { type SkinSiteWikiNode } from '@/helpers/skin-site-api'
|
||||
|
||||
import { safeExternalUrl, safeWikiColor } from './wiki-color'
|
||||
|
||||
defineOptions({ name: 'WikiNodeRenderer' })
|
||||
|
||||
defineProps<{ nodes: SkinSiteWikiNode[] }>()
|
||||
const emit = defineEmits<{ (e: 'navigate', title: string): void }>()
|
||||
|
||||
function headingTag(level?: number | null): string {
|
||||
return 'h' + Math.min(6, Math.max(1, level ?? 2))
|
||||
}
|
||||
|
||||
function navigate(title?: string | null) {
|
||||
emit('navigate', (title ?? '').replaceAll('_', ' '))
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-for="(node, index) in nodes" :key="node.type + '-' + index">
|
||||
<component
|
||||
:is="headingTag(node.level)"
|
||||
v-if="node.type === 'heading'"
|
||||
class="wiki-heading scroll-mt-24"
|
||||
:style="{ textAlign: node.align ?? undefined }"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</component>
|
||||
<p
|
||||
v-else-if="node.type === 'paragraph'"
|
||||
class="my-3 leading-7 break-words whitespace-pre-wrap"
|
||||
:style="{ textAlign: node.align ?? undefined }"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</p>
|
||||
<strong v-else-if="node.type === 'strong'" class="font-bold">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</strong>
|
||||
<small v-else-if="node.type === 'small'">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</small>
|
||||
<span
|
||||
v-else-if="node.type === 'color'"
|
||||
:style="{ color: safeWikiColor(node.color ?? '') ?? undefined }"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</span>
|
||||
<em v-else-if="node.type === 'emphasis'" class="italic">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</em>
|
||||
<u v-else-if="node.type === 'underline'">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</u>
|
||||
<s v-else-if="node.type === 'strike'">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</s>
|
||||
<mark v-else-if="node.type === 'highlight'" class="rounded bg-yellow/25 px-0.5 text-contrast">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</mark>
|
||||
<code v-else-if="node.type === 'inlineCode'" class="rounded bg-button-bg px-1 font-mono text-sm">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</code>
|
||||
<span
|
||||
v-else-if="node.type === 'spoiler'"
|
||||
class="cursor-help rounded bg-contrast text-contrast transition-colors hover:bg-transparent hover:text-inherit"
|
||||
:title="node.tooltip || '我知道你在偷看'"
|
||||
tabindex="0"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</span>
|
||||
<br v-else-if="node.type === 'break'" />
|
||||
<hr v-else-if="node.type === 'rule'" class="my-6 border-surface-5" />
|
||||
<button
|
||||
v-else-if="node.type === 'internalLink'"
|
||||
type="button"
|
||||
class="font-medium underline-offset-2 hover:underline"
|
||||
:class="node.exists === false ? 'text-red' : 'text-brand'"
|
||||
:title="node.exists === false ? '该词条尚未创建' : undefined"
|
||||
@click="navigate(node.title)"
|
||||
>
|
||||
<WikiNodeRenderer v-if="node.children.length" :nodes="node.children" @navigate="navigate" />
|
||||
<template v-else>{{ node.text }}</template>
|
||||
</button>
|
||||
<a
|
||||
v-else-if="node.type === 'externalLink'"
|
||||
class="text-brand underline-offset-2 hover:underline"
|
||||
:href="safeExternalUrl(node.href)"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
>
|
||||
<WikiNodeRenderer v-if="node.children.length" :nodes="node.children" @navigate="navigate" />
|
||||
<template v-else>{{ node.text }}</template>
|
||||
</a>
|
||||
<ul v-else-if="node.type === 'unorderedList'" class="my-3 list-disc pl-7">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</ul>
|
||||
<ol
|
||||
v-else-if="node.type === 'orderedList'"
|
||||
:start="node.start ?? undefined"
|
||||
class="my-3 list-decimal pl-7"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</ol>
|
||||
<li v-else-if="node.type === 'listItem'" class="my-1">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</li>
|
||||
<blockquote
|
||||
v-else-if="node.type === 'quote'"
|
||||
class="my-4 border-l-4 border-brand/60 bg-brand/5 px-4 py-2"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</blockquote>
|
||||
<pre
|
||||
v-else-if="node.type === 'code'"
|
||||
class="my-4 overflow-x-auto rounded-lg border border-solid border-surface-5 bg-bg-raised p-4 font-mono text-sm"
|
||||
><code>{{ node.text }}</code></pre>
|
||||
<div v-else-if="node.type === 'table'" class="my-5 overflow-x-auto">
|
||||
<table class="w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
<WikiNodeRenderer
|
||||
v-if="node.children.length"
|
||||
:nodes="node.children"
|
||||
@navigate="navigate"
|
||||
/>
|
||||
<tr v-for="(row, rowIndex) in node.rows" :key="rowIndex">
|
||||
<td v-for="(cell, cellIndex) in row" :key="cellIndex" class="border border-solid border-surface-5 px-2 py-1">
|
||||
<WikiNodeRenderer :nodes="cell" @navigate="navigate" />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<tr v-else-if="node.type === 'tableRow'">
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</tr>
|
||||
<component
|
||||
:is="node.type === 'tableHeader' ? 'th' : 'td'"
|
||||
v-else-if="node.type === 'tableCell' || node.type === 'tableHeader'"
|
||||
class="border border-solid border-surface-5 px-2 py-1"
|
||||
:colspan="node.colspan ?? 1"
|
||||
:rowspan="node.rowspan ?? 1"
|
||||
>
|
||||
<WikiNodeRenderer :nodes="node.children" @navigate="navigate" />
|
||||
</component>
|
||||
<WikiAttachmentNode
|
||||
v-else-if="node.type === 'attachment' && node.title"
|
||||
:name="node.title"
|
||||
:caption="node.text"
|
||||
/>
|
||||
<WikiNotice
|
||||
v-else-if="node.type === 'notice' && node.title"
|
||||
:title="node.title"
|
||||
:description="node.text"
|
||||
:variant="node.variant"
|
||||
>
|
||||
<WikiNodeRenderer v-if="node.children.length" :nodes="node.children" @navigate="navigate" />
|
||||
<p v-else-if="node.text" class="whitespace-pre-wrap">{{ node.text }}</p>
|
||||
</WikiNotice>
|
||||
<span v-else>{{ node.text }}</span>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wiki-heading {
|
||||
margin-top: 1.65rem;
|
||||
margin-bottom: 0.7rem;
|
||||
border-bottom: 1px solid color-mix(in oklab, currentColor 16%, transparent);
|
||||
padding-bottom: 0.4rem;
|
||||
font-weight: 750;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
h1.wiki-heading {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
h2.wiki-heading {
|
||||
font-size: 1.55rem;
|
||||
}
|
||||
|
||||
h3.wiki-heading {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
title: string
|
||||
description?: string | null
|
||||
variant?: string | null
|
||||
}>()
|
||||
|
||||
const variantClass = computed(() => {
|
||||
switch (props.variant) {
|
||||
case 'warning':
|
||||
return 'border-yellow/40 bg-yellow/10 text-yellow'
|
||||
case 'error':
|
||||
return 'border-red/40 bg-red/10 text-red'
|
||||
case 'success':
|
||||
return 'border-green/40 bg-green/10 text-green'
|
||||
default:
|
||||
return 'border-brand/40 bg-brand/10 text-brand'
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="my-4 rounded-lg border border-solid p-4" :class="variantClass">
|
||||
<p class="m-0 text-sm font-bold">{{ title }}</p>
|
||||
<p v-if="description" class="m-0 mt-1 text-xs whitespace-pre-wrap opacity-90">
|
||||
{{ description }}
|
||||
</p>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
export function safeWikiColor(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null
|
||||
const color = value.trim()
|
||||
return color.length <= 80 &&
|
||||
/^(?:[a-z]{1,20}|#[\da-f]{3}|#[\da-f]{4}|#[\da-f]{6}|#[\da-f]{8}|rgba?\([\d\s.,%]+\))$/i.test(color)
|
||||
? color
|
||||
: null
|
||||
}
|
||||
|
||||
export function safeExternalUrl(url?: string | null): string {
|
||||
if (!url) return '#'
|
||||
try {
|
||||
const parsed = new URL(url)
|
||||
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.toString() : '#'
|
||||
} catch {
|
||||
return '#'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { registerHooks } from 'node:module'
|
||||
import test from 'node:test'
|
||||
|
||||
type FetchHandler = (url: string, options: RequestInit) => Promise<Response>
|
||||
const testGlobal = globalThis as unknown as { skinSiteTestFetch: FetchHandler }
|
||||
const hooks = registerHooks({
|
||||
resolve(specifier, context, nextResolve) {
|
||||
if (specifier === '@tauri-apps/plugin-http') {
|
||||
return {
|
||||
url: 'data:text/javascript,export const fetch=(...args)=>globalThis.skinSiteTestFetch(...args)',
|
||||
shortCircuit: true,
|
||||
}
|
||||
}
|
||||
if (specifier.startsWith('@/')) {
|
||||
return nextResolve(new URL(`../${specifier.slice(2)}.ts`, import.meta.url).href, context)
|
||||
}
|
||||
return nextResolve(specifier, context)
|
||||
},
|
||||
})
|
||||
const session = await import('./skin-site-session.ts')
|
||||
hooks.deregister()
|
||||
|
||||
const user = { uuid: 'owner', username: 'Player', permissions: [] }
|
||||
const ok = (payload: unknown) => Response.json({ payload })
|
||||
const storage = new Map<string, string>()
|
||||
const tokenKey = 'starlight-skin-site-token'
|
||||
let calls: Array<{ path: string; token: string | undefined }> = []
|
||||
let respond: FetchHandler
|
||||
|
||||
test.beforeEach(() => {
|
||||
storage.clear()
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
removeItem: (key: string) => storage.delete(key),
|
||||
},
|
||||
})
|
||||
calls = []
|
||||
respond = async (url) => {
|
||||
if (url.endsWith('/user/refresh')) return ok({ username: 'Player', jwt: 'fresh-token' })
|
||||
if (url.endsWith('/user')) return ok(user)
|
||||
return ok([])
|
||||
}
|
||||
testGlobal.skinSiteTestFetch = async (url, options) => {
|
||||
calls.push({
|
||||
path: new URL(url).pathname,
|
||||
token: (options.headers as Record<string, string>)?.Authorization,
|
||||
})
|
||||
return respond(url, options)
|
||||
}
|
||||
session.resetSkinSiteSession()
|
||||
})
|
||||
|
||||
test.afterEach(async () => {
|
||||
session.signOutSkinSite()
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
Reflect.deleteProperty(globalThis, 'localStorage')
|
||||
})
|
||||
|
||||
test('startup renews the stored JWT before loading the user with the new token', async () => {
|
||||
storage.set(tokenKey, 'old-token')
|
||||
await session.initSkinSiteSession()
|
||||
assert.deepEqual(calls.slice(0, 2), [
|
||||
{ path: '/starlight/user/refresh', token: 'Bearer old-token' },
|
||||
{ path: '/starlight/user', token: 'Bearer fresh-token' },
|
||||
])
|
||||
assert.equal(storage.get(tokenKey), 'fresh-token')
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-in')
|
||||
})
|
||||
|
||||
test('simultaneous startup consumers share one refresh', async () => {
|
||||
storage.set(tokenKey, 'old-token')
|
||||
await Promise.all([
|
||||
session.initSkinSiteSession(),
|
||||
session.initSkinSiteSession(),
|
||||
session.waitForSkinSiteSession(),
|
||||
])
|
||||
assert.equal(calls.filter((call) => call.path.endsWith('/refresh')).length, 1)
|
||||
})
|
||||
|
||||
test('startup without a stored token does not make authenticated requests', async () => {
|
||||
await session.initSkinSiteSession()
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-out')
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
|
||||
test('an expired token is cleared when renewal is rejected', async () => {
|
||||
storage.set(tokenKey, 'expired-token')
|
||||
respond = async () => Response.json({ errorMessage: 'Expired' }, { status: 401 })
|
||||
await session.initSkinSiteSession()
|
||||
assert.equal(storage.has(tokenKey), false)
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-out')
|
||||
assert.equal(calls.length, 1)
|
||||
})
|
||||
|
||||
test('temporary renewal failure preserves the token and allows startup retry', async () => {
|
||||
storage.set(tokenKey, 'old-token')
|
||||
respond = async () => Response.json({ errorMessage: 'Unavailable' }, { status: 503 })
|
||||
await session.initSkinSiteSession()
|
||||
assert.equal(session.skinSiteStatus.value, 'error')
|
||||
assert.equal(storage.get(tokenKey), 'old-token')
|
||||
respond = async (url) =>
|
||||
url.endsWith('/refresh')
|
||||
? ok({ jwt: 'fresh-token' })
|
||||
: url.endsWith('/user')
|
||||
? ok(user)
|
||||
: ok([])
|
||||
await session.initSkinSiteSession()
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-in')
|
||||
})
|
||||
|
||||
test('a late refresh cannot restore a session after sign-out', async () => {
|
||||
storage.set(tokenKey, 'old-token')
|
||||
let finish!: (response: Response) => void
|
||||
respond = () =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
const initializing = session.initSkinSiteSession()
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
session.signOutSkinSite()
|
||||
finish(ok({ username: 'Player', jwt: 'late-token' }))
|
||||
await initializing
|
||||
assert.equal(storage.has(tokenKey), false)
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-out')
|
||||
assert.equal(session.skinSiteUser.value, null)
|
||||
})
|
||||
|
||||
test('a malformed refresh response never replaces the saved token', async () => {
|
||||
storage.set(tokenKey, 'old-token')
|
||||
respond = async () => ok({ username: 'Player' })
|
||||
await session.initSkinSiteSession()
|
||||
assert.equal(storage.get(tokenKey), 'old-token')
|
||||
assert.equal(session.skinSiteStatus.value, 'error')
|
||||
})
|
||||
|
||||
test('a failed sign-in attempt does not invalidate a pending startup renewal', async () => {
|
||||
storage.set(tokenKey, 'old-token')
|
||||
let finish!: (response: Response) => void
|
||||
respond = async (url) => {
|
||||
if (url.endsWith('/refresh'))
|
||||
return new Promise((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
if (url.endsWith('/login'))
|
||||
return Response.json({ errorMessage: 'Invalid password' }, { status: 401 })
|
||||
return url.endsWith('/user') ? ok(user) : ok([])
|
||||
}
|
||||
const initializing = session.initSkinSiteSession()
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
await session.signInSkinSite({ username: 'Player', password: 'wrong', clientId: 'captcha' })
|
||||
finish(ok({ username: 'Player', jwt: 'fresh-token' }))
|
||||
await initializing
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-in')
|
||||
assert.equal(storage.get(tokenKey), 'fresh-token')
|
||||
})
|
||||
|
||||
test('rejection of an old startup token does not discard a new successful login', async () => {
|
||||
storage.set(tokenKey, 'expired-token')
|
||||
let finishRefresh!: (response: Response) => void
|
||||
let finishLogin!: (response: Response) => void
|
||||
respond = async (url) => {
|
||||
if (url.endsWith('/refresh'))
|
||||
return new Promise((resolve) => {
|
||||
finishRefresh = resolve
|
||||
})
|
||||
if (url.endsWith('/login'))
|
||||
return new Promise((resolve) => {
|
||||
finishLogin = resolve
|
||||
})
|
||||
return url.endsWith('/user') ? ok(user) : ok([])
|
||||
}
|
||||
const initializing = session.initSkinSiteSession()
|
||||
const signingIn = session.signInSkinSite({
|
||||
username: 'Player',
|
||||
password: 'valid',
|
||||
clientId: 'captcha',
|
||||
})
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
finishRefresh(Response.json({ errorMessage: 'Expired' }, { status: 401 }))
|
||||
await initializing
|
||||
finishLogin(ok({ username: 'Player', jwt: 'login-token' }))
|
||||
await signingIn
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-in')
|
||||
assert.equal(storage.get(tokenKey), 'login-token')
|
||||
})
|
||||
|
||||
test('explicit sign-out discards a late successful login', async () => {
|
||||
let finishLogin!: (response: Response) => void
|
||||
respond = () =>
|
||||
new Promise((resolve) => {
|
||||
finishLogin = resolve
|
||||
})
|
||||
const signingIn = session.signInSkinSite({
|
||||
username: 'Player',
|
||||
password: 'valid',
|
||||
clientId: 'captcha',
|
||||
})
|
||||
await new Promise((resolve) => setImmediate(resolve))
|
||||
session.signOutSkinSite()
|
||||
finishLogin(ok({ username: 'Player', jwt: 'late-login-token' }))
|
||||
await signingIn
|
||||
assert.equal(session.skinSiteStatus.value, 'signed-out')
|
||||
assert.equal(storage.has(tokenKey), false)
|
||||
})
|
||||
@@ -65,13 +65,54 @@ function clearSessionState() {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let initialized: Promise<void> | null = null
|
||||
let sessionRevision = 0
|
||||
let loginRevision = 0
|
||||
let refreshRequest: { token: string; revision: number; promise: Promise<boolean> } | null = null
|
||||
|
||||
/** Share renewals and discard results from a session that has since changed. */
|
||||
function renewSkinSiteToken(): Promise<boolean> {
|
||||
const token = getSkinSiteToken()
|
||||
if (!token) return Promise.resolve(false)
|
||||
const revision = sessionRevision
|
||||
if (refreshRequest?.token === token && refreshRequest.revision === revision) {
|
||||
return refreshRequest.promise
|
||||
}
|
||||
const request = {
|
||||
token,
|
||||
revision,
|
||||
promise: (async () => {
|
||||
let result: SkinSiteResponse<{ username: string; jwt: string }>
|
||||
try {
|
||||
result = await skinSiteRefresh()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (revision !== sessionRevision || getSkinSiteToken() !== token) return false
|
||||
if (result.success) {
|
||||
if (typeof result.payload?.jwt !== 'string' || !result.payload.jwt.trim()) return false
|
||||
setSkinSiteToken(result.payload.jwt)
|
||||
return true
|
||||
}
|
||||
if (result.errorCode === 401 || result.errorCode === 403) invalidateSkinSiteSession()
|
||||
return false
|
||||
})(),
|
||||
}
|
||||
refreshRequest = request
|
||||
const clearRequest = () => {
|
||||
if (refreshRequest === request) refreshRequest = null
|
||||
}
|
||||
void request.promise.then(clearRequest, clearRequest)
|
||||
return request.promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the current session from the stored JWT. Safe to call repeatedly;
|
||||
* Renew the saved JWT on each launcher startup before loading the user.
|
||||
* Safe to call repeatedly;
|
||||
* the first call performs the actual work and later ones reuse it.
|
||||
*/
|
||||
export function initSkinSiteSession(): Promise<void> {
|
||||
if (initialized) return initialized
|
||||
const revision = sessionRevision
|
||||
initialized = (async () => {
|
||||
const token = getSkinSiteToken()
|
||||
if (!token) {
|
||||
@@ -79,7 +120,13 @@ export function initSkinSiteSession(): Promise<void> {
|
||||
return
|
||||
}
|
||||
status.value = 'checking'
|
||||
if (!(await renewSkinSiteToken())) {
|
||||
if (revision === sessionRevision) status.value = 'error'
|
||||
return
|
||||
}
|
||||
if (revision !== sessionRevision) return
|
||||
const result = await skinSiteCurrentUser()
|
||||
if (revision !== sessionRevision) return
|
||||
if (result.success) {
|
||||
user.value = toUser(result.payload)
|
||||
status.value = 'signed-in'
|
||||
@@ -92,11 +139,18 @@ export function initSkinSiteSession(): Promise<void> {
|
||||
status.value = 'error'
|
||||
}
|
||||
})()
|
||||
.catch(() => {
|
||||
if (revision === sessionRevision) status.value = 'error'
|
||||
})
|
||||
.finally(() => {
|
||||
if (revision === sessionRevision && status.value === 'error') initialized = null
|
||||
})
|
||||
return initialized
|
||||
}
|
||||
|
||||
/** Force a re-check (e.g. after the user signs in from another view). */
|
||||
export function reloadSkinSiteSession(): Promise<void> {
|
||||
sessionRevision++
|
||||
initialized = null
|
||||
return initSkinSiteSession()
|
||||
}
|
||||
@@ -106,10 +160,14 @@ export async function signInSkinSite(payload: {
|
||||
password: string
|
||||
clientId: string
|
||||
}): Promise<SkinSiteResponse<{ username: string; jwt: string }>> {
|
||||
const attemptRevision = ++loginRevision
|
||||
const result = await skinSiteLogin(payload)
|
||||
if (result.success) {
|
||||
if (result.success && attemptRevision === loginRevision) {
|
||||
const revision = ++sessionRevision
|
||||
initialized = null
|
||||
setSkinSiteToken(result.payload.jwt)
|
||||
const current = await skinSiteCurrentUser()
|
||||
if (revision !== sessionRevision) return result
|
||||
if (current.success) {
|
||||
user.value = toUser(current.payload)
|
||||
status.value = 'signed-in'
|
||||
@@ -122,23 +180,25 @@ export async function signInSkinSite(payload: {
|
||||
return result
|
||||
}
|
||||
|
||||
export function signOutSkinSite() {
|
||||
/** Reject an old credential without cancelling a newer explicit login attempt. */
|
||||
function invalidateSkinSiteSession() {
|
||||
sessionRevision++
|
||||
refreshRequest = null
|
||||
clearSkinSiteToken()
|
||||
clearSessionState()
|
||||
status.value = 'signed-out'
|
||||
initialized = null
|
||||
}
|
||||
|
||||
export function signOutSkinSite() {
|
||||
loginRevision++
|
||||
invalidateSkinSiteSession()
|
||||
}
|
||||
|
||||
/** Refresh the JWT; returns true when a new token was stored. */
|
||||
export async function refreshSkinSiteSession(): Promise<boolean> {
|
||||
if (status.value !== 'signed-in') return false
|
||||
const result = await skinSiteRefresh()
|
||||
if (result.success) {
|
||||
setSkinSiteToken(result.payload.jwt)
|
||||
return true
|
||||
}
|
||||
if (result.errorCode === 401 || result.errorCode === 403) signOutSkinSite()
|
||||
return false
|
||||
return renewSkinSiteToken()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -157,6 +217,9 @@ export function receiveSkinSiteMessage(_event: MessageEvent, _frame: Window | nu
|
||||
export function openSkinSiteLogin() {}
|
||||
|
||||
export function resetSkinSiteSession() {
|
||||
loginRevision++
|
||||
sessionRevision++
|
||||
refreshRequest = null
|
||||
clearSessionState()
|
||||
status.value = getSkinSiteToken() ? 'checking' : 'signed-out'
|
||||
initialized = null
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
hostedDownloadActions,
|
||||
hostedDownloadState,
|
||||
runHostedDownloadAction,
|
||||
runHostedDownloadControl,
|
||||
} from './hosted-download-controls.ts'
|
||||
|
||||
test('only a controllable parent hosted task offers pause, resume and stop', () => {
|
||||
const bar = {
|
||||
bar_type: {
|
||||
type: 'hosted_pack_sync',
|
||||
instance_id: 'one',
|
||||
state: 'running' as const,
|
||||
can_pause: true,
|
||||
can_cancel: true,
|
||||
},
|
||||
}
|
||||
assert.deepEqual(hostedDownloadActions(bar), ['pause', 'cancel'])
|
||||
assert.deepEqual(hostedDownloadActions({ bar_type: { ...bar.bar_type, state: 'paused' } }), [
|
||||
'resume',
|
||||
'cancel',
|
||||
])
|
||||
for (const state of ['finalizing', 'canceling'] as const) {
|
||||
assert.deepEqual(hostedDownloadActions({ bar_type: { ...bar.bar_type, state } }), [])
|
||||
}
|
||||
assert.deepEqual(
|
||||
hostedDownloadActions({ bar_type: { ...bar.bar_type, type: 'hosted_mod_download' } }),
|
||||
[],
|
||||
)
|
||||
assert.deepEqual(
|
||||
hostedDownloadActions({ bar_type: { type: 'hosted_pack_sync', instance_id: 'one' } }),
|
||||
[],
|
||||
)
|
||||
})
|
||||
|
||||
test('failed and canceled hosted tasks offer direct retry, preserving terminal state', () => {
|
||||
for (const state of ['failed', 'canceled'] as const) {
|
||||
const bar = {
|
||||
bar_type: { type: 'hosted_pack_sync', instance_id: 'one', state, error: 'failure' },
|
||||
}
|
||||
assert.deepEqual(hostedDownloadActions(bar), ['retry'])
|
||||
assert.equal(hostedDownloadState(bar), state)
|
||||
}
|
||||
assert.equal(hostedDownloadState({ bar_type: { error: 'old backend failure' } }), 'failed')
|
||||
})
|
||||
|
||||
test('resume refreshes the session before invoking controls; pause and stop need no session', async () => {
|
||||
const calls: string[] = []
|
||||
const deps = {
|
||||
prepareSession: async () => {
|
||||
calls.push('session')
|
||||
},
|
||||
invoke: async (command: string, args: { instanceId: string }) => {
|
||||
calls.push(`${command}:${args.instanceId}`)
|
||||
},
|
||||
}
|
||||
await runHostedDownloadControl('resume', 'one', deps)
|
||||
await runHostedDownloadControl('pause', 'one', deps)
|
||||
await runHostedDownloadControl('cancel', 'one', deps)
|
||||
assert.deepEqual(calls, [
|
||||
'session',
|
||||
'plugin:install|hosted_resume:one',
|
||||
'plugin:install|hosted_pause:one',
|
||||
'plugin:install|hosted_cancel:one',
|
||||
])
|
||||
})
|
||||
|
||||
test('session refresh failures prevent resume', async () => {
|
||||
await assert.rejects(
|
||||
runHostedDownloadControl('resume', 'one', {
|
||||
prepareSession: async () => {
|
||||
throw new Error('signed out')
|
||||
},
|
||||
invoke: async () => {
|
||||
assert.fail('resume must not run')
|
||||
},
|
||||
}),
|
||||
/signed out/,
|
||||
)
|
||||
})
|
||||
|
||||
test('retry immediately restarts the existing hosted instance through the manager', async () => {
|
||||
const calls: string[] = []
|
||||
await runHostedDownloadAction('retry', 'existing-instance', {
|
||||
retryHosted: async (instanceId) => {
|
||||
calls.push(instanceId)
|
||||
},
|
||||
control: async () => {
|
||||
assert.fail('retry must use the full hosted transaction')
|
||||
},
|
||||
})
|
||||
assert.deepEqual(calls, ['existing-instance'])
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { LoadingBar } from './state.ts'
|
||||
|
||||
export type HostedDownloadControl = 'pause' | 'resume' | 'cancel'
|
||||
export type HostedDownloadAction = HostedDownloadControl | 'retry'
|
||||
|
||||
export function runHostedDownloadAction(
|
||||
action: HostedDownloadAction,
|
||||
instanceId: string,
|
||||
operations: {
|
||||
retryHosted: (instanceId: string) => Promise<void>
|
||||
control: (action: HostedDownloadControl, instanceId: string) => Promise<void>
|
||||
},
|
||||
) {
|
||||
return action === 'retry'
|
||||
? operations.retryHosted(instanceId)
|
||||
: operations.control(action, instanceId)
|
||||
}
|
||||
|
||||
export function hostedDownloadState(bar: LoadingBar) {
|
||||
return bar.bar_type?.state ?? (bar.bar_type?.error ? 'failed' : 'running')
|
||||
}
|
||||
|
||||
export function hostedDownloadActions(bar: LoadingBar): HostedDownloadAction[] {
|
||||
const type = bar.bar_type
|
||||
if (type?.type !== 'hosted_pack_sync' || !type.instance_id) return []
|
||||
const state = hostedDownloadState(bar)
|
||||
if (state === 'failed' || state === 'canceled') return ['retry']
|
||||
if (state !== 'running' && state !== 'paused') return []
|
||||
const actions: HostedDownloadAction[] = []
|
||||
if (type.can_pause) actions.push(state === 'paused' ? 'resume' : 'pause')
|
||||
if (type.can_cancel) actions.push('cancel')
|
||||
return actions
|
||||
}
|
||||
|
||||
export async function runHostedDownloadControl(
|
||||
action: HostedDownloadControl,
|
||||
instanceId: string,
|
||||
dependencies: {
|
||||
prepareSession: () => Promise<void>
|
||||
invoke: (command: string, args: { instanceId: string }) => Promise<void>
|
||||
},
|
||||
) {
|
||||
if (action === 'resume') await dependencies.prepareSession()
|
||||
await dependencies.invoke(`plugin:install|hosted_${action}`, { instanceId })
|
||||
}
|
||||
@@ -3,6 +3,27 @@ import test from 'node:test'
|
||||
|
||||
import { createHostedDownloadFailures } from './hosted-download-failures.ts'
|
||||
|
||||
test('stopped hosted downloads retain their state and instance for direct retry', () => {
|
||||
const state = createHostedDownloadFailures()
|
||||
state.update({
|
||||
fraction: null,
|
||||
loader_uuid: 'stopped',
|
||||
event: {
|
||||
type: 'hosted_pack_sync',
|
||||
instance_id: 'existing-instance',
|
||||
state: 'canceled',
|
||||
error: 'Stopped by user',
|
||||
can_pause: false,
|
||||
can_cancel: false,
|
||||
},
|
||||
})
|
||||
assert.equal(state.values()[0]?.bar_type?.state, 'canceled')
|
||||
assert.equal(state.values()[0]?.bar_type?.instance_id, 'existing-instance')
|
||||
state.begin('existing-instance', state.values())
|
||||
assert.equal(state.has('existing-instance'), false)
|
||||
assert.equal(state.isRetired('stopped'), true)
|
||||
})
|
||||
|
||||
test('retry clears only its own failure before progress arrives and ignores late old events', () => {
|
||||
const state = createHostedDownloadFailures()
|
||||
const failed = (instanceId: string, loader: string, error: string) => ({
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
skinSiteUser,
|
||||
waitForSkinSiteSession,
|
||||
} from '../composables/skin-site-session.ts'
|
||||
import { type HostedDownloadControl, runHostedDownloadControl } from './hosted-download-controls.ts'
|
||||
import { authenticateInstancePlayer } from './instance-player.ts'
|
||||
|
||||
export const HOSTED_ACCOUNT_REQUIRED_MESSAGE = '您需要登录正版或皮肤站账号后才能操作'
|
||||
@@ -146,6 +147,11 @@ export const hostedCreate = async (gameDirRoot?: string | null) => {
|
||||
}
|
||||
export const hostedBinding = (instanceId: string) =>
|
||||
invokeHosted<HostedBinding | null>('plugin:install|hosted_binding', { instanceId })
|
||||
export const controlHostedDownload = (action: HostedDownloadControl, instanceId: string) =>
|
||||
runHostedDownloadControl(action, instanceId, {
|
||||
prepareSession: prepareHostedSession,
|
||||
invoke: invokeHosted<void>,
|
||||
})
|
||||
export const hostedSync = async (instanceId: string) => {
|
||||
await requireHostedGameAccount()
|
||||
startHostedPackAttempt(instanceId)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,9 @@ export interface LoadingBarType {
|
||||
batch_id?: string
|
||||
file_name?: string
|
||||
error?: string | null
|
||||
state?: 'running' | 'paused' | 'canceling' | 'canceled' | 'failed' | 'finalizing'
|
||||
can_pause?: boolean
|
||||
can_cancel?: boolean
|
||||
type?: string
|
||||
version?: string
|
||||
instance_id?: string
|
||||
@@ -28,7 +31,12 @@ export interface LoadingBar {
|
||||
}
|
||||
|
||||
export type OpeningCommandEvent =
|
||||
'RunMRPack' | 'InstallServer' | 'InstallVersion' | 'InstallMod' | 'InstallModpack' | string
|
||||
| 'RunMRPack'
|
||||
| 'InstallServer'
|
||||
| 'InstallVersion'
|
||||
| 'InstallMod'
|
||||
| 'InstallModpack'
|
||||
| string
|
||||
|
||||
export interface OpeningCommand {
|
||||
event: OpeningCommandEvent
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -84,7 +84,7 @@
|
||||
</TagItem>
|
||||
<Badge
|
||||
:color="bar.bar_type?.error ? 'red' : 'orange'"
|
||||
:type="statusLabel(bar.bar_type?.error ? 'failed' : 'running')"
|
||||
:type="statusLabel(hostedDownloadState(bar))"
|
||||
/>
|
||||
</div>
|
||||
<ProgressBar
|
||||
@@ -94,16 +94,35 @@
|
||||
:progress="legacyPercent(bar)"
|
||||
:max="100"
|
||||
:label="formatMessage(messages.progress)"
|
||||
:waiting="!bar.total"
|
||||
:waiting="!bar.total && hostedDownloadState(bar) !== 'paused'"
|
||||
:show-progress="Boolean(bar.total)"
|
||||
/>
|
||||
<RouterLink
|
||||
v-else
|
||||
:to="hostedRetryRoute(bar.bar_type?.instance_id ?? '')"
|
||||
class="mt-3 inline-block text-brand hover:underline"
|
||||
<div
|
||||
v-if="hostedDownloadActions(bar).length"
|
||||
class="mt-3 flex flex-wrap items-center gap-2"
|
||||
>
|
||||
{{ formatMessage(messages.hostedRetry) }}
|
||||
</RouterLink>
|
||||
<ButtonStyled
|
||||
v-for="action in hostedDownloadActions(bar)"
|
||||
:key="action"
|
||||
:color="action === 'retry' ? 'brand' : action === 'cancel' ? 'red' : 'standard'"
|
||||
:type="action === 'retry' ? 'standard' : 'outlined'"
|
||||
size="small"
|
||||
>
|
||||
<button
|
||||
:disabled="busy.has(hostedBusyKey(bar, action))"
|
||||
@click="hostedAction(bar, action)"
|
||||
>
|
||||
{{ formatMessage(hostedActionMessages[action]) }}
|
||||
</button>
|
||||
</ButtonStyled>
|
||||
<RouterLink
|
||||
v-if="bar.bar_type?.error"
|
||||
:to="hostedRetryRoute(bar.bar_type.instance_id ?? '')"
|
||||
class="text-brand hover:underline"
|
||||
>
|
||||
{{ formatMessage(messages.openInstance) }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
@@ -471,7 +490,14 @@ import { useRoute, useRouter } from 'vue-router'
|
||||
import MissingModpackContentModal from '@/components/ui/modal/MissingModpackContentModal.vue'
|
||||
import { listPendingCurseForgeManualDownloads } from '@/helpers/curseforge'
|
||||
import type { CurseForgeManualDownloadItem } from '@/helpers/curseforge-manual'
|
||||
import {
|
||||
type HostedDownloadAction,
|
||||
hostedDownloadActions,
|
||||
hostedDownloadState,
|
||||
runHostedDownloadAction,
|
||||
} from '@/helpers/hosted-download-controls'
|
||||
import { hostedRetryRoute } from '@/helpers/hosted-install-retry'
|
||||
import { controlHostedDownload } from '@/helpers/hosted-packs'
|
||||
import {
|
||||
download_job_support_details,
|
||||
type InstallJobSnapshot,
|
||||
@@ -517,10 +543,6 @@ const focusedJobId = computed(() => focusedDownloadJobId(route.query.job))
|
||||
const focusState = ref(createDownloadFocusState(focusedJobId.value))
|
||||
|
||||
const messages = defineMessages({
|
||||
hostedRetry: {
|
||||
id: 'app.hosted-packs.progress.retry',
|
||||
defaultMessage: 'Return to the instance to retry',
|
||||
},
|
||||
newDownload: { id: 'app.downloads.new-download', defaultMessage: 'New download' },
|
||||
inProgress: { id: 'app.downloads.in-progress', defaultMessage: 'In progress' },
|
||||
history: { id: 'app.downloads.history', defaultMessage: 'History' },
|
||||
@@ -653,7 +675,15 @@ const messages = defineMessages({
|
||||
unknownPhase: { id: 'app.downloads.phase.unknown', defaultMessage: 'Working' },
|
||||
})
|
||||
|
||||
const hostedActionMessages = defineMessages({
|
||||
pause: { id: 'app.hosted-packs.progress.pause', defaultMessage: 'Pause' },
|
||||
resume: { id: 'app.hosted-packs.progress.resume', defaultMessage: 'Resume' },
|
||||
cancel: { id: 'app.hosted-packs.progress.stop', defaultMessage: 'Stop' },
|
||||
retry: { id: 'app.downloads.retry', defaultMessage: 'Retry' },
|
||||
})
|
||||
|
||||
const statusMessages = defineMessages({
|
||||
paused: { id: 'app.downloads.status.paused', defaultMessage: 'Paused' },
|
||||
queued: { id: 'app.downloads.status.queued', defaultMessage: 'Queued' },
|
||||
running: { id: 'app.downloads.status.running', defaultMessage: 'Running' },
|
||||
canceling: { id: 'app.downloads.status.canceling', defaultMessage: 'Canceling' },
|
||||
@@ -1262,6 +1292,7 @@ function toggleExpanded(jobId: string) {
|
||||
}
|
||||
|
||||
async function withBusy(jobId: string, action: () => Promise<void>) {
|
||||
if (busy.value.has(jobId)) return
|
||||
busy.value = new Set([...busy.value, jobId])
|
||||
try {
|
||||
await action()
|
||||
@@ -1278,6 +1309,21 @@ async function cancel(job: InstallJobSnapshot) {
|
||||
await withBusy(job.job_id, () => manager.cancel(job.job_id))
|
||||
}
|
||||
|
||||
function hostedBusyKey(bar: LoadingBar, action: HostedDownloadAction) {
|
||||
return `hosted-${action === 'retry' ? 'retry' : 'control'}:${bar.bar_type?.instance_id}`
|
||||
}
|
||||
|
||||
async function hostedAction(bar: LoadingBar, action: HostedDownloadAction) {
|
||||
const instanceId = bar.bar_type?.instance_id
|
||||
if (!instanceId || !hostedDownloadActions(bar).includes(action)) return
|
||||
await withBusy(hostedBusyKey(bar, action), () =>
|
||||
runHostedDownloadAction(action, instanceId, {
|
||||
retryHosted: manager.retryHosted,
|
||||
control: controlHostedDownload,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
async function retry(job: InstallJobSnapshot) {
|
||||
await withBusy(job.job_id, () => manager.retry(job.job_id))
|
||||
}
|
||||
@@ -1293,12 +1339,14 @@ async function resolveMissing(job: InstallJobSnapshot) {
|
||||
(item) =>
|
||||
item.status === 'skipped' && item.manual_url && item.project_id && item.version_id,
|
||||
)
|
||||
.map((item): CurseForgeManualDownloadItem => ({
|
||||
projectId: Number(item.project_id),
|
||||
fileId: Number(item.version_id),
|
||||
fileName: item.name,
|
||||
websiteUrl: item.manual_url ?? undefined,
|
||||
}))
|
||||
.map(
|
||||
(item): CurseForgeManualDownloadItem => ({
|
||||
projectId: Number(item.project_id),
|
||||
fileId: Number(item.version_id),
|
||||
fileName: item.name,
|
||||
websiteUrl: item.manual_url ?? undefined,
|
||||
}),
|
||||
)
|
||||
const instanceId = job.instance_id
|
||||
const hasGeneralMissingItems = job.items.some((item) => item.status === 'failed')
|
||||
if (instanceId && (job.provider === 'curse_forge' || fallbackCurseForgeItems.length > 0)) {
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "theseus_gui"
|
||||
# The actual version is set by the theseus-build workflow on tagging
|
||||
version = "1.0.2-beta7"
|
||||
version = "1.0.2-beta11"
|
||||
edition.workspace = true
|
||||
description = "Axolotl Launcher is a cross-platform Minecraft launcher"
|
||||
homepage = "https://www.ghs.red"
|
||||
|
||||
@@ -380,6 +380,9 @@ fn main() {
|
||||
"hosted_create",
|
||||
"hosted_binding",
|
||||
"hosted_sync",
|
||||
"hosted_pause",
|
||||
"hosted_resume",
|
||||
"hosted_cancel",
|
||||
"hosted_instance_mode",
|
||||
"hosted_set_instance_mode",
|
||||
"install_pack_to_existing_instance",
|
||||
|
||||
@@ -20,6 +20,9 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
|
||||
hosted_create,
|
||||
hosted_binding,
|
||||
hosted_sync,
|
||||
hosted_pause,
|
||||
hosted_resume,
|
||||
hosted_cancel,
|
||||
hosted_instance_mode,
|
||||
hosted_set_instance_mode,
|
||||
install_get_modpack_preview,
|
||||
@@ -105,6 +108,21 @@ pub async fn hosted_sync(
|
||||
Ok(theseus::pack::hosted::synchronize(&instance_id).await?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn hosted_pause(instance_id: String) -> Result<()> {
|
||||
Ok(theseus::pack::hosted::pause(&instance_id).await?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn hosted_resume(instance_id: String) -> Result<()> {
|
||||
Ok(theseus::pack::hosted::resume(&instance_id).await?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn hosted_cancel(instance_id: String) -> Result<()> {
|
||||
Ok(theseus::pack::hosted::cancel(&instance_id).await?)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallCreateInstanceRequest {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "theseus"
|
||||
# The actual version is set by the theseus-build workflow on tagging
|
||||
version = "1.0.2-beta7"
|
||||
version = "1.0.2-beta11"
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -5197,19 +5197,9 @@ fn modpack_zip_error(error: zip::result::ZipError) -> crate::Error {
|
||||
}
|
||||
|
||||
fn safe_archive_relative_path(value: &str) -> crate::Result<String> {
|
||||
let path = Path::new(value);
|
||||
if value.is_empty()
|
||||
|| path.is_absolute()
|
||||
|| path
|
||||
.components()
|
||||
.any(|component| !matches!(component, Component::Normal(_)))
|
||||
{
|
||||
return Err(ErrorKind::InputError(
|
||||
"CurseForge modpack contains an invalid override path".to_string(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(path.to_string_lossy().replace('\\', "/"))
|
||||
let normalized = value.replace('\\', "/");
|
||||
crate::util::io::safe_relative_join(Path::new(""), &normalized)?;
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
pub(crate) fn loader_family(loader_id: &str) -> &str {
|
||||
@@ -10933,6 +10923,21 @@ mod tests {
|
||||
);
|
||||
assert!(safe_archive_relative_path("../options.txt").is_err());
|
||||
assert!(safe_archive_relative_path("/options.txt").is_err());
|
||||
for path in [
|
||||
r"..\options.txt",
|
||||
"config/.. /outside",
|
||||
"config/file:stream",
|
||||
"C:/outside",
|
||||
"C:outside",
|
||||
"config/NUL",
|
||||
"config/file.",
|
||||
] {
|
||||
assert!(safe_archive_relative_path(path).is_err(), "{path}");
|
||||
}
|
||||
assert_eq!(
|
||||
safe_archive_relative_path(r"config\example.toml").unwrap(),
|
||||
"config/example.toml"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Shared helpers for extracting content from local modpack archives.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::detect::decode_zip_entry_name;
|
||||
use crate::util::io;
|
||||
@@ -13,22 +13,6 @@ fn archive_error(error: zip::result::ZipError) -> crate::Error {
|
||||
.into()
|
||||
}
|
||||
|
||||
pub(crate) fn safe_relative_path(value: &str) -> crate::Result<String> {
|
||||
let path = Path::new(value);
|
||||
if value.is_empty()
|
||||
|| path.is_absolute()
|
||||
|| path
|
||||
.components()
|
||||
.any(|component| !matches!(component, Component::Normal(_)))
|
||||
{
|
||||
return Err(crate::ErrorKind::InputError(
|
||||
"Modpack archive contains an invalid file path".to_string(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(path.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// Extracts every file under `prefix` in the archive into `target_dir`,
|
||||
/// preserving the directory structure below the prefix. Returns the number of
|
||||
/// files written.
|
||||
@@ -114,7 +98,8 @@ fn extract_archive_subdir_sync(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let target = target_dir.join(safe_relative_path(relative)?);
|
||||
let target =
|
||||
io::safe_relative_join(target_dir, &relative.replace('\\', "/"))?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|error| io::IOError::with_path(error, parent))?;
|
||||
@@ -252,6 +237,87 @@ pub(crate) async fn create_import_scratch_dir(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn unsafe_override_paths_fail_without_writing_outside_target() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let archive_path = root.path().join("pack.zip");
|
||||
let target_dir = root.path().join("server");
|
||||
std::fs::create_dir(&target_dir).unwrap();
|
||||
let outside = root.path().join("outside.txt");
|
||||
std::fs::write(&outside, b"unchanged").unwrap();
|
||||
for prefix in ["overrides/", "server/overrides/"] {
|
||||
for relative in [
|
||||
"../outside.txt",
|
||||
r"..\outside.txt",
|
||||
"config/../../outside.txt",
|
||||
"/outside.txt",
|
||||
"C:/outside.txt",
|
||||
"C:outside.txt",
|
||||
r"\\server\share\outside.txt",
|
||||
"config/.. /outside.txt",
|
||||
"config/mod.jar:payload",
|
||||
"config/NUL",
|
||||
"config/secret.",
|
||||
] {
|
||||
let mut archive = zip::ZipWriter::new(
|
||||
std::fs::File::create(&archive_path).unwrap(),
|
||||
);
|
||||
archive
|
||||
.start_file(
|
||||
format!("{prefix}{relative}"),
|
||||
zip::write::SimpleFileOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
archive.write_all(b"malicious").unwrap();
|
||||
archive.finish().unwrap();
|
||||
assert!(
|
||||
extract_archive_subdir_sync(
|
||||
&archive_path,
|
||||
prefix,
|
||||
&target_dir,
|
||||
None,
|
||||
)
|
||||
.is_err(),
|
||||
"{prefix}{relative}"
|
||||
);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"unchanged");
|
||||
assert_eq!(std::fs::read_dir(&target_dir).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_paths_with_backslashes_are_normalized() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let archive_path = root.path().join("pack.zip");
|
||||
let target_dir = root.path().join("server");
|
||||
let mut archive =
|
||||
zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap());
|
||||
archive
|
||||
.start_file(
|
||||
r"overrides/config\example.toml",
|
||||
zip::write::SimpleFileOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
archive.write_all(b"valid").unwrap();
|
||||
archive.finish().unwrap();
|
||||
assert_eq!(
|
||||
extract_archive_subdir_sync(
|
||||
&archive_path,
|
||||
"overrides/",
|
||||
&target_dir,
|
||||
None,
|
||||
)
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(target_dir.join("config/example.toml")).unwrap(),
|
||||
b"valid"
|
||||
);
|
||||
}
|
||||
|
||||
struct CancelOnRead {
|
||||
cancellation: CancellationToken,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Administrator-approved skin-site packs. Only content-addressed changed files cross the network.
|
||||
mod control;
|
||||
mod progress;
|
||||
pub use control::{HostedTaskState, cancel, pause, resume};
|
||||
mod tagged;
|
||||
mod transport;
|
||||
use crate::{
|
||||
@@ -938,10 +940,20 @@ async fn synchronize_locked(instance_id: &str) -> crate::Result<SyncResult> {
|
||||
let metadata = crate::instance::get(instance_id)
|
||||
.await?
|
||||
.ok_or_else(|| invalid("Unknown instance"))?;
|
||||
let task = control::Registration::new(instance_id)?;
|
||||
let progress =
|
||||
PackProgress::new(instance_id, &metadata.instance.name).await?;
|
||||
let result =
|
||||
synchronize_with_progress(instance_id, metadata, &progress).await;
|
||||
let result = task
|
||||
.control
|
||||
.run(|| {
|
||||
synchronize_with_progress(
|
||||
instance_id,
|
||||
metadata.clone(),
|
||||
&progress,
|
||||
&task.control,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = &result {
|
||||
progress.fail(error);
|
||||
}
|
||||
@@ -952,6 +964,7 @@ async fn synchronize_with_progress(
|
||||
instance_id: &str,
|
||||
metadata: crate::state::InstanceMetadata,
|
||||
progress: &PackProgress,
|
||||
control: &control::Control,
|
||||
) -> crate::Result<SyncResult> {
|
||||
if metadata.instance.linked_launcher.is_some()
|
||||
|| metadata.instance.symlink_target.is_some()
|
||||
@@ -1275,7 +1288,7 @@ async fn synchronize_with_progress(
|
||||
&format!("文件 0/{total_files}"),
|
||||
true,
|
||||
);
|
||||
let results = stream::iter(pending_downloads.into_values().map(
|
||||
downloaded += control::collect_downloads(stream::iter(pending_downloads.into_values().map(
|
||||
|(file, url, object)| {
|
||||
let current = ¤t;
|
||||
let completed = &completed;
|
||||
@@ -1342,34 +1355,14 @@ async fn synchronize_with_progress(
|
||||
request = request
|
||||
.with_header("Authorization", auth.clone());
|
||||
}
|
||||
let first_result = download_to_path(
|
||||
download_to_path(
|
||||
request.clone(),
|
||||
&object,
|
||||
&state.fetch_semaphore,
|
||||
&state.pool,
|
||||
Some(&mut on_progress),
|
||||
)
|
||||
.await;
|
||||
if let Err(error) = first_result {
|
||||
tracing::warn!(
|
||||
path = %file_path,
|
||||
%error,
|
||||
"Parallel StarLight file download failed; retrying after the batch load has eased"
|
||||
);
|
||||
ensure_session(auth).await?;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(
|
||||
750,
|
||||
))
|
||||
.await;
|
||||
download_to_path(
|
||||
request,
|
||||
&object,
|
||||
&state.fetch_semaphore,
|
||||
&state.pool,
|
||||
Some(&mut on_progress),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
.await.map_err(|error| error.with_context(format!("下载整合包文件失败:{file_path}")))?;
|
||||
let completed_files =
|
||||
completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let completed_bytes = {
|
||||
@@ -1391,12 +1384,7 @@ async fn synchronize_with_progress(
|
||||
}
|
||||
},
|
||||
))
|
||||
.buffer_unordered(concurrency)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
downloaded += results.into_iter().try_fold(0, |sum, result| {
|
||||
Ok::<u64, crate::Error>(sum + result?)
|
||||
})?;
|
||||
.buffer_unordered(concurrency)).await?;
|
||||
}
|
||||
ensure_session(&auth).await?;
|
||||
downloaded += tagged::download(
|
||||
@@ -1446,6 +1434,8 @@ async fn synchronize_with_progress(
|
||||
previous,
|
||||
metadata,
|
||||
};
|
||||
// From this atomic boundary onward the rollback/runtime transaction must finish.
|
||||
control.begin_finalizing()?;
|
||||
write_json(&root, JOURNAL, &journal)?;
|
||||
let result = async {
|
||||
progress.update(0, 0, "正在安装游戏组件", true);
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
use futures::{Stream, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
future::Future,
|
||||
sync::{Arc, LazyLock, Mutex},
|
||||
};
|
||||
use tokio::sync::watch;
|
||||
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, Deserialize, Serialize, Hash, PartialEq, Eq,
|
||||
)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HostedTaskState {
|
||||
#[default]
|
||||
Running,
|
||||
Paused,
|
||||
Canceling,
|
||||
Canceled,
|
||||
Failed,
|
||||
Finalizing,
|
||||
}
|
||||
|
||||
static CONTROLS: LazyLock<dashmap::DashMap<String, Arc<Control>>> =
|
||||
LazyLock::new(dashmap::DashMap::new);
|
||||
|
||||
pub(super) struct Control {
|
||||
instance_id: String,
|
||||
state: Mutex<HostedTaskState>,
|
||||
changes: watch::Sender<HostedTaskState>,
|
||||
}
|
||||
|
||||
fn stopped() -> crate::Error {
|
||||
super::invalid("已停止整合包下载;已下载的缓存会保留,可重试继续")
|
||||
}
|
||||
|
||||
impl Control {
|
||||
fn new(instance_id: &str) -> Self {
|
||||
Self {
|
||||
instance_id: instance_id.to_owned(),
|
||||
state: Mutex::new(HostedTaskState::Running),
|
||||
changes: watch::channel(HostedTaskState::Running).0,
|
||||
}
|
||||
}
|
||||
|
||||
fn state(&self) -> HostedTaskState {
|
||||
*self.state.lock().unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
|
||||
fn transition(
|
||||
&self,
|
||||
allowed: &[HostedTaskState],
|
||||
next: HostedTaskState,
|
||||
) -> crate::Result<()> {
|
||||
let mut state =
|
||||
self.state.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if !allowed.contains(&state) {
|
||||
return Err(super::invalid(
|
||||
"任务状态已变化或正在应用安装文件,当前操作不可用",
|
||||
));
|
||||
}
|
||||
*state = next;
|
||||
// Publish under the transition lock, so a late pause cannot overwrite finalization.
|
||||
crate::event::emit::set_hosted_loading_state(&self.instance_id, next);
|
||||
self.changes.send_replace(next);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pause(&self) -> crate::Result<()> {
|
||||
self.transition(&[HostedTaskState::Running], HostedTaskState::Paused)
|
||||
}
|
||||
|
||||
fn resume(&self) -> crate::Result<()> {
|
||||
self.transition(&[HostedTaskState::Paused], HostedTaskState::Running)
|
||||
}
|
||||
|
||||
fn cancel(&self) -> crate::Result<()> {
|
||||
self.transition(
|
||||
&[HostedTaskState::Running, HostedTaskState::Paused],
|
||||
HostedTaskState::Canceling,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn begin_finalizing(&self) -> crate::Result<()> {
|
||||
self.transition(
|
||||
&[HostedTaskState::Running],
|
||||
HostedTaskState::Finalizing,
|
||||
)
|
||||
}
|
||||
|
||||
/// The operation may be dropped only before begin_finalizing. Restarting
|
||||
/// re-plans from verified cache objects and the downloader's partial files.
|
||||
pub(super) async fn run<T, F, Fut>(
|
||||
&self,
|
||||
mut operation: F,
|
||||
) -> crate::Result<T>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: Future<Output = crate::Result<T>>,
|
||||
{
|
||||
let mut changes = self.changes.subscribe();
|
||||
loop {
|
||||
let state = *changes.borrow_and_update();
|
||||
match state {
|
||||
HostedTaskState::Paused => {
|
||||
changes.changed().await.map_err(|_| stopped())?;
|
||||
continue;
|
||||
}
|
||||
HostedTaskState::Canceling => return Err(stopped()),
|
||||
_ => {}
|
||||
}
|
||||
let work = operation();
|
||||
tokio::pin!(work);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
changed = changes.changed() => {
|
||||
changed.map_err(|_| stopped())?;
|
||||
match self.state() {
|
||||
HostedTaskState::Paused => break,
|
||||
HostedTaskState::Canceling => return Err(stopped()),
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
result = &mut work => {
|
||||
match self.state() {
|
||||
HostedTaskState::Paused => break,
|
||||
HostedTaskState::Canceling => return Err(stopped()),
|
||||
_ => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Registration {
|
||||
instance_id: String,
|
||||
pub(super) control: Arc<Control>,
|
||||
}
|
||||
|
||||
impl Registration {
|
||||
pub(super) fn new(instance_id: &str) -> crate::Result<Self> {
|
||||
use dashmap::mapref::entry::Entry;
|
||||
let control = Arc::new(Control::new(instance_id));
|
||||
match CONTROLS.entry(instance_id.to_owned()) {
|
||||
Entry::Occupied(_) => {
|
||||
return Err(super::invalid("此实例已有整合包下载任务"));
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(control.clone());
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
instance_id: instance_id.to_owned(),
|
||||
control,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Registration {
|
||||
fn drop(&mut self) {
|
||||
CONTROLS.remove_if(&self.instance_id, |_, value| {
|
||||
Arc::ptr_eq(value, &self.control)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn lookup(instance_id: &str) -> crate::Result<Arc<Control>> {
|
||||
CONTROLS
|
||||
.get(instance_id)
|
||||
.map(|entry| entry.value().clone())
|
||||
.ok_or_else(|| super::invalid("整合包下载任务已结束,请重试"))
|
||||
}
|
||||
|
||||
pub async fn pause(instance_id: &str) -> crate::Result<()> {
|
||||
lookup(instance_id)?.pause()
|
||||
}
|
||||
pub async fn resume(instance_id: &str) -> crate::Result<()> {
|
||||
lookup(instance_id)?.resume()
|
||||
}
|
||||
pub async fn cancel(instance_id: &str) -> crate::Result<()> {
|
||||
lookup(instance_id)?.cancel()
|
||||
}
|
||||
|
||||
/// Stop the batch on its first error so stalled peers cannot hide failure.
|
||||
pub(super) async fn collect_downloads<S>(downloads: S) -> crate::Result<u64>
|
||||
where
|
||||
S: Stream<Item = crate::Result<u64>>,
|
||||
{
|
||||
tokio::pin!(downloads);
|
||||
let mut total = 0;
|
||||
while let Some(result) = downloads.next().await {
|
||||
total += result?;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::FutureExt;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use tokio::sync::{Notify, Semaphore};
|
||||
|
||||
struct TransferGuard(Arc<AtomicUsize>, Arc<Notify>);
|
||||
|
||||
impl Drop for TransferGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
self.1.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pause_drops_live_transfers_and_resume_restarts_before_stop() {
|
||||
let control = Arc::new(Control::new("pause-resume-test"));
|
||||
let starts = Arc::new(Semaphore::new(0));
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let dropped = Arc::new(Notify::new());
|
||||
let task = {
|
||||
let control = control.clone();
|
||||
let starts = starts.clone();
|
||||
let drops = drops.clone();
|
||||
let dropped = dropped.clone();
|
||||
tokio::spawn(async move {
|
||||
control
|
||||
.run(|| {
|
||||
let guard =
|
||||
TransferGuard(drops.clone(), dropped.clone());
|
||||
starts.add_permits(1);
|
||||
async move {
|
||||
let _guard = guard;
|
||||
std::future::pending::<crate::Result<()>>().await
|
||||
}
|
||||
})
|
||||
.await
|
||||
})
|
||||
};
|
||||
starts.acquire().await.unwrap().forget();
|
||||
control.pause().unwrap();
|
||||
dropped.notified().await;
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(control.state(), HostedTaskState::Paused);
|
||||
control.resume().unwrap();
|
||||
starts.acquire().await.unwrap().forget();
|
||||
control.cancel().unwrap();
|
||||
let result = task.await.unwrap();
|
||||
assert!(result.unwrap_err().to_string().contains("停止"));
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stopping_an_already_paused_task_never_starts_a_transfer() {
|
||||
let control = Arc::new(Control::new("paused-stop-test"));
|
||||
control.pause().unwrap();
|
||||
let task = {
|
||||
let control = control.clone();
|
||||
tokio::spawn(async move {
|
||||
control
|
||||
.run(|| async {
|
||||
panic!("paused work was polled");
|
||||
Ok::<(), crate::Error>(())
|
||||
})
|
||||
.await
|
||||
})
|
||||
};
|
||||
control.cancel().unwrap();
|
||||
assert!(task.await.unwrap().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finalization_rejects_pause_and_stop() {
|
||||
let control = Control::new("finalization-test");
|
||||
control.begin_finalizing().unwrap();
|
||||
assert_eq!(control.state(), HostedTaskState::Finalizing);
|
||||
assert!(control.pause().is_err());
|
||||
assert!(control.cancel().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pause_and_finalization_have_only_one_winner() {
|
||||
for _ in 0..32 {
|
||||
let control = Arc::new(Control::new("finalization-race-test"));
|
||||
let barrier = Arc::new(std::sync::Barrier::new(2));
|
||||
let task = {
|
||||
let control = control.clone();
|
||||
let barrier = barrier.clone();
|
||||
std::thread::spawn(move || {
|
||||
barrier.wait();
|
||||
control.pause().is_ok()
|
||||
})
|
||||
};
|
||||
barrier.wait();
|
||||
let finalized = control.begin_finalizing().is_ok();
|
||||
assert_ne!(finalized, task.join().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_failure_drops_stalled_peer_downloads() {
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let guard = TransferGuard(drops.clone(), Arc::new(Notify::new()));
|
||||
let downloads = futures::stream::iter(vec![
|
||||
async move {
|
||||
let _guard = guard;
|
||||
std::future::pending::<crate::Result<u64>>().await
|
||||
}
|
||||
.boxed(),
|
||||
async { Err(super::super::invalid("failed file")) }.boxed(),
|
||||
])
|
||||
.buffer_unordered(2);
|
||||
let result = collect_downloads(downloads).await;
|
||||
assert!(result.unwrap_err().to_string().contains("failed file"));
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_is_unique_and_released_on_drop() {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let registration = Registration::new(&id).unwrap();
|
||||
assert!(Registration::new(&id).is_err());
|
||||
drop(registration);
|
||||
assert!(Registration::new(&id).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,9 @@ impl PackProgress {
|
||||
instance_id: instance_id.to_owned(),
|
||||
instance_name: name.to_owned(),
|
||||
error: None,
|
||||
state: super::HostedTaskState::Running,
|
||||
can_pause: true,
|
||||
can_cancel: true,
|
||||
},
|
||||
1.0,
|
||||
"正在获取整合包信息",
|
||||
|
||||
@@ -681,7 +681,7 @@ pub(super) async fn download(
|
||||
set_loading(&bar, 0, file.size, "等待下载")?;
|
||||
work.push((file, url, object, bar));
|
||||
}
|
||||
let results =
|
||||
control::collect_downloads(
|
||||
stream::iter(work.into_iter().map(|(file, url, object, bar)| {
|
||||
let current = ¤t;
|
||||
let state = &state;
|
||||
@@ -740,10 +740,7 @@ pub(super) async fn download(
|
||||
result
|
||||
}
|
||||
}))
|
||||
.buffer_unordered(concurrency)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
results
|
||||
.into_iter()
|
||||
.try_fold(0, |sum, result| Ok(sum + result?))
|
||||
.buffer_unordered(concurrency),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::pin::Pin;
|
||||
|
||||
use zip::ZipArchive;
|
||||
@@ -320,23 +320,13 @@ pub(crate) async fn generate_pack_from_version_id_with_reporter(
|
||||
"Specified version has no files".to_string(),
|
||||
)
|
||||
})?;
|
||||
let file_name = Path::new(&pack_file.filename);
|
||||
if file_name.components().count() != 1
|
||||
|| !matches!(file_name.components().next(), Some(Component::Normal(_)))
|
||||
{
|
||||
return Err(crate::ErrorKind::InputError(
|
||||
"Modrinth returned an invalid modpack file name".to_string(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let hash = pack_file.hashes.get("sha1");
|
||||
let pack_path = state
|
||||
.directories
|
||||
.caches_dir()
|
||||
.join("modpacks")
|
||||
.join(&project_id)
|
||||
.join(&version_id)
|
||||
.join(file_name);
|
||||
let pack_path = modpack_cache_path(
|
||||
&state.directories.caches_dir().join("modpacks"),
|
||||
&project_id,
|
||||
&version_id,
|
||||
&pack_file.filename,
|
||||
)?;
|
||||
|
||||
let details = InstallPhaseDetails::Modpack {
|
||||
project_id: Some(project_id.clone()),
|
||||
@@ -517,8 +507,70 @@ pub(crate) async fn generate_pack_from_version_id_with_reporter(
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
fn modpack_cache_path(
|
||||
root: &Path,
|
||||
project_id: &str,
|
||||
version_id: &str,
|
||||
filename: &str,
|
||||
) -> crate::Result<PathBuf> {
|
||||
let mut path = root.to_path_buf();
|
||||
for segment in [project_id, version_id, filename] {
|
||||
if segment.contains('/') {
|
||||
return Err(crate::ErrorKind::InputError(
|
||||
"Invalid modpack cache path component".to_string(),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
path = crate::util::io::safe_relative_join(&path, segment)?;
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cache_path_tests {
|
||||
use super::modpack_cache_path;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn cache_components_cannot_escape_their_directories() {
|
||||
let root = Path::new("modpacks");
|
||||
assert_eq!(
|
||||
modpack_cache_path(root, "project", "version", "pack.mrpack")
|
||||
.unwrap(),
|
||||
root.join("project/version/pack.mrpack")
|
||||
);
|
||||
for malicious in [
|
||||
"../outside",
|
||||
"nested/name",
|
||||
r"..\outside",
|
||||
"C:/outside",
|
||||
"C:outside",
|
||||
r"\\server\share",
|
||||
".",
|
||||
"",
|
||||
"NUL",
|
||||
"pack.mrpack:stream",
|
||||
".. ",
|
||||
] {
|
||||
for position in 0..3 {
|
||||
let mut components = ["project", "version", "pack.mrpack"];
|
||||
components[position] = malicious;
|
||||
assert!(
|
||||
modpack_cache_path(
|
||||
root,
|
||||
components[0],
|
||||
components[1],
|
||||
components[2]
|
||||
)
|
||||
.is_err(),
|
||||
"{position}: {malicious:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument]
|
||||
pub async fn generate_pack_from_file(
|
||||
path: PathBuf,
|
||||
instance_id: String,
|
||||
|
||||
@@ -891,6 +891,12 @@ pub(crate) async fn install_zipped_mrpack_files_with_reporter(
|
||||
num_files,
|
||||
content_total_bytes,
|
||||
};
|
||||
for file in &pack.files {
|
||||
io::join_within_root(
|
||||
&content_context.instance_full_path,
|
||||
&content_context.resolve_install_path(file),
|
||||
)?;
|
||||
}
|
||||
let skipped_missing_content_paths = Arc::new(
|
||||
reporter
|
||||
.current_state()
|
||||
@@ -1039,8 +1045,14 @@ pub(crate) async fn install_zipped_mrpack_files_with_reporter(
|
||||
let project_size = project.file_size as u64;
|
||||
let project_path =
|
||||
content_context.resolve_install_path(&project);
|
||||
let target_path =
|
||||
content_context.instance_full_path.join(&project_path);
|
||||
let target_path = io::join_within_root(
|
||||
&content_context.instance_full_path,
|
||||
&project_path,
|
||||
).map_err(|error| RequiredFileFailure::new(
|
||||
manifest_index,
|
||||
&project_path,
|
||||
&error.to_string(),
|
||||
))?;
|
||||
let context =
|
||||
InstallErrorContext::new("download modpack content file")
|
||||
.maybe_project_id(
|
||||
@@ -1451,7 +1463,10 @@ pub(crate) async fn install_zipped_mrpack_files_with_reporter(
|
||||
entry_name: filename.to_string(),
|
||||
crc32: file.crc32(),
|
||||
uncompressed_size: file.uncompressed_size(),
|
||||
target_path: instance_full_path.join(&relative_path),
|
||||
target_path: io::safe_relative_join(
|
||||
&instance_full_path,
|
||||
&relative_path,
|
||||
)?,
|
||||
relative_path,
|
||||
})
|
||||
})
|
||||
@@ -1739,6 +1754,7 @@ fn override_relative_path(
|
||||
"Invalid modpack override path: {relative}"
|
||||
))
|
||||
})?;
|
||||
io::safe_relative_join(Path::new(""), relative.as_str())?;
|
||||
Ok(relative.as_str().to_string())
|
||||
}
|
||||
|
||||
@@ -1885,7 +1901,11 @@ pub async fn remove_all_related_files(
|
||||
// Iterate over all Modrinth project file paths in the json, and remove them
|
||||
// (There should be few, but this removes any files the .mrpack intended as Modrinth projects but were unrecognized)
|
||||
for file in pack.files {
|
||||
match io::remove_file(instance_full_path.join(file.path.as_str())).await
|
||||
match io::remove_file(io::safe_relative_join(
|
||||
&instance_full_path,
|
||||
file.path.as_str(),
|
||||
)?)
|
||||
.await
|
||||
{
|
||||
Ok(_) => (),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => (),
|
||||
@@ -1904,23 +1924,14 @@ pub async fn remove_all_related_files(
|
||||
|
||||
for file in override_file_entries {
|
||||
let entry_name = file.filename().as_str().unwrap();
|
||||
let entry_name =
|
||||
entry_name.strip_prefix(&archive_base).unwrap_or(entry_name);
|
||||
let relative_override_file_path =
|
||||
SafeRelativeUtf8UnixPathBuf::try_from(entry_name.to_string())?;
|
||||
let relative_override_file_path = relative_override_file_path
|
||||
.strip_prefix("overrides")
|
||||
.or_else(|_| relative_override_file_path.strip_prefix("client-overrides"))
|
||||
.map_err(|_| {
|
||||
crate::Error::from(crate::ErrorKind::OtherError(
|
||||
format!("Failed to strip override prefix from override file path: {relative_override_file_path}")
|
||||
))
|
||||
})?;
|
||||
override_relative_path(entry_name, &archive_base)?;
|
||||
|
||||
// Remove this file if a corresponding one exists in the filesystem
|
||||
match io::remove_file(
|
||||
instance_full_path.join(relative_override_file_path.as_str()),
|
||||
)
|
||||
match io::remove_file(io::safe_relative_join(
|
||||
&instance_full_path,
|
||||
&relative_override_file_path,
|
||||
)?)
|
||||
.await
|
||||
{
|
||||
Ok(_) => (),
|
||||
@@ -1939,6 +1950,35 @@ mod tests {
|
||||
use async_zip::{Compression, ZipEntryBuilder};
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
#[test]
|
||||
fn override_paths_reject_portable_traversal_and_windows_aliases() {
|
||||
for prefix in ["overrides/", "client-overrides/"] {
|
||||
assert_eq!(
|
||||
override_relative_path(
|
||||
&format!("{prefix}config/example.toml"),
|
||||
""
|
||||
)
|
||||
.unwrap(),
|
||||
"config/example.toml"
|
||||
);
|
||||
for relative in [
|
||||
"../outside",
|
||||
"config/.. /outside",
|
||||
"config/file:stream",
|
||||
"C:/outside",
|
||||
"C:outside",
|
||||
"config/NUL",
|
||||
"config/file.",
|
||||
] {
|
||||
assert!(
|
||||
override_relative_path(&format!("{prefix}{relative}"), "")
|
||||
.is_err(),
|
||||
"{prefix}{relative}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn override_spec(index: usize, target: &str) -> OverrideExtractionSpec {
|
||||
OverrideExtractionSpec {
|
||||
index,
|
||||
|
||||
@@ -12,6 +12,8 @@ use crate::{ErrorKind, Result};
|
||||
|
||||
use super::manifest::server_path;
|
||||
|
||||
pub(super) use crate::util::io::safe_relative_join;
|
||||
|
||||
const DOWNLOAD_PROGRESS_STEP: u64 = 512 * 1024;
|
||||
|
||||
pub async fn read_file(server_id: &str, file: &str) -> Result<String> {
|
||||
@@ -124,44 +126,7 @@ pub(super) async fn download_to_dir(
|
||||
|
||||
async fn resolve_server_file(server_id: &str, file: &str) -> Result<PathBuf> {
|
||||
let dir = server_path(server_id).await?;
|
||||
safe_join(&dir, file)
|
||||
}
|
||||
|
||||
fn safe_join(dir: &Path, file: &str) -> Result<PathBuf> {
|
||||
if file.is_empty()
|
||||
|| file.contains('\\')
|
||||
|| file.starts_with('/')
|
||||
|| file
|
||||
.split('/')
|
||||
.any(|segment| segment == ".." || segment.is_empty())
|
||||
{
|
||||
return Err(ErrorKind::InputError(format!(
|
||||
"Invalid file name: {file}"
|
||||
))
|
||||
.as_error());
|
||||
}
|
||||
Ok(dir.join(file))
|
||||
}
|
||||
|
||||
/// Joins a relative path that may contain `/` separators but never escapes the
|
||||
/// server directory (no `..`, empty segments, or absolute/Windows roots).
|
||||
pub(super) fn safe_relative_join(dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
let is_windows_drive_root =
|
||||
rel.as_bytes().get(1).is_some_and(|byte| *byte == b':')
|
||||
&& rel.as_bytes().first().is_some_and(u8::is_ascii_alphabetic);
|
||||
if rel.is_empty()
|
||||
|| Path::new(rel).is_absolute()
|
||||
|| is_windows_drive_root
|
||||
|| rel.starts_with('/')
|
||||
|| rel.starts_with('\\')
|
||||
|| rel.split(['/', '\\']).any(|segment| {
|
||||
segment.is_empty() || segment == ".." || segment == "."
|
||||
})
|
||||
{
|
||||
return Err(ErrorKind::InputError(format!("Invalid file path: {rel}"))
|
||||
.as_error());
|
||||
}
|
||||
Ok(dir.join(rel))
|
||||
safe_relative_join(&dir, file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -169,13 +134,34 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn safe_join_rejects_traversal() {
|
||||
fn safe_relative_join_rejects_unsafe_paths() {
|
||||
let dir = Path::new("/tmp/servers/a");
|
||||
assert!(safe_join(dir, "server.properties").is_ok());
|
||||
assert!(safe_join(dir, "../secret").is_err());
|
||||
assert!(safe_join(dir, "/etc/passwd").is_err());
|
||||
assert!(safe_join(dir, "a//b").is_err());
|
||||
assert!(safe_join(dir, "").is_err());
|
||||
for path in [
|
||||
"../secret",
|
||||
"mods/../../secret",
|
||||
r"..\secret",
|
||||
r"mods/..\../secret",
|
||||
"/etc/passwd",
|
||||
"C:/windows/system32",
|
||||
r"C:\windows\system32",
|
||||
"C:secret",
|
||||
r"\\server\share\secret",
|
||||
r"\secret",
|
||||
r"\\?\C:\secret",
|
||||
"a//b",
|
||||
"a/./b",
|
||||
".",
|
||||
"",
|
||||
"mods/.. /secret",
|
||||
"mods/secret.",
|
||||
"mods/secret ",
|
||||
"mods/mod.jar:payload",
|
||||
"NUL/secret",
|
||||
"mods/CON.jar",
|
||||
"mods/mod\0.jar",
|
||||
] {
|
||||
assert!(safe_relative_join(dir, path).is_err(), "{path:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::event::emit::emit_server;
|
||||
use crate::util::io::IOError;
|
||||
use crate::{ErrorKind, Result};
|
||||
|
||||
use super::files::download_to_dir;
|
||||
use super::files::{download_to_dir, safe_relative_join};
|
||||
use super::manifest::{
|
||||
InstallState, read_manifest, server_path, write_manifest,
|
||||
};
|
||||
@@ -41,6 +41,7 @@ pub async fn install_forge(
|
||||
drop(manifest);
|
||||
|
||||
let installer_name = format!("forge-{mc_version}-{build}-installer.jar");
|
||||
let installer_path = safe_relative_join(&dir, &installer_name)?;
|
||||
let installer_url =
|
||||
format!("{FORGE_MAVEN}/{mc_version}-{build}/{installer_name}");
|
||||
|
||||
@@ -52,7 +53,6 @@ pub async fn install_forge(
|
||||
download_to_dir(server_id, &dir, &installer_url, &installer_name, None)
|
||||
.await?;
|
||||
|
||||
let installer_path = dir.join(&installer_name);
|
||||
let java = java_path.clone().unwrap_or_else(|| "java".to_string());
|
||||
|
||||
log(server_id, "Running Forge installer (this may take a while)").await?;
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::state::{clear_log_buffer, get_log_buffer, push_log_line};
|
||||
use crate::util::io::IOError;
|
||||
use crate::{ErrorKind, Result};
|
||||
|
||||
use super::files::safe_relative_join;
|
||||
use super::logs::{
|
||||
analyze_exit_reason, stream_server_output, stream_server_pty_output,
|
||||
tail_server_log_file,
|
||||
@@ -131,7 +132,7 @@ async fn start_inner(
|
||||
forge_launch_args(&dir)?
|
||||
} else {
|
||||
let jar_name = resolve_jar_name(&manifest);
|
||||
let jar_path = dir.join(&jar_name);
|
||||
let jar_path = safe_relative_join(&dir, &jar_name)?;
|
||||
if !jar_path.exists() {
|
||||
return Err(ErrorKind::LauncherError(format!(
|
||||
"Server jar not found: {jar_name}. Download the server files first."
|
||||
@@ -275,9 +276,11 @@ async fn start_inner(
|
||||
// so these lines stop the console from looking frozen.
|
||||
let loader_first_run =
|
||||
matches!(manifest.server_type.as_str(), "fabric" | "quilt")
|
||||
&& !dir
|
||||
.join(format!("{}-server-launch.jar", manifest.server_type))
|
||||
.exists();
|
||||
&& !safe_relative_join(
|
||||
&dir,
|
||||
&format!("{}-server-launch.jar", manifest.server_type),
|
||||
)?
|
||||
.exists();
|
||||
|
||||
log_server_step(
|
||||
server_id,
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::state::remove_log_buffer;
|
||||
use crate::util::io::{self, IOError};
|
||||
use crate::{ErrorKind, Result, State};
|
||||
|
||||
use super::files::safe_relative_join;
|
||||
use super::lifecycle::is_running;
|
||||
use super::manifest::{
|
||||
ServerInfo, ServerManifest, build_server_info, read_manifest,
|
||||
@@ -72,7 +73,7 @@ pub async fn create(
|
||||
let state = State::get().await?;
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let dir_name = format!("{}-{}", sanitize_folder_name(name), &id[..8]);
|
||||
let dir = state.directories.servers_dir().join(&dir_name);
|
||||
let dir = safe_relative_join(&state.directories.servers_dir(), &dir_name)?;
|
||||
io::create_dir_all(&dir).await?;
|
||||
|
||||
let manifest = ServerManifest {
|
||||
|
||||
@@ -118,7 +118,7 @@ pub(super) async fn server_path(server_id: &str) -> Result<PathBuf> {
|
||||
.as_error());
|
||||
}
|
||||
let state = State::get().await?;
|
||||
let path = state.directories.server_dir(server_id);
|
||||
let path = state.directories.server_dir(server_id)?;
|
||||
if !path.is_dir() {
|
||||
return Err(ErrorKind::InputError(format!(
|
||||
"Unknown server: {server_id}"
|
||||
|
||||
@@ -33,7 +33,7 @@ use crate::util::fetch::{
|
||||
use crate::util::io::IOError;
|
||||
use crate::{ErrorKind, Result};
|
||||
|
||||
use super::files::download_to_dir;
|
||||
use super::files::{download_to_dir, safe_relative_join};
|
||||
use super::manifest::{
|
||||
InstallState, ModpackInfo, read_manifest, server_path, write_manifest,
|
||||
};
|
||||
@@ -92,10 +92,52 @@ struct MrpackFile {
|
||||
env: Option<MrpackEnv>,
|
||||
#[serde(default)]
|
||||
downloads: Vec<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, rename = "fileSize")]
|
||||
file_size: Option<u64>,
|
||||
}
|
||||
|
||||
impl MrpackFile {
|
||||
fn integrity(&self) -> Result<Integrity> {
|
||||
let sha1 = self.hashes.get("sha1").cloned();
|
||||
let sha512 = self.hashes.get("sha512").cloned();
|
||||
if sha1.is_none() && sha512.is_none() {
|
||||
return Err(ErrorKind::InputError(format!(
|
||||
"Modpack file {} is missing a SHA-1 or SHA-512 checksum",
|
||||
self.path
|
||||
))
|
||||
.as_error());
|
||||
}
|
||||
for (hash, length) in [(&sha1, 40), (&sha512, 128)] {
|
||||
if let Some(hash) = hash
|
||||
&& (hash.len() != length
|
||||
|| !hash.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
||||
{
|
||||
return Err(ErrorKind::InputError(format!(
|
||||
"Modpack file {} has an invalid checksum",
|
||||
self.path
|
||||
))
|
||||
.as_error());
|
||||
}
|
||||
}
|
||||
Ok(Integrity {
|
||||
sha1,
|
||||
sha512,
|
||||
size: self.file_size,
|
||||
..Integrity::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the entire index before starting concurrent downloads, including
|
||||
/// entries excluded from server installation but fetched for metadata.
|
||||
fn validate_index(index: &MrpackIndex, dir: &Path) -> Result<()> {
|
||||
for file in &index.files {
|
||||
safe_relative_join(dir, &file.path)?;
|
||||
file.integrity()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
struct MrpackEnv {
|
||||
#[serde(default)]
|
||||
@@ -272,7 +314,7 @@ async fn run_modpack_install(
|
||||
&state,
|
||||
mrpack_url,
|
||||
&dir.join(MRPACK_FILENAME),
|
||||
mrpack_sha1.map(str::to_string),
|
||||
mrpack_sha1.map(Integrity::sha1).unwrap_or_default(),
|
||||
ResourceClass::Modpack,
|
||||
AggregateProgress::new(0),
|
||||
)
|
||||
@@ -282,6 +324,7 @@ async fn run_modpack_install(
|
||||
let manifest_entry = find_manifest_entry(&archive_path).await?;
|
||||
let base_folder = base_folder(&manifest_entry);
|
||||
let index = parse_index(&archive_path, &manifest_entry).await?;
|
||||
validate_index(&index, dir)?;
|
||||
|
||||
let (installable_files, excluded_files): (
|
||||
Vec<&MrpackFile>,
|
||||
@@ -310,19 +353,19 @@ async fn run_modpack_install(
|
||||
)
|
||||
.await?;
|
||||
|
||||
let files: Vec<(String, String, Option<String>, u64)> = installable_files
|
||||
let files: Vec<(String, String, Integrity, u64)> = installable_files
|
||||
.iter()
|
||||
.filter_map(|file| {
|
||||
file.downloads.first().map(|url| {
|
||||
(
|
||||
Ok((
|
||||
file.path.clone(),
|
||||
url.clone(),
|
||||
file.hashes.get("sha1").cloned(),
|
||||
file.integrity()?,
|
||||
file.file_size.unwrap_or(0),
|
||||
)
|
||||
))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
.collect::<Result<_>>()?;
|
||||
|
||||
let progress = AggregateProgress::new(total_bytes);
|
||||
let state_ref = state.clone();
|
||||
@@ -336,14 +379,14 @@ async fn run_modpack_install(
|
||||
0.0,
|
||||
num_files,
|
||||
None,
|
||||
move |(path, url, sha1, size)| {
|
||||
move |(path, url, integrity, size)| {
|
||||
let server_id = server_id_ref.clone();
|
||||
let dir = dir_ref.clone();
|
||||
let state = state_ref.clone();
|
||||
let progress = progress.clone();
|
||||
async move {
|
||||
log(&server_id, &format!("Downloading {path}")).await?;
|
||||
let destination = dir.join(&path);
|
||||
let destination = safe_relative_join(&dir, &path)?;
|
||||
if let Some(parent) = destination.parent() {
|
||||
crate::util::io::create_dir_all(parent).await?;
|
||||
}
|
||||
@@ -352,7 +395,7 @@ async fn run_modpack_install(
|
||||
&state,
|
||||
&url,
|
||||
&destination,
|
||||
sha1,
|
||||
integrity,
|
||||
ResourceClass::Modpack,
|
||||
progress.clone(),
|
||||
)
|
||||
@@ -446,7 +489,7 @@ async fn download_icon(dir: &Path, icon_url: &str) -> Result<PathBuf> {
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| "png".to_string());
|
||||
let destination = dir.join(format!("icon.{extension}"));
|
||||
let destination = safe_relative_join(dir, &format!("icon.{extension}"))?;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.user_agent(crate::launcher_user_agent())
|
||||
@@ -476,15 +519,13 @@ async fn download_with_engine(
|
||||
state: &State,
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
sha1: Option<String>,
|
||||
integrity: Integrity,
|
||||
resource: ResourceClass,
|
||||
progress: AggregateProgress,
|
||||
) -> Result<()> {
|
||||
let mut request = DownloadRequest::new(url, resource);
|
||||
if let Some(sha1) = &sha1 {
|
||||
request = request.with_integrity(Integrity::sha1(sha1.clone()));
|
||||
}
|
||||
request = request.with_segmented_download(true);
|
||||
let request = DownloadRequest::new(url, resource)
|
||||
.with_integrity(integrity)
|
||||
.with_segmented_download(true);
|
||||
|
||||
let server_id = server_id.to_string();
|
||||
let progress = progress.clone();
|
||||
@@ -579,7 +620,7 @@ async fn fetch_excluded_mod_ids(
|
||||
state: &State,
|
||||
excluded_files: &[&MrpackFile],
|
||||
) -> Result<HashSet<String>> {
|
||||
let candidates: Vec<(String, String, Option<String>)> = excluded_files
|
||||
let candidates: Vec<(String, String, Integrity)> = excluded_files
|
||||
.iter()
|
||||
.filter_map(|file| {
|
||||
let path = file.path.replace('\\', "/");
|
||||
@@ -589,14 +630,14 @@ async fn fetch_excluded_mod_ids(
|
||||
return None;
|
||||
}
|
||||
file.downloads.first().map(|url| {
|
||||
(
|
||||
Ok((
|
||||
path.rsplit('/').next().unwrap_or(&path).to_string(),
|
||||
url.clone(),
|
||||
file.hashes.get("sha1").cloned(),
|
||||
)
|
||||
file.integrity()?,
|
||||
))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
.collect::<Result<_>>()?;
|
||||
if candidates.is_empty() {
|
||||
return Ok(HashSet::new());
|
||||
}
|
||||
@@ -611,9 +652,10 @@ async fn fetch_excluded_mod_ids(
|
||||
ErrorKind::FSError(format!("Failed to create temporary directory: {e}"))
|
||||
})?;
|
||||
let mut unavailable = HashSet::new();
|
||||
for (filename, url, sha1) in candidates {
|
||||
let destination = temp_dir.path().join(&filename);
|
||||
match download_metadata_jar(state, &url, &destination, sha1).await {
|
||||
for (filename, url, integrity) in candidates {
|
||||
let destination = safe_relative_join(temp_dir.path(), &filename)?;
|
||||
match download_metadata_jar(state, &url, &destination, integrity).await
|
||||
{
|
||||
Ok(()) => match read_mod_metadata(&destination) {
|
||||
Some(metadata) => {
|
||||
unavailable
|
||||
@@ -647,12 +689,10 @@ async fn download_metadata_jar(
|
||||
state: &State,
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
sha1: Option<String>,
|
||||
integrity: Integrity,
|
||||
) -> Result<()> {
|
||||
let mut request = DownloadRequest::new(url, ResourceClass::Modpack);
|
||||
if let Some(sha1) = &sha1 {
|
||||
request = request.with_integrity(Integrity::sha1(sha1.clone()));
|
||||
}
|
||||
let request = DownloadRequest::new(url, ResourceClass::Modpack)
|
||||
.with_integrity(integrity);
|
||||
download_to_path(
|
||||
request,
|
||||
destination,
|
||||
@@ -908,6 +948,122 @@ mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn index_file(path: &str) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"path": path,
|
||||
"hashes": { "sha1": "0".repeat(40) },
|
||||
"downloads": ["https://example.com/mod.jar"],
|
||||
"fileSize": 10
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malicious_index_paths_fail_before_materializing_files() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let server = temp.path().join("server");
|
||||
std::fs::create_dir(&server).unwrap();
|
||||
let outside = temp.path().join("outside.txt");
|
||||
std::fs::write(&outside, "unchanged").unwrap();
|
||||
let archive = temp.path().join("pack.mrpack");
|
||||
for path in [
|
||||
"../outside.txt",
|
||||
"mods/../../outside.txt",
|
||||
r"..\outside.txt",
|
||||
r"mods/..\../outside.txt",
|
||||
"/tmp/outside.txt",
|
||||
"C:/outside.txt",
|
||||
r"C:\outside.txt",
|
||||
"C:outside.txt",
|
||||
r"\\server\share\outside.txt",
|
||||
r"\outside.txt",
|
||||
r"\\?\C:\outside.txt",
|
||||
"mods//mod.jar",
|
||||
"mods/./mod.jar",
|
||||
"mods/.. /outside.txt",
|
||||
"mods/mod.jar:payload",
|
||||
"NUL/outside.txt",
|
||||
"mods/CON.jar",
|
||||
"",
|
||||
] {
|
||||
for environment in ["required", "unsupported"] {
|
||||
let mut malicious = index_file(path);
|
||||
// Filtered entries must also fail before any downloads.
|
||||
malicious["env"] = serde_json::json!({"server": environment});
|
||||
let contents = serde_json::json!({
|
||||
"files": [index_file("mods/valid.jar"), malicious]
|
||||
})
|
||||
.to_string();
|
||||
create_jar(&archive, &[(MRPACK_MANIFEST_ENTRY, &contents)]);
|
||||
let index =
|
||||
parse_index(&archive, MRPACK_MANIFEST_ENTRY).await.unwrap();
|
||||
assert!(validate_index(&index, &server).is_err(), "{path:?}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&outside).unwrap(),
|
||||
"unchanged"
|
||||
);
|
||||
assert_eq!(std::fs::read_dir(&server).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_requires_valid_supported_checksums() {
|
||||
for hashes in [
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({"md5": "0".repeat(32)}),
|
||||
serde_json::json!({"sha1": ""}),
|
||||
serde_json::json!({"sha1": "0".repeat(39)}),
|
||||
serde_json::json!({"sha512": "g".repeat(128)}),
|
||||
serde_json::json!({"sha1": "invalid", "sha512": "0".repeat(128)}),
|
||||
] {
|
||||
let mut file = index_file("mods/mod.jar");
|
||||
file["hashes"] = hashes;
|
||||
let index: MrpackIndex =
|
||||
serde_json::from_value(serde_json::json!({"files": [file]}))
|
||||
.unwrap();
|
||||
assert!(validate_index(&index, Path::new("server")).is_err());
|
||||
}
|
||||
let mut file = index_file("mods/mod.jar");
|
||||
file.as_object_mut().unwrap().remove("hashes");
|
||||
let index: MrpackIndex =
|
||||
serde_json::from_value(serde_json::json!({"files": [file]}))
|
||||
.unwrap();
|
||||
assert!(validate_index(&index, Path::new("server")).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn index_checksums_verify_file_contents() {
|
||||
use crate::util::fetch::verify_file;
|
||||
use sha2::{Digest, Sha512};
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let target = temp.path().join("mod.jar");
|
||||
let contents = b"verified mod";
|
||||
std::fs::write(&target, contents).unwrap();
|
||||
for hashes in [
|
||||
serde_json::json!({"sha1": sha1_smol::Sha1::from(contents).digest().to_string()}),
|
||||
serde_json::json!({"sha512": format!("{:x}", Sha512::digest(contents))}),
|
||||
serde_json::json!({
|
||||
"sha1": sha1_smol::Sha1::from(contents).digest().to_string(),
|
||||
"sha512": format!("{:x}", Sha512::digest(contents))
|
||||
}),
|
||||
] {
|
||||
let mut file = index_file("mods/mod.jar");
|
||||
file["hashes"] = hashes;
|
||||
file["fileSize"] = serde_json::json!(contents.len());
|
||||
let index: MrpackIndex =
|
||||
serde_json::from_value(serde_json::json!({"files": [file]}))
|
||||
.unwrap();
|
||||
validate_index(&index, temp.path()).unwrap();
|
||||
let integrity = index.files[0].integrity().unwrap();
|
||||
assert_eq!(integrity.size, Some(contents.len() as u64));
|
||||
verify_file(&target, &integrity).await.unwrap();
|
||||
std::fs::write(&target, b"tampered mod").unwrap();
|
||||
assert!(verify_file(&target, &integrity).await.is_err());
|
||||
std::fs::write(&target, contents).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_only_files_are_installable() {
|
||||
let installable = MrpackFile {
|
||||
|
||||
@@ -232,8 +232,24 @@ pub fn fail_hosted_loading(key: &LoadingBarId, error: &str) {
|
||||
&& let Some(mut bar) = state.loading_bars.get_mut(&key.0)
|
||||
{
|
||||
match &mut bar.bar_type {
|
||||
LoadingBarType::HostedPackSync { error: failure, .. }
|
||||
| LoadingBarType::HostedModDownload { error: failure, .. } => {
|
||||
LoadingBarType::HostedPackSync {
|
||||
error: failure,
|
||||
state,
|
||||
can_pause,
|
||||
can_cancel,
|
||||
..
|
||||
} => {
|
||||
use crate::api::pack::hosted::HostedTaskState;
|
||||
*state = if *state == HostedTaskState::Canceling {
|
||||
HostedTaskState::Canceled
|
||||
} else {
|
||||
HostedTaskState::Failed
|
||||
};
|
||||
*can_pause = false;
|
||||
*can_cancel = false;
|
||||
*failure = Some(error.to_owned());
|
||||
}
|
||||
LoadingBarType::HostedModDownload { error: failure, .. } => {
|
||||
*failure = Some(error.to_owned())
|
||||
}
|
||||
_ => {}
|
||||
@@ -241,6 +257,67 @@ pub fn fail_hosted_loading(key: &LoadingBarId, error: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the authoritative snapshot and notify observers even while all
|
||||
/// transfer futures are paused and no byte-progress event can be produced.
|
||||
pub fn set_hosted_loading_state(
|
||||
instance_id: &str,
|
||||
next: crate::api::pack::hosted::HostedTaskState,
|
||||
) {
|
||||
use crate::api::pack::hosted::HostedTaskState;
|
||||
let Ok(event_state) = crate::EventState::get() else {
|
||||
return;
|
||||
};
|
||||
for mut bar in event_state.loading_bars.iter_mut() {
|
||||
let LoadingBarType::HostedPackSync {
|
||||
instance_id: id,
|
||||
state,
|
||||
can_pause,
|
||||
can_cancel,
|
||||
..
|
||||
} = &mut bar.bar_type
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if id != instance_id {
|
||||
continue;
|
||||
}
|
||||
*state = next;
|
||||
let controllable =
|
||||
matches!(next, HostedTaskState::Running | HostedTaskState::Paused);
|
||||
*can_pause = controllable;
|
||||
*can_cancel = controllable;
|
||||
match next {
|
||||
HostedTaskState::Paused => {
|
||||
bar.message = "已暂停,点击继续以恢复下载".into()
|
||||
}
|
||||
HostedTaskState::Canceling => {
|
||||
bar.message = "正在停止整合包下载".into()
|
||||
}
|
||||
HostedTaskState::Running => {
|
||||
bar.message = "正在继续整合包下载".into()
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
#[cfg(feature = "tauri")]
|
||||
{
|
||||
let _ = event_state.app.emit(
|
||||
"loading",
|
||||
LoadingPayload {
|
||||
fraction: Some(if bar.total > 0.0 {
|
||||
bar.current / bar.total
|
||||
} else {
|
||||
0.0
|
||||
}),
|
||||
message: bar.message.clone(),
|
||||
event: bar.bar_type.clone(),
|
||||
loader_uuid: bar.loading_bar_uuid,
|
||||
total: Some(bar.total),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// emit_warning(message)
|
||||
pub async fn emit_warning(message: &str) -> crate::Result<()> {
|
||||
#[cfg(feature = "tauri")]
|
||||
|
||||
@@ -142,6 +142,12 @@ pub enum LoadingBarType {
|
||||
instance_id: String,
|
||||
instance_name: String,
|
||||
error: Option<String>,
|
||||
#[serde(default)]
|
||||
state: crate::api::pack::hosted::HostedTaskState,
|
||||
#[serde(default)]
|
||||
can_pause: bool,
|
||||
#[serde(default)]
|
||||
can_cancel: bool,
|
||||
},
|
||||
HostedModDownload {
|
||||
instance_id: String,
|
||||
|
||||
@@ -171,8 +171,8 @@ impl DirectoryInfo {
|
||||
|
||||
/// Gets the directory of a managed dedicated server by id
|
||||
#[inline]
|
||||
pub fn server_dir(&self, server_id: &str) -> PathBuf {
|
||||
self.servers_dir().join(server_id)
|
||||
pub fn server_dir(&self, server_id: &str) -> crate::Result<PathBuf> {
|
||||
crate::util::io::safe_relative_join(&self.servers_dir(), server_id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -708,6 +708,28 @@ mod resolve_game_dir_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_directory_rejects_absolute_and_windows_alias_paths() {
|
||||
let dirs = dirs();
|
||||
assert_eq!(
|
||||
dirs.server_dir("server-1234").unwrap(),
|
||||
dirs.servers_dir().join("server-1234")
|
||||
);
|
||||
for id in [
|
||||
"../outside",
|
||||
"C:outside",
|
||||
"C:/outside",
|
||||
r"\outside",
|
||||
r"\\server\share",
|
||||
".",
|
||||
"NUL",
|
||||
"server:stream",
|
||||
"server.",
|
||||
] {
|
||||
assert!(dirs.server_dir(id).is_err(), "{id:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn override_used_when_set_and_absolute() {
|
||||
let dirs = dirs();
|
||||
|
||||
@@ -689,6 +689,46 @@ fn bounded_diagnostic_text(value: impl AsRef<str>, max_chars: usize) -> String {
|
||||
value.as_ref().chars().take(max_chars).collect()
|
||||
}
|
||||
|
||||
fn sanitize_download_error_text(value: &str) -> String {
|
||||
static URLS: LazyLock<regex::Regex> = LazyLock::new(|| {
|
||||
regex::Regex::new(r"(?i)\b(?:https?|socks4a?|socks5h?)://[^\s]+")
|
||||
.expect("download diagnostic URL pattern should be valid")
|
||||
});
|
||||
let sanitized = URLS.replace_all(value, |matched: ®ex::Captures<'_>| {
|
||||
let url = &matched[0];
|
||||
// A malformed URL must not fall back to logging its userinfo. The
|
||||
// normal helper also strips signed query strings and fragments.
|
||||
if Url::parse(url).is_ok() {
|
||||
sanitize_url_for_log(url)
|
||||
} else {
|
||||
"[redacted URL]".to_string()
|
||||
}
|
||||
});
|
||||
bounded_diagnostic_text(sanitized, 256)
|
||||
}
|
||||
|
||||
fn download_transport_error_detail(source: &reqwest::Error) -> String {
|
||||
// reqwest's Display stops before the useful DNS/TLS/socket cause and can
|
||||
// include a signed request URL. Walk only its underlying causes instead.
|
||||
let mut details = Vec::new();
|
||||
let mut cause = source.source();
|
||||
while let Some(error) = cause {
|
||||
let detail = sanitize_download_error_text(&error.to_string());
|
||||
if details.last() != Some(&detail) {
|
||||
details.push(detail);
|
||||
}
|
||||
if details.len() == 8 {
|
||||
break;
|
||||
}
|
||||
cause = error.source();
|
||||
}
|
||||
if details.is_empty() {
|
||||
sanitize_download_error_text(&source.to_string())
|
||||
} else {
|
||||
bounded_diagnostic_text(details.join(": "), 256)
|
||||
}
|
||||
}
|
||||
|
||||
fn download_error_category(error: &crate::Error) -> &'static str {
|
||||
match error.raw.as_ref() {
|
||||
ErrorKind::FetchError(source) => {
|
||||
@@ -750,7 +790,16 @@ fn download_error_category(error: &crate::Error) -> &'static str {
|
||||
fn download_error_detail(error: &crate::Error) -> String {
|
||||
match error.raw.as_ref() {
|
||||
ErrorKind::FetchError(source) => source.status().map_or_else(
|
||||
|| format!("{} failure", download_error_category(error)),
|
||||
|| {
|
||||
bounded_diagnostic_text(
|
||||
format!(
|
||||
"{} failure: {}",
|
||||
download_error_category(error),
|
||||
download_transport_error_detail(source)
|
||||
),
|
||||
256,
|
||||
)
|
||||
},
|
||||
|status| format!("HTTP {}", status.as_u16()),
|
||||
),
|
||||
ErrorKind::LabrinthError(error) => error.status.map_or_else(
|
||||
@@ -929,8 +978,10 @@ fn add_starlight_direct_recovery_route(routes: &mut Vec<DownloadRoute>) {
|
||||
.filter(|route| {
|
||||
route.proxy == ProxyPolicy::System
|
||||
&& Url::parse(&route.url).ok().is_some_and(|url| {
|
||||
url.host_str() == Some("skin.starlight.cool")
|
||||
&& url.path().starts_with("/starlight/mod/packs/files/")
|
||||
matches!(
|
||||
url.host_str(),
|
||||
Some("skin.starlight.cool" | "download.starlight.cool")
|
||||
) && url.path().starts_with("/starlight/mod/packs/files/")
|
||||
})
|
||||
})
|
||||
.cloned()
|
||||
@@ -6308,7 +6359,9 @@ async fn download_to_path_inner(
|
||||
source = route.source.as_str(),
|
||||
attempt = attempts,
|
||||
max_attempts = file_attempt_budget,
|
||||
error = %error,
|
||||
proxy = ?route.proxy,
|
||||
category = download_error_category(&error),
|
||||
error = %download_error_detail(&error),
|
||||
"File download request failed; trying the next source or retry"
|
||||
);
|
||||
last_error = Some(error);
|
||||
@@ -8857,18 +8910,86 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn starlight_hosted_files_have_a_direct_recovery_route() {
|
||||
let mut routes = vec![official_route(
|
||||
for url in [
|
||||
"https://skin.starlight.cool/starlight/mod/packs/files/release/hash",
|
||||
ResourceClass::Modpack,
|
||||
)];
|
||||
"https://download.starlight.cool:20443/starlight/mod/packs/files/4/hash",
|
||||
] {
|
||||
let mut routes = vec![official_route(url, ResourceClass::Modpack)];
|
||||
add_starlight_direct_recovery_route(&mut routes);
|
||||
add_starlight_direct_recovery_route(&mut routes);
|
||||
|
||||
add_starlight_direct_recovery_route(&mut routes);
|
||||
assert_eq!(routes.len(), 2, "{url}");
|
||||
assert_eq!(routes[0].proxy, ProxyPolicy::System);
|
||||
assert_eq!(routes[1].proxy, ProxyPolicy::Direct);
|
||||
assert_eq!(routes[0].url, routes[1].url);
|
||||
assert!(routes[1].allow_sensitive_headers);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(routes.len(), 2);
|
||||
assert_eq!(routes[0].proxy, ProxyPolicy::System);
|
||||
assert_eq!(routes[1].proxy, ProxyPolicy::Direct);
|
||||
assert_eq!(routes[0].url, routes[1].url);
|
||||
assert!(routes[1].allow_sensitive_headers);
|
||||
#[test]
|
||||
fn starlight_direct_recovery_excludes_other_paths_and_lookalike_hosts() {
|
||||
for url in [
|
||||
"https://download.starlight.cool:20443/starlight/mod/packs",
|
||||
"https://download.starlight.cool.evil.example/starlight/mod/packs/files/4/hash",
|
||||
"https://evil.example/starlight/mod/packs/files/4/hash",
|
||||
"https://skin.starlight.cool/yggdrasil",
|
||||
] {
|
||||
let mut routes = vec![official_route(url, ResourceClass::Modpack)];
|
||||
add_starlight_direct_recovery_route(&mut routes);
|
||||
assert_eq!(routes.len(), 1, "{url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_transport_diagnostic_preserves_causes_without_url_secrets()
|
||||
{
|
||||
let listener =
|
||||
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
let url = format!(
|
||||
"http://username:password@{address}/file?token=secret#fragment"
|
||||
);
|
||||
let error: crate::Error = reqwest::Client::builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap()
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.into();
|
||||
let detail = download_error_detail(&error);
|
||||
assert_eq!(download_error_category(&error), "connect");
|
||||
assert!(detail.contains("connect"), "{detail}");
|
||||
assert!(
|
||||
detail.contains("tcp") || detail.contains("os error"),
|
||||
"{detail}"
|
||||
);
|
||||
for secret in ["username", "password", "token", "secret", "fragment"] {
|
||||
assert!(!detail.contains(secret), "{detail}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_transport_diagnostic_scrubs_embedded_urls() {
|
||||
let detail = sanitize_download_error_text(
|
||||
"request https://username:password@example.com/file?token=secret#fragment failed: connecting to http://proxyuser:proxypass@proxy.example:8080/?key=proxysecret: connection refused",
|
||||
);
|
||||
assert!(detail.contains("https://example.com/file"), "{detail}");
|
||||
assert!(detail.contains("http://proxy.example:8080/"), "{detail}");
|
||||
assert!(detail.contains("connection refused"), "{detail}");
|
||||
for secret in [
|
||||
"username",
|
||||
"password",
|
||||
"token",
|
||||
"secret",
|
||||
"fragment",
|
||||
"proxyuser",
|
||||
"proxypass",
|
||||
] {
|
||||
assert!(!detail.contains(secret), "{detail}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -60,6 +60,34 @@ pub(crate) fn io_error_with_lock_info(
|
||||
io_error_with_lock_info_for_paths(source, path, &[path])
|
||||
}
|
||||
|
||||
/// Joins an untrusted Unix-style relative file path, rejecting traversal and
|
||||
/// Windows aliases on every platform. This is a lexical check, not a symlink
|
||||
/// sandbox.
|
||||
pub(crate) fn safe_relative_join(
|
||||
root: &Path,
|
||||
relative: &str,
|
||||
) -> crate::Result<PathBuf> {
|
||||
path_util::SafeRelativeUtf8UnixPathBuf::try_from(relative.to_string())
|
||||
.map_err(|error| {
|
||||
crate::ErrorKind::InputError(format!(
|
||||
"Invalid file path {relative}: {error}"
|
||||
))
|
||||
})?;
|
||||
if relative.split('/').any(|segment| {
|
||||
segment.is_empty()
|
||||
|| segment == "."
|
||||
|| segment.ends_with(['.', ' '])
|
||||
|| segment.contains(':')
|
||||
|| segment.chars().any(char::is_control)
|
||||
}) {
|
||||
return Err(crate::ErrorKind::InputError(format!(
|
||||
"Invalid file path: {relative}"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
Ok(root.join(relative))
|
||||
}
|
||||
|
||||
/// Join a user-provided relative path onto `root`, rejecting traversal.
|
||||
pub(crate) fn join_within_root(
|
||||
root: &Path,
|
||||
@@ -95,7 +123,7 @@ pub(crate) fn join_within_root(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(root.join(safe))
|
||||
safe_relative_join(root, &safe.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
pub(crate) fn io_error_with_lock_info_for_paths(
|
||||
@@ -895,6 +923,39 @@ mod windows_sharing_violation_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod path_join_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn join_within_root_uses_portable_path_validation() {
|
||||
let root = Path::new("root");
|
||||
assert_eq!(
|
||||
join_within_root(root, r"config\example.toml").unwrap(),
|
||||
root.join("config/example.toml")
|
||||
);
|
||||
assert_eq!(
|
||||
join_within_root(root, "./config/./example.toml").unwrap(),
|
||||
root.join("config/example.toml")
|
||||
);
|
||||
for relative in [
|
||||
"../outside",
|
||||
r"..\outside",
|
||||
"/outside",
|
||||
"C:/outside",
|
||||
"C:outside",
|
||||
r"\\server\share",
|
||||
"config/.. /outside",
|
||||
"config/file:stream",
|
||||
"config/NUL",
|
||||
"config/file.",
|
||||
"config/file\0",
|
||||
] {
|
||||
assert!(join_within_root(root, relative).is_err(), "{relative:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod copy_dir_tests {
|
||||
use super::*;
|
||||
|
||||
Generated
+8
@@ -188,6 +188,9 @@ importers:
|
||||
vuedraggable:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0(vue@3.5.27(typescript@5.9.3))
|
||||
xxhash-wasm:
|
||||
specifier: 1.1.0
|
||||
version: 1.1.0
|
||||
devDependencies:
|
||||
'@eslint/compat':
|
||||
specifier: ^1.1.1
|
||||
@@ -7103,6 +7106,9 @@ packages:
|
||||
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
|
||||
engines: {node: '>=0.4'}
|
||||
|
||||
xxhash-wasm@1.1.0:
|
||||
resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==}
|
||||
|
||||
y18n@5.0.8:
|
||||
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -14160,6 +14166,8 @@ snapshots:
|
||||
|
||||
xtend@4.0.2: {}
|
||||
|
||||
xxhash-wasm@1.1.0: {}
|
||||
|
||||
y18n@5.0.8: {}
|
||||
|
||||
yallist@3.1.1: {}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { parse, TYPE } from '@formatjs/icu-messageformat-parser'
|
||||
import { collectSkinSiteMessages } from './skin-site-messages.mjs'
|
||||
|
||||
const localePairs = [
|
||||
[
|
||||
@@ -10,6 +11,22 @@ const localePairs = [
|
||||
]
|
||||
|
||||
const failures = []
|
||||
const skinSiteCatalogs = Object.fromEntries(
|
||||
await Promise.all(
|
||||
['en-US', 'zh-CN'].map(async (locale) => [
|
||||
locale,
|
||||
JSON.parse(await readFile(`apps/app-frontend/src/locales/${locale}/index.json`, 'utf8')),
|
||||
]),
|
||||
),
|
||||
)
|
||||
for (const { id, file } of collectSkinSiteMessages()) {
|
||||
for (const locale of ['en-US', 'zh-CN']) {
|
||||
const catalogPath = `apps/app-frontend/src/locales/${locale}/index.json`
|
||||
const catalog = skinSiteCatalogs[locale]
|
||||
if (!catalog[id]?.message)
|
||||
failures.push(`${catalogPath}: missing source message ${id} (${file})`)
|
||||
}
|
||||
}
|
||||
const allowedUntranslatedMessages = new Set([
|
||||
'Chaos Cubed',
|
||||
'MINECON Earth 2017',
|
||||
@@ -31,8 +48,11 @@ const allowedUntranslatedMessages = new Set([
|
||||
'LiteLoader',
|
||||
'LogShare.CN',
|
||||
'UUID',
|
||||
'ID',
|
||||
'QQ',
|
||||
'IP',
|
||||
'URL',
|
||||
'Mod ID',
|
||||
'LogShare AI',
|
||||
'NeoForge',
|
||||
'OptiFine',
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { open, stat } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
export async function publishSkinSite({
|
||||
archivePath,
|
||||
tag,
|
||||
token,
|
||||
baseUrl = 'https://skin.starlight.cool',
|
||||
fetchImpl = fetch,
|
||||
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
now = Date.now,
|
||||
timeoutMs = 30 * 60 * 1000,
|
||||
pollIntervalMs = 2000,
|
||||
log = console.log,
|
||||
}) {
|
||||
if (!token) throw new Error('SKIN_SITE_CI_UPLOAD_TOKEN is required to publish to the skin site')
|
||||
if (!archivePath || !/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(tag ?? '')) {
|
||||
throw new Error('Expected a complete update ZIP and a semantic version tag')
|
||||
}
|
||||
const version = tag.replace(/^v/, '')
|
||||
const url = new URL(baseUrl)
|
||||
if (url.protocol !== 'https:' || url.username || url.password) {
|
||||
throw new Error('SKIN_SITE_URL must be an HTTPS URL without credentials')
|
||||
}
|
||||
const { size } = await stat(archivePath)
|
||||
if (!archivePath.toLowerCase().endsWith('.zip') || size < 1 || size > 4 * 1024 ** 3) {
|
||||
throw new Error('Expected a nonempty complete update ZIP no larger than 4 GiB')
|
||||
}
|
||||
const deadline = now() + timeoutMs
|
||||
function remainingTime() {
|
||||
const remaining = deadline - now()
|
||||
if (remaining <= 0) throw new Error('Skin site publication timed out')
|
||||
return remaining
|
||||
}
|
||||
async function request(route, { method = 'GET', body, chunk = false } = {}) {
|
||||
const attempts = chunk ? 3 : 1
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
const requestTimeout = Math.min(120_000, remainingTime())
|
||||
let response
|
||||
try {
|
||||
response = await fetchImpl(`${baseUrl.replace(/\/$/, '')}/starlight/${route}`, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(body && !chunk ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body && !chunk ? JSON.stringify(body) : body,
|
||||
signal: AbortSignal.timeout(requestTimeout),
|
||||
redirect: 'error',
|
||||
})
|
||||
} catch {
|
||||
if (attempt + 1 === attempts)
|
||||
throw new Error(`Skin site ${route}: network request failed or timed out`)
|
||||
await sleep(500 * (attempt + 1))
|
||||
continue
|
||||
}
|
||||
if (!response.ok) {
|
||||
const details = await response.json().catch(() => null)
|
||||
if ((response.status === 429 || response.status >= 500) && attempt + 1 < attempts) {
|
||||
await sleep(500 * (attempt + 1))
|
||||
continue
|
||||
}
|
||||
throw new Error(
|
||||
`Skin site ${route}: HTTP ${response.status}${typeof details?.errorMessage === 'string' ? ` - ${details.errorMessage.slice(0, 1000)}` : ''}`,
|
||||
)
|
||||
}
|
||||
let result
|
||||
try {
|
||||
result = await response.json()
|
||||
} catch {
|
||||
throw new Error(`Skin site ${route}: invalid JSON response`)
|
||||
}
|
||||
if (result?.success === false || result?.error || !result?.payload) {
|
||||
throw new Error(
|
||||
`Skin site ${route}: ${result?.errorMessage || 'request was rejected or payload is missing'}`,
|
||||
)
|
||||
}
|
||||
return result.payload
|
||||
}
|
||||
}
|
||||
|
||||
let status = await request('launcher/admin/uploads', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
uploadId: randomUUID(),
|
||||
filename: path.basename(archivePath),
|
||||
size,
|
||||
forceUpdate: false,
|
||||
},
|
||||
})
|
||||
if (typeof status.id !== 'string' || !status.id)
|
||||
throw new Error('Skin site returned an invalid upload ID')
|
||||
const uploadRoute = `launcher/admin/uploads/${encodeURIComponent(status.id)}`
|
||||
log(`Skin site upload ${status.id}: ${size} bytes`)
|
||||
const file = await open(archivePath, 'r')
|
||||
try {
|
||||
for (;;) {
|
||||
remainingTime()
|
||||
if (status.state === 'ready') {
|
||||
const release = status.release
|
||||
if (!Number.isSafeInteger(release?.id) || release.id <= 0 || release.version !== version) {
|
||||
throw new Error(
|
||||
`Skin site returned an invalid release or a version other than ${version}`,
|
||||
)
|
||||
}
|
||||
const activated = await request(`launcher/admin/${release.id}/activate`, { method: 'POST' })
|
||||
if (
|
||||
activated.id !== release.id ||
|
||||
activated.version !== version ||
|
||||
activated.active !== true
|
||||
) {
|
||||
throw new Error(`Skin site did not confirm activation of ${version}`)
|
||||
}
|
||||
log(`Skin site release ${version} published (id ${release.id})`)
|
||||
return activated
|
||||
}
|
||||
if (status.state === 'failed' || status.state === 'cancelled') {
|
||||
throw new Error(
|
||||
`Skin site archive processing ${status.state}: ${status.errorMessage || 'no error details'}`,
|
||||
)
|
||||
}
|
||||
if (status.state === 'processing') {
|
||||
await sleep(Math.min(pollIntervalMs, remainingTime()))
|
||||
status = await request(uploadRoute)
|
||||
continue
|
||||
}
|
||||
if (
|
||||
status.state !== 'uploading' ||
|
||||
status.size !== size ||
|
||||
!Number.isSafeInteger(status.chunkSize) ||
|
||||
status.chunkSize < 1 ||
|
||||
status.chunkSize > 64 * 1024 ** 2 ||
|
||||
!Number.isSafeInteger(status.received) ||
|
||||
status.received < 0 ||
|
||||
status.received > size ||
|
||||
!Array.isArray(status.receivedChunks)
|
||||
) {
|
||||
throw new Error('Skin site returned invalid upload status or chunk size')
|
||||
}
|
||||
const count = Math.ceil(size / status.chunkSize)
|
||||
if (
|
||||
status.receivedChunks.some(
|
||||
(index) => !Number.isSafeInteger(index) || index < 0 || index >= count,
|
||||
)
|
||||
) {
|
||||
throw new Error('Skin site returned invalid received chunk indices')
|
||||
}
|
||||
const received = new Set(status.receivedChunks)
|
||||
const missing = Array.from({ length: count }, (_, index) => index).filter(
|
||||
(index) => !received.has(index),
|
||||
)
|
||||
if (!missing.length) {
|
||||
if (status.received !== size)
|
||||
throw new Error('Skin site received byte count does not match the archive')
|
||||
status = await request(`${uploadRoute}/complete`, { method: 'POST' })
|
||||
continue
|
||||
}
|
||||
const chunkSize = status.chunkSize
|
||||
const concurrency = Math.min(
|
||||
Number.isSafeInteger(status.uploadConcurrency) && status.uploadConcurrency > 0
|
||||
? status.uploadConcurrency
|
||||
: 1,
|
||||
6,
|
||||
missing.length,
|
||||
)
|
||||
let cursor = 0
|
||||
let uploadError
|
||||
async function worker() {
|
||||
try {
|
||||
while (!uploadError && cursor < missing.length) {
|
||||
remainingTime()
|
||||
const index = missing[cursor++]
|
||||
const start = index * chunkSize
|
||||
const bytes = Buffer.alloc(Math.min(chunkSize, size - start))
|
||||
let offset = 0
|
||||
while (offset < bytes.length) {
|
||||
const { bytesRead } = await file.read(
|
||||
bytes,
|
||||
offset,
|
||||
bytes.length - offset,
|
||||
start + offset,
|
||||
)
|
||||
if (!bytesRead) throw new Error('Update archive changed or ended during upload')
|
||||
offset += bytesRead
|
||||
}
|
||||
const form = new FormData()
|
||||
form.append('file', new Blob([bytes]), 'chunk.bin')
|
||||
await request(`${uploadRoute}/chunks/${index}`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
chunk: true,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
uploadError ??= error
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: concurrency }, worker))
|
||||
if (uploadError) throw uploadError
|
||||
status = await request(uploadRoute)
|
||||
log(`Skin site uploaded ${status.received}/${size} bytes`)
|
||||
}
|
||||
} finally {
|
||||
await file.close()
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
|
||||
try {
|
||||
await publishSkinSite({
|
||||
archivePath: process.argv[2],
|
||||
tag: process.argv[3],
|
||||
token: process.env.SKIN_SITE_TOKEN,
|
||||
baseUrl: process.env.SKIN_SITE_URL || 'https://skin.starlight.cool',
|
||||
})
|
||||
} catch (error) {
|
||||
const message = String(error.message).replaceAll(
|
||||
process.env.SKIN_SITE_TOKEN || '\0',
|
||||
'[redacted]',
|
||||
)
|
||||
console.error(
|
||||
`::error::${message.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')}`,
|
||||
)
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, writeFile, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { publishSkinSite } from './publish-skin-site.mjs'
|
||||
|
||||
async function fixture(t) {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), 'skin-site-publish-'))
|
||||
t.after(() => rm(directory, { recursive: true, force: true }))
|
||||
const archivePath = path.join(directory, 'Starlight_Launcher_1.0.2-beta10_skin-site-update.zip')
|
||||
const bytes = Buffer.from('a small archive split into several chunks')
|
||||
await writeFile(archivePath, bytes)
|
||||
return { archivePath, bytes }
|
||||
}
|
||||
|
||||
function apiFixture(bytes, options = {}) {
|
||||
const chunks = new Map()
|
||||
const events = []
|
||||
const release = { id: 17, version: '1.0.2-beta10', active: false }
|
||||
let state = 'uploading'
|
||||
let failedOnce = false
|
||||
if (options.resume) chunks.set(0, bytes.subarray(0, 8))
|
||||
const status = () => ({
|
||||
id: 'session-1',
|
||||
chunkSize: 8,
|
||||
size: bytes.length,
|
||||
received: [...chunks.values()].reduce((total, part) => total + part.length, 0),
|
||||
receivedChunks: [...chunks.keys()],
|
||||
uploadConcurrency: 3,
|
||||
state,
|
||||
...(state === 'ready' ? { release } : {}),
|
||||
...(state === 'failed' ? { errorMessage: 'Invalid archive manifest' } : {}),
|
||||
})
|
||||
// The frontend derives success from HTTP status; the wire envelope only needs payload.
|
||||
const reply = (payload) => Response.json({ payload })
|
||||
return {
|
||||
chunks,
|
||||
events,
|
||||
fetch: async (url, init) => {
|
||||
assert.equal(init.headers.Authorization, 'Bearer test-token')
|
||||
const route = new URL(url).pathname.replace('/starlight/', '')
|
||||
events.push(route)
|
||||
if (route === 'launcher/admin/uploads') {
|
||||
assert.equal(JSON.parse(init.body).size, bytes.length)
|
||||
assert.equal(JSON.parse(init.body).forceUpdate, false)
|
||||
return reply({ ...status(), ...(options.invalidChunkSize ? { chunkSize: 0 } : {}) })
|
||||
}
|
||||
if (route.includes('/chunks/')) {
|
||||
if (options.rejectChunks) return new Response('too large', { status: 413 })
|
||||
if (options.retryChunk && !failedOnce) {
|
||||
failedOnce = true
|
||||
return new Response('temporary failure', { status: 503 })
|
||||
}
|
||||
const index = Number(route.split('/').at(-1))
|
||||
const file = init.body.get('file')
|
||||
assert.equal(file.name, 'chunk.bin')
|
||||
chunks.set(index, Buffer.from(await file.arrayBuffer()))
|
||||
return reply(status())
|
||||
}
|
||||
if (route.endsWith('/complete')) {
|
||||
assert.deepEqual(
|
||||
Buffer.concat([...chunks].sort(([a], [b]) => a - b).map(([, part]) => part)),
|
||||
bytes,
|
||||
)
|
||||
state = 'processing'
|
||||
return reply(status())
|
||||
}
|
||||
if (route.endsWith('/activate')) {
|
||||
assert.equal(state, 'ready')
|
||||
return options.activationFailure
|
||||
? Response.json({ success: false, errorMessage: 'Activation denied' })
|
||||
: reply({ ...release, active: true })
|
||||
}
|
||||
if (route === 'launcher/admin/uploads/session-1') {
|
||||
if (state === 'processing' && !options.stuck)
|
||||
state = options.processingFailure ? 'failed' : 'ready'
|
||||
return reply({
|
||||
...status(),
|
||||
...(options.wrongVersion && state === 'ready'
|
||||
? { release: { ...release, version: '1.0.2-beta9' } }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected route ${route}`)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function settings(archivePath, api) {
|
||||
return {
|
||||
archivePath,
|
||||
tag: 'v1.0.2-beta10',
|
||||
token: 'test-token',
|
||||
baseUrl: 'https://skin.example',
|
||||
fetchImpl: api.fetch,
|
||||
pollIntervalMs: 1,
|
||||
sleep: async () => {},
|
||||
log: () => {},
|
||||
}
|
||||
}
|
||||
|
||||
test('uploads exact bounded chunks, retries temporary errors, then completes and activates', async (t) => {
|
||||
const { archivePath, bytes } = await fixture(t)
|
||||
const api = apiFixture(bytes, { retryChunk: true })
|
||||
const result = await publishSkinSite(settings(archivePath, api))
|
||||
assert.equal(result.active, true)
|
||||
assert.equal(api.chunks.size, Math.ceil(bytes.length / 8))
|
||||
assert.ok([...api.chunks.values()].every((part) => part.length <= 8))
|
||||
assert.equal(api.events.at(-1), 'launcher/admin/17/activate')
|
||||
})
|
||||
|
||||
for (const [name, options, error] of [
|
||||
['HTTP upload rejection', { rejectChunks: true }, /413/],
|
||||
['archive processing failure', { processingFailure: true }, /Invalid archive manifest/],
|
||||
['application-level activation failure', { activationFailure: true }, /Activation denied/],
|
||||
['invalid server chunk size', { invalidChunkSize: true }, /invalid upload status/],
|
||||
['mismatched release version', { wrongVersion: true }, /version other than/],
|
||||
]) {
|
||||
test(`fails explicitly on ${name}`, async (t) => {
|
||||
const { archivePath, bytes } = await fixture(t)
|
||||
const api = apiFixture(bytes, options)
|
||||
await assert.rejects(publishSkinSite(settings(archivePath, api)), error)
|
||||
if (!options.activationFailure)
|
||||
assert.ok(!api.events.some((event) => event.endsWith('/activate')))
|
||||
})
|
||||
}
|
||||
|
||||
test('fails instead of hanging when processing never finishes', async (t) => {
|
||||
const { archivePath, bytes } = await fixture(t)
|
||||
const api = apiFixture(bytes, { stuck: true })
|
||||
let now = 0
|
||||
await assert.rejects(
|
||||
publishSkinSite({
|
||||
...settings(archivePath, api),
|
||||
timeoutMs: 10,
|
||||
now: () => now,
|
||||
sleep: async () => {
|
||||
now += 5
|
||||
},
|
||||
}),
|
||||
/timed out/i,
|
||||
)
|
||||
})
|
||||
|
||||
test('missing credentials fail before any network request', async (t) => {
|
||||
const { archivePath } = await fixture(t)
|
||||
await assert.rejects(
|
||||
publishSkinSite({
|
||||
...settings(archivePath, { fetch: () => assert.fail('Unexpected network request') }),
|
||||
token: '',
|
||||
}),
|
||||
/SKIN_SITE_CI_UPLOAD_TOKEN/,
|
||||
)
|
||||
})
|
||||
|
||||
test('resumes server-acknowledged chunks without uploading them again', async (t) => {
|
||||
const { archivePath, bytes } = await fixture(t)
|
||||
const api = apiFixture(bytes, { resume: true })
|
||||
await publishSkinSite(settings(archivePath, api))
|
||||
assert.ok(!api.events.some((event) => event.endsWith('/chunks/0')))
|
||||
})
|
||||
|
||||
test('CLI emits a GitHub error and exits nonzero when credentials are missing', () => {
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
['scripts/axolotl/publish-skin-site.mjs', 'missing.zip', 'v1.0.2-beta10'],
|
||||
{ encoding: 'utf8', env: { ...process.env, SKIN_SITE_TOKEN: '' } },
|
||||
)
|
||||
assert.equal(result.status, 1)
|
||||
assert.match(result.stderr, /::error::.*SKIN_SITE_CI_UPLOAD_TOKEN/)
|
||||
})
|
||||
|
||||
test('reports structured server errors when creating the upload session fails', async (t) => {
|
||||
const { archivePath } = await fixture(t)
|
||||
await assert.rejects(
|
||||
publishSkinSite(
|
||||
settings(archivePath, {
|
||||
fetch: async () =>
|
||||
Response.json({ errorMessage: 'Upload storage unavailable' }, { status: 500 }),
|
||||
}),
|
||||
),
|
||||
/HTTP 500 - Upload storage unavailable/,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
import { collectSkinSiteMessages } from './skin-site-messages.mjs'
|
||||
|
||||
test('all skin-site messages used in source exist in both release language catalogs', () => {
|
||||
const messages = collectSkinSiteMessages()
|
||||
assert.ok(messages.length > 100, 'The check must scan the actual UI')
|
||||
for (const locale of ['en-US', 'zh-CN']) {
|
||||
const catalog = JSON.parse(
|
||||
fs.readFileSync(`apps/app-frontend/src/locales/${locale}/index.json`, 'utf8'),
|
||||
)
|
||||
const missing = messages.filter(({ id }) => !catalog[id]?.message)
|
||||
assert.deepEqual(
|
||||
missing.map(({ id }) => id),
|
||||
[],
|
||||
`${locale} has uncatalogued UI messages`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('Chinese login and announcement labels do not fall back to English', () => {
|
||||
const catalog = JSON.parse(
|
||||
fs.readFileSync('apps/app-frontend/src/locales/zh-CN/index.json', 'utf8'),
|
||||
)
|
||||
for (const id of [
|
||||
'app.skin-site.login.title',
|
||||
'app.skin-site.login.username',
|
||||
'app.skin-site.login.password-hint',
|
||||
'app.skin-site.home.announcements.title',
|
||||
'app.skin-site.home.announcements.failed',
|
||||
]) {
|
||||
assert.match(catalog[id]?.message ?? '', /\p{Script=Han}/u, id)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(new URL('../../apps/app-frontend/package.json', import.meta.url))
|
||||
const ts = require('typescript')
|
||||
const { parse } = require('vue/compiler-sfc')
|
||||
|
||||
/** Read the message IDs actually used by skin-site UI, including uncatalogued messages. */
|
||||
export function collectSkinSiteMessages(root = 'apps/app-frontend/src') {
|
||||
const messages = new Map()
|
||||
function walk(directory) {
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const file = path.join(directory, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
if (entry.name !== 'locales') walk(file)
|
||||
continue
|
||||
}
|
||||
if (!/\.(vue|ts)$/.test(file) || file.endsWith('.test.ts')) continue
|
||||
let source = fs.readFileSync(file, 'utf8')
|
||||
if (file.endsWith('.vue')) {
|
||||
const { descriptor } = parse(source)
|
||||
source = [descriptor.script?.content, descriptor.scriptSetup?.content]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
}
|
||||
const ast = ts.createSourceFile(`${file}.ts`, source, ts.ScriptTarget.Latest, true)
|
||||
function visit(node) {
|
||||
if (ts.isObjectLiteralExpression(node)) {
|
||||
const properties = Object.fromEntries(
|
||||
node.properties
|
||||
.filter(ts.isPropertyAssignment)
|
||||
.map((property) => [
|
||||
property.name.getText(ast).replace(/^['"]|['"]$/g, ''),
|
||||
property.initializer,
|
||||
]),
|
||||
)
|
||||
if (
|
||||
properties.id &&
|
||||
properties.defaultMessage &&
|
||||
ts.isStringLiteralLike(properties.id) &&
|
||||
ts.isStringLiteralLike(properties.defaultMessage) &&
|
||||
properties.id.text.startsWith('app.skin-site.')
|
||||
) {
|
||||
messages.set(properties.id.text, {
|
||||
id: properties.id.text,
|
||||
defaultMessage: properties.defaultMessage.text,
|
||||
file,
|
||||
})
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(ast)
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
return [...messages.values()]
|
||||
}
|
||||
Reference in new issue
Block a user