diff --git a/.dockerignore b/.dockerignore index fadcae4..bd3ef79 100644 --- a/.dockerignore +++ b/.dockerignore @@ -16,4 +16,3 @@ docs .github .qa explorer-dist -desktop diff --git a/DEVELOPMENT.en.md b/DEVELOPMENT.en.md new file mode 100644 index 0000000..6a0a912 --- /dev/null +++ b/DEVELOPMENT.en.md @@ -0,0 +1,113 @@ +# Web development + +[简体中文](DEVELOPMENT.md) | **English** · [Use and deployment](README.en.md) + +## Requirements + +Python 3.10+, Node.js 22.15+, and pnpm 10.28.2. Run the Windows commands in PowerShell. + +## First run + +Install dependencies from the repository root. + +```powershell +python -m venv .venv +.\.venv\Scripts\python.exe -m pip install -r web/requirements.txt +pnpm --dir web install --frozen-lockfile +pnpm --dir web build +cd web +..\.venv\Scripts\python.exe app.py +``` + +Open and press Ctrl+C to stop the server. The default local SQLite database is created at `data/ledger.sqlite3` in the repository root. + +On Linux / macOS, use these commands. + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r web/requirements.txt +pnpm --dir web install --frozen-lockfile +pnpm --dir web build +cd web +../.venv/bin/python app.py +``` + +## Edit the application + +| Path | Contents | +| --- | --- | +| `web/src/` | React pages, styles, and interactions | +| `web/public/` | Website icons and static files | +| `web/backend/` | HTTP API, validation, and ledger storage | +| `web/runtime/` | Container startup and health checks | +| `web/tests/` | Frontend, backend, and database tests | +| `deploy/` | Docker runtime and database deployment configuration | +| `.github/workflows/publish.yml` | Automated checks and image publishing | + +For frontend changes, keep the Python server running. Open another terminal in `web/` and run the build watcher. + +```sh +pnpm exec vite build --watch +``` + +Saving a change rebuilds the frontend. Refresh to view it. Restart the Python server after backend changes. + +## Local configuration + +`python app.py` reads process environment variables. Docker Compose loads `.env`. When running Python directly, set variables in the terminal. + +For a fixed local privacy password, set this in the PowerShell terminal that starts the server. + +```powershell +$env:DATABACK_PRIVACY_PASSWORD = "replace-with-your-own-privacy-password" +``` + +| Setting | Purpose | +| --- | --- | +| `DATABACK_PORT` | Python server port, default `8767` | +| `DATABACK_DATA_DIR` | SQLite directory, default `data/` in the repository root | +| `DATABACK_SNAPSHOT_DIR` | Snapshot directory, default `snapshots/` beside the SQLite file | +| `MONGODB_URI`, `MONGODB_DATABASE` | Development MongoDB replica-set connection and database name | + +From `web/`, use the same virtual-environment Python path as in the first-run commands and add `--port 8768 --db /path/to/ledger.sqlite3` to select a port and a separate test ledger. Keep test data in a different location from your daily ledger. + +## Checks + +Run from `web/`. + +```sh +pnpm test +pnpm build +``` + +On Windows, run backend tests with the project virtual environment. + +```powershell +..\.venv\Scripts\python.exe -m unittest discover -s tests -p 'test_*.py' +``` + +On Linux / macOS, use `../.venv/bin/python`. Full MongoDB tests require `DATABACK_TEST_MONGO_URI` pointing to an isolated replica set. Those tests are skipped locally when it is unset. GitHub Actions creates a test database and runs the full checks. + +## Commit and publish + +1. Create a branch from the latest `main`, make changes, and run the checks. +2. Commit, push the branch, and open a PR. Reference the relevant issue in fix commits and use `Fixes #number` when the issue is fully resolved. +3. Merge into `main` after PR checks pass. +4. Wait for the GitHub Actions `test` and `publish` jobs to succeed. +5. Pull the image and update the application on the Docker host. + +```sh +docker compose pull app +docker compose up -d --no-deps app +docker compose ps +``` + +Builds publish `ghcr.io/cimorn/databack:latest` and `sha-` for `amd64` and `arm64`. In a NAS interface, redeploy the DataBack project with the option to pull the latest image selected. + +## Data and cleanup + +- For a full local backup, stop the Python server and copy `data/`. To restore, stop the server, restore the data directory, and restart. +- The server creates daily ledger snapshots and retains the latest 30. New snapshots continue to be created after old ones are cleared. +- Follow the deployment guide for Docker database, snapshot, and configuration backups. [Database backup and restore](docs/docker.en.md#full-backup) +- Run `git status --short` before committing. Commit source, lockfiles, and documentation. Keep credentials, databases, snapshots, dependencies, builds, and test output on the local or deployment host. +- After development, you can remove `web/dist/`, `web/node_modules/`, `.venv/`, and Python caches. Reinstall dependencies and rebuild when you return. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md new file mode 100644 index 0000000..00414d0 --- /dev/null +++ b/DEVELOPMENT.md @@ -0,0 +1,113 @@ +# 网页开发 + +**简体中文** | [English](DEVELOPMENT.en.md) · [使用与部署](README.md) + +## 环境 + +Python 3.10+、Node.js 22.15+、pnpm 10.28.2。以下 Windows 命令在 PowerShell 中执行。 + +## 首次运行 + +在项目根目录安装依赖。 + +```powershell +python -m venv .venv +.\.venv\Scripts\python.exe -m pip install -r web/requirements.txt +pnpm --dir web install --frozen-lockfile +pnpm --dir web build +cd web +..\.venv\Scripts\python.exe app.py +``` + +打开 ,按 Ctrl+C 停止。默认使用本机 SQLite,首次运行会在项目根目录创建 `data/ledger.sqlite3`。 + +Linux / macOS 使用以下命令。 + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r web/requirements.txt +pnpm --dir web install --frozen-lockfile +pnpm --dir web build +cd web +../.venv/bin/python app.py +``` + +## 修改代码 + +| 路径 | 内容 | +| --- | --- | +| `web/src/` | React 页面、样式和交互 | +| `web/public/` | 网站图标和静态文件 | +| `web/backend/` | HTTP 接口、校验和台账存储 | +| `web/runtime/` | 容器启动与健康检查 | +| `web/tests/` | 前端、后端和数据库测试 | +| `deploy/` | Docker 运行与数据库部署配置 | +| `.github/workflows/publish.yml` | 自动测试和镜像发布 | + +修改前端时,保留 Python 服务,在另一个终端进入 `web/` 执行。 + +```sh +pnpm exec vite build --watch +``` + +保存代码后会重新构建,刷新 查看。修改后端后,重启 Python 服务。 + +## 本机配置 + +`python app.py` 读取进程环境变量。`.env` 由 Docker Compose 加载,直接运行 Python 时需在终端设置变量。 + +在启动服务的 PowerShell 终端中,可设置固定的本机隐私密码。 + +```powershell +$env:DATABACK_PRIVACY_PASSWORD = "替换为你自己的隐私密码" +``` + +| 配置 | 用途 | +| --- | --- | +| `DATABACK_PORT` | Python 服务端口,默认 `8767` | +| `DATABACK_DATA_DIR` | SQLite 数据目录,默认项目根目录的 `data/` | +| `DATABACK_SNAPSHOT_DIR` | 快照目录,默认与 SQLite 文件同级的 `snapshots/` | +| `MONGODB_URI`、`MONGODB_DATABASE` | 开发用 MongoDB 副本集连接和数据库名 | + +在 `web/` 沿用首次运行的虚拟环境 Python 路径,添加 `--port 8768 --db /path/to/ledger.sqlite3` 可指定端口和独立测试台账。测试数据与日常台账使用不同路径。 + +## 检查 + +在 `web/` 执行。 + +```sh +pnpm test +pnpm build +``` + +Windows 后端测试使用项目虚拟环境。 + +```powershell +..\.venv\Scripts\python.exe -m unittest discover -s tests -p 'test_*.py' +``` + +Linux / macOS 将 Python 路径换为 `../.venv/bin/python`。完整 MongoDB 测试需用 `DATABACK_TEST_MONGO_URI` 指向独立副本集,本机未配置时对应测试会跳过。GitHub Actions 会创建测试数据库并执行完整检查。 + +## 提交与发布 + +1. 从最新 `main` 创建分支,修改并完成检查。 +2. 提交、推送分支,创建 PR。修复提交引用对应 issue,完整解决使用 `Fixes #编号`。 +3. PR 检查通过后合并到 `main`。 +4. 等待 GitHub Actions 的 `test` 和 `publish` 成功。 +5. Docker 主机拉取镜像并更新应用。 + +```sh +docker compose pull app +docker compose up -d --no-deps app +docker compose ps +``` + +构建发布 `ghcr.io/cimorn/databack:latest` 和 `sha-完整提交编号`,支持 `amd64`、`arm64`。NAS 图形界面可在 DataBack 项目中重新部署并勾选“拉取最新镜像”。 + +## 数据与清理 + +- 本机完整备份时,先停止 Python 服务,再复制 `data/`。恢复时停止服务,放回对应数据目录后启动。 +- 服务端每天生成台账快照,保留最新 30 份。清空历史快照后,服务会继续生成新快照。 +- Docker 的数据库、快照和配置备份按部署文档操作。 [数据库备份与恢复](docs/docker.md#完整备份) +- 提交前运行 `git status --short`,只提交源码、锁文件和文档。凭据、数据库、快照、依赖、构建产物和测试输出保存在本机或部署主机。 +- 开发结束后可删除 `web/dist/`、`web/node_modules/`、`.venv/` 和 Python 缓存,再次开发时重新安装依赖并构建。 diff --git a/README.en.md b/README.en.md index f1b2c11..78830d7 100644 --- a/README.en.md +++ b/README.en.md @@ -53,36 +53,12 @@ Updates preserve data volumes and `.env`. Check status with `docker compose ps` ## Develop and publish -Requires Python 3.10+, Node.js 22.15+, and pnpm 10.28.2. +See [Web development](DEVELOPMENT.en.md) for setup, local previews, code changes, and test commands. -```sh -cd web -python -m pip install -r requirements.txt -pnpm install --frozen-lockfile -pnpm build -python app.py -``` - -Open . For frontend development, run `pnpm dev` from `web/` in another terminal. Keep the Python server running for API requests. - -```sh -pnpm test -pnpm build -python -m unittest discover -s tests -p 'test_*.py' -``` - -MongoDB integration tests require a separate replica set. Set `DATABACK_TEST_MONGO_URI` to its connection string. CI creates an isolated test database automatically. - -Edit `web/src/` for the interface and `web/backend/` for the API. Push to `main` to run tests and publish `ghcr.io/cimorn/databack:latest` through GitHub Actions. Each build also publishes a `sha-` tag for pinning or rolling back an image. +Push a branch and open a PR → merge into `main` after checks pass → wait for GitHub Actions to publish the image → pull the update on the Docker host. Images use `latest` and `sha-` tags. To build locally, run `docker build -t databack .` from the repository root. -## Desktop launcher - -On Windows, build `web/`, then double-click `desktop/启动.cmd` to start and `desktop/关闭.cmd` to stop. The launcher opens the local web app in your browser. Data is stored in `data/` at the repository root. - -Set the `DATABACK_PRIVACY_PASSWORD` environment variable before using private folders locally. - ## Back up and restore data - **Automatic backups:** The server saves one ledger snapshot per day and retains the latest 30. Docker stores these in the `databack_snapshots` volume by default. @@ -95,7 +71,7 @@ The ledger records folders and backup information. Save actual files and deploym ```text web/ Web interface, API, and tests -desktop/ Windows start and stop scripts +DEVELOPMENT.en.md Web development guide deploy/mongodb/ Optional MongoDB replica-set configuration Dockerfile Image build compose.yaml Docker deployment diff --git a/README.md b/README.md index 25c81fa..aeca750 100644 --- a/README.md +++ b/README.md @@ -53,36 +53,12 @@ docker compose up -d app ## 开发与发布 -需要 Python 3.10+、Node.js 22.15+、pnpm 10.28.2。 +环境安装、本地运行、修改代码和测试命令见 [网页开发文档](DEVELOPMENT.md)。 -```sh -cd web -python -m pip install -r requirements.txt -pnpm install --frozen-lockfile -pnpm build -python app.py -``` - -打开 。开发界面时另开终端,在 `web/` 运行 `pnpm dev`,API 由 Python 服务提供。 - -```sh -pnpm test -pnpm build -python -m unittest discover -s tests -p 'test_*.py' -``` - -MongoDB 集成测试使用独立副本集,通过 `DATABACK_TEST_MONGO_URI` 指定测试连接。CI 自动创建测试数据库。 - -修改 `web/src/` 更新界面,修改 `web/backend/` 更新接口。提交并推送到 `main` 后,GitHub Actions 自动测试并发布 `ghcr.io/cimorn/databack:latest`。也会发布 `sha-完整提交编号` 标签,可用于固定镜像或回退。 +推送分支并创建 PR → 检查通过后合并到 `main` → 等待 GitHub Actions 发布镜像 → Docker 主机拉取更新。镜像同时提供 `latest` 和 `sha-完整提交编号` 标签。 本机构建镜像:`docker build -t databack .`(在项目根目录执行)。 -## 桌面启动 - -Windows 构建 `web/` 后,双击 `desktop/启动.cmd`;关闭时双击 `desktop/关闭.cmd`。启动器使用浏览器打开本机网页,数据保存在项目根目录的 `data/`。 - -使用本机隐私目录前,设置 `DATABACK_PRIVACY_PASSWORD` 环境变量。 - ## 数据备份与恢复 - **自动备份:** 服务端每天保存一份台账快照,保留最新 30 份;Docker 默认保存在 `databack_snapshots` 数据卷。 @@ -95,7 +71,7 @@ Windows 构建 `web/` 后,双击 `desktop/启动.cmd`;关闭时双击 `deskt ```text web/ 网页界面、API、测试 -desktop/ Windows 启动与关闭脚本 +DEVELOPMENT.md 网页开发说明 deploy/mongodb/ 可选 MongoDB 副本集配置 Dockerfile 镜像构建 compose.yaml Docker 部署 diff --git a/desktop/launcher-utils.ps1 b/desktop/launcher-utils.ps1 deleted file mode 100644 index afce230..0000000 --- a/desktop/launcher-utils.ps1 +++ /dev/null @@ -1,111 +0,0 @@ -# Shared ownership checks for startup, readiness cleanup and shutdown. -# Parse Windows argv rather than searching for the script in arbitrary arguments. -if (-not ('FileBackup.Launcher.NativeCommandLine' -as [type])) { - Add-Type -TypeDefinition @' -using System; -using System.ComponentModel; -using System.Runtime.InteropServices; -namespace FileBackup.Launcher { - public static class NativeCommandLine { - [DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern IntPtr CommandLineToArgvW(string commandLine, out int count); - [DllImport("kernel32.dll")] - private static extern IntPtr LocalFree(IntPtr memory); - public static string[] Split(string commandLine) { - if (String.IsNullOrWhiteSpace(commandLine)) { return new string[0]; } - int count; - IntPtr memory = CommandLineToArgvW(commandLine, out count); - if (memory == IntPtr.Zero) { throw new Win32Exception(); } - try { - string[] result = new string[count]; - for (int index = 0; index < count; index++) { - result[index] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(memory, index * IntPtr.Size)); - } - return result; - } finally { LocalFree(memory); } - } - } -} -'@ -} - -function ConvertFrom-WindowsCommandLine { - param([string]$CommandLine) - return [FileBackup.Launcher.NativeCommandLine]::Split($CommandLine) -} - -function Get-CanonicalAbsolutePath { - param([string]$Path) - if ([string]::IsNullOrWhiteSpace($Path)) { return $null } - if ($Path -notmatch '^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+[\\/])') { return $null } - try { return [System.IO.Path]::GetFullPath($Path.Replace('/', '\')) } - catch { return $null } -} - -function Test-PythonCandidate { - param([string]$Executable, [switch]$PyLauncher) - if ([string]::IsNullOrWhiteSpace($Executable)) { return $null } - if ($Executable -match '\\WindowsApps\\') { return $null } - $probe = New-Object System.Diagnostics.Process - try { - $probe.StartInfo.FileName = $Executable - $prefix = if ($PyLauncher) { '-3 ' } else { '' } - $probe.StartInfo.Arguments = $prefix + '-c "import sys; sys.exit(1) if sys.version_info < (3, 10) else print(sys.executable)"' - $probe.StartInfo.UseShellExecute = $false - $probe.StartInfo.CreateNoWindow = $true - $probe.StartInfo.RedirectStandardOutput = $true - $probe.StartInfo.RedirectStandardError = $true - $probe.StartInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8 - $probe.StartInfo.StandardErrorEncoding = [System.Text.Encoding]::UTF8 - $probe.StartInfo.EnvironmentVariables['PYTHONIOENCODING'] = 'utf-8' - if (-not $probe.Start()) { return $null } - if (-not $probe.WaitForExit(4000)) { $probe.Kill(); return $null } - if ($probe.ExitCode -ne 0) { return $null } - $resolvedExecutable = $probe.StandardOutput.ReadToEnd().Trim() - if (Test-Path -LiteralPath $resolvedExecutable -PathType Leaf) { return $resolvedExecutable } - } catch { return $null } - finally { $probe.Dispose() } - return $null -} - -$script:ledgerVerifiedPythonExecutables = @{} - -function Test-LedgerProcessOwnership { - param( - [object]$Candidate, - [string]$AppPath, - [string]$DatabasePath, - [int]$ListenPort = 0, - [string]$ExpectedPythonExecutable - ) - if ($null -eq $Candidate) { return $false } - $actualExecutable = Get-CanonicalAbsolutePath -Path $Candidate.ExecutablePath - $expectedApp = Get-CanonicalAbsolutePath -Path $AppPath - $expectedDatabase = Get-CanonicalAbsolutePath -Path $DatabasePath - if (-not $actualExecutable -or -not $expectedApp -or -not $expectedDatabase) { return $false } - if ([System.IO.Path]::GetFileName($actualExecutable) -notmatch '^python(?:\d+(?:\.\d+)*)?\.exe$') { return $false } - try { $arguments = @(ConvertFrom-WindowsCommandLine -CommandLine $Candidate.CommandLine) } - catch { return $false } - # Exactly the invocation produced by start.ps1; app.py must be the script entry. - if ($arguments.Count -ne 7 -or $arguments[1] -cne '-u' -or $arguments[3] -cne '--port' -or $arguments[5] -cne '--db') { return $false } - $invokedExecutable = Get-CanonicalAbsolutePath -Path $arguments[0] - $invokedApp = Get-CanonicalAbsolutePath -Path $arguments[2] - $invokedDatabase = Get-CanonicalAbsolutePath -Path $arguments[6] - if ($invokedExecutable -ne $actualExecutable -or $invokedApp -ne $expectedApp -or $invokedDatabase -ne $expectedDatabase) { return $false } - $invokedPort = 0 - if (-not [int]::TryParse($arguments[4], [ref]$invokedPort) -or $invokedPort -lt 1 -or $invokedPort -gt 65535) { return $false } - if ($ListenPort -ne 0 -and $invokedPort -ne $ListenPort) { return $false } - if (-not [string]::IsNullOrWhiteSpace($ExpectedPythonExecutable)) { - $expectedExecutable = Get-CanonicalAbsolutePath -Path $ExpectedPythonExecutable - if (-not $expectedExecutable -or $expectedExecutable -ne $actualExecutable) { return $false } - } - # ExecutablePath must identify a working Python interpreter, not an editor or - # merely an executable whose name looks like Python. Cache only this run's probe. - $cacheKey = $actualExecutable.ToLowerInvariant() - if (-not $script:ledgerVerifiedPythonExecutables.ContainsKey($cacheKey)) { - $confirmedExecutable = Get-CanonicalAbsolutePath -Path (Test-PythonCandidate -Executable $actualExecutable) - if ($confirmedExecutable -ne $actualExecutable) { return $false } - $script:ledgerVerifiedPythonExecutables[$cacheKey] = $true - } - return $true -} diff --git a/desktop/start.ps1 b/desktop/start.ps1 deleted file mode 100644 index aaaceeb..0000000 --- a/desktop/start.ps1 +++ /dev/null @@ -1,215 +0,0 @@ -[CmdletBinding()] -param( - [ValidateRange(1, 65535)] - [int]$Port = 8767, - [switch]$NoBrowser -) - -$ErrorActionPreference = 'Stop' -$projectRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) -$webRoot = Join-Path $projectRoot 'web' -$appPath = Join-Path $webRoot 'app.py' -$dataDirectory = Join-Path $projectRoot 'data' -$metadataPath = Join-Path $dataDirectory 'server.json' -$databasePath = Join-Path $dataDirectory 'ledger.sqlite3' -$stdoutPath = Join-Path $dataDirectory 'server.stdout.log' -$stderrPath = Join-Path $dataDirectory 'server.stderr.log' -$portWasSpecified = $PSBoundParameters.ContainsKey('Port') - -function Get-OwnedProcess { - param([int]$ProcessId, [int]$ListenPort = 0, [string]$PythonExecutable) - if ($ProcessId -le 0) { return $null } - $candidate = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $ProcessId" -ErrorAction SilentlyContinue - if (-not (Test-LedgerProcessOwnership -Candidate $candidate -AppPath $appPath -DatabasePath $databasePath -ListenPort $ListenPort -ExpectedPythonExecutable $PythonExecutable)) { return $null } - return $candidate -} - -function Get-ServerMetadata { - if (-not (Test-Path -LiteralPath $metadataPath -PathType Leaf)) { return $null } - try { return Get-Content -LiteralPath $metadataPath -Raw -Encoding UTF8 | ConvertFrom-Json } - catch { Write-Warning '启动记录无法读取,将重新检查端口。'; return $null } -} - -function Test-LedgerHealth { - param([int]$ListenPort) - try { - $health = Invoke-RestMethod -Uri "http://127.0.0.1:$ListenPort/api/health" -Method Get -TimeoutSec 1 -UseBasicParsing - return ($health.app -eq 'filebackup-ledger' -and $health.status -eq 'ok') - } catch { return $false } -} - -function Get-PortState { - param([int]$ListenPort) - $ownerIds = @() - try { - $listeners = @(Get-NetTCPConnection -LocalPort $ListenPort -State Listen -ErrorAction Stop) - $ownerIds = @($listeners | Select-Object -ExpandProperty OwningProcess -Unique) - if ($ownerIds.Count -gt 0) { return [pscustomobject]@{ Busy = $true; OwnerIds = $ownerIds } } - } catch { - # On Windows without TCP ownership data, never infer ownership from health alone. - } - $client = New-Object System.Net.Sockets.TcpClient - try { - $attempt = $client.BeginConnect('127.0.0.1', $ListenPort, $null, $null) - if ($attempt.AsyncWaitHandle.WaitOne(300)) { - try { $client.EndConnect($attempt) } catch { } - } - return [pscustomobject]@{ Busy = $client.Connected; OwnerIds = $ownerIds } - } finally { $client.Dispose() } -} - -function Save-ServerMetadata { - param([int]$ProcessId, [int]$ListenPort, [string]$PythonExecutable) - $record = [ordered]@{ - schemaVersion = 1 - pid = $ProcessId - port = $ListenPort - appPath = $appPath - pythonExecutable = $PythonExecutable - startedAt = [DateTime]::UtcNow.ToString('o') - url = "http://127.0.0.1:$ListenPort/" - } - $temporaryPath = Join-Path $dataDirectory ('server.' + [guid]::NewGuid().ToString('N') + '.tmp') - try { - $record | ConvertTo-Json | Set-Content -LiteralPath $temporaryPath -Encoding UTF8 - Move-Item -LiteralPath $temporaryPath -Destination $metadataPath -Force - } finally { - if (Test-Path -LiteralPath $temporaryPath -PathType Leaf) { Remove-Item -LiteralPath $temporaryPath -Force } - } -} - -function ConvertTo-WindowsArgument { - param([string]$Value) - $escaped = [regex]::Replace($Value, '(\\*)"', '$1$1\"') - $escaped = [regex]::Replace($escaped, '(\\+)$', '$1$1') - return '"' + $escaped + '"' -} - -function Find-Python { - $seen = @{} - foreach ($name in @('python.exe', 'python3.exe', 'python', 'python3')) { - $commands = @(Get-Command -Name $name -CommandType Application -ErrorAction SilentlyContinue) - foreach ($command in $commands) { - if ($seen.ContainsKey($command.Source)) { continue } - $seen[$command.Source] = $true - $found = Test-PythonCandidate -Executable $command.Source - if ($found) { return $found } - } - } - $py = Get-Command -Name 'py.exe' -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($py) { - $found = Test-PythonCandidate -Executable $py.Source -PyLauncher - if ($found) { return $found } - } - foreach ($candidate in @( - (Join-Path $projectRoot '.venv\Scripts\python.exe'), - (Join-Path $env:USERPROFILE 'miniconda3\python.exe'), - (Join-Path $env:USERPROFILE '.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe') - )) { - if (Test-Path -LiteralPath $candidate -PathType Leaf) { - $found = Test-PythonCandidate -Executable $candidate - if ($found) { return $found } - } - } - throw '找不到 Python 3.10 或更高版本。请先安装 Python,或配置可用的本地 Python 运行环境,再双击“启动.cmd”。启动脚本不会联网安装软件。' -} - -function Open-Ledger { - param([int]$ListenPort) - $url = "http://127.0.0.1:$ListenPort/" - Write-Host "文件备份台账已就绪:$url" - if (-not $NoBrowser) { - try { Start-Process -FilePath $url } - catch { Write-Warning "浏览器未自动打开,请复制上面的地址访问。" } - } -} - -function Invoke-LedgerStartup { - if (-not (Test-Path -LiteralPath $appPath -PathType Leaf)) { throw '缺少 app.py,请保持程序文件夹完整。' } - if (-not (Test-Path -LiteralPath (Join-Path $webRoot 'dist\index.html') -PathType Leaf)) { - throw '缺少 dist/index.html。请使用完整发行文件夹;开发者可运行 pnpm build 生成界面。' - } - $requestedPort = $Port - $metadata = Get-ServerMetadata - if ($metadata -and $metadata.appPath -eq $appPath -and $metadata.pid -and $metadata.port) { - $owned = Get-OwnedProcess -ProcessId ([int]$metadata.pid) -ListenPort ([int]$metadata.port) -PythonExecutable $metadata.pythonExecutable - if ($owned) { - $recordedPort = [int]$metadata.port - if ($portWasSpecified -and $requestedPort -ne $recordedPort) { - throw '本项目已在其他端口运行。请先双击“关闭.cmd”,再用 -Port 指定新端口。' - } - $state = Get-PortState -ListenPort $recordedPort - if ($state.OwnerIds -contains [int]$metadata.pid -and (Test-LedgerHealth -ListenPort $recordedPort)) { - Open-Ledger -ListenPort $recordedPort - return - } - throw '本项目后台仍在运行,但未通过就绪检查。请查看 data/server.stderr.log,或先双击“关闭.cmd”再启动。' - } - } - $state = Get-PortState -ListenPort $requestedPort - if ($state.Busy) { - foreach ($ownerId in $state.OwnerIds) { - $owner = Get-OwnedProcess -ProcessId ([int]$ownerId) -ListenPort $requestedPort - if ($owner -and (Test-LedgerHealth -ListenPort $requestedPort)) { - New-Item -ItemType Directory -Path $dataDirectory -Force | Out-Null - Save-ServerMetadata -ProcessId ([int]$ownerId) -ListenPort $requestedPort -PythonExecutable $owner.ExecutablePath - Open-Ledger -ListenPort $requestedPort - return - } - } - throw "端口 $requestedPort 已被占用,无法确认该服务属于本项目。脚本没有停止它。请运行 powershell -NoProfile -ExecutionPolicy Bypass -File start.ps1 -Port 8768,或先自行处理端口占用。" - } - $python = Find-Python - New-Item -ItemType Directory -Path $dataDirectory -Force | Out-Null - $arguments = '-u ' + (ConvertTo-WindowsArgument $appPath) + ' --port ' + $requestedPort + ' --db ' + (ConvertTo-WindowsArgument $databasePath) - $started = Start-Process -FilePath $python -ArgumentList $arguments -WorkingDirectory $projectRoot -WindowStyle Hidden -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath -PassThru - try { - Save-ServerMetadata -ProcessId $started.Id -ListenPort $requestedPort -PythonExecutable $python - $timer = [System.Diagnostics.Stopwatch]::StartNew() - while ($timer.Elapsed.TotalSeconds -lt 10) { - $started.Refresh() - if ($started.HasExited) { throw '后台进程提前退出。请查看 data/server.stderr.log 中的错误信息。' } - if (Test-LedgerHealth -ListenPort $requestedPort) { - $readyState = Get-PortState -ListenPort $requestedPort - if ($readyState.OwnerIds -contains $started.Id -and (Get-OwnedProcess -ProcessId $started.Id -ListenPort $requestedPort -PythonExecutable $python)) { - Open-Ledger -ListenPort $requestedPort - return - } - } - Start-Sleep -Milliseconds 250 - } - throw '后台未在 10 秒内就绪。请查看 data/server.stderr.log,检查运行环境后重试。' - } catch { - $startupFailure = $_ - if (Get-OwnedProcess -ProcessId $started.Id -ListenPort $requestedPort -PythonExecutable $python) { - Stop-Process -Id $started.Id -Force -ErrorAction SilentlyContinue - } - $latest = Get-ServerMetadata - if ($latest -and $latest.appPath -eq $appPath -and [int]$latest.pid -eq $started.Id) { - Remove-Item -LiteralPath $metadataPath -Force -ErrorAction SilentlyContinue - } - throw $startupFailure - } -} - -$mutex = $null -$lockTaken = $false -$exitCode = 0 -try { - . (Join-Path $PSScriptRoot 'launcher-utils.ps1') - $sha = [System.Security.Cryptography.SHA256]::Create() - try { $digest = $sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($projectRoot.ToLowerInvariant())) } - finally { $sha.Dispose() } - $lockName = 'Local\FileBackupLedger-' + ([System.BitConverter]::ToString($digest).Replace('-', '').Substring(0, 24)) - $mutex = New-Object System.Threading.Mutex($false, $lockName) - try { $lockTaken = $mutex.WaitOne(0) } catch [System.Threading.AbandonedMutexException] { $lockTaken = $true } - if (-not $lockTaken) { throw '本项目的启动检查正在进行,请稍后重试。' } - Invoke-LedgerStartup -} catch { - Write-Host ('启动失败:' + $_.Exception.Message) -ForegroundColor Red - $exitCode = 1 -} finally { - if ($lockTaken) { $mutex.ReleaseMutex() } - if ($mutex) { $mutex.Dispose() } -} -exit $exitCode diff --git a/desktop/stop.ps1 b/desktop/stop.ps1 deleted file mode 100644 index 50e7815..0000000 --- a/desktop/stop.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -[CmdletBinding()] -param() - -$ErrorActionPreference = 'Stop' -$projectRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) -$webRoot = Join-Path $projectRoot 'web' -$appPath = Join-Path $webRoot 'app.py' -$databasePath = Join-Path $projectRoot 'data\ledger.sqlite3' -$metadataPath = Join-Path $projectRoot 'data\server.json' -$exitCode = 0 - -try { - . (Join-Path $PSScriptRoot 'launcher-utils.ps1') - if (-not (Test-Path -LiteralPath $metadataPath -PathType Leaf)) { - Write-Host '没有本项目的后台启动记录。' - } else { - try { $metadata = Get-Content -LiteralPath $metadataPath -Raw -Encoding UTF8 | ConvertFrom-Json } - catch { throw '无法读取 data/server.json,未停止任何进程。请检查启动记录。' } - if ($metadata.appPath -ne $appPath -or -not $metadata.pid) { - throw '启动记录不属于当前程序文件夹,未停止任何进程。移动文件夹前请先在原位置关闭后台。' - } - $processId = [int]$metadata.pid - if ($processId -le 0) { throw '启动记录中的 PID 无效,未停止任何进程。' } - $candidate = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $processId" -ErrorAction SilentlyContinue - if ($null -eq $candidate) { - Remove-Item -LiteralPath $metadataPath -Force - Write-Host '后台已经关闭,已清理旧启动记录。' - } else { - if (-not (Test-LedgerProcessOwnership -Candidate $candidate -AppPath $appPath -DatabasePath $databasePath -ListenPort ([int]$metadata.port) -ExpectedPythonExecutable $metadata.pythonExecutable)) { - throw '启动记录的 PID 对应其他进程,未停止它。请重新启动本项目以更新记录。' - } - Stop-Process -Id $processId -Force -ErrorAction Stop - Remove-Item -LiteralPath $metadataPath -Force - Write-Host '文件备份台账后台已关闭。数据保存在 data/ledger.sqlite3。' - } - } -} catch { - Write-Host ('关闭失败:' + $_.Exception.Message) -ForegroundColor Red - $exitCode = 1 -} -exit $exitCode diff --git "a/desktop/\345\205\263\351\227\255.cmd" "b/desktop/\345\205\263\351\227\255.cmd" deleted file mode 100644 index 841b734..0000000 --- "a/desktop/\345\205\263\351\227\255.cmd" +++ /dev/null @@ -1,9 +0,0 @@ -@echo off -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop.ps1" %* -if errorlevel 1 ( - echo. - echo Shutdown failed. Read the error above and README.md for help. - pause - exit /b 1 -) -exit /b 0 diff --git "a/desktop/\345\220\257\345\212\250.cmd" "b/desktop/\345\220\257\345\212\250.cmd" deleted file mode 100644 index a1f5438..0000000 --- "a/desktop/\345\220\257\345\212\250.cmd" +++ /dev/null @@ -1,9 +0,0 @@ -@echo off -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start.ps1" %* -if errorlevel 1 ( - echo. - echo Startup failed. Read the error above and README.md for help. - pause - exit /b 1 -) -exit /b 0 diff --git a/web/app.py b/web/app.py index 104c605..0b2544f 100644 --- a/web/app.py +++ b/web/app.py @@ -1,4 +1,4 @@ -"""Absolute-path entry point used by the Windows launcher.""" +"""Start the local DataBack web server.""" from backend.server import main