feat(cms): download portable backups from site settings
DC CMS qualification / qualify (push) Successful in 1m57s
DC CMS qualification / qualify (push) Successful in 1m57s
This commit is contained in:
+25
-25
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -12,6 +12,35 @@
|
||||
|
||||
ZIP нужен для обновления кода и шаблонов локально. Для обычного редактирования текста и изображений повторный импорт не нужен. Новые изображения получают уникальный URL, поэтому кеш браузера не скрывает замену.
|
||||
|
||||
## Скачать бэкап
|
||||
|
||||
В настройках каждого сайта рядом с публикацией доступна кнопка «Скачать бэкап».
|
||||
Она скачивает текущую **сохранённую** копию выбранного сайта: модели контента,
|
||||
SEO и базы знаний, шаблоны, инструменты рендера, готовые страницы и медиа.
|
||||
Несохранённые изменения редактора в архив не входят; скачивание ничего не
|
||||
сохраняет и не публикует. Архив можно вернуть через существующий импорт ZIP.
|
||||
|
||||
Маршрут `POST /s/<id>/api/project/backup` готовит снимок; одноразовый GET
|
||||
по возвращённой ссылке передаёт ZIP штатному загрузчику браузера без Blob в JS.
|
||||
Оба маршрута закрыты общей авторизацией CMS и не принимают произвольный путь
|
||||
к файлам. Невостребованный архив удаляется через 10 минут. Имя содержит ID сайта, дату по Москве
|
||||
и суффикс TECH: `NODEDC_SITE_2026-11-05_MISSION_CORE_TECH.zip`.
|
||||
Это бэкап сайта, а не инсталляции CMS: реквизиты публикации, учётные записи
|
||||
и реестр сайтов находятся отдельно. `.env*`, `*.secrets.json`, `.git`,
|
||||
старые бэкапы, корзина и зависимости исключены; символические ссылки отклоняются.
|
||||
|
||||
Подготовка блокирует одновременную запись, импорт и публикацию этого сайта.
|
||||
Файлы и их состав проверяются повторно: при внешнем изменении скачивание
|
||||
возвращает ошибку с предложением повторить. Готовый ZIP передаётся из приватной
|
||||
временной папки, которая удаляется после передачи или отключения клиента.
|
||||
ZIP собирается потоково методом STORE, без полной копии медиа в памяти и новых
|
||||
runtime-зависимостей. Лимит — 2 ГБ и 60 000 файлов. После подготовки снимка
|
||||
обычное редактирование снова доступно, пока браузер скачивает архив.
|
||||
|
||||
Проверки: `test/backup.test.mjs` сверяет ZIP/CRC, UTF-8 имена, медиа, исключения,
|
||||
ссылки и отмену; `test/multisite.test.mjs` скачивает оба сайта, проверяет
|
||||
изоляцию и авторизацию и импортирует полученный ZIP обратно в тестовый сайт.
|
||||
|
||||
## Git
|
||||
|
||||
Workflow `.gitea/workflows/ci.yml` квалифицирует точный commit в `master`, устанавливает зависимости по lockfile, проверяет синтаксис и изоляцию сайтов. Он сохраняет артефакт `dc-cms-release`. CI не получает учётные данные продакшена.
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ def main():
|
||||
files=tracked_payload()
|
||||
for name in files:
|
||||
if name.endswith(('.js','.mjs')): run(['node','--check',name])
|
||||
run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs'])
|
||||
run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs','test/backup.test.mjs'])
|
||||
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
|
||||
# The ordinary release cannot change its build, dependency or deployment foundation.
|
||||
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
|
||||
|
||||
@@ -9,6 +9,8 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes,
|
||||
import { createLocalJWKSet, jwtVerify } from "jose";
|
||||
import SftpClient from "ssh2-sftp-client";
|
||||
import AdmZip from "adm-zip";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { createSiteBackup, siteBackupFilename } from "./site-backup.mjs";
|
||||
|
||||
const cmsRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const port = Number(process.env.PORT || 8090);
|
||||
@@ -20,6 +22,8 @@ const projectSecretsPath = join(projectsRoot, `${activeProjectId}.secrets.json`)
|
||||
const publishLogPath = join(projectsRoot, `${activeProjectId}.publish.log.jsonl`);
|
||||
const publishStatePath = join(projectsRoot, `${activeProjectId}.publish-state.json`);
|
||||
const publishJobs = new Map();
|
||||
let backupRunning = false;
|
||||
let preparedBackup = null;
|
||||
const PUBLISH_JOB_RETENTION_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
async function loadProjectConfig() {
|
||||
@@ -2899,6 +2903,60 @@ async function handle(req, res) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/api/project/backup") {
|
||||
if (!ensureSiteReady(res)) return;
|
||||
if (backupRunning) {
|
||||
sendJson(res, 409, { ok: false, error: "Бэкап этого сайта уже готовится или скачивается" });
|
||||
return;
|
||||
}
|
||||
backupRunning = true;
|
||||
const abort = new AbortController();
|
||||
const onClose = () => abort.abort();
|
||||
res.once("close", onClose);
|
||||
try {
|
||||
const backup = await createSiteBackup(repoRoot, { required: REQUIRED_SITE_FILES.map(file => file.label), signal: abort.signal });
|
||||
res.off("close", onClose);
|
||||
if (res.destroyed) { await backup.cleanup(); backupRunning = false; return; }
|
||||
const token = randomBytes(24).toString("hex");
|
||||
const fileName = siteBackupFilename(activeProjectId);
|
||||
const release = async () => {
|
||||
if (preparedBackup?.token === token) preparedBackup = null;
|
||||
try { await backup.cleanup(); } finally { backupRunning = false; }
|
||||
};
|
||||
const timer = setTimeout(() => release().catch(error => console.error("Backup cleanup failed", error)), 10 * 60 * 1000);
|
||||
timer.unref();
|
||||
preparedBackup = { ...backup, token, fileName, timer, release, claimed: false };
|
||||
sendJson(res, 200, { ok: true, fileName, files: backup.files, bytes: backup.size, downloadUrl: `/api/project/backup?token=${token}` });
|
||||
} catch (error) {
|
||||
res.off("close", onClose); backupRunning = false;
|
||||
if (!res.destroyed) throw error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "GET" && url.pathname === "/api/project/backup") {
|
||||
const backup = preparedBackup;
|
||||
if (!backup || backup.claimed || url.searchParams.get("token") !== backup.token) {
|
||||
sendJson(res, 404, { ok: false, error: "Бэкап недоступен. Нажмите «Скачать бэкап» ещё раз" });
|
||||
return;
|
||||
}
|
||||
backup.claimed = true; clearTimeout(backup.timer);
|
||||
res.writeHead(200, {
|
||||
"content-type": "application/zip",
|
||||
"content-disposition": `attachment; filename="${backup.fileName}"`,
|
||||
"content-length": backup.size,
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
"referrer-policy": "no-referrer",
|
||||
});
|
||||
// Native browser download streams an immutable ZIP without a JS Blob.
|
||||
pipeline(createReadStream(backup.path), res)
|
||||
.catch(() => {})
|
||||
.finally(backup.release)
|
||||
.catch(error => console.error("Backup cleanup failed", error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === "POST" && url.pathname === "/api/project/publish") {
|
||||
if (!ensureSiteReady(res)) return;
|
||||
const publish = await publishProject();
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { constants } from 'node:fs';
|
||||
import { lstat, mkdtemp, open, readdir, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { crc32 } from 'node:zlib';
|
||||
|
||||
const excluded = new Set(['.git', '.cms-backups', '.trash', 'node_modules', '.DS_Store', '__MACOSX']);
|
||||
const skip = name => excluded.has(name) || name.startsWith('._') || name === '.env' || name.startsWith('.env.') || name.endsWith('.secrets.json');
|
||||
const fail = (message, status = 409) => Object.assign(new Error(message), { status });
|
||||
const signature = s => `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
|
||||
const MAX_BYTES = 2 * 1024 ** 3;
|
||||
|
||||
// STORE is intentional: site media is already compressed. Write in bounded
|
||||
// chunks rather than loading hundreds of MB into the CMS process or blocking it.
|
||||
export async function createSiteBackup(root, { required = [], signal } = {}) {
|
||||
async function scan(directory = root, prefix = '') {
|
||||
signal?.throwIfAborted();
|
||||
const directoryStat = await lstat(directory);
|
||||
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw fail('Бэкап сайта с символическими ссылками не поддерживается');
|
||||
const result = [];
|
||||
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, 'en'))) {
|
||||
if (skip(entry.name)) continue;
|
||||
const path = join(directory, entry.name), name = prefix + entry.name;
|
||||
if (entry.name.includes('\\') || Buffer.byteLength(name) > 65535) throw fail('Недопустимый путь в сайте');
|
||||
if (entry.isSymbolicLink()) throw fail('Бэкап сайта с символическими ссылками не поддерживается');
|
||||
if (entry.isDirectory()) result.push(...await scan(path, name + '/'));
|
||||
else if (entry.isFile()) {
|
||||
const info = await lstat(path, { bigint: true });
|
||||
result.push({ name, path, size: Number(info.size), stamp: signature(info), modified: new Date(Number(info.mtimeMs)) });
|
||||
} else throw fail('Бэкап поддерживает только обычные файлы и папки');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const files = await scan();
|
||||
if (!files.length || files.length > 60000 || files.reduce((n, f) => n + f.size, 0) > MAX_BYTES) throw fail('Бэкап поддерживает сайты до 2 ГБ и 60 000 файлов', 413);
|
||||
if (required.some(name => !files.some(file => file.name === name))) throw fail('Сайт неполный: отсутствуют файлы для восстановления');
|
||||
const temp = await mkdtemp(join(tmpdir(), 'dc-cms-backup-'));
|
||||
const cleanup = () => rm(temp, { recursive: true, force: true });
|
||||
const path = join(temp, 'site.zip');
|
||||
let output;
|
||||
try {
|
||||
output = await open(path, 'wx', 0o600);
|
||||
let offset = 0;
|
||||
const directory = [];
|
||||
async function write(data, position = offset) {
|
||||
let written = 0;
|
||||
while (written < data.length) {
|
||||
signal?.throwIfAborted();
|
||||
const result = await output.write(data, written, data.length - written, position + written);
|
||||
if (!result.bytesWritten) throw fail('Не удалось записать бэкап', 500);
|
||||
written += result.bytesWritten;
|
||||
}
|
||||
offset = Math.max(offset, position + written);
|
||||
}
|
||||
for (const file of files) {
|
||||
signal?.throwIfAborted();
|
||||
const input = await open(file.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
if (signature(await input.stat({ bigint: true })) !== file.stamp) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
|
||||
const name = Buffer.from(file.name), start = offset, date = file.modified;
|
||||
const dosTime = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
|
||||
const dosDate = ((Math.min(2107, Math.max(1980, date.getFullYear())) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
|
||||
const header = Buffer.alloc(30);
|
||||
header.writeUInt32LE(0x04034b50, 0); header.writeUInt16LE(20, 4); header.writeUInt16LE(0x800, 6);
|
||||
header.writeUInt16LE(dosTime, 10); header.writeUInt16LE(dosDate, 12);
|
||||
header.writeUInt32LE(file.size, 18); header.writeUInt32LE(file.size, 22); header.writeUInt16LE(name.length, 26);
|
||||
await write(header); await write(name);
|
||||
let checksum = 0, bytes = 0;
|
||||
for await (const chunk of input.createReadStream({ autoClose: false, highWaterMark: 256 * 1024 })) {
|
||||
bytes += chunk.length;
|
||||
if (bytes > file.size) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
|
||||
checksum = crc32(chunk, checksum); await write(chunk);
|
||||
}
|
||||
if (bytes !== file.size || signature(await input.stat({ bigint: true })) !== file.stamp) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
|
||||
header.writeUInt32LE(checksum, 14); await write(header, start);
|
||||
const central = Buffer.alloc(46);
|
||||
central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6);
|
||||
header.copy(central, 8, 6, 28); central.writeUInt32LE(start, 42);
|
||||
directory.push(central, name);
|
||||
} finally { await input.close(); }
|
||||
}
|
||||
const after = await scan();
|
||||
if (JSON.stringify(after.map(f => [f.name, f.stamp])) !== JSON.stringify(files.map(f => [f.name, f.stamp]))) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
|
||||
const directoryStart = offset;
|
||||
for (const data of directory) await write(data);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(offset - directoryStart, 12); end.writeUInt32LE(directoryStart, 16);
|
||||
await write(end);
|
||||
await output.close(); output = null;
|
||||
return { path, size: offset, files: files.length, cleanup };
|
||||
} catch (error) {
|
||||
await output?.close(); await cleanup(); throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function siteBackupFilename(projectId, now = new Date()) {
|
||||
const date = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Moscow', year: 'numeric', month: '2-digit', day: '2-digit' }).format(now);
|
||||
const id = String(projectId).replace(/[^a-zA-Z0-9-]/g, '').replace(/-/g, '_').toUpperCase() || 'SITE';
|
||||
return `NODEDC_SITE_${date}_${id}_TECH.zip`;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, mkdir, writeFile, readFile, rm, symlink, stat } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, dirname } from 'node:path';
|
||||
import AdmZip from 'adm-zip';
|
||||
import { createSiteBackup, siteBackupFilename } from '../server/site-backup.mjs';
|
||||
|
||||
test('backup is a portable current workspace, with UTF-8 paths and exact media bytes', async t => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'backup-fixture-'));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const files = {
|
||||
'content/pages/home.json': Buffer.from('{"title":"Current"}'),
|
||||
'templates/pages/home/shell.html': Buffer.from('<html>current</html>'),
|
||||
'assets/фото ровера.bin': Buffer.from(Array.from({ length: 700000 }, (_, i) => i % 251)),
|
||||
'.htaccess': Buffer.from('DirectoryIndex index.html'),
|
||||
'empty.txt': Buffer.alloc(0),
|
||||
};
|
||||
const privateFiles = ['.cms-backups/old.zip', '.git/config', '.env', '.env.local', 'demo.secrets.json', 'assets/.trash/old.png', 'assets/._photo', 'node_modules/package/a.js'];
|
||||
for (const [name, value] of [...Object.entries(files), ...privateFiles.map(name => [name, Buffer.from('private')])]) {
|
||||
await mkdir(dirname(join(root, name)), { recursive: true }); await writeFile(join(root, name), value);
|
||||
}
|
||||
const backup = await createSiteBackup(root, { required: ['content/pages/home.json'] });
|
||||
try {
|
||||
const zip = new AdmZip(await readFile(backup.path));
|
||||
assert.equal(zip.test(), true);
|
||||
assert.deepEqual(zip.getEntries().map(e => e.entryName).sort(), Object.keys(files).sort());
|
||||
for (const [name, value] of Object.entries(files)) assert.deepEqual(zip.readFile(name), value, name);
|
||||
assert.equal(backup.size, (await stat(backup.path)).size);
|
||||
assert.equal((await stat(backup.path)).mode & 0o777, 0o600);
|
||||
} finally { await backup.cleanup(); }
|
||||
await assert.rejects(stat(backup.path));
|
||||
assert.equal(await readFile(join(root, '.env'), 'utf8'), 'private');
|
||||
await assert.rejects(createSiteBackup(root, { required: ['missing.json'] }), /неполный/);
|
||||
await symlink(join(root, '.env'), join(root, 'linked-secret'));
|
||||
await assert.rejects(createSiteBackup(root), /символическими/);
|
||||
await rm(join(root, 'linked-secret'));
|
||||
const abort = new AbortController(); abort.abort();
|
||||
await assert.rejects(createSiteBackup(root, { signal: abort.signal }), { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test('backup filename identifies the selected site and Moscow calendar date', () => {
|
||||
assert.equal(siteBackupFilename('mission-core', new Date('2026-11-05T20:59:00Z')), 'NODEDC_SITE_2026-11-05_MISSION_CORE_TECH.zip');
|
||||
assert.equal(siteBackupFilename('nodedc', new Date('2026-11-05T21:01:00Z')), 'NODEDC_SITE_2026-11-06_NODEDC_TECH.zip');
|
||||
});
|
||||
+27
-1
@@ -110,6 +110,31 @@ test('independent sites, rendering, secrets and publication ownership', async t
|
||||
assert.equal((await fetch(base+'/s/mission-core/api/project/upload-site',{method:'POST',body:invalid})).status,500);
|
||||
assert.equal((await api('/s/mission-core/api/page/home')).title,'Mission edited');
|
||||
});
|
||||
await t.test('downloaded backup is current, isolated and can be imported unchanged',async()=>{
|
||||
const beforePage=await api('/s/mission-core/api/page/home');
|
||||
const prepared=await api('/s/mission-core/api/project/backup','POST');
|
||||
await api('/s/mission-core/api/project/backup','POST',undefined,409);
|
||||
const response=await fetch(base+'/s/mission-core'+prepared.downloadUrl);
|
||||
assert.equal(response.status,200);assert.equal(response.headers.get('content-type'),'application/zip');
|
||||
assert.match(response.headers.get('content-disposition'),/MISSION_CORE_TECH\.zip/);
|
||||
assert.equal(response.headers.get('cache-control'),'no-store');
|
||||
const bytes=Buffer.from(await response.arrayBuffer());const zip=new AdmZip(bytes);
|
||||
assert.equal(bytes.length,Number(response.headers.get('content-length')));assert.equal(zip.test(),true);
|
||||
assert.equal((await fetch(base+'/s/mission-core'+prepared.downloadUrl)).status,404);
|
||||
assert.deepEqual(JSON.parse(zip.readAsText('content/pages/home.json')),beforePage);
|
||||
assert.ok(zip.getEntry('tools/render-home.mjs'));assert.ok(zip.getEntry('templates/pages/home/shell.html'));
|
||||
assert.ok(!zip.getEntries().some(e=>/\.cms-backups|\.git\/|secrets|publish-state/.test(e.entryName)));
|
||||
const preparedAgent=await api('/s/nodedc/api/project/backup','POST');
|
||||
assert.equal((await fetch(base+'/s/mission-core'+preparedAgent.downloadUrl)).status,404);
|
||||
const agentResponse=await fetch(base+'/s/nodedc'+preparedAgent.downloadUrl);assert.equal(agentResponse.status,200);
|
||||
const agentZip=new AdmZip(Buffer.from(await agentResponse.arrayBuffer()));
|
||||
assert.equal(JSON.parse(agentZip.readAsText('content/pages/home.json')).title,'Agent edited');
|
||||
const form=new FormData();form.append('file',new Blob([bytes],{type:'application/zip'}),'restored.zip');
|
||||
const restored=await fetch(base+'/s/mission-core/api/project/upload-site',{method:'POST',body:form});
|
||||
assert.equal(restored.status,200);assert.equal((await restored.json()).site.ready,true);
|
||||
assert.deepEqual(await api('/s/mission-core/api/page/home'),beforePage);
|
||||
assert.equal((await api('/s/nodedc/api/page/home')).title,'Agent edited');
|
||||
});
|
||||
await t.test('encrypted credentials transfer with source disabled',async()=>{
|
||||
const config=await api('/s/nodedc/api/project/config');
|
||||
await api('/s/nodedc/api/project/config','PUT',{...config,deploy:{...config.deploy,enabled:true}});
|
||||
@@ -139,7 +164,8 @@ test('independent sites, rendering, secrets and publication ownership', async t
|
||||
});
|
||||
await stop();await start(true);
|
||||
await t.test('registry, scoped content and preview retain authentication',async()=>{
|
||||
for(const path of ['/api/sites','/s/mission-core/api/page/home']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
|
||||
for(const path of ['/api/sites','/s/mission-core/api/page/home','/s/mission-core/api/project/backup']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
|
||||
assert.equal((await fetch(base+'/s/mission-core/api/project/backup',{method:'POST',redirect:'manual'})).status,401);
|
||||
assert.equal((await fetch(base+'/s/mission-core/index.html',{redirect:'manual'})).status,302);
|
||||
assert.equal((await fetch(base+'/healthz')).status,200);
|
||||
});
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ const siteContext = h("div", { className: "cms-site-context" },
|
||||
h("span", { id: "cms-add-block-parking", hidden: true }, ib("add-block", "Добавить блок", "plus"))
|
||||
);
|
||||
const nav = h(AdminNavigationPanel, { eyebrow: "NODE.DC / CMS", title: h("span", { id: "sidebar-title" }, "\u0410\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435"), headerActions: ib("add-project", "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0430\u0439\u0442", "plus"), contextSlot: siteContext, items: [], onClose: noop, onItemChange: noop });
|
||||
const actions = h("div", { className: "cms-editor-actions" }, h(StatusBadge, { id: "dirty-state", "data-dirty": "false" }, "\u0421\u0438\u043D\u0445\u0440\u043E\u043D\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E"), ib("reload", "\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435", "refresh"), btn("save", "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C", "primary"), btn("render", "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0430\u0439\u0442"), h(Button, { id: "publish", className: "hidden", tone: "neutral" }, "\u041E\u043F\u0443\u0431\u043B\u0438\u043A\u043E\u0432\u0430\u0442\u044C"));
|
||||
const actions = h("div", { className: "cms-editor-actions" }, h(StatusBadge, { id: "dirty-state", "data-dirty": "false" }, "\u0421\u0438\u043D\u0445\u0440\u043E\u043D\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E"), ib("reload", "\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435", "refresh"), btn("save", "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C", "primary"), btn("render", "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0430\u0439\u0442"), h(Button, { id: "publish", className: "hidden", tone: "neutral" }, "\u041E\u043F\u0443\u0431\u043B\u0438\u043A\u043E\u0432\u0430\u0442\u044C"), h(Button, {id: "download-backup", variant: "secondary", tone: "neutral", className: "hidden"}, "Скачать бэкап"));
|
||||
const content = h(ApplicationPanel, { eyebrow: h("span", { id: "editor-heading" }, "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0441\u0430\u0439\u0442\u0430"), title: "\u041A\u043E\u043D\u0442\u0435\u043D\u0442", description: "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0440\u0430\u0437\u0434\u0435\u043B", headerTools: actions, expanded: true, onClose: noop }, h("div", { className: "cms-editor", dangerouslySetInnerHTML: { __html: await read("editor.html") } }));
|
||||
const shell = html(h(ApplicationShell, { id: "cms-shell", header, stage: h("div", { className: "cms-stage" }, h("p", null, "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0430\u0439\u0442\u0430\u043C\u0438 NODE.DC"), btn("open-navigation", "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0440\u0430\u0437\u0434\u0435\u043B\u044B")), navigation: nav, content, navigationOpen: true, contentOpen: true, contentExpanded: true }));
|
||||
const icons = ["close", "plus", "chevron-up", "chevron-down", "copy", "clipboard", "trash", "eye", "eye-off", "layers", "panel", "file", "settings", "folder", "image", "video", "refresh", "move", "edit"];
|
||||
|
||||
@@ -110,6 +110,7 @@ const state = {
|
||||
projectConfigDirty: false,
|
||||
keepSiteArchiveBackup: true,
|
||||
publishJob: null,
|
||||
backupDownloading: false,
|
||||
publishResumeAttempted: false,
|
||||
knowledge: null,
|
||||
knowledgeSelectedId: null,
|
||||
@@ -232,6 +233,7 @@ const el = {
|
||||
save: document.querySelector("#save"),
|
||||
render: document.querySelector("#render"),
|
||||
publish: document.querySelector("#publish"),
|
||||
downloadBackup: document.querySelector("#download-backup"),
|
||||
dirtyState: document.querySelector("#dirty-state"),
|
||||
status: document.querySelector("#status"),
|
||||
empty: document.querySelector("#empty-state"),
|
||||
@@ -768,6 +770,27 @@ async function publishProject() {
|
||||
await pollPublishJob(payload.job.id);
|
||||
}
|
||||
|
||||
async function downloadSiteBackup() {
|
||||
if (state.backupDownloading) return;
|
||||
state.backupDownloading = true;
|
||||
el.downloadBackup.disabled = true;
|
||||
el.downloadBackup.textContent = "Готовим бэкап…";
|
||||
setStatus("Подготавливаем ZIP сохранённой версии сайта…");
|
||||
try {
|
||||
const response = await siteFetch("/api/project/backup", { method: "POST" });
|
||||
const backup = await readApiJson(response, "Не удалось подготовить бэкап");
|
||||
if (!backup?.ok || !/^\/api\/project\/backup\?token=[a-f0-9]{48}$/.test(backup.downloadUrl || "")) throw new Error("Сервер не вернул ссылку на бэкап");
|
||||
const link = document.createElement("a");
|
||||
link.href = siteUrl(backup.downloadUrl); link.download = backup.fileName;
|
||||
document.body.append(link); link.click(); link.remove();
|
||||
setStatus(`Бэкап подготовлен: ${backup.fileName}. Скачивание передано браузеру.`);
|
||||
} finally {
|
||||
state.backupDownloading = false;
|
||||
el.downloadBackup.disabled = !siteReady();
|
||||
el.downloadBackup.textContent = "Скачать бэкап";
|
||||
}
|
||||
}
|
||||
|
||||
function publishJobRunning(job = state.publishJob) {
|
||||
return Boolean(job && !["completed", "failed"].includes(job.state));
|
||||
}
|
||||
@@ -1015,6 +1038,7 @@ function updateAdminModeSurface() {
|
||||
el.publish.classList.add("hidden");
|
||||
el.publish.disabled = true;
|
||||
}
|
||||
el.downloadBackup?.classList.add("hidden");
|
||||
if (el.reload) {
|
||||
el.reload.disabled = !hasSite && !isProjectSettingsSelected();
|
||||
}
|
||||
@@ -2475,6 +2499,10 @@ function renderProjectSettings() {
|
||||
],
|
||||
});
|
||||
|
||||
el.downloadBackup.classList.remove("hidden");
|
||||
el.downloadBackup.disabled = !siteReady() || state.backupDownloading;
|
||||
el.downloadBackup.title = "Скачать сохранённые файлы выбранного сайта: контент, шаблоны, код и медиа";
|
||||
|
||||
const transferButton = document.createElement("button");
|
||||
transferButton.type = "button"; transferButton.className = "secondary-button";
|
||||
transferButton.textContent = "Перенести настройки публикации с другого сайта";
|
||||
@@ -6218,6 +6246,10 @@ el.publish?.addEventListener("click", () => {
|
||||
if (!isProjectSettingsSelected()) return;
|
||||
publishProject().catch((error) => setStatus(error.message));
|
||||
});
|
||||
el.downloadBackup?.addEventListener("click", () => {
|
||||
if (!isProjectSettingsSelected()) return;
|
||||
downloadSiteBackup().catch(error => setStatus(`Ошибка бэкапа: ${error.message}`));
|
||||
});
|
||||
el.moveUp.addEventListener("click", () => moveSelected(-1));
|
||||
el.moveDown.addEventListener("click", () => moveSelected(1));
|
||||
el.duplicate.addEventListener("click", duplicateSelected);
|
||||
|
||||
Reference in New Issue
Block a user