Restore PROMPT branding, rename waterfall-wiki, and add system tag workflows
This commit is contained in:
@@ -5,11 +5,11 @@ command=${1:-qr}
|
||||
cd /opt/prompt/current
|
||||
compose(){ env -u AUTH_CONFIG_FILE -u AUTH_COOKIE_SECURE docker compose -p prompt --env-file /etc/prompt.env --env-file release.env -f compose.yml "$@"; }
|
||||
case "$command" in
|
||||
qr|token) compose exec web node auth-cli.cjs "$command" ;;
|
||||
qr|token) compose exec waterfall-wiki node auth-cli.cjs "$command" ;;
|
||||
rotate)
|
||||
if [ "${2:-}" != "--confirm" ]; then echo 'This invalidates all bound authenticators and JWT sessions. Use: auth rotate --confirm'; exit 1; fi
|
||||
compose run --rm --no-deps auth-admin node auth-cli.cjs rotate --confirm
|
||||
echo 'Rotation complete. Run auth qr to bind again.' ;;
|
||||
verify) compose exec -T web node auth-cli.cjs verify ;;
|
||||
verify) compose exec -T waterfall-wiki node auth-cli.cjs verify ;;
|
||||
*) echo 'Usage: auth [qr | token | verify | rotate --confirm]'; exit 1 ;;
|
||||
esac
|
||||
|
||||
@@ -12,7 +12,7 @@ if [ "$latest" != "$sha" ]; then
|
||||
fi
|
||||
mkdir -p /opt/prompt-studio
|
||||
previous=$(cat /opt/prompt-studio/image 2>/dev/null || true)
|
||||
write_compose(){ printf 'services:\n studio:\n image: %s\n restart: unless-stopped\n ports: ["127.0.0.1:18134:3000"]\n networks:\n wiki:\n aliases: [prompt-studio]\nnetworks:\n wiki:\n external: true\n name: prompt_default\n' "$1" > /opt/prompt-studio/compose.yml; }
|
||||
write_compose(){ printf 'services:\n studio:\n image: %s\n restart: unless-stopped\n ports: ["127.0.0.1:18134:3000"]\n networks:\n waterfall-wiki:\n aliases: [prompt-studio]\nnetworks:\n waterfall-wiki:\n external: true\n name: prompt_default\n' "$1" > /opt/prompt-studio/compose.yml; }
|
||||
write_compose "prompt-studio:$sha"
|
||||
rollback(){ if [ -n "$previous" ]; then write_compose "$previous"; docker compose -p prompt-studio -f /opt/prompt-studio/compose.yml up -d; fi; }
|
||||
trap rollback ERR
|
||||
|
||||
+22
-16
@@ -3,7 +3,7 @@ set -Eeuo pipefail
|
||||
if [ "$(id -u)" -ne 0 ]; then exec sudo -n bash "$0" "$@"; fi
|
||||
RELEASE_SHA="${1:?Release SHA is required}"
|
||||
[[ "$RELEASE_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo 'Invalid release SHA'; exit 1; }
|
||||
IMAGE="prompt:$RELEASE_SHA"
|
||||
IMAGE="waterfall-wiki:$RELEASE_SHA"
|
||||
APP_ROOT=/opt/prompt
|
||||
RELEASE_DIR="$APP_ROOT/releases/$RELEASE_SHA"
|
||||
PORT=18131
|
||||
@@ -17,17 +17,22 @@ test "$(git -c safe.directory="$PWD" rev-parse HEAD)" = "$RELEASE_SHA"
|
||||
LATEST_MAIN=$(git -c safe.directory="$PWD" ls-remote origin refs/heads/main | cut -f1)
|
||||
if [ "$LATEST_MAIN" != "$RELEASE_SHA" ]; then
|
||||
git -c safe.directory="$PWD" fetch origin main
|
||||
if ! git -c safe.directory="$PWD" diff --quiet "$RELEASE_SHA" origin/main -- apps/wiki Dockerfile compose.yml scripts/deploy.sh scripts/infra.sh scripts/integration.sh scripts/auth-admin.sh .gitea/workflows/wiki.yml pnpm-workspace.yaml; then
|
||||
if ! git -c safe.directory="$PWD" diff --quiet "$RELEASE_SHA" origin/main -- apps/waterfall-wiki Dockerfile compose.yml scripts/deploy.sh scripts/infra.sh scripts/integration.sh scripts/auth-admin.sh .gitea/workflows/waterfall-wiki.yml pnpm-workspace.yaml; then
|
||||
echo 'Skipping deployment: Wiki has a newer commit'; exit 0
|
||||
fi
|
||||
fi
|
||||
PREVIOUS=""
|
||||
PREVIOUS_WEB=web
|
||||
PREVIOUS_WORKER=worker
|
||||
if [ -L "$APP_ROOT/current" ] && [ -d "$APP_ROOT/current" ]; then PREVIOUS=$(readlink -f "$APP_ROOT/current"); fi
|
||||
if [ -n "$PREVIOUS" ] && grep -q '^ waterfall-wiki:' "$PREVIOUS/compose.yml"; then
|
||||
PREVIOUS_WEB=waterfall-wiki; PREVIOUS_WORKER=waterfall-wiki-worker
|
||||
fi
|
||||
bash scripts/infra.sh "$IMAGE"
|
||||
mkdir -p "$RELEASE_DIR"
|
||||
install -m 0644 compose.yml "$RELEASE_DIR/compose.yml"
|
||||
printf 'PROMPT_IMAGE=%s\nRELEASE_SHA=%s\nWEB_PORT=%s\nAUTH_CONFIG_FILE=/auth/config.json\n' "$IMAGE" "$RELEASE_SHA" "$PORT" > "$RELEASE_DIR/release.env"
|
||||
compose_at(){ local release="$1"; shift; env -u AUTH_CONFIG_FILE -u AUTH_COOKIE_SECURE -u PROMPT_IMAGE -u PROMPT_TEST_IMAGE -u RELEASE_SHA -u WEB_PORT -u WEB_BIND_ADDRESS docker compose -p prompt --env-file /etc/prompt.env --env-file "$release/release.env" -f "$release/compose.yml" "$@"; }
|
||||
printf 'WATERFALL_WIKI_IMAGE=%s\nRELEASE_SHA=%s\nWEB_PORT=%s\nAUTH_CONFIG_FILE=/auth/config.json\n' "$IMAGE" "$RELEASE_SHA" "$PORT" > "$RELEASE_DIR/release.env"
|
||||
compose_at(){ local release="$1"; shift; env -u PROMPT_IMAGE -u PROMPT_TEST_IMAGE -u AUTH_CONFIG_FILE -u AUTH_COOKIE_SECURE -u WATERFALL_WIKI_IMAGE -u WATERFALL_WIKI_TEST_IMAGE -u RELEASE_SHA -u WEB_PORT -u WEB_BIND_ADDRESS docker compose -p prompt --env-file /etc/prompt.env --env-file "$release/release.env" -f "$release/compose.yml" "$@"; }
|
||||
compose(){ compose_at "$RELEASE_DIR" "$@"; }
|
||||
LEGACY_WEB=0
|
||||
LEGACY_WORKER=0
|
||||
@@ -47,7 +52,7 @@ rollback(){
|
||||
trap - ERR
|
||||
set +e
|
||||
if [ "$CUTOVER" -eq 1 ]; then
|
||||
compose stop web worker
|
||||
compose stop waterfall-wiki waterfall-wiki-worker
|
||||
if [ "$MIGRATION_STARTED" -eq 1 ] && [ -s "$BACKUP_FILE" ]; then
|
||||
if ! compose exec -T postgres pg_restore -U prompt -d prompt --clean --if-exists --exit-on-error < "$BACKUP_FILE"; then
|
||||
echo 'Database rollback failed; application remains stopped. Backup retained.'
|
||||
@@ -56,11 +61,11 @@ rollback(){
|
||||
echo 'Restored the database backup compatible with the previous application'
|
||||
fi
|
||||
if [ -n "$PREVIOUS" ] && [ -f "$PREVIOUS/compose.yml" ]; then
|
||||
compose_at "$PREVIOUS" up -d --no-build web worker
|
||||
compose_at "$PREVIOUS" up -d --no-build "$PREVIOUS_WEB" "$PREVIOUS_WORKER"
|
||||
echo 'Restored the previous Docker application image'
|
||||
else
|
||||
compose stop web worker
|
||||
compose rm -f web worker
|
||||
compose stop waterfall-wiki waterfall-wiki-worker
|
||||
compose rm -f waterfall-wiki waterfall-wiki-worker
|
||||
if [ "$LEGACY_WORKER_ENABLED" -eq 1 ]; then systemctl enable prompt-worker.service; fi
|
||||
if [ "$LEGACY_WEB_ENABLED" -eq 1 ]; then systemctl enable prompt.service; fi
|
||||
if [ "$LEGACY_WEB" -eq 1 ]; then systemctl start prompt.service; fi
|
||||
@@ -80,7 +85,8 @@ trap rollback ERR
|
||||
compose up -d --no-build --wait --wait-timeout 120 postgres objects
|
||||
install -d -o root -g root -m 0700 /var/lib/prompt/backups
|
||||
CUTOVER=1
|
||||
compose stop web worker
|
||||
compose stop waterfall-wiki waterfall-wiki-worker
|
||||
if [ -n "$PREVIOUS" ]; then compose_at "$PREVIOUS" stop "$PREVIOUS_WEB" "$PREVIOUS_WORKER"; fi
|
||||
BACKUP_FILE="/var/lib/prompt/backups/$(date -u +%Y%m%dT%H%M%S)-$RELEASE_SHA.dump"
|
||||
compose exec -T postgres pg_dump -U prompt -d prompt -Fc > "$BACKUP_FILE"
|
||||
find /var/lib/prompt/backups -name '*.dump' -printf '%T@ %p\n' | sort -rn | tail -n +11 | cut -d' ' -f2- | xargs -r rm --
|
||||
@@ -92,13 +98,13 @@ CUTOVER=1
|
||||
# One-time migration: finish a current host worker job before switching the web port.
|
||||
if [ "$LEGACY_WORKER" -eq 1 ] || [ "$LEGACY_WORKER_ENABLED" -eq 1 ]; then systemctl disable --now prompt-worker.service; fi
|
||||
if [ "$LEGACY_WEB" -eq 1 ] || [ "$LEGACY_WEB_ENABLED" -eq 1 ]; then systemctl disable --now prompt.service; fi
|
||||
compose up -d --no-build --wait --wait-timeout 180 web worker
|
||||
compose exec -T web node container-health.mjs
|
||||
compose exec -T web node auth-cli.cjs verify
|
||||
compose exec -T web node auth-cli.cjs run scripts/import-character-packs.mjs
|
||||
compose exec -T worker sh -c 'test "$(id -u)" -ne 0 && ffmpeg -version >/dev/null'
|
||||
compose up -d --no-build --wait --wait-timeout 180 waterfall-wiki waterfall-wiki-worker
|
||||
compose exec -T waterfall-wiki node container-health.mjs
|
||||
compose exec -T waterfall-wiki node auth-cli.cjs verify
|
||||
compose exec -T waterfall-wiki node auth-cli.cjs run scripts/import-character-packs.mjs
|
||||
compose exec -T waterfall-wiki-worker sh -c 'test "$(id -u)" -ne 0 && ffmpeg -version >/dev/null'
|
||||
# Editorial posts may be older than the first 24 entries. Verify the complete paged feed.
|
||||
compose exec -T web sh -c 'cat > /tmp/prompt-release-check.mjs && node auth-cli.cjs run /tmp/prompt-release-check.mjs' <<'NODE'
|
||||
compose exec -T waterfall-wiki sh -c 'cat > /tmp/prompt-release-check.mjs && node auth-cli.cjs run /tmp/prompt-release-check.mjs' <<'NODE'
|
||||
(async()=>{
|
||||
const slugs=['learning-skills-notes','learning-skills-teaching','learning-skills-english'];
|
||||
const missing=new Set(slugs),seen=new Set();let cursor='';
|
||||
@@ -121,7 +127,7 @@ ln -sfn "$RELEASE_DIR" "$APP_ROOT/.current.next"
|
||||
mv -Tf "$APP_ROOT/.current.next" "$APP_ROOT/current"
|
||||
install -m 0755 scripts/auth-admin.sh "$APP_ROOT/auth"
|
||||
compose ps
|
||||
for service in web worker postgres objects; do
|
||||
for service in waterfall-wiki waterfall-wiki-worker postgres objects; do
|
||||
id=$(compose ps -q "$service")
|
||||
docker inspect --format '{{.Name}} running={{.State.Running}} restart={{.HostConfig.RestartPolicy.Name}}' "$id"
|
||||
done
|
||||
|
||||
+12
-12
@@ -1,29 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
: "${PROMPT_IMAGE:?Build the runtime image first}"
|
||||
: "${PROMPT_TEST_IMAGE:?Build the integration image first}"
|
||||
: "${WATERFALL_WIKI_IMAGE:?Build the runtime image first}"
|
||||
: "${WATERFALL_WIKI_TEST_IMAGE:?Build the integration image first}"
|
||||
export COMPOSE_PROJECT_NAME="prompt-ci-${GITEA_RUN_ID:-$$}"
|
||||
export PG_PORT=0 S3_PORT=0 WEB_PORT=0 WEB_BIND_ADDRESS=127.0.0.1
|
||||
TEST_ENV=$(mktemp)
|
||||
chmod 0600 "$TEST_ENV"
|
||||
compose(){ docker compose -p "$COMPOSE_PROJECT_NAME" --env-file "$TEST_ENV" -f compose.yml "$@"; }
|
||||
cleanup(){ code=$?; if [ "$code" -ne 0 ]; then compose logs --tail 160 web worker; fi; compose down -v --remove-orphans; rm -f "$TEST_ENV"; }
|
||||
cleanup(){ code=$?; if [ "$code" -ne 0 ]; then compose logs --tail 160 waterfall-wiki waterfall-wiki-worker; fi; compose down -v --remove-orphans; rm -f "$TEST_ENV"; }
|
||||
trap cleanup EXIT
|
||||
# Random credentials exist only for this disposable stack; no host Node required.
|
||||
docker run --rm --entrypoint node "$PROMPT_IMAGE" -e "const c=require('crypto');const hex=()=>c.randomBytes(24).toString('hex');console.log('POSTGRES_PASSWORD='+hex()+'\nS3_ACCESS_KEY='+hex()+'\nS3_SECRET_KEY='+hex())" > "$TEST_ENV"
|
||||
docker run --rm --entrypoint node "$WATERFALL_WIKI_IMAGE" -e "const c=require('crypto');const hex=()=>c.randomBytes(24).toString('hex');console.log('POSTGRES_PASSWORD='+hex()+'\nS3_ACCESS_KEY='+hex()+'\nS3_SECRET_KEY='+hex())" > "$TEST_ENV"
|
||||
compose up -d --no-build --wait --wait-timeout 120 postgres objects
|
||||
compose run --rm --no-deps migrate
|
||||
compose up -d --no-build --wait --wait-timeout 150 web worker
|
||||
compose up -d --no-build --wait --wait-timeout 150 waterfall-wiki waterfall-wiki-worker
|
||||
# The test runner calls the actual non-root production web/worker containers.
|
||||
compose run --rm --no-deps tests
|
||||
compose exec -T web node container-health.mjs
|
||||
compose exec -T worker sh -c 'test "$(id -u)" -ne 0 && ffmpeg -version >/dev/null'
|
||||
compose exec -T waterfall-wiki node container-health.mjs
|
||||
compose exec -T waterfall-wiki-worker sh -c 'test "$(id -u)" -ne 0 && ffmpeg -version >/dev/null'
|
||||
|
||||
# Repeat route and login checks with production authentication enabled.
|
||||
printf '\nAUTH_CONFIG_FILE=/auth/config.json\nAUTH_COOKIE_SECURE=false\n' >> "$TEST_ENV"
|
||||
compose run --rm --no-deps auth-admin
|
||||
compose up -d --no-build --wait --wait-timeout 150 web
|
||||
compose exec -T web node auth-cli.cjs exercise
|
||||
compose restart web
|
||||
compose up -d --no-build --wait --wait-timeout 150 web
|
||||
compose exec -T web node auth-cli.cjs verify
|
||||
compose up -d --no-build --wait --wait-timeout 150 waterfall-wiki
|
||||
compose exec -T waterfall-wiki node auth-cli.cjs exercise
|
||||
compose restart waterfall-wiki
|
||||
compose up -d --no-build --wait --wait-timeout 150 waterfall-wiki
|
||||
compose exec -T waterfall-wiki node auth-cli.cjs verify
|
||||
|
||||
@@ -3,7 +3,7 @@ import {readFile} from 'node:fs/promises';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import path from 'node:path';
|
||||
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
||||
const require=createRequire(path.join(root,'apps/wiki/package.json')),sharp=require('sharp');
|
||||
const require=createRequire(path.join(root,'apps/waterfall-wiki/package.json')),sharp=require('sharp');
|
||||
const layouts=JSON.parse(await readFile(path.join(root,'content/layout-reference/manifest.json'),'utf8'));
|
||||
const layers=[];let shapes='';
|
||||
for(const[i,l]of layouts.entries()){
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Author distinct document cover PNGs locally. Run with tsx from apps/waterfall-wiki. */
|
||||
import {createRequire} from 'node:module';import {fileURLToPath} from 'node:url';import path from 'node:path';import {mkdir,writeFile} from 'node:fs/promises';import {createHash} from 'node:crypto';
|
||||
const require=createRequire(import.meta.url),sharp=require('sharp'),root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
||||
const {guidanceDocuments}=require('../apps/waterfall-wiki/src/content/skills/guidance.ts'),{pageId}=require('../apps/waterfall-wiki/src/content/page-links.ts'),{chapters}=require('../apps/waterfall-wiki/src/content/learning-skills/data.ts');
|
||||
const out=process.env.PROMPT_COVER_OUTPUT||path.resolve(root,'../output/prompt-tags-upgrade');await mkdir(out,{recursive:true});
|
||||
function stableId(name){const b=createHash('sha256').update('prompt:learning-series:'+name).digest().subarray(0,16);b[6]=(b[6]&15)|80;b[8]=(b[8]&63)|128;const h=b.toString('hex');return `${h.slice(0,8)}-${h.slice(8,12)}-${h.slice(12,16)}-${h.slice(16,20)}-${h.slice(20)}`}
|
||||
const notes=[...guidanceDocuments.filter(d=>d.path.includes('/')).map((d,i)=>({id:pageId('guidance:'+d.path),title:d.title,collection:d.collection,slug:'guide-'+d.path.replaceAll('/','-'),file:d.path.replaceAll('/','-')+'.png',theme:d.collection==='照片入皮影'?'chinese':'sticker',number:String(i+1).padStart(2,'0')})),...chapters.map((c,i)=>({id:stableId(c.key),title:['复习资料整理','出题与教学资料','英语学习资料'][i],collection:['笔记复习','教学资料','英语学习'][i],file:c.slug+'.png',theme:['notes','teaching','english'][i],number:c.number})),{id:'9ebd8f78d54b4b9db741b4e8',title:'Studio 封面工具',collection:'同一母版 / 三种构图',file:'studio-tools.png',theme:'studio',number:'TOOL',rebrand:true}];
|
||||
const xml=s=>s.replaceAll('&','&').replaceAll('<','<').replaceAll('>','>');
|
||||
for(const [i,n] of notes.entries()){
|
||||
const palettes={chinese:['#f5ead7','#7e322e','#b4835a'],sticker:['#f7f1e7','#334c46','#a6b9a1'],notes:['#edf0e5','#354b3b','#a7b48c'],teaching:['#f3e7da','#6c483b','#c99773'],english:['#e9edf1','#35485b','#9db1c4'],studio:['#efeee5','#334d43','#9cac9f']},[paper,ink,accent]=palettes[n.theme];
|
||||
const lines=Array.from(n.title).reduce((arr,c,j)=>(j%7===0?arr.push(c):arr[arr.length-1]+=c,arr),[]);
|
||||
const ornament=n.theme==='chinese'?`<circle cx="694" cy="660" r="155" fill="${accent}" opacity=".23"/><path d="M160 780Q320 510 610 620T790 520M156 808Q355 580 745 710" fill="none" stroke="${ink}" stroke-width="3"/><rect x="685" y="430" width="73" height="94" fill="none" stroke="${ink}" stroke-width="3"/><text x="721" y="469" text-anchor="middle" font-size="25">文</text><text x="721" y="503" text-anchor="middle" font-size="25">档</text>`:n.theme==='sticker'?`<g transform="rotate(${i%2?7:-7} 450 680)"><rect x="166" y="474" width="535" height="347" rx="28" fill="${accent}" stroke="white" stroke-width="24"/><text x="204" y="645" font-size="95" font-family="Georgia,serif">${['Make.','Share.','Check.'][i%3]}</text><path d="M215 714h340m-340 35h240" stroke="${ink}" stroke-width="5"/></g><circle cx="711" cy="493" r="38" fill="${paper}" stroke="${ink}" stroke-width="2"/>`:`<rect x="170" y="500" width="547" height="335" rx="4" fill="${accent}" opacity=".55"/><path d="M215 577h390m-390 65h390m-390 65h260m-260 65h325" stroke="${ink}" stroke-width="3"/><text x="649" y="543" text-anchor="end" font-size="46" font-family="Georgia,serif">${n.theme==='english'?'Aa':n.number}</text>`;
|
||||
const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="900" height="1200" viewBox="0 0 900 1200"><rect width="900" height="1200" fill="${paper}"/><g fill="${ink}" font-family="Arial,'Noto Sans CJK SC','PingFang SC',sans-serif"><text x="70" y="84" font-size="24" letter-spacing="3">PROMPT / DOCUMENTS</text><path d="M70 120H830" stroke="${ink}" stroke-width="2"/><text x="70" y="177" font-size="24">${xml(n.collection)}</text>${lines.map((l,j)=>`<text x="66" y="${278+j*88}" font-size="76" font-weight="600">${xml(l)}</text>`).join('')}${ornament}<text x="70" y="973" font-size="23" letter-spacing="2">${n.theme==='chinese'?'阅读 · 理解 · 制作':'READ / MAKE / KEEP'}</text><path d="M70 1032H830" stroke="${ink}" stroke-width="1"/><text x="70" y="1093" font-size="22">独立文档封面 · 参考素材见正文</text><text x="830" y="1145" text-anchor="end" font-family="Georgia,serif" font-size="42">${n.number}</text></g></svg>`;
|
||||
await sharp(Buffer.from(svg)).png().toFile(path.join(out,n.file));
|
||||
}
|
||||
await writeFile(path.join(out,'catalog.json'),JSON.stringify({notes,roots:['street-people','shadow-puppet'].map(p=>({id:pageId('guidance:'+p),topic:p==='street-people'?'贴纸':'中国风'})),entries:['8eb8c76500580f7a4b56ba3c','9ebd8f78d54b4b9db741b4e8'],references:['street-people-reference','street-people-original']},null,2));console.log('Prepared '+notes.length+' independent covers and an API publication catalogue.');
|
||||
@@ -0,0 +1,26 @@
|
||||
/** Run INSIDE the server using auth-cli.cjs run; no content or credentials are exported. */
|
||||
import {readFile,writeFile,mkdir} from 'node:fs/promises';import path from 'node:path';
|
||||
const base=process.env.PROMPT_LOCAL_API||'http://127.0.0.1:3000',dir=process.env.PROMPT_COVER_BUNDLE||'/tmp/prompt-document-covers';
|
||||
const catalog=JSON.parse(await readFile(path.join(dir,'catalog.json'),'utf8')),stateFile=process.env.PROMPT_COVER_STATE||'/tmp/prompt-document-cover-state.json';
|
||||
let state;try{state=JSON.parse(await readFile(stateFile,'utf8'))}catch{state={assets:{},snapshots:{},done:[]}};
|
||||
const save=()=>writeFile(stateFile,JSON.stringify(state),{mode:0o600});
|
||||
async function api(route,options={}){const r=await fetch(base+route,options);if(!r.ok)throw Error(route+': '+r.status);return r.json()}
|
||||
const json=(method,body)=>({method,headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
|
||||
let allTags=await api('/api/tags');if(allTags.filter(t=>t.kind==='system').length!==2)throw Error('System tag migration is not deployed');
|
||||
async function tag(name){let t=allTags.find(t=>t.name===name);if(!t){t=await api('/api/tags',json('POST',{name:'#'+name}));allTags.push(t)}return t.id;}
|
||||
const sys=key=>{const t=allTags.find(t=>t.system_key===key);if(!t)throw Error('Missing system tag');return t.id};
|
||||
async function upload(key,bytes,name){if(state.assets[key])return state.assets[key];const f=new FormData();f.set('kind','image');f.set('assetOnly','true');f.append('files',new Blob([bytes],{type:'image/png'}),name);const d=await api('/api/upload',{method:'POST',body:f});state.assets[key]=d.assets[0];await save();return d.assets[0]}
|
||||
async function oldMedia(entry){if(entry.assets)return entry.assets;const assets=[];for(const m of entry.media){if(m.kind!=='image')continue;const u=new URL(m.url,base);if(u.origin!==new URL(base).origin)throw Error('Unexpected media origin');const r=await fetch(u);if(!r.ok)throw Error('Source image unavailable');assets.push({id:await upload(m.url,await r.arrayBuffer(),'original-reference.png'),role:'content'});}return assets;}
|
||||
async function read(id){return (await api('/api/notes/'+id)).entry}
|
||||
async function snapshot(entry){if(!state.snapshots[entry.id]){state.snapshots[entry.id]=entry;await save()}}
|
||||
async function labels(entry,extra=[],system=[]){const ids=[];for(const name of new Set([...entry.categories,...extra]))ids.push(await tag(name));for(const s of entry.systemTags||[])ids.push(s.id);for(const key of system)ids.push(sys(key));return [...new Set(ids)]}
|
||||
await mkdir(dir,{recursive:true});
|
||||
for(const n of catalog.notes){if(state.done.includes(n.id))continue;const entry=await read(n.id);await snapshot(entry);const cover=await upload('cover:'+n.id,await readFile(path.join(dir,n.file)),n.file),assets=[{id:cover,role:'content'},...await oldMedia(entry)].filter((a,i,arr)=>arr.findIndex(b=>b.id===a.id)===i);
|
||||
const extra=n.collection==='照片入皮影'?['中国风']:n.collection==='街头小人'?['贴纸']:[],tagIds=await labels(entry,extra,n.rebrand?['document-entry']:[]),markdown=n.rebrand?entry.editableMarkdown.replaceAll('waterfall-wiki','PROMPT'):entry.editableMarkdown;
|
||||
if(entry.postSlug)await api('/api/notes/'+n.id,json('PUT',{title:entry.title,description:entry.description,markdown,tags:tagIds,assets,coverAssetId:cover,revision:entry.revision}));
|
||||
else await api('/api/posts',json('POST',{publicId:n.id,slug:n.slug,kind:'article',title:entry.title,description:entry.description,text:markdown,tags:tagIds,assets,coverAssetId:cover}));
|
||||
state.done.push(n.id);await save();
|
||||
}
|
||||
for(const n of [...catalog.roots,...catalog.entries.map(id=>({id}))]){const entry=await read(n.id);await snapshot(entry);await api('/api/notes/'+n.id,json('PATCH',{tags:await labels(entry,n.topic?[n.topic]:[],['document-entry']),revision:entry.revision}));}
|
||||
for(const slug of catalog.references){const r=await fetch(base+'/p/'+slug,{redirect:'manual'});const location=r.headers.get('location');if(!location?.startsWith('/explore/'))throw Error('Reference post unavailable');const entry=await read(location.split('/').at(-1));await snapshot(entry);await api('/api/notes/'+entry.id,json('PATCH',{tags:await labels(entry,['贴纸'],['reference-image']),revision:entry.revision}));}
|
||||
console.log(JSON.stringify({independentCovers:catalog.notes.length,rootEntries:catalog.roots.length+catalog.entries.length,referencePosts:catalog.references.length,contentExported:false}));
|
||||
@@ -12,7 +12,7 @@ for(const name of ['cover.png','ref17-master.png','ref17-notes.png','ref17-teach
|
||||
const ids=JSON.parse(await readFile('content/layout-reference/post-ids.json','utf8'));
|
||||
const gallery=Object.entries(state.assets).filter(([name])=>name!=='cover.png').map(([name,id])=>``).join('\n\n');
|
||||
const text=(await readFile('content/studio-tools/tutorial.md','utf8')).replace('{{GALLERY}}',gallery).replace('{{REF26}}',`[ref-26](/explore/${ids['ref-26']})`);
|
||||
const tag=await post('/api/tags',{name:'Studio工具',slug:'studio-tools'}),title='Studio 封面工具 · 同一母版与三种构图',description='从 waterfall-wiki 进入两件 Studio 工具:ref-17 四张同母版试版,以及 ref-01/07/26 三种构图。含可访问图像、GET/POST API、HTML/React/Next.js 示例与构件验收。';
|
||||
const tag=await post('/api/tags',{name:'Studio工具',slug:'studio-tools'}),title='Studio 封面工具 · 同一母版与三种构图',description='从 PROMPT 进入两件 Studio 工具:ref-17 四张同母版试版,以及 ref-01/07/26 三种构图。含可访问图像、GET/POST API、HTML/React/Next.js 示例与构件验收。';
|
||||
const assets=Object.values(state.assets).map(id=>({id,role:'content'})),coverAssetId=state.assets['cover.png'],old=await api('/api/notes/'+publicId);
|
||||
state.post=old?await post('/api/notes/'+publicId,{title,description,markdown:text,tags:[tag.id],assets,coverAssetId,revision:old.entry.revision},'PUT'):await post('/api/posts',{publicId,slug:'studio-cover-tools',kind:'article',title,description,text,tags:[tag.id],assets,coverAssetId});
|
||||
await writeFile(out+'/published.json',JSON.stringify(state,null,2));console.log(base+'/explore/'+publicId);
|
||||
|
||||
Reference in New Issue
Block a user