diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d291942..e486259 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,52 +1,52 @@ -name: release draft +name: release +# Every push to main is checked; only a commit whose VERSION has no tag yet +# builds, tags, and publishes. Manual runs retry the same decision on main. on: push: - tags: ['v*'] + branches: [main] workflow_dispatch: - inputs: - tag: - description: Existing tag matching VERSION on main (never creates a tag) - type: string - required: true permissions: contents: read concurrency: - group: release-${{ inputs.tag || github.ref_name }} + group: release cancel-in-progress: false jobs: prepare: + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 5 outputs: - commit: ${{ steps.tag.outputs.commit }} - version: ${{ steps.tag.outputs.version }} + release: ${{ steps.plan.outputs.release }} + commit: ${{ steps.plan.outputs.commit }} + version: ${{ steps.plan.outputs.version }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: + ref: ${{ github.sha }} fetch-depth: 0 persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: '3.12' - - name: Verify existing main-line tag and VERSION - id: tag - env: - PT_TAG: ${{ inputs.tag || github.ref_name }} - run: python scripts/release.py check-tag --tag "$PT_TAG" + - name: Decide whether VERSION is new + id: plan + run: python scripts/release.py plan --commit "$GITHUB_SHA" build: needs: prepare + if: needs.prepare.outputs.release == 'true' uses: ./.github/workflows/build.yml with: source-ref: ${{ needs.prepare.outputs.commit }} release-version: ${{ needs.prepare.outputs.version }} - draft: + publish: needs: [prepare, build] + if: needs.prepare.outputs.release == 'true' runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -64,11 +64,9 @@ jobs: with: name: pt-cli-bundle-${{ needs.build.outputs.commit }}-${{ github.run_attempt }} path: dist/release - - name: Recheck tag and upload only an unpublished draft + - name: Tag, upload to a draft, and publish env: GH_TOKEN: ${{ github.token }} PT_TAG: ${{ needs.prepare.outputs.version }} - PT_COMMIT: ${{ needs.build.outputs.commit }} - run: | - python scripts/release.py check-tag --tag "$PT_TAG" --expected-commit "$PT_COMMIT" - python scripts/release.py create-draft --repository "$GITHUB_REPOSITORY" --tag "$PT_TAG" --commit "$PT_COMMIT" --assets dist/release + PT_COMMIT: ${{ needs.prepare.outputs.commit }} + run: python scripts/release.py publish --repository "$GITHUB_REPOSITORY" --tag "$PT_TAG" --commit "$PT_COMMIT" --assets dist/release --changelog CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..47be57c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog + +Each release has one section, headed by its exact `VERSION`. A merge to `main` +that changes `VERSION` publishes that section as the release notes; see +[docs/RELEASING.md](docs/RELEASING.md). Links inside a section are absolute, +because the notes are also shown on the release page. + +## v0.4.0-alpha.1 + +The first published release of pt cli. Both `pt` and the compatible `ptctl` +entry point are in every package. Everything here is alpha: the commands, the +`ptctl.dev/v1` JSON schema, and the private-store formats can still change. + +### What works + +- **Metafiles:** strict bounded bencode, exact v1/v2/hybrid identity, and a + private exact-byte, no-clobber metafile store. +- **Content proof:** v1 piece and v2 Merkle verification, bounded discovery of + renamed or scattered bytes, and copy-only, journaled materialization. +- **TJUPT:** session, account, search, detail, and bonus reads; acknowledged + metafile fetch; at-most-once bonus exchange; and `site login` with password + and optional two-step code, saving the session cookie to an owner-only file. +- **M-Team:** session, account, search (with paging and filters), detail, own + torrent lists (seeding, leeching, completed, incomplete, uploaded), and bonus + reads; acknowledged metafile fetch and at-most-once bonus exchange through the + official API; and `site login` saving the API key. +- **Saved credentials:** after `site login`, every site command uses the saved + credential; `site logout` removes it. +- **Downloaders:** qBittorrent and Transmission reads, plus reviewed stopped + adoption, recheck/start, stop, and keep-data removal of one exact job. +- **Reconciliation:** one report that keeps site, downloader, metafile, and + storage evidence on separate axes. +- **Source retirement:** reviewed unlinking of exact source names and removal + of exact empty parents. +- **Automation:** `--output json` on every command, stable exit codes, stdin-only + secrets, and explicit `--acknowledge-*` flags for every effect; see + [docs/AUTOMATION.md](https://github.com/tonycoder-hub/ptctl/blob/v0.4.0-alpha.1/docs/AUTOMATION.md). + +### Known limits + +- M-Team metafile fetch and bonus exchange pass offline tests but were not run + against a real torrent or exchange. M-Team messages and RSS are not supported. +- A TJUPT session cookie expires; run `site login` again when a read reports + the session is no longer authenticated. +- Concurrent `pt` processes do not share a request rate limit; run site + commands one at a time. +- Packages exist for Windows amd64, Linux amd64, and macOS arm64 only, and are + not code-signed or notarized. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 034e72c..5b82e22 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,7 +47,8 @@ before artifact upload; the final assembly checks that all three targets agree on version and commit. CI and release calls share `.github/workflows/build.yml`. The release controls have standard-library regression tests: `python -B -m unittest discover -s scripts/tests -v`. -See [RELEASING.md](docs/RELEASING.md) for version/tag rules and draft-only delivery. +See [RELEASING.md](docs/RELEASING.md) for VERSION and CHANGELOG rules and the +merge-triggered release. For a local snapshot, inject `cli.Version` and `cli.Commit` with the same `-X` linker flags used by CI, then run the acceptance script with the two binaries and matching `--version` / `--commit` values. Mark uncommitted builds as local diff --git a/README.md b/README.md index 3fdea89..e1123a7 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,8 @@ For an extracted macOS/Linux package, run `sh examples/readonly/try.sh` for an offline walkthrough. Discover the core commands with `pt torrent --help`, `pt help client list`, and `pt help config`. -> Status: `v0.4.0-alpha` development. Ordinary inspection, downloader reads, -> content proof, discovery, planning, and reconciliation are intentionally +> Status: `v0.4.0-alpha.1`, an alpha release. Ordinary inspection, downloader +> reads, content proof, discovery, planning, and reconciliation are intentionally > zero-write. Persistent writes and tracker-visible effects are confined to > explicit store/index commands and separately acknowledged operations; see > [write boundaries](#write-boundaries) and the full @@ -55,7 +55,7 @@ capabilities at the edge, not assumptions in the core domain model. and password login with an optional two-step code that issues the session cookie; and an experimental M-Team adapter with session, account, search, detail, - and bonus reads plus acknowledged metafile fetch and at-most-once bonus + own-torrent-list, and bonus reads plus acknowledged metafile fetch and at-most-once bonus exchange through the official API and a site-issued API key. - **Downloaders:** qBittorrent and Transmission reads, plus reviewed stopped adoption, recheck/start, stop, and keep-data removal of one exact job. @@ -83,29 +83,32 @@ Run `ptctl help` for the exact flags of every command. ## Install -Preview packages for Windows amd64, Linux amd64, and macOS arm64 are built by -CI after tests and extracted-binary acceptance. Download the -`pt-cli-bundle--` artifact from a successful `ci` run on -[Actions](https://github.com/tonycoder-hub/ptctl/actions) (artifacts expire -after 14 days), then follow the +Packages for Windows amd64, Linux amd64, and macOS arm64 are on +[Releases](https://github.com/tonycoder-hub/ptctl/releases), with +`SHA256SUMS` and `release-manifest.json`; follow the [checksum and extraction steps](docs/READ_ONLY_QUICKSTART.md). Each package contains both commands, the short guide, synthetic samples, licenses, build identity, and SHA-256 checksums. Packages are not code-signed or notarized. +What changed in each release is in [CHANGELOG.md](CHANGELOG.md). Preview +packages of any commit are the `pt-cli-bundle--` artifact of +a successful `ci` run on +[Actions](https://github.com/tonycoder-hub/ptctl/actions) (artifacts expire +after 14 days). -To build from source you need Go 1.24 or newer. The published tags predate the -current code, so install from `main`: +To build from source you need Go 1.24 or newer: ```bash -go install github.com/tonycoder-hub/ptctl/cmd/pt@main -go install github.com/tonycoder-hub/ptctl/cmd/ptctl@main # optional compatible name +go install github.com/tonycoder-hub/ptctl/cmd/pt@v0.4.0-alpha.1 +go install github.com/tonycoder-hub/ptctl/cmd/ptctl@v0.4.0-alpha.1 # optional compatible name ``` -Source builds report `dev` / `unknown` from `pt version`. CI stamps both -commands with `+g` and the full commit (on pull -requests, the tested merge commit). Maintainers stage releases with the -[release procedure](docs/RELEASING.md): it builds an existing version tag and -only ever creates an unpublished draft. See [CONTRIBUTING.md](CONTRIBUTING.md) -for local checks and synthetic binary acceptance. +Use `@main` instead for unreleased changes. Source builds report `dev` / +`unknown` from `pt version`. CI stamps both commands with +`+g` and the full commit (on pull requests, the tested +merge commit). A merge to `main` that changes `VERSION` publishes that version; +see the [release procedure](docs/RELEASING.md). See +[CONTRIBUTING.md](CONTRIBUTING.md) for local checks and synthetic binary +acceptance. ## Five-minute start diff --git a/VERSION b/VERSION index 3db6d73..d2c2720 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v0.4.0-alpha +v0.4.0-alpha.1 diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index 7537013..6aebf15 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -107,6 +107,7 @@ constant, a port interface, and one entry there. | `bonus.offer.review` | `BonusReviewReader` | config and session | `site bonus review` | | `bonus.exchange.submit_effectful` | `BonusExchangeWriter` | config and session | `site bonus exchange prepare`, `submit` | | `auth.login_effectful` | `SessionLoginer` | login | `site login` | +| `account.torrents.read` | `AccountTorrentLister` | direct | `site torrents` | ### Direct ports @@ -209,7 +210,7 @@ change: add it to the allowlist and to the CLI tests in the same commit. ## Public failure causes -Ordinary reads (`status`, `account`, `search`, `bonus-catalog`) fold every +Ordinary reads (`status`, `account`, `search`, `torrents`, `bonus-catalog`) fold every adapter error into `site CMD failed`, so an adapter's own error text never reaches the user. An adapter may wrap one of the sentinels in `internal/site/errors.go` to let the CLI name a fixed, secret-free cause: @@ -269,7 +270,7 @@ and do it in a separate behavior-preserving commit. | NexusPHP forks, including TJUPT | Cookie sessions match `cookie_header`, and HTML responses match the existing ports. | Page recognition and parsers for that fork, with synthetic fixtures. Forks differ, so do not assume TJUPT's pages. | | Unit3D | Cookie-session web pages fit. | Using its token-authenticated API instead runs into the gaps below. | | Gazelle-based trackers | Cookie sessions fit; their JSON responses need a JSON parser rather than HTML recognition. | Where an API key replaces the session cookie, the gaps below apply. | -| M-Team | Status, account, search, detail, the bonus shop catalog, review, and exchange, the signed-link metafile download, and live-site reconciliation are implemented in `internal/site/mteam` over the JSON API with an API key. | RSS, seeding lists, and messages are not implemented. | +| M-Team | Status, account, search, detail, the account's own torrent lists, the bonus shop catalog, review, and exchange, the signed-link metafile download, and live-site reconciliation are implemented in `internal/site/mteam` over the JSON API with an API key. | Messages need a browser login the API key cannot replace, and RSS links are rotating secrets; neither is implemented. | ## Gaps for API-token sites @@ -282,7 +283,7 @@ or a security control, so it needs its own review. | Gap | Status | Where | What is left | |---|---|---|---| | Only one auth method existed | Done | `domain.AuthMethodAPIKeyHeader` (`api_key_header`); `knownAuthMethod` in `internal/site/descriptor.go` | Nothing. | -| Credential input was cookie-only | Done | `--api-key-stdin` and `readAPIKeyCredential` in `internal/cli` serve `site status`, `account`, `search`, `detail`, `bonus-catalog`, and `bonus review`; `site metafile fetch` and `site bonus exchange submit` read it with `readEffectfulAPIKeyCredential`; `reconcile` takes `--site-api-key-stdin`, `--site-live`, and the bundle's `site_api_key` | Nothing. The `--credential-bundle-stdin` of `site bonus exchange submit` still carries a cookie, because only TJUPT confirms an exchange with the password. | +| Credential input was cookie-only | Done | `--api-key-stdin` and `readAPIKeyCredential` in `internal/cli` serve `site status`, `account`, `search`, `torrents`, `detail`, `bonus-catalog`, and `bonus review`; `site metafile fetch` and `site bonus exchange submit` read it with `readEffectfulAPIKeyCredential`; `reconcile` takes `--site-api-key-stdin`, `--site-live`, and the bundle's `site_api_key` | Nothing. The `--credential-bundle-stdin` of `site bonus exchange submit` still carries a cookie, because only TJUPT confirms an exchange with the password. | | The CLI gated on cookies | Done | Every site command picks the method with `siteCredentialSourceFor` and checks that the site supports it | Nothing. | | The transport only sent `Cookie` | Done | `httpguard.NewWithHeaderCredential` binds one validated, non-reserved header | Nothing. | | Redaction did not know the header | Done | `security.Redact` covers `x-api-key` header lines and `apiKey`-style fields | Nothing. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0fd9545..fed328a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -79,7 +79,8 @@ internal/reconcile internal/site optional AuthChecker / AccountReader / TorrentSearcher / - BonusCatalogReader / BonusReviewReader ports and a capability-gated + BonusCatalogReader / BonusReviewReader / AccountTorrentLister ports and + a capability-gated effectful metafile port |-- httpguard the only HTTP client site adapters use |-- mteam M-Team JSON API reads with an API key @@ -356,6 +357,7 @@ Capabilities are small and explicit: - `bonus.offer.review` - `bonus.exchange.submit_effectful` - `auth.login_effectful` +- `account.torrents.read` `auth.login_effectful` (`site.SessionLoginer`) signs in with an account password and optional one-time code, typed at hidden terminal prompts or read diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 3a69988..ad03da3 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -50,8 +50,8 @@ Every JSON result is a single object on stdout, indented with two spaces: | Area | Kinds | |---|---| | General | `version` | -| Site reads | `site.descriptor.list` (`site list`, `site capabilities`), `site.session`, `site.account`, `site.torrent.list`, `site.torrent.detail`, `site.bonus.catalog`, `site.bonus.offer_review` | -| Site login | `site.login` | +| Site reads | `site.descriptor.list` (`site list`, `site capabilities`), `site.session`, `site.account`, `site.torrent.list`, `site.torrent.detail`, `site.account.torrent.list` (`site torrents`), `site.bonus.catalog`, `site.bonus.offer_review` | +| Site login | `site.login`, `site.logout` | | Bonus exchange | `site.bonus.exchange.prepare`, `site.bonus.exchange.submit`, `site.bonus.exchange.status`, `site.bonus.exchange.operation_list`, `site.bonus.exchange.prune`, `site.bonus.exchange.forget` | | Site metafiles | `site.metafile.fetch`, `site.metafile.binding.list`, `site.metafile.binding.inspect` | | Metafiles | `metafile.manifest` (`torrent inspect`), `content.verification` (`torrent verify`), `metafile.store.init`, `metafile.store.import`, `metafile.store.inspect` | diff --git a/docs/FEATURES.md b/docs/FEATURES.md index dd4df0b..9ef7864 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -114,9 +114,12 @@ deliberately does not. For step-by-step usage, see the - an experimental M-Team session check, account snapshot (username, uploaded and downloaded bytes, ratio, and bonus), torrent search by page, mode, category, and free promotion with seeders, leechers, promotion factors, and - category names, torrent detail for one remote ID, and a bonus-shop catalog - and exact-goods review, through read-only POSTs to the official JSON API (one - per invocation; the catalog reads the balance and the shop on one client), + category names, torrent detail for one remote ID, the account's own + seeding, leeching, completed, incomplete, and uploaded torrent lists with + each row's traffic scope, and a bonus-shop catalog and exact-goods review, + through read-only POSTs to the official JSON API (one per invocation; the + torrent lists read the account ID and the list, and the catalog the balance + and the shop, on one client), authenticated by a site-issued API key saved by `site login` or piped on stdin, with no redirect, proxy, or retry; - an explicitly acknowledged M-Team metafile fetch for one remote ID: one diff --git a/docs/MTEAM_ADAPTER.md b/docs/MTEAM_ADAPTER.md index 155d997..13320fe 100644 --- a/docs/MTEAM_ADAPTER.md +++ b/docs/MTEAM_ADAPTER.md @@ -5,13 +5,15 @@ M-Team (馒头PT, TP :: mTorrent) is the second experimental site and the first that uses a site-issued API key instead of a session cookie. The adapter talks only to M-Team's own hosts, starting at the official JSON API at -`https://api2.m-team.cc`, and declares six reads and two acknowledged +`https://api2.m-team.cc`, and declares seven reads and two acknowledged effects: - session check (`site status`); - account snapshot (`site account`); - torrent search (`site search`), with category names; - torrent detail (`site detail`); +- the account's own torrent lists (`site torrents`): seeding, leeching, + completed, incomplete, and uploaded; - bonus shop catalog (`site bonus-catalog`) and one-offer review (`site bonus review`); - metafile download (`site metafile fetch`), which is tracker-visible and needs @@ -55,6 +57,8 @@ ptctl site search mteam "Ubuntu" ptctl site search --output json mteam "Ubuntu" ptctl site search --page 2 --category 419,439 --free mteam "Ubuntu" ptctl site detail mteam REMOTE_ID +ptctl site torrents mteam +ptctl site torrents --state completed --page 2 mteam ptctl site bonus-catalog mteam ptctl site bonus review mteam OPTION ptctl site metafile fetch --acknowledge-site-effect --metafile-store "$PTCTL_STORE" mteam REMOTE_ID @@ -82,19 +86,20 @@ sent. `--cookie-stdin` is refused because the adapter does not accept cookies. ## Requests -Each read sends exactly one request and never retries, except `bonus-catalog`, -which sends two on one connection (the download takes more; see [Metafile -download](#metafile-download)): +Each read sends exactly one request and never retries, except `torrents` and +`bonus-catalog`, which send two on one connection (the download takes more; see +[Metafile download](#metafile-download)): | Command | Request | Body | |---|---|---| | `site status`, `site account` | `POST /api/member/profile` | an empty `multipart/form-data` form | | `site search` | `POST /api/torrent/search` | `{"mode":"normal","keyword":QUERY,"pageNumber":1,"pageSize":50}`; the options below add `categories` and `discount` and change `mode` and `pageNumber` | | `site detail` | `POST /api/torrent/detail` | a `multipart/form-data` form with the one field `id` | +| `site torrents` | `POST /api/member/profile`, then `POST /api/member/getUserTorrentList` | an empty `multipart/form-data` form, then `{"userid":ID,"type":STATE,"pageNumber":N,"pageSize":50}` | | `site bonus-catalog` | `POST /api/member/profile`, then `POST /api/mall/list` | an empty `multipart/form-data` form each | | `site bonus review` | `POST /api/mall/list` | an empty `multipart/form-data` form | -The API exposes these reads as POST requests. All five endpoints only read; +The API exposes these reads as POST requests. All six endpoints only read; the reads send no other endpoint. In particular, `site detail` never calls `/api/torrent/viewHits`, which the website's own detail page calls to count a view. The request uses the same strict transport as every @@ -164,6 +169,46 @@ exact pair is read as not found, because the API uses code `1` for other refusals too. Live-site reconciliation reads the same detail, as described in [Reconciliation](#reconciliation). +**Own torrents.** `site torrents` reads one page of up to 50 of the account's +own torrents, by default the first page of the seeding list. The list needs +the account's numeric ID, so the command first reads the profile and then the +list, on one connection; the ID is never printed. + +| Option | API field | Accepts | +|---|---|---| +| `--state STATE` | `type` | `seeding` (default), `leeching`, `completed`, `incomplete`, or `uploaded` | +| `--page N` | `pageNumber` | 1 to 1000 | + +A page past the last one is empty; an empty list shows its page without a +page count in the table. An invalid state or page is a usage error +(exit 2) before the key is read or any request is sent. + +Each row has the torrent fields that search reports, plus the account's +traffic, seed time, and last action. Traffic is in bytes actually transferred, +not the promotion-adjusted amounts that count toward the ratio, and comes from +one of two sources, named by `traffic_scope` in JSON and `TRAFFIC` in the +table: + +| `traffic_scope` | Table | Source | Covers | +|---|---|---|---| +| `account_total` | `total` | the snatch record (`uploadedReal`, `downloadedReal`) | the account's whole history with the torrent | +| `current_session` | `session` | the current peer (`uploaded`, `downloaded`) | what the running client reported for its current session | + +The snatch record wins when the API sends both, and the two are never mixed in +one row. Seed time comes only from the snatch record, in seconds. In the live +check the seeding list carried only the current peer, so its traffic was +`session` and its seed time was absent, while the completed list carried the +snatch record. The peer's IP addresses, peer ID, and client name are in the +API answer but are never decoded, so they cannot reach the output. A response +without a list, or with any row that has no recognizable torrent, fails the +whole page; a torrent repeated on one page is kept once. + +**Live check.** On 2026-10-16 and 2026-10-17 `site torrents mteam` and `site +torrents --state completed --output json mteam` were run live with a saved key, +two requests each. The seeding list first held five torrents with `session` +traffic and later was empty; the completed list held five torrents, all +`account_total` with a seed time. No output held the key or a peer address. + **Times.** The API returns times without a zone, such as `2026-10-14 09:30:00`. ptctl reads them as UTC+8, the site's time zone, and reports them in UTC. @@ -341,7 +386,13 @@ item; it is covered by synthetic tests only. ## Not supported yet -RSS, seeding lists, and messages are not implemented. +- **Messages.** The API refuses message reads with an API key: `msg/search` + answers code `401` with "Full authentication is required", so messages need + a browser login that ptctl does not hold. Two counter endpoints do answer, + but what they count cannot be checked against readable messages, so ptctl + does not report them. +- **RSS.** An RSS link carries its own signed, rotating secret; ptctl does not + create, print, or store one. ## Fixtures diff --git a/docs/README.md b/docs/README.md index dcdac0d..89c3d0a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -32,7 +32,7 @@ documents that matter to them. adapter and its page-level contract. - [Materialize retention](MATERIALIZE_RETENTION.md): the prune/forget state machine for materialize operations. -- [Releasing](RELEASING.md): VERSION and tag rules, and the draft-only release +- [Releasing](RELEASING.md): VERSION and CHANGELOG rules, and the merge-triggered release workflow. ## Coding agents and automation diff --git a/docs/READ_ONLY_QUICKSTART.md b/docs/READ_ONLY_QUICKSTART.md index b1fa54e..ff5c35f 100644 --- a/docs/READ_ONLY_QUICKSTART.md +++ b/docs/READ_ONLY_QUICKSTART.md @@ -14,8 +14,9 @@ commit **整体成功**的 `ci` run,下载 `pt-cli-bundle--` artifact,或单独的 `pt-cli-windows-amd64--` artifact。 bundle 同时含 Windows amd64、Linux amd64、macOS arm64 包。PR run 的版本标识 是实际测试的 merge commit。artifact 保留 14 天。已正式发布的版本可以从 -仓库 Releases 下载对应 ZIP、`SHA256SUMS` 和 `release-manifest.json`;维护者 -创建的 Draft 不等于已公开发布。所有包均无代码签名或 macOS notarization。 +仓库 [Releases](https://github.com/tonycoder-hub/ptctl/releases) 下载对应 ZIP、 +`SHA256SUMS` 和 `release-manifest.json`;它们没有外层 artifact ZIP,其余校验 +步骤相同。所有包均无代码签名或 macOS notarization。 先解开 GitHub 下载的 artifact 外层 ZIP;其中是产品 ZIP 和 `SHA256SUMS`。 在该目录打开 PowerShell,验证并解包: diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 1eed97f..6e15a5f 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,21 +1,26 @@ # pt cli 发布流程 -发布源版本在仓库根目录 `VERSION`,当前是 `v0.4.0-alpha`。CI 预览身份为 -`+g<实际测试提交前12位>`;发布身份必须与已存在的 tag 和该提交的 -`VERSION` 完全一致。接受 `vMAJOR.MINOR.PATCH` 和 `-rc.1`、`-alpha` 等 -SemVer prerelease,不接受发布 tag 的 build metadata 或前导零。 +发布由合入 main 触发,版本号以仓库根目录 `VERSION` 为准。CI 预览身份为 +`+g<实际测试提交前12位>`;发布身份就是该提交的 `VERSION`。接受 +`vMAJOR.MINOR.PATCH` 和 `-rc.1`、`-alpha.1` 等 SemVer prerelease,不接受 +build metadata 或前导零。 ## 维护者操作 -1. 通过正常 PR 更新 `VERSION`、说明和代码,检查 CI,再经授权合入 main。 -2. 确认要发布的 main-line commit、版本和授权后,创建并推送该版本的 tag。 - 推荐 annotated tag。此步骤由维护者显式执行,工作流从不创建或移动 tag。 -3. `v*` tag push 自动触发 `release draft`。也可以在 Actions 手动运行它, - 输入一个已经存在的 tag。手动触发需要此工作流已进入默认分支。 -4. 等待整个 run 成功,再检查 Draft Release 的三个 ZIP、`SHA256SUMS` 和 - `release-manifest.json`,核对 tag、完整 commit、CI、下载后校验与发行说明。 -5. **公开发布是独立的人工操作**。工作流只创建 draft,不自动发布、不合并 PR, - 不设置 latest。带 prerelease 后缀的 tag 会标记为 prerelease。 +1. 在一个正常 PR 里把 `VERSION` 改成新版本,并在 `CHANGELOG.md` 里加一节 + `## `,写这一版的发行说明。新版本必须按 SemVer 高于所有已有的 + `v*` tag。PR CI 会检查当前 `VERSION` 在 `CHANGELOG.md` 里恰好有一节且非空, + 缺了就失败。 +2. CI 全绿后合入 main。合入后 `release` 工作流自动运行:三平台测试与构建、 + 创建 annotated tag ``、上传资产并公开发布 Release。 +3. 不改 `VERSION` 的普通合入也会触发 `release`,但只做判定:该版本的 tag + 已在更早的提交上,于是跳过构建和发布。 +4. 发布说明是 `CHANGELOG.md` 对应一节,后接 GitHub 自动生成的 PR 列表和 + 完整 commit。带 prerelease 后缀(含 `-`)的版本标记为 prerelease,不设为 + latest;正式版本设为 latest。 + +不需要手动打 tag;工作流从不移动已有 tag。也可以在 Actions 对 main 手动运行 +`release`,它按同样规则判定当前 main。 ## 构建与验收 @@ -44,20 +49,30 @@ Windows 使用 PowerShell `Expand-Archive`;macOS/Linux 使用系统 `unzip`。 ## 权限与失败语义 -默认 `contents: read`,仅依赖全部验证成功的最后一个 draft job 使用 +默认 `contents: read`,仅依赖全部验证成功的最后一个 publish job 使用 `contents: write`。只使用内置 `GITHUB_TOKEN`,checkout 不保留凭据;不要求 PAT。 -tag 必须解析到 main 历史中的提交,且其 `.github/workflows` 与当前 main 一致。 +发布的提交必须在 main 历史中,且其 `.github/workflows` 与当前 main 一致。 这也避免 GitHub 创建 Release 时对不同工作流版本要求额外 workflow 写权限, 详见 [GitHub Release API](https://docs.github.com/en/rest/releases/releases#create-a-release)。 -上传前再次读取 tag,上传后再核对,移动或不匹配会失败。 - -缺失 tag、版本不符、非 main 提交、任一测试失败、构建不一致、缺包、校验失败 -都会阻止 Release 创建。已存在的 draft 或公开 Release 均拒绝覆盖。资产上传 -按新 draft 的 ID 进行,并核对服务端 digest/state;网络中断或部分上传失败时, -留下未公开的 draft 供维护者检查,不自动重试、删除、替换或公开发布。修复后 -需先人工处理已有的不完整 draft,再 **Re-run all jobs**;不要只重跑个别 job, -因为资产名包含 run attempt,以免混用不同轮次的包。 - -这套流程的接入不等于已经创建正式 tag 或 Release。Release API 写入路径采用 -无网络的模拟回归验证;首次实际 draft 上传仍需在维护者授权的真实 tag 上确认。 -没有代码签名、Windows 签名或 macOS notarization;没有验证真实下载器凭据或任务。 +`release` 工作流串行运行,排队中的较新 run 会取代较早的待运行 run;较新的 +提交只要仍是同一 `VERSION`,就由它发布这一版。 + +判定在 `plan` 一步完成:`VERSION` 的 tag 在更早的提交上就跳过;没有 tag 时, +`VERSION` 低于或等于任一已有 tag、缺少发行说明、提交不在 main 上,都会让 +run 失败而不发布。发布按固定顺序写入,任一步失败即停止: + +1. 本地核对 main 历史、三平台资产、清单和全部校验值; +2. 确认没有同名 Release(含 draft),已存在则拒绝覆盖; +3. tag 不存在就创建 annotated tag;已存在则必须指向同一提交,否则失败; +4. 创建 draft,逐个上传资产并核对服务端 digest/state; +5. 再次读取 tag,确认上传期间没有移动; +6. 最后才把 draft 公开,并核对公开后的状态和资产。 + +因此失败最多留下 tag 和一个未公开的 draft,不会有资产不全的公开 Release。 +不自动重试、删除或替换。修复后先人工删除不完整的 draft(tag 保留),再对该 +run **Re-run all jobs**;tag 已在本提交上时会继续完成发布。不要只重跑个别 +job,因为资产名包含 run attempt,以免混用不同轮次的包。 + +Release API 写入路径采用无网络的模拟回归验证,首次真实运行是 +`v0.4.0-alpha.1`。没有代码签名、Windows 签名或 macOS notarization;没有验证 +真实下载器凭据或任务。 diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 620e890..bf3a0f5 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -179,22 +179,26 @@ session or revoke the key on the site. Account and downloader passwords are never saved. The file is not encrypted; an OS keyring or credential helper remains future work (see [Known gaps](#known-gaps-before-broader-mutation-support)). -The M-Team adapter's reads send bounded POSTs to four read-only JSON API -endpoints (`member/profile`, `torrent/search`, `torrent/detail`, and -`mall/list`), one per command except `bonus-catalog`, which sends `member/profile` -then `mall/list` on one client spaced three seconds apart. Each body is +The M-Team adapter's reads send bounded POSTs to five read-only JSON API +endpoints (`member/profile`, `torrent/search`, `torrent/detail`, +`member/getUserTorrentList`, and `mall/list`), one per command except +`torrents` and `bonus-catalog`, which send `member/profile` then +`member/getUserTorrentList` or `mall/list` on one client spaced three seconds +apart. The torrent list answer carries the account's peer addresses, peer ID, +and client name; the adapter never decodes them, so they cannot reach output +or logs. Each body is non-replayable and at most 16 KiB, and nothing is retried. Its metafile fetch sends one token POST, waits three seconds, and then makes at most two GETs as described above; the site's per-torrent daily download limit and burst refusals stop it as `rate_limited`. HTTP 429 is terminal. There is no cross-process limiter in the alpha, so callers must not loop or parallelize site commands. There is no Cloudflare or CAPTCHA bypass. -Ordinary status, account, search, bonus catalog/review, and detail reads use the +Ordinary status, account, search, own-torrent-list, bonus catalog/review, and detail reads use the same fresh HTTP/1.1, no-reuse, no-redirect transport as the effectful fetch. -For the shared ordinary read path (`status`, `account`, `search`, and -`bonus-catalog`), output mode, site/capability/authentication support, the -actual typed port, and a nonblank search query are checked before credential -stdin is consumed. Runtime adapter errors are mapped to fixed diagnostics; +For the shared ordinary read path (`status`, `account`, `search`, `torrents`, +and `bonus-catalog`), output mode, site/capability/authentication support, the +actual typed port, a nonblank search query, and the torrent list's state and +page are checked before credential stdin is consumed. Runtime adapter errors are mapped to fixed diagnostics; only cancellation and deadline causes, plus four fixed causes an adapter may opt in to (malformed or rejected credential, rate limit, blocked address), are preserved, never arbitrary cookie, key, URL, header, or response text. diff --git a/docs/guide/README.md b/docs/guide/README.md index a8a4af3..5eee531 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -14,7 +14,7 @@ and issues. | [Metafiles and the private store](metafiles.md) | `torrent inspect`, `metafile store`, `site metafile fetch`, sealed site bindings, and stored-metafile selectors | | [Storage profiles and indexes](storage.md) | `storage profile`, `storage index`, `reconcile refresh-report`, snapshot-backed discovery, and explicit source selection | | [Verify, discover, plan, and materialize](verify-and-materialize.md) | `torrent verify`, `seed discover`, `seed plan`, and `seed materialize` | -| [Site reads and bonus exchange](sites.md) | `site status`, `account`, `search`, `detail`, `bonus-catalog`, `site bonus review`, and `site bonus exchange` | +| [Site reads and bonus exchange](sites.md) | `site status`, `account`, `search`, `torrents`, `detail`, `bonus-catalog`, `site bonus review`, and `site bonus exchange` | | [Downloader reads, path mapping, and adoption](downloader.md) | `storage map`, `client status`, `client list`, and `client adopt` | | [Client activation, stop, and removal](client-lifecycle.md) | `client activate`, `client stop`, and `client remove` | | [Source retirement and parent cleanup](source-retirement.md) | `seed retire` and `seed retire parent-cleanup` | @@ -35,8 +35,8 @@ complete surface. ## Current status and write boundaries -> Status: `v0.4.0-alpha` development. Ordinary inspection, downloader reads, -> content proof, discovery, planning, and reconciliation are intentionally +> Status: `v0.4.0-alpha.1`, an alpha release. Ordinary inspection, downloader +> reads, content proof, discovery, planning, and reconciliation are intentionally > zero-write. Persistent writes are confined to explicit private-store/index > operations, the acknowledged `site metafile fetch`, the separately > acknowledged target-root-local `seed materialize run|resume|abandon|prune|forget` diff --git a/docs/guide/sites.md b/docs/guide/sites.md index 84358fa..6d8f509 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -163,7 +163,11 @@ API and never retry; search results add seeders, leechers, promotion, and category-name columns, and `search` takes `--page N`, `--mode normal|adult`, `--category ID`, and `--free`. `site metafile fetch` downloads one `.torrent` into the private store through M-Team's signed link, as described in -[metafiles.md](metafiles.md). `bonus-catalog` and `bonus review` read M-Team's +[metafiles.md](metafiles.md). `torrents` lists the account's own seeding, +leeching, completed, incomplete, or uploaded torrents with `--state` and +`--page`, reading the profile and then the list on one client; each row says +whether its traffic is the account's total or the running client's session. +`bonus-catalog` and `bonus review` read M-Team's bonus shop, and `bonus exchange submit` buys one unit of goods that need no input with the API key alone. `reconcile --site-live` reads live detail with the saved key. Setup, results, and error lines are in @@ -176,6 +180,8 @@ ptctl site account mteam ptctl site search mteam "Ubuntu" ptctl site search --page 2 --free mteam "Ubuntu" ptctl site detail mteam REMOTE_ID +ptctl site torrents mteam +ptctl site torrents --state completed mteam ptctl site bonus-catalog mteam ptctl site bonus review mteam GOODS_ID printf '%s' "$MTEAM_API_KEY" | ptctl site status --api-key-stdin mteam diff --git a/internal/cli/output.go b/internal/cli/output.go index 454fe06..d05c825 100644 --- a/internal/cli/output.go +++ b/internal/cli/output.go @@ -57,6 +57,8 @@ func jsonKind(data any) string { return typed.kind case domain.BonusCatalog: return "site.bonus.catalog" + case domain.AccountTorrentList: + return "site.account.torrent.list" case siteLoginReport: return "site.login" case siteLogoutReport: diff --git a/internal/cli/run.go b/internal/cli/run.go index a119d5f..2780646 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -141,6 +141,7 @@ Usage: ptctl site account [--cookie-stdin | --api-key-stdin] [--output table|json] SITE ptctl site search [--cookie-stdin | --api-key-stdin] [--page N] [--mode MODE] [--category ID]... [--free] [--output table|json] SITE QUERY... ptctl site detail [--cookie-stdin | --api-key-stdin] [--output table|json] SITE REMOTE_ID + ptctl site torrents [--cookie-stdin | --api-key-stdin] [--state seeding|leeching|completed|incomplete|uploaded] [--page N] [--output table|json] SITE ptctl site bonus-catalog [--cookie-stdin | --api-key-stdin] [--output table|json] SITE ptctl site bonus review [--cookie-stdin | --api-key-stdin] [--output table|json] SITE OPTION ptctl site bonus exchange prepare --state-store DIR --expect-review-id ID [--output table|json] SITE OPTION diff --git a/internal/cli/site.go b/internal/cli/site.go index 47d9688..0b143e7 100644 --- a/internal/cli/site.go +++ b/internal/cli/site.go @@ -23,7 +23,7 @@ func (a *app) site(args []string) error { return a.siteList(args[1:]) case "capabilities": return a.siteCapabilities(args[1:]) - case "status", "account", "search", "bonus-catalog": + case "status", "account", "search", "bonus-catalog", "torrents": return a.siteRead(args[0], args[1:]) case "detail": return a.siteDetail(args[1:]) @@ -128,6 +128,11 @@ func (a *app) siteRead(command string, args []string) error { fs.Var((*categoryListFlag)(&searchOptions.Categories), "category", "keep only this site category ID; repeat or separate with commas") fs.BoolVar(&searchOptions.FreeOnly, "free", false, "keep only torrents whose download is not counted") } + torrentQuery := site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding} + if command == "torrents" { + fs.Var((*accountTorrentStateFlag)(&torrentQuery.State), "state", "list to read: seeding, leeching, completed, incomplete, or uploaded (default seeding)") + fs.IntVar(&torrentQuery.Page, "page", 0, "result page, from 1 (default: the first page)") + } if err := fs.Parse(args); err != nil { return usageError("site %s: %v", command, err) } @@ -155,6 +160,7 @@ func (a *app) siteRead(command string, args []string) error { "account": domain.CapabilityAccountRead, "search": domain.CapabilitySearch, "bonus-catalog": domain.CapabilityBonusRead, + "torrents": domain.CapabilityAccountTorrents, }[command] descriptor := adapter.Descriptor() if !descriptor.Supports(capability) { @@ -225,6 +231,22 @@ func (a *app) siteRead(command string, args []string) error { return reader.BonusCatalog(ctx, credential) } warnings = append(warnings, "catalog is read-only; this command never submits purchase or redemption forms") + case "torrents": + lister, ok := adapter.(site.AccountTorrentLister) + if !ok { + return fmt.Errorf("site %q declares %q but does not implement its typed port", descriptor.ID, capability) + } + pageSet := false + fs.Visit(func(flag *flag.Flag) { pageSet = pageSet || flag.Name == "page" }) + if pageSet && torrentQuery.Page < 1 { + return usageError("--page must be 1 or more") + } + if err := lister.ValidateAccountTorrentQuery(torrentQuery); err != nil { + return usageError("%v", err) + } + read = func(ctx context.Context, credential site.Credential) (any, error) { + return lister.AccountTorrents(ctx, credential, torrentQuery) + } default: return usageError("unknown site read command %q", command) } @@ -328,6 +350,23 @@ func writeSiteHuman(out io.Writer, command string, data any, warnings []string) } fmt.Fprintf(w, "%s\t%s\n", terminalSafe(selector), terminalSafe(strings.Join(row.Columns, " | "))) } + case "torrents": + list := data.(domain.AccountTorrentList) + page := fmt.Sprint(list.Page) + // An empty list has zero pages; "1 of 0" would read as an error. + if list.TotalPages != nil && *list.TotalPages > 0 { + page += fmt.Sprintf(" of %d", *list.TotalPages) + } + fmt.Fprintf(w, "STATE\t%s\nPAGE\t%s\n", terminalSafe(string(list.State)), page) + if list.Total != nil { + fmt.Fprintf(w, "TOTAL\t%d\n", *list.Total) + } + fmt.Fprintln(w, "REF\tNAME\tSIZE\tTRAFFIC\tUPLOADED\tDOWNLOADED\tSEED TIME\tLAST ACTION") + for _, item := range list.Torrents { + fmt.Fprintf(w, "%s/%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", terminalSafe(item.Torrent.Ref.SiteID), terminalSafe(item.Torrent.Ref.RemoteID), + terminalSafe(item.Torrent.Name), searchSize(item.Torrent), trafficScope(item.TrafficScope), + optionalBytes(item.UploadedBytes), optionalBytes(item.DownloadedBytes), seedTime(item.SeedTimeSeconds), optionalTime(item.LastActionAt)) + } } if err := w.Flush(); err != nil { return err @@ -402,6 +441,68 @@ func promotionLabel(promotion *domain.Promotion) string { return label } +func optionalBytes(value *int64) string { + if value == nil { + return "-" + } + return humanBytes(*value) +} + +func optionalTime(value *time.Time) string { + if value == nil { + return "-" + } + return value.UTC().Format(time.RFC3339) +} + +// trafficScope names the span a row's traffic covers: "total" for the +// account's whole history, "session" for the client's running session. +func trafficScope(scope domain.AccountTrafficScope) string { + switch scope { + case domain.AccountTrafficTotal: + return "total" + case domain.AccountTrafficCurrentSession: + return "session" + case "": + return "-" + } + return "unknown" +} + +// seedTime renders whole seconds as days, hours, and minutes, for example +// "2d 3h 4m"; anything under a minute prints "0m". +func seedTime(seconds *int64) string { + if seconds == nil { + return "-" + } + minutes := *seconds / 60 + days, hours := minutes/(24*60), minutes/60%24 + minutes %= 60 + switch { + case days > 0: + return fmt.Sprintf("%dd %dh %dm", days, hours, minutes) + case hours > 0: + return fmt.Sprintf("%dh %dm", hours, minutes) + } + return fmt.Sprintf("%dm", minutes) +} + +// accountTorrentStateFlag accepts only the lists the CLI names, so a typo is +// a usage error before any site is consulted. +type accountTorrentStateFlag domain.AccountTorrentState + +func (state *accountTorrentStateFlag) String() string { return string(*state) } + +func (state *accountTorrentStateFlag) Set(value string) error { + switch parsed := domain.AccountTorrentState(value); parsed { + case domain.AccountTorrentsSeeding, domain.AccountTorrentsLeeching, domain.AccountTorrentsCompleted, + domain.AccountTorrentsIncomplete, domain.AccountTorrentsUploaded: + *state = accountTorrentStateFlag(parsed) + return nil + } + return fmt.Errorf("state must be seeding, leeching, completed, incomplete, or uploaded") +} + // categoryListFlag collects site category IDs from repeated or // comma-separated --category values. type categoryListFlag []string diff --git a/internal/cli/site_contract_test.go b/internal/cli/site_contract_test.go index ea0b9a9..de1b53c 100644 --- a/internal/cli/site_contract_test.go +++ b/internal/cli/site_contract_test.go @@ -52,7 +52,8 @@ const mteamDescriptorJSON = ` { "torrent.detail", "torrent.metafile.read_effectful", "bonus.offer.review", - "bonus.exchange.submit_effectful" + "bonus.exchange.submit_effectful", + "account.torrents.read" ] }` @@ -71,7 +72,7 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { {args: []string{"site", "capabilities", "--output", "json", "mteam"}, want: descriptorListJSON(mteamDescriptorJSON)}, {args: []string{"site", "list"}, want: "" + "ID NAME STABILITY BASE URL CAPABILITIES\n" + - "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 8\n" + + "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 9\n" + "tjupt TJUPT / 北洋园PT experimental https://www.tjupt.org/ 9\n"}, {args: []string{"site", "capabilities", "tjupt"}, want: "" + "SITE KIND VALUE\n" + @@ -95,7 +96,8 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { "mteam capability torrent.detail\n" + "mteam capability torrent.metafile.read_effectful\n" + "mteam capability bonus.offer.review\n" + - "mteam capability bonus.exchange.submit_effectful\n"}, + "mteam capability bonus.exchange.submit_effectful\n" + + "mteam capability account.torrents.read\n"}, } for _, test := range tests { t.Run(strings.Join(test.args, " "), func(t *testing.T) { diff --git a/internal/cli/site_torrents_test.go b/internal/cli/site_torrents_test.go new file mode 100644 index 0000000..ab853e0 --- /dev/null +++ b/internal/cli/site_torrents_test.go @@ -0,0 +1,208 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +// torrentListAdapter is an API-key site that lists the account's own torrents. +type torrentListAdapter struct { + apiKeySiteAdapter + list domain.AccountTorrentList + query site.AccountTorrentQuery + validateErr error + validated []site.AccountTorrentQuery +} + +func (*torrentListAdapter) Descriptor() domain.SiteDescriptor { + return domain.SiteDescriptor{ + ID: "api-key-test", Name: "API key test", BaseURL: "https://api.invalid/", Stability: "test", + AuthMethods: []domain.AuthMethod{domain.AuthMethodAPIKeyHeader}, + Capabilities: []domain.Capability{domain.CapabilityAuthCheck, domain.CapabilityAccountTorrents}, + } +} + +func (adapter *torrentListAdapter) ValidateAccountTorrentQuery(query site.AccountTorrentQuery) error { + adapter.validated = append(adapter.validated, query) + return adapter.validateErr +} + +func (adapter *torrentListAdapter) AccountTorrents(_ context.Context, credential site.Credential, query site.AccountTorrentQuery) (domain.AccountTorrentList, error) { + adapter.record(credential) + adapter.query = query + return adapter.list, adapter.err +} + +func sampleAccountTorrents() domain.AccountTorrentList { + size, uploaded, downloaded, seed := int64(1<<30), int64(2048), int64(0), int64(93784) + last := time.Date(2026, 10, 16, 4, 0, 0, 0, time.UTC) + total, pages := 51, 2 + return domain.AccountTorrentList{ + SiteID: "api-key-test", State: domain.AccountTorrentsCompleted, Page: 2, TotalPages: &pages, Total: &total, + Torrents: []domain.AccountTorrent{ + {Torrent: domain.TorrentSummary{Ref: domain.TorrentRef{SiteID: "api-key-test", RemoteID: "9001"}, Name: "Seeding canary", SizeBytes: &size}, + TrafficScope: domain.AccountTrafficTotal, UploadedBytes: &uploaded, DownloadedBytes: &downloaded, SeedTimeSeconds: &seed, LastActionAt: &last}, + {Torrent: domain.TorrentSummary{Ref: domain.TorrentRef{SiteID: "api-key-test", RemoteID: "9002"}, Name: "Bare\x1b[31m canary"}}, + {Torrent: domain.TorrentSummary{Ref: domain.TorrentRef{SiteID: "api-key-test", RemoteID: "9003"}, Name: "Session canary"}, + TrafficScope: domain.AccountTrafficCurrentSession, UploadedBytes: &uploaded}, + }, + ObservedAt: time.Date(2026, 10, 16, 5, 0, 0, 0, time.UTC), + } +} + +func TestSiteTorrentsReadsTheRequestedList(t *testing.T) { + useTempConfigDir(t) + adapter := &torrentListAdapter{list: sampleAccountTorrents()} + var out bytes.Buffer + a := &app{stdin: strings.NewReader(apiKeyCanary + "\n"), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.siteRead("torrents", []string{"--api-key-stdin", "--state", "completed", "--page", "2", "api-key-test"}); err != nil { + t.Fatal(err) + } + if adapter.calls != 1 || adapter.secret != apiKeyCanary || adapter.method != domain.AuthMethodAPIKeyHeader || + adapter.query != (site.AccountTorrentQuery{State: domain.AccountTorrentsCompleted, Page: 2}) || len(adapter.validated) != 1 { + t.Fatalf("calls=%d query=%#v validated=%#v", adapter.calls, adapter.query, adapter.validated) + } + want := "" + + "STATE completed\n" + + "PAGE 2 of 2\n" + + "TOTAL 51\n" + + "REF NAME SIZE TRAFFIC UPLOADED DOWNLOADED SEED TIME LAST ACTION\n" + + "api-key-test/9001 Seeding canary 1.00 GiB total 2.00 KiB 0 B 1d 2h 3m 2026-10-16T04:00:00Z\n" + + "api-key-test/9002 Bare\\x1b[31m canary unknown - - - - -\n" + + "api-key-test/9003 Session canary unknown session 2.00 KiB - - -\n" + if got := out.String(); got != want { + t.Fatalf("table drifted:\n%s\nwant:\n%s", got, want) + } + + // With the saved key and no flags, the seeding list's first page is read. + writeSavedCredential(t, "api-key-test", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary+"\n") + adapter = &torrentListAdapter{list: sampleAccountTorrents()} + stdin := &trackingReader{} + out.Reset() + a = &app{stdin: stdin, stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.siteRead("torrents", []string{"--output", "json", "api-key-test"}); err != nil { + t.Fatal(err) + } + if stdin.read || adapter.secret != savedAPIKeyCanary || adapter.query != (site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding}) { + t.Fatalf("read=%t query=%#v", stdin.read, adapter.query) + } + var envelope struct { + Schema string `json:"schema"` + Kind string `json:"kind"` + Data domain.AccountTorrentList `json:"data"` + } + if err := json.Unmarshal(out.Bytes(), &envelope); err != nil { + t.Fatal(err) + } + if envelope.Schema != "ptctl.dev/v1" || envelope.Kind != "site.account.torrent.list" || len(envelope.Data.Torrents) != 3 || + envelope.Data.Torrents[2].TrafficScope != domain.AccountTrafficCurrentSession || + envelope.Data.Torrents[0].SeedTimeSeconds == nil || *envelope.Data.Torrents[0].SeedTimeSeconds != 93784 || + strings.Contains(out.String(), "CANARY") { + t.Fatalf("json=%s", out.String()) + } +} + +func TestSiteTorrentsRefusesBadInputBeforeStdin(t *testing.T) { + useTempConfigDir(t) + for _, test := range []struct { + name string + adapter site.Adapter + args []string + want string + }{ + {name: "unknown state", adapter: &torrentListAdapter{}, args: []string{"--state", "seek", "api-key-test"}, + want: `site torrents: invalid value "seek" for flag -state: state must be seeding, leeching, completed, incomplete, or uploaded`}, + {name: "page zero", adapter: &torrentListAdapter{}, args: []string{"--page", "0", "api-key-test"}, want: "--page must be 1 or more"}, + {name: "site refuses the query", adapter: &torrentListAdapter{validateErr: errors.New("page must be from 1 to 9")}, + args: []string{"--page", "10", "api-key-test"}, want: "page must be from 1 to 9"}, + {name: "site without the capability", adapter: &apiKeySiteAdapter{}, args: []string{"api-key-test"}, + want: `site "api-key-test" does not declare capability "account.torrents.read"`}, + {name: "search flag", adapter: &torrentListAdapter{}, args: []string{"--free", "api-key-test"}, + want: "site torrents: flag provided but not defined: -free"}, + {name: "extra argument", adapter: &torrentListAdapter{}, args: []string{"api-key-test", "seeding"}, + want: "site torrents requires exactly one SITE"}, + {name: "nothing saved", adapter: &torrentListAdapter{}, args: []string{"api-key-test"}, + want: `no saved API key for site "api-key-test"; run 'ptctl site login api-key-test' first, or pipe one with --api-key-stdin`}, + } { + t.Run(test.name, func(t *testing.T) { + reader := &trackingReader{} + var out bytes.Buffer + a := &app{stdin: reader, stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(test.adapter)} + var usage *usageErr + if err := a.siteRead("torrents", test.args); !errors.As(err, &usage) || err.Error() != test.want || reader.read || out.Len() != 0 { + t.Fatalf("err=%v read=%t stdout=%q", err, reader.read, out.String()) + } + if lister, ok := test.adapter.(*torrentListAdapter); ok && lister.calls != 0 { + t.Fatalf("site read %d times", lister.calls) + } + }) + } +} + +func TestSiteTorrentsKeepsPublicErrorsSecretFree(t *testing.T) { + useTempConfigDir(t) + for _, cause := range []error{site.ErrCredentialRejected, site.ErrRateLimited, errors.New("CANARY server text")} { + adapter := &torrentListAdapter{apiKeySiteAdapter: apiKeySiteAdapter{err: fmt.Errorf("wrapped: %w", cause)}} + var out bytes.Buffer + a := &app{stdin: strings.NewReader(apiKeyCanary), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + err := a.siteRead("torrents", []string{"--api-key-stdin", "api-key-test"}) + want := "site torrents failed" + if errors.Is(cause, site.ErrCredentialRejected) || errors.Is(cause, site.ErrRateLimited) { + want = fmt.Sprintf("site torrents failed: %v", cause) + } + if err == nil || err.Error() != want || out.Len() != 0 { + t.Fatalf("cause=%v err=%v stdout=%q", cause, err, out.String()) + } + } +} + +func TestSeedTimeRendersDaysHoursAndMinutes(t *testing.T) { + for _, test := range []struct { + seconds *int64 + want string + }{ + {nil, "-"}, + {int64Pointer(0), "0m"}, + {int64Pointer(59), "0m"}, + {int64Pointer(3599), "59m"}, + {int64Pointer(3600), "1h 0m"}, + {int64Pointer(86399), "23h 59m"}, + {int64Pointer(86400), "1d 0h 0m"}, + {int64Pointer(400 * 86400), "400d 0h 0m"}, + } { + if got := seedTime(test.seconds); got != test.want { + t.Fatalf("seedTime(%v)=%q want %q", test.seconds, got, test.want) + } + } +} + +func int64Pointer(value int64) *int64 { return &value } + +func TestSiteTorrentsShowsAnEmptyList(t *testing.T) { + useTempConfigDir(t) + zero := 0 + adapter := &torrentListAdapter{list: domain.AccountTorrentList{SiteID: "api-key-test", State: domain.AccountTorrentsSeeding, Page: 1, + TotalPages: &zero, Total: &zero, Torrents: []domain.AccountTorrent{}}} + var out bytes.Buffer + a := &app{stdin: strings.NewReader(apiKeyCanary), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.siteRead("torrents", []string{"--api-key-stdin", "api-key-test"}); err != nil { + t.Fatal(err) + } + want := "" + + "STATE seeding\n" + + "PAGE 1\n" + + "TOTAL 0\n" + + "REF NAME SIZE TRAFFIC UPLOADED DOWNLOADED SEED TIME LAST ACTION\n" + if got := out.String(); got != want { + t.Fatalf("table drifted:\n%s\nwant:\n%s", got, want) + } +} diff --git a/internal/domain/site.go b/internal/domain/site.go index 42e362f..5858a24 100644 --- a/internal/domain/site.go +++ b/internal/domain/site.go @@ -25,6 +25,8 @@ const ( CapabilityBonusRead Capability = "bonus.catalog.read" CapabilityBonusReview Capability = "bonus.offer.review" CapabilityBonusExchange Capability = "bonus.exchange.submit_effectful" + // CapabilityAccountTorrents lists the account's own torrents by state. + CapabilityAccountTorrents Capability = "account.torrents.read" ) type SiteDescriptor struct { @@ -142,6 +144,54 @@ type Promotion struct { EndsAt *time.Time `json:"ends_at,omitempty"` } +// AccountTorrentState names one of the account's own torrent lists. +type AccountTorrentState string + +const ( + AccountTorrentsSeeding AccountTorrentState = "seeding" + AccountTorrentsLeeching AccountTorrentState = "leeching" + AccountTorrentsCompleted AccountTorrentState = "completed" + AccountTorrentsIncomplete AccountTorrentState = "incomplete" + AccountTorrentsUploaded AccountTorrentState = "uploaded" +) + +// AccountTrafficScope says what span of time an AccountTorrent's traffic +// covers. +type AccountTrafficScope string + +const ( + // AccountTrafficTotal is the account's whole history with the torrent. + AccountTrafficTotal AccountTrafficScope = "account_total" + // AccountTrafficCurrentSession is what the account's client reported for + // the session it is running now. + AccountTrafficCurrentSession AccountTrafficScope = "current_session" +) + +// AccountTorrent is one row of the account's own torrent list. The traffic +// fields are the site's claim for this account and torrent, in bytes actually +// transferred; they are not the promotion-adjusted amounts that count toward +// the ratio. TrafficScope says which span they cover and is absent when the +// row has no traffic. +type AccountTorrent struct { + Torrent TorrentSummary `json:"torrent"` + TrafficScope AccountTrafficScope `json:"traffic_scope,omitempty"` + UploadedBytes *int64 `json:"uploaded_bytes,omitempty"` + DownloadedBytes *int64 `json:"downloaded_bytes,omitempty"` + SeedTimeSeconds *int64 `json:"seed_time_seconds,omitempty"` + LastActionAt *time.Time `json:"last_action_at,omitempty"` +} + +// AccountTorrentList is one page of one of the account's own torrent lists. +type AccountTorrentList struct { + SiteID string `json:"site_id"` + State AccountTorrentState `json:"state"` + Page int `json:"page"` + TotalPages *int `json:"total_pages,omitempty"` + Total *int `json:"total,omitempty"` + Torrents []AccountTorrent `json:"torrents"` + ObservedAt time.Time `json:"observed_at"` +} + // BonusCatalogRow intentionally preserves site-defined columns. Bonus shop // semantics are not portable enough to force into a universal purchase model. type BonusCatalogRow struct { diff --git a/internal/site/descriptor.go b/internal/site/descriptor.go index abb2682..670f12a 100644 --- a/internal/site/descriptor.go +++ b/internal/site/descriptor.go @@ -76,15 +76,16 @@ func knownAuthMethod(method domain.AuthMethod) bool { // typed port an adapter must implement for it. Adding a capability means // adding a domain constant, a port interface, and one entry here. var capabilityPorts = map[domain.Capability]func(Adapter) bool{ - domain.CapabilityAuthCheck: func(a Adapter) bool { _, ok := a.(AuthChecker); return ok }, - domain.CapabilityAccountRead: func(a Adapter) bool { _, ok := a.(AccountReader); return ok }, - domain.CapabilitySearch: func(a Adapter) bool { _, ok := a.(TorrentSearcher); return ok }, - domain.CapabilityBonusRead: func(a Adapter) bool { _, ok := a.(BonusCatalogReader); return ok }, - domain.CapabilityDetail: func(a Adapter) bool { _, ok := a.(TorrentDetailReader); return ok }, - domain.CapabilityMetafile: func(a Adapter) bool { _, ok := a.(MetafileFetcher); return ok }, - domain.CapabilityBonusReview: func(a Adapter) bool { _, ok := a.(BonusReviewReader); return ok }, - domain.CapabilityBonusExchange: func(a Adapter) bool { _, ok := a.(BonusExchangeWriter); return ok }, - domain.CapabilityLogin: func(a Adapter) bool { _, ok := a.(SessionLoginer); return ok }, + domain.CapabilityAuthCheck: func(a Adapter) bool { _, ok := a.(AuthChecker); return ok }, + domain.CapabilityAccountRead: func(a Adapter) bool { _, ok := a.(AccountReader); return ok }, + domain.CapabilitySearch: func(a Adapter) bool { _, ok := a.(TorrentSearcher); return ok }, + domain.CapabilityBonusRead: func(a Adapter) bool { _, ok := a.(BonusCatalogReader); return ok }, + domain.CapabilityDetail: func(a Adapter) bool { _, ok := a.(TorrentDetailReader); return ok }, + domain.CapabilityMetafile: func(a Adapter) bool { _, ok := a.(MetafileFetcher); return ok }, + domain.CapabilityBonusReview: func(a Adapter) bool { _, ok := a.(BonusReviewReader); return ok }, + domain.CapabilityBonusExchange: func(a Adapter) bool { _, ok := a.(BonusExchangeWriter); return ok }, + domain.CapabilityLogin: func(a Adapter) bool { _, ok := a.(SessionLoginer); return ok }, + domain.CapabilityAccountTorrents: func(a Adapter) bool { _, ok := a.(AccountTorrentLister); return ok }, } // KnownCapabilities returns every capability that has a typed port, in a @@ -100,6 +101,7 @@ func KnownCapabilities() []domain.Capability { domain.CapabilityBonusReview, domain.CapabilityBonusExchange, domain.CapabilityLogin, + domain.CapabilityAccountTorrents, } } diff --git a/internal/site/descriptor_test.go b/internal/site/descriptor_test.go index c8e9158..3d231c4 100644 --- a/internal/site/descriptor_test.go +++ b/internal/site/descriptor_test.go @@ -128,7 +128,7 @@ func TestKnownCapabilitiesCoverEveryDomainCapabilityOnce(t *testing.T) { for _, capability := range []domain.Capability{ domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityDetail, domain.CapabilityMetafile, domain.CapabilityBonusRead, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, - domain.CapabilityLogin, + domain.CapabilityLogin, domain.CapabilityAccountTorrents, } { if !seen[capability] { t.Fatalf("missing %q", capability) diff --git a/internal/site/driver.go b/internal/site/driver.go index 7cef2e3..7dd456d 100644 --- a/internal/site/driver.go +++ b/internal/site/driver.go @@ -95,6 +95,22 @@ type BonusCatalogReader interface { BonusCatalog(context.Context, Credential) (domain.BonusCatalog, error) } +// AccountTorrentQuery picks one page of one of the account's own torrent +// lists. +type AccountTorrentQuery struct { + State domain.AccountTorrentState + // Page is 1-based; zero means the first page. + Page int +} + +// AccountTorrentLister reads the account's own torrent lists. +// ValidateAccountTorrentQuery runs before any credential is read, so a state +// or page the site cannot serve is refused without a request. +type AccountTorrentLister interface { + ValidateAccountTorrentQuery(AccountTorrentQuery) error + AccountTorrents(context.Context, Credential, AccountTorrentQuery) (domain.AccountTorrentList, error) +} + type Registry struct { adapters map[string]Adapter } diff --git a/internal/site/mteam/adapter.go b/internal/site/mteam/adapter.go index 80aee86..dfda76f 100644 --- a/internal/site/mteam/adapter.go +++ b/internal/site/mteam/adapter.go @@ -92,6 +92,7 @@ func (a *Adapter) Descriptor() domain.SiteDescriptor { domain.CapabilityMetafile, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, + domain.CapabilityAccountTorrents, }, } } diff --git a/internal/site/mteam/adapter_test.go b/internal/site/mteam/adapter_test.go index 07a4ad1..14052f6 100644 --- a/internal/site/mteam/adapter_test.go +++ b/internal/site/mteam/adapter_test.go @@ -86,6 +86,7 @@ func TestIdentityIsPinned(t *testing.T) { Capabilities: []domain.Capability{ domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityBonusRead, domain.CapabilityDetail, domain.CapabilityMetafile, domain.CapabilityBonusReview, domain.CapabilityBonusExchange, + domain.CapabilityAccountTorrents, }, } if got := New().Descriptor(); !reflect.DeepEqual(got, want) { diff --git a/internal/site/mteam/parse.go b/internal/site/mteam/parse.go index b27627e..4a0e838 100644 --- a/internal/site/mteam/parse.go +++ b/internal/site/mteam/parse.go @@ -127,38 +127,48 @@ func parseSearch(data json.RawMessage) ([]domain.TorrentSummary, error) { results := make([]domain.TorrentSummary, 0, len(*response.Data)) seen := make(map[string]struct{}, len(*response.Data)) for _, item := range *response.Data { - if !item.ID.set || !canonicalID(item.ID.value) || item.Name == nil { - return nil, fmt.Errorf("M-Team search row was not recognized") - } - name, ok := cleanText(*item.Name, 1024) - if !ok || name == "" { + summary, ok := summaryFromItem(item) + if !ok { return nil, fmt.Errorf("M-Team search row was not recognized") } if _, duplicate := seen[item.ID.value]; duplicate { continue } seen[item.ID.value] = struct{}{} - summary := domain.TorrentSummary{ - Ref: domain.TorrentRef{SiteID: SiteID, RemoteID: item.ID.value}, - Name: name, - SizeBytes: byteCount(item.Size), - PublishedAt: siteTime(item.CreatedDate), - } - if canonicalID(item.Category.value) { - summary.Category = item.Category.value - summary.CategoryName = categoryName(item.Category.value) - } - if status := item.Status; status != nil { - summary.Seeders = count(status.Seeders) - summary.Leechers = count(status.Leechers) - summary.Snatches = count(status.TimesCompleted) - summary.Promotion = promotion(status.Discount.value, siteTime(status.DiscountEndTime)) - } results = append(results, summary) } return results, nil } +// summaryFromItem maps one API torrent object. It refuses an object without a +// canonical ID and a name; every other field is optional. +func summaryFromItem(item searchItem) (domain.TorrentSummary, bool) { + if !item.ID.set || !canonicalID(item.ID.value) || item.Name == nil { + return domain.TorrentSummary{}, false + } + name, ok := cleanText(*item.Name, 1024) + if !ok || name == "" { + return domain.TorrentSummary{}, false + } + summary := domain.TorrentSummary{ + Ref: domain.TorrentRef{SiteID: SiteID, RemoteID: item.ID.value}, + Name: name, + SizeBytes: byteCount(item.Size), + PublishedAt: siteTime(item.CreatedDate), + } + if canonicalID(item.Category.value) { + summary.Category = item.Category.value + summary.CategoryName = categoryName(item.Category.value) + } + if status := item.Status; status != nil { + summary.Seeders = count(status.Seeders) + summary.Leechers = count(status.Leechers) + summary.Snatches = count(status.TimesCompleted) + summary.Promotion = promotion(status.Discount.value, siteTime(status.DiscountEndTime)) + } + return summary, true +} + // promotion maps the API's discount names to traffic factors. An absent // discount means NORMAL, as on the site itself; an unknown name yields no // claim rather than a guessed one. diff --git a/internal/site/mteam/torrents.go b/internal/site/mteam/torrents.go new file mode 100644 index 0000000..08a2e8b --- /dev/null +++ b/internal/site/mteam/torrents.go @@ -0,0 +1,186 @@ +package mteam + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +const ( + userTorrentsPath = "api/member/getUserTorrentList" + userTorrentsPageSize = 50 + // maxUserTorrentsPage is the largest pageNumber the API accepts. + maxUserTorrentsPage = 1000 +) + +// userTorrentTypes maps each list the adapter serves to the API's type name. +var userTorrentTypes = map[domain.AccountTorrentState]string{ + domain.AccountTorrentsSeeding: "SEEDING", + domain.AccountTorrentsLeeching: "LEECHING", + domain.AccountTorrentsCompleted: "COMPLETED", + domain.AccountTorrentsIncomplete: "INCOMPLETE", + domain.AccountTorrentsUploaded: "UPLOADED", +} + +// ValidateAccountTorrentQuery accepts the seeding, leeching, completed, +// incomplete, and uploaded lists and a page from 1 to 1000. +func (a *Adapter) ValidateAccountTorrentQuery(query site.AccountTorrentQuery) error { + if _, ok := userTorrentTypes[query.State]; !ok { + return fmt.Errorf("M-Team torrent list state must be seeding, leeching, completed, incomplete, or uploaded") + } + if query.Page < 0 || query.Page > maxUserTorrentsPage { + return fmt.Errorf("M-Team torrent list page must be from 1 to %d", maxUserTorrentsPage) + } + return nil +} + +// AccountTorrents reads the account ID from the profile and then one page of +// the list, both on one client. Each row carries the torrent and the +// account's snatch record, the current peer, or both; the peer's address, +// peer ID, and client name are never decoded. +func (a *Adapter) AccountTorrents(ctx context.Context, credential site.Credential, query site.AccountTorrentQuery) (domain.AccountTorrentList, error) { + if err := a.ValidateAccountTorrentQuery(query); err != nil { + return domain.AccountTorrentList{}, err + } + if err := ctx.Err(); err != nil { + return domain.AccountTorrentList{}, err + } + client, err := a.openClient(credential) + if err != nil { + return domain.AccountTorrentList{}, err + } + defer client.Close() + data, err := post(ctx, client, profilePath, emptyFormMediaType, []byte(emptyFormBody)) + if err != nil { + return domain.AccountTorrentList{}, err + } + userID, err := parseProfileID(data) + if err != nil { + return domain.AccountTorrentList{}, err + } + page := query.Page + if page == 0 { + page = 1 + } + body, err := json.Marshal(userTorrentsRequest{UserID: userID, Type: userTorrentTypes[query.State], PageNumber: page, PageSize: userTorrentsPageSize}) + if err != nil { + return domain.AccountTorrentList{}, fmt.Errorf("encode M-Team torrent list request failed") + } + data, err = post(ctx, client, userTorrentsPath, jsonMediaType, body) + if err != nil { + return domain.AccountTorrentList{}, err + } + list, err := parseUserTorrents(data) + if err != nil { + return domain.AccountTorrentList{}, err + } + list.State = query.State + list.Page = page + list.ObservedAt = time.Now().UTC() + return list, nil +} + +type userTorrentsRequest struct { + UserID string `json:"userid"` + Type string `json:"type"` + PageNumber int `json:"pageNumber"` + PageSize int `json:"pageSize"` +} + +type userTorrentsResponse struct { + Total flexText `json:"total"` + TotalPages flexText `json:"totalPages"` + Data *[]userTorrentRow `json:"data"` +} + +// userTorrentRow deliberately omits the peer's ip, ipv6, peerId, and agent. +type userTorrentRow struct { + Torrent *searchItem `json:"torrent"` + Peer *struct { + Uploaded flexText `json:"uploaded"` + Downloaded flexText `json:"downloaded"` + LastAction flexText `json:"lastAction"` + } `json:"peer"` + Snatched *struct { + UploadedReal flexText `json:"uploadedReal"` + DownloadedReal flexText `json:"downloadedReal"` + SeedTime flexText `json:"seedtime"` + LastAction flexText `json:"lastAction"` + } `json:"snatched"` +} + +// parseProfileID reads the account's numeric ID from /member/profile data. +func parseProfileID(data json.RawMessage) (string, error) { + var profile struct { + ID flexText `json:"id"` + } + if !isJSONObject(data) || json.Unmarshal(data, &profile) != nil || !canonicalID(profile.ID.value) { + return "", fmt.Errorf("M-Team profile response had no account ID") + } + return profile.ID.value, nil +} + +// parseUserTorrents maps /member/getUserTorrentList data. A missing list or +// any row without a recognizable torrent fails the whole page rather than +// returning a silently partial or empty one. Traffic comes from the snatch +// record when the API sends one, which counts real bytes over the account's +// whole history of the torrent, and otherwise from the current peer's report +// for its running session, which is all the seeding list carried when it was +// checked live. +func parseUserTorrents(data json.RawMessage) (domain.AccountTorrentList, error) { + var response userTorrentsResponse + if !isJSONObject(data) || json.Unmarshal(data, &response) != nil || response.Data == nil { + return domain.AccountTorrentList{}, fmt.Errorf("M-Team torrent list response was not recognized; refusing to treat it as an empty list") + } + list := domain.AccountTorrentList{ + SiteID: SiteID, + Total: count(response.Total), + TotalPages: count(response.TotalPages), + Torrents: make([]domain.AccountTorrent, 0, len(*response.Data)), + } + seen := make(map[string]struct{}, len(*response.Data)) + for _, row := range *response.Data { + if row.Torrent == nil { + return domain.AccountTorrentList{}, fmt.Errorf("M-Team torrent list row was not recognized") + } + summary, ok := summaryFromItem(*row.Torrent) + if !ok { + return domain.AccountTorrentList{}, fmt.Errorf("M-Team torrent list row was not recognized") + } + if _, duplicate := seen[summary.Ref.RemoteID]; duplicate { + continue + } + seen[summary.Ref.RemoteID] = struct{}{} + item := domain.AccountTorrent{Torrent: summary} + // Traffic comes from one source only, so the two spans never mix + // in one row. + if snatched := row.Snatched; snatched != nil { + item.UploadedBytes = byteCount(snatched.UploadedReal) + item.DownloadedBytes = byteCount(snatched.DownloadedReal) + // Seconds follow the same non-negative integer rule as bytes. + item.SeedTimeSeconds = byteCount(snatched.SeedTime) + item.LastActionAt = siteTime(snatched.LastAction) + if item.UploadedBytes != nil || item.DownloadedBytes != nil { + item.TrafficScope = domain.AccountTrafficTotal + } + } + if peer := row.Peer; peer != nil { + if item.UploadedBytes == nil && item.DownloadedBytes == nil { + item.UploadedBytes = byteCount(peer.Uploaded) + item.DownloadedBytes = byteCount(peer.Downloaded) + if item.UploadedBytes != nil || item.DownloadedBytes != nil { + item.TrafficScope = domain.AccountTrafficCurrentSession + } + } + if item.LastActionAt == nil { + item.LastActionAt = siteTime(peer.LastAction) + } + } + list.Torrents = append(list.Torrents, item) + } + return list, nil +} diff --git a/internal/site/mteam/torrents_test.go b/internal/site/mteam/torrents_test.go new file mode 100644 index 0000000..a4fc350 --- /dev/null +++ b/internal/site/mteam/torrents_test.go @@ -0,0 +1,228 @@ +package mteam + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +// userTorrentsFixture is synthetic. It mirrors the shape of +// api/member/getUserTorrentList: a seeding row with a peer, a completed row +// with a snatch record, a row with both whose traffic must not mix, and a +// repeated torrent. PEER-SECRET marks peer fields that must never be decoded. +const userTorrentsFixture = `{"code":"0","message":"SUCCESS","data":{"pageNumber":"1","pageSize":"50","total":"3","totalPages":"1","data":[ + {"torrent":{"id":"9001","name":"Seeding CANARY","size":"1073741824","category":"401", + "status":{"discount":"FREE","discountEndTime":"2026-10-20 08:00:00","seeders":"12","leechers":"3","timesCompleted":"40"}}, + "peer":{"ip":"PEER-SECRET-IP","ipv6":"PEER-SECRET-IPV6","peerId":"PEER-SECRET-ID","agent":"PEER-SECRET-AGENT", + "uploaded":"2048","downloaded":"0","lastAction":"2026-10-16 12:00:00","left":null}, + "snatched":null,"seek":null}, + {"torrent":{"id":"9002","name":"Completed CANARY","size":"4096"}, + "peer":null, + "snatched":{"uploaded":"999","uploadedReal":"8192","download":"0","downloadedReal":"4096","seedtime":"3600","leechtime":"60", + "lastAction":"2026-10-15 20:00:00","userid":"100001"}, + "seek":null}, + {"torrent":{"id":"9003","name":"Both CANARY","size":"10"}, + "peer":{"ip":"PEER-SECRET-IP","uploaded":"1","downloaded":"2","lastAction":"2026-10-16 01:00:00"}, + "snatched":{"uploadedReal":"30","seedtime":"5"}}, + {"torrent":{"id":"9001","name":"Repeated CANARY","size":"1"},"peer":null,"snatched":null} +]}}` + +func utc(value string) time.Time { + parsed, err := time.Parse(time.RFC3339, value) + if err != nil { + panic(err) + } + return parsed +} + +func int64Value(value *int64) any { + if value == nil { + return nil + } + return *value +} + +func TestAccountTorrentsReadsProfileThenListOnOneClient(t *testing.T) { + client := &scriptedClient{steps: steps(jsonResponse(profileFixture), jsonResponse(userTorrentsFixture))} + adapter, record := scriptedAdapter(client) + list, err := adapter.AccountTorrents(context.Background(), apiKey(t), site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding}) + if err != nil { + t.Fatal(err) + } + if record.opened != 1 || record.baseURL != DefaultBaseURL || record.apiKey != testAPIKey || record.interval != minRequestInterval || + !client.closed || len(client.calls) != 2 { + t.Fatalf("record=%#v calls=%d closed=%t", record, len(client.calls), client.closed) + } + profile, request := client.calls[0], client.calls[1] + if profile.path != profilePath || profile.body != emptyFormBody || profile.effect || + request.path != userTorrentsPath || request.contentType != jsonMediaType || request.effect || request.accept != apiAccept || + request.body != `{"userid":"100001","type":"SEEDING","pageNumber":1,"pageSize":50}` || + request.maxRequest != maxRequestBytes || request.maxBody != maxResponseBytes || request.maxHeader != maxResponseHeaderBytes { + t.Fatalf("calls=%#v", client.calls) + } + if list.SiteID != SiteID || list.State != domain.AccountTorrentsSeeding || list.Page != 1 || list.ObservedAt.IsZero() || + list.Total == nil || *list.Total != 3 || list.TotalPages == nil || *list.TotalPages != 1 || len(list.Torrents) != 3 { + t.Fatalf("list=%#v", list) + } + type row struct { + id string + scope domain.AccountTrafficScope + uploaded, downloaded any + seedTime any + lastAction time.Time + } + want := []row{ + {id: "9001", scope: domain.AccountTrafficCurrentSession, uploaded: int64(2048), downloaded: int64(0), seedTime: nil, + lastAction: utc("2026-10-16T04:00:00Z")}, + {id: "9002", scope: domain.AccountTrafficTotal, uploaded: int64(8192), downloaded: int64(4096), seedTime: int64(3600), + lastAction: utc("2026-10-15T12:00:00Z")}, + // The snatch record wins, so the peer's session traffic does not fill + // its missing download; only the last action falls back to the peer. + {id: "9003", scope: domain.AccountTrafficTotal, uploaded: int64(30), downloaded: nil, seedTime: int64(5), + lastAction: utc("2026-10-15T17:00:00Z")}, + } + for i, item := range list.Torrents { + got := row{id: item.Torrent.Ref.RemoteID, scope: item.TrafficScope, uploaded: int64Value(item.UploadedBytes), + downloaded: int64Value(item.DownloadedBytes), seedTime: int64Value(item.SeedTimeSeconds)} + if item.LastActionAt != nil { + got.lastAction = *item.LastActionAt + } + if got != want[i] || item.Torrent.Ref.SiteID != SiteID { + t.Fatalf("row %d=%#v want %#v", i, got, want[i]) + } + } + seeding := list.Torrents[0].Torrent + if seeding.Name != "Seeding CANARY" || seeding.SizeBytes == nil || *seeding.SizeBytes != 1<<30 || seeding.Category != "401" || + seeding.Seeders == nil || *seeding.Seeders != 12 || seeding.Promotion == nil || seeding.Promotion.DownloadFactor != "0" { + t.Fatalf("seeding torrent=%#v", seeding) + } + encoded, err := json.Marshal(list) + if err != nil || strings.Contains(string(encoded), "PEER-SECRET") || strings.Contains(string(encoded), "100001") { + t.Fatalf("list leaks peer or account fields: %s err=%v", encoded, err) + } +} + +func TestAccountTorrentsMapsEveryStateAndPage(t *testing.T) { + for _, test := range []struct { + state domain.AccountTorrentState + page int + body string + }{ + {domain.AccountTorrentsSeeding, 0, `{"userid":"100001","type":"SEEDING","pageNumber":1,"pageSize":50}`}, + {domain.AccountTorrentsLeeching, 2, `{"userid":"100001","type":"LEECHING","pageNumber":2,"pageSize":50}`}, + {domain.AccountTorrentsCompleted, 1, `{"userid":"100001","type":"COMPLETED","pageNumber":1,"pageSize":50}`}, + {domain.AccountTorrentsIncomplete, 1000, `{"userid":"100001","type":"INCOMPLETE","pageNumber":1000,"pageSize":50}`}, + {domain.AccountTorrentsUploaded, 3, `{"userid":"100001","type":"UPLOADED","pageNumber":3,"pageSize":50}`}, + } { + client := &scriptedClient{steps: steps(jsonResponse(profileFixture), jsonResponse(`{"code":"0","data":{"data":[]}}`))} + adapter, _ := scriptedAdapter(client) + list, err := adapter.AccountTorrents(context.Background(), apiKey(t), site.AccountTorrentQuery{State: test.state, Page: test.page}) + wantPage := test.page + if wantPage == 0 { + wantPage = 1 + } + if err != nil || len(client.calls) != 2 || client.calls[1].body != test.body || list.State != test.state || list.Page != wantPage || + list.Torrents == nil || len(list.Torrents) != 0 || list.Total != nil || list.TotalPages != nil { + t.Fatalf("%s: list=%#v err=%v calls=%#v", test.state, list, err, client.calls) + } + } +} + +func TestAccountTorrentQueryValidation(t *testing.T) { + adapter := New() + for _, query := range []site.AccountTorrentQuery{ + {State: domain.AccountTorrentsSeeding}, + {State: domain.AccountTorrentsLeeching, Page: 1}, + {State: domain.AccountTorrentsCompleted, Page: 1000}, + {State: domain.AccountTorrentsIncomplete}, + {State: domain.AccountTorrentsUploaded}, + } { + if err := adapter.ValidateAccountTorrentQuery(query); err != nil { + t.Fatalf("%+v rejected: %v", query, err) + } + } + for _, query := range []site.AccountTorrentQuery{ + {}, + {State: "SEEDING"}, + {State: "seek"}, + {State: "hitrun"}, + {State: domain.AccountTorrentsSeeding, Page: -1}, + {State: domain.AccountTorrentsSeeding, Page: 1001}, + } { + if err := adapter.ValidateAccountTorrentQuery(query); err == nil { + t.Fatalf("%+v accepted", query) + } + client := &scriptedClient{} + scripted, record := scriptedAdapter(client) + if _, err := scripted.AccountTorrents(context.Background(), apiKey(t), query); err == nil || record.opened != 0 { + t.Fatalf("%+v read err=%v opened=%d", query, err, record.opened) + } + } +} + +func TestAccountTorrentsFailClosed(t *testing.T) { + seeding := site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding} + for _, test := range []struct { + name string + profile string + list string + calls int + cause error + }{ + {name: "rejected key", profile: `{"code":"401","message":"CANARY","data":null}`, calls: 1, cause: site.ErrCredentialRejected}, + {name: "profile without an ID", profile: `{"code":"0","data":{"username":"canary_user"}}`, calls: 1}, + {name: "profile with a bad ID", profile: `{"code":"0","data":{"id":"01","username":"canary_user"}}`, calls: 1}, + {name: "rate limited", profile: profileFixture, list: `{"code":"4","message":"CANARY","data":null}`, calls: 2, cause: site.ErrRateLimited}, + {name: "refused", profile: profileFixture, list: `{"code":"1","message":"CANARY refusal","data":null}`, calls: 2}, + {name: "no data", profile: profileFixture, list: `{"code":"0","data":null}`, calls: 2}, + {name: "no list", profile: profileFixture, list: `{"code":"0","data":{"total":"0"}}`, calls: 2}, + {name: "list is not an object", profile: profileFixture, list: `{"code":"0","data":[]}`, calls: 2}, + {name: "row without a torrent", profile: profileFixture, list: `{"code":"0","data":{"data":[{"peer":{"uploaded":"1"}}]}}`, calls: 2}, + {name: "torrent with a bad ID", profile: profileFixture, list: `{"code":"0","data":{"data":[{"torrent":{"id":"01","name":"CANARY"}}]}}`, calls: 2}, + {name: "torrent without a name", profile: profileFixture, list: `{"code":"0","data":{"data":[{"torrent":{"id":"1"}}]}}`, calls: 2}, + } { + t.Run(test.name, func(t *testing.T) { + client := &scriptedClient{steps: steps(jsonResponse(test.profile), jsonResponse(test.list))} + adapter, _ := scriptedAdapter(client) + list, err := adapter.AccountTorrents(context.Background(), apiKey(t), seeding) + if err == nil || len(list.Torrents) != 0 || len(client.calls) != test.calls || !client.closed || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("list=%#v err=%v calls=%d", list, err, len(client.calls)) + } + if test.cause != nil && !errors.Is(err, test.cause) { + t.Fatalf("err=%v want %v", err, test.cause) + } + }) + } +} + +func TestAccountTorrentsRefuseForeignCredentialsBeforeAnyRequest(t *testing.T) { + seeding := site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding} + cookie, err := site.NewCookieCredential("sid=CANARY") + if err != nil { + t.Fatal(err) + } + malformed, err := site.NewAPIKeyCredential("KEY WITH SPACE") + if err != nil { + t.Fatal(err) + } + for _, credential := range []site.Credential{cookie, malformed} { + client := &scriptedClient{} + adapter, record := scriptedAdapter(client) + if _, err := adapter.AccountTorrents(context.Background(), credential, seeding); err == nil || record.opened != 0 { + t.Fatalf("method=%s err=%v opened=%d", credential.Method(), err, record.opened) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + client := &scriptedClient{} + adapter, record := scriptedAdapter(client) + if _, err := adapter.AccountTorrents(ctx, apiKey(t), seeding); !errors.Is(err, context.Canceled) || record.opened != 0 { + t.Fatalf("err=%v opened=%d", err, record.opened) + } +} diff --git a/internal/site/sitetest/sitetest.go b/internal/site/sitetest/sitetest.go index 01ca977..590b15a 100644 --- a/internal/site/sitetest/sitetest.go +++ b/internal/site/sitetest/sitetest.go @@ -62,6 +62,9 @@ func TestAdapter(t *testing.T, adapter site.Adapter, samples Samples) { } }) } + if lister, ok := adapter.(site.AccountTorrentLister); ok && descriptor.Supports(domain.CapabilityAccountTorrents) { + t.Run(string(domain.CapabilityAccountTorrents)+"/query", func(t *testing.T) { testAccountTorrentQuery(t, lister) }) + } if loginer, ok := adapter.(site.SessionLoginer); ok && descriptor.Supports(domain.CapabilityLogin) { t.Run(string(domain.CapabilityLogin), func(t *testing.T) { testLogin(t, loginer) }) } @@ -76,6 +79,23 @@ func TestAdapter(t *testing.T, adapter site.Adapter, samples Samples) { } } +// testAccountTorrentQuery checks that every lister serves the seeding list +// and refuses an unknown state or a negative page. +func testAccountTorrentQuery(t *testing.T, lister site.AccountTorrentLister) { + if err := lister.ValidateAccountTorrentQuery(site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding}); err != nil { + t.Fatalf("seeding query rejected: %v", err) + } + for _, query := range []site.AccountTorrentQuery{ + {}, + {State: "sitetest-unknown"}, + {State: domain.AccountTorrentsSeeding, Page: -1}, + } { + if err := lister.ValidateAccountTorrentQuery(query); err == nil { + t.Fatalf("query %+v accepted", query) + } + } +} + // testLogin checks the login config and that a done context stops a login // before its first request. The credentials are synthetic. func testLogin(t *testing.T, loginer site.SessionLoginer) { @@ -167,6 +187,12 @@ func directPorts(adapter site.Adapter) []directPort { return err }}) } + if port, ok := adapter.(site.AccountTorrentLister); ok { + ports = append(ports, directPort{domain.CapabilityAccountTorrents, func(ctx context.Context, credential site.Credential) error { + _, err := port.AccountTorrents(ctx, credential, site.AccountTorrentQuery{State: domain.AccountTorrentsSeeding}) + return err + }}) + } return ports } diff --git a/scripts/release.py b/scripts/release.py index d9e01a1..1fd7697 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Validate existing release tags, assemble checked assets, and create drafts only.""" +"""Decide main-line releases, assemble checked assets, and tag and publish them.""" import argparse import json import os @@ -29,16 +29,60 @@ def version_file(content): return release_version(value) -def check_tag(tag, expected_commit=None, cwd=None): - release_version(tag) - commit = git("rev-parse", "--verify", f"refs/tags/{tag}^{{commit}}", cwd=cwd) - require(expected_commit is None or commit == expected_commit, "tag moved since validation") - # Only main-line releases; no implicit Git tag creation or branch fallback. +def version_key(value): + """Order release versions by SemVer precedence.""" + release_version(value) + core, _, prerelease = value[1:].partition("-") + numbers = tuple(int(part) for part in core.split(".")) + if not prerelease: + return numbers, (1,) + # Numeric identifiers sort before alphanumeric ones; a shorter list sorts first. + return numbers, (0, tuple((0, int(part), "") if part.isdigit() else (1, 0, part) for part in prerelease.split("."))) + + +def release_notes(changelog, version): + """Return the body of the one CHANGELOG.md section headed by version.""" + lines = changelog.split("\n") + starts = [i for i, line in enumerate(lines) if re.fullmatch(r"## " + re.escape(version) + r"( .*)?", line)] + require(len(starts) == 1, "CHANGELOG.md needs exactly one section for " + version) + end = next((i for i in range(starts[0] + 1, len(lines)) if lines[i].startswith("## ")), len(lines)) + body = "\n".join(lines[starts[0] + 1:end]).strip() + require(body, "CHANGELOG.md section for " + version + " is empty") + return body + "\n" + + +def main_line(commit, cwd=None): + """Require a full commit on main whose workflows are main's own.""" + require(re.fullmatch(r"[0-9a-f]{40}", commit), "full source commit required") + # Only main-line releases; no branch fallback. subprocess.run(["git", "merge-base", "--is-ancestor", commit, "refs/remotes/origin/main"], cwd=cwd, check=True) subprocess.run(["git", "diff", "--quiet", "--no-ext-diff", commit, "refs/remotes/origin/main", "--", ".github/workflows"], cwd=cwd, check=True, capture_output=True) - content = subprocess.check_output(["git", "show", f"{commit}:VERSION"], cwd=cwd).decode() - require(version_file(content) == tag, "tag and VERSION differ") - return {"commit": commit, "version": tag, "channel": "release"} + + +def plan(commit, cwd=None): + """Decide whether a main-line commit releases its VERSION. + + A VERSION tagged on an earlier commit is not released again. An untagged + one must be newer than every release tag, and either needs release notes. + """ + main_line(commit, cwd) + version = version_file(subprocess.check_output(["git", "show", f"{commit}:VERSION"], cwd=cwd).decode()) + tags = set() + for name in git("tag", "--list", "v*", cwd=cwd).splitlines(): + try: + tags.add(release_version(name)) + except ValueError: + continue + result = {"commit": commit, "version": version, "channel": "release", "release": "false"} + if version in tags: + # A tag on this very commit is a rerun that has to finish the release. + if git("rev-parse", "--verify", f"refs/tags/{version}^{{commit}}", cwd=cwd) != commit: + return result + else: + require(all(version_key(tag) < version_key(version) for tag in tags), "VERSION must be newer than every release tag") + release_notes(subprocess.check_output(["git", "show", f"{commit}:CHANGELOG.md"], cwd=cwd).decode(), version) + result["release"] = "true" + return result def identity(version, commit, channel): @@ -89,11 +133,11 @@ def verify_assets(directory, tag, commit): return [directory / name for name in sorted(expected)] -def gh_json(endpoint, body=None, upload=None): +def gh_json(endpoint, body=None, upload=None, method="POST"): command = ["gh", "api", endpoint, "-H", "X-GitHub-Api-Version: 2022-11-28"] payload = None if body is not None: - command += ["--method", "POST", "--input", "-"] + command += ["--method", method, "--input", "-"] payload = json.dumps(body) if upload is not None: command += ["--method", "POST", "-H", "Content-Type: application/octet-stream", "--input", str(upload)] @@ -127,25 +171,60 @@ def remote_tag(repository, tag): raise ValueError("tag chain exceeds limit") -def create_draft(repository, tag, commit, assets): +def find_remote_tag(repository, tag): + """Return the commit a remote tag names, or None when no such tag exists.""" + # matching-refs answers an absent tag with an empty list, so no failure is + # ever read as absence. + refs = gh_json(f"repos/{repository}/git/matching-refs/tags/{quote(tag, safe='')}") + require(isinstance(refs, list), "tag listing response differs") + if not any(item.get("ref") == f"refs/tags/{tag}" for item in refs): + return None + return remote_tag(repository, tag) + + +def create_tag(repository, tag, commit): + """Create one annotated tag for commit; never moves an existing tag.""" + obj = gh_json(f"repos/{repository}/git/tags", body={ + "tag": tag, "message": "pt cli " + tag, "object": commit, "type": "commit"}) + require(re.fullmatch(r"[0-9a-f]{40}", str(obj.get("sha"))) and obj.get("tag") == tag + and obj.get("object", {}).get("sha") == commit, "tag object response differs") + ref = gh_json(f"repos/{repository}/git/refs", body={"ref": f"refs/tags/{tag}", "sha": obj["sha"]}) + require(ref.get("ref") == f"refs/tags/{tag}" and ref.get("object", {}).get("sha") == obj["sha"], "tag ref response differs") + + +def publish(repository, tag, commit, assets, notes, cwd=None): + """Tag a tested main-line commit and publish its release. + + The release is drafted, filled, and checked before it is made public, so a + failure at any step leaves at most an unpublished draft. + """ release_version(tag) require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository), "invalid repository") + main_line(commit, cwd) files = verify_assets(assets, tag, commit) # All local validation precedes any remote write. - require(remote_tag(repository, tag) == commit, "remote tag is missing or moved") + prerelease = "-" in tag endpoint = f"repos/{repository}/releases" require(existing_release(repository, tag) is None, "a release already exists; refusing to replace a draft or published release") + current = find_remote_tag(repository, tag) + if current is None: + create_tag(repository, tag, commit) + else: + # A rerun after a failure past tagging finds its own tag. + require(current == commit, "tag already exists on another commit") + require(remote_tag(repository, tag) == commit, "remote tag is missing or moved") release = gh_json(endpoint, body={ "tag_name": tag, "target_commitish": commit, "name": "pt cli " + tag, - "draft": True, "prerelease": "-" in tag, "make_latest": "false", - "body": f"Native tested packages for `{commit}`. Verify SHA256SUMS before use.\n\n" - "Review all three platform assets and the successful workflow before manually publishing. " - "No code signing or notarization is provided.", + "draft": True, "prerelease": prerelease, "make_latest": "false", + "generate_release_notes": True, + "body": notes.rstrip("\n") + "\n\n---\n\n" + f"Native tested packages for `{commit}`. Verify SHA256SUMS before use. " + "No code signing or notarization is provided.\n", }) require(release.get("draft") is True and isinstance(release.get("id"), int), "draft creation response differs") release_id = release["id"] - # No overwrite, automatic retry, deletion, or publish API exists in this helper. - # Any partial-upload failure leaves an unpublished draft for manual inspection. + # No overwrite, automatic retry, or deletion exists in this helper. Any + # partial-upload failure leaves an unpublished draft for manual inspection. expected = {} for path in files: expected[path.name] = "sha256:" + sha256(path.read_bytes()) @@ -158,7 +237,11 @@ def create_draft(repository, tag, commit, assets): require(len(remote_assets) == len(expected) and {a["name"]: a.get("digest") for a in remote_assets} == expected and all(a.get("state") == "uploaded" for a in remote_assets), "draft asset set differs") require(remote_tag(repository, tag) == commit, "remote tag moved during upload; inspect the unpublished draft") - return {"draft": True, "url": final["html_url"], "commit": commit, "version": tag} + public = gh_json(f"{endpoint}/{release_id}", method="PATCH", body={ + "draft": False, "make_latest": "false" if prerelease else "true"}) + require(public.get("draft") is False and public.get("tag_name") == tag and public.get("prerelease") is prerelease + and {a["name"]: a.get("digest") for a in public.get("assets", [])} == expected, "published release differs") + return {"draft": False, "url": public["html_url"], "commit": commit, "version": tag} def main(): @@ -166,35 +249,39 @@ def main(): sub = parser.add_subparsers(dest="command", required=True) meta = sub.add_parser("identity") meta.add_argument("--release-version", default="") - tag = sub.add_parser("check-tag") - tag.add_argument("--tag", required=True) - tag.add_argument("--expected-commit") + decide = sub.add_parser("plan") + decide.add_argument("--commit", required=True) collect = sub.add_parser("assemble") for name in ("source", "output"): collect.add_argument("--" + name, type=Path, required=True) for name in ("version", "commit", "channel"): collect.add_argument("--" + name, required=True) - draft = sub.add_parser("create-draft") + release = sub.add_parser("publish") for name in ("repository", "tag", "commit"): - draft.add_argument("--" + name, required=True) - draft.add_argument("--assets", type=Path, required=True) + release.add_argument("--" + name, required=True) + for name in ("assets", "changelog"): + release.add_argument("--" + name, type=Path, required=True) args = parser.parse_args() if args.command == "identity": version = version_file(Path("VERSION").read_bytes().decode()) + # Every VERSION, released or not yet, carries its release notes. + release_notes(Path("CHANGELOG.md").read_bytes().decode(), version) commit = git("rev-parse", "HEAD") require(not args.release_version or args.release_version == version, "release version differs from source VERSION") result = identity(version if args.release_version else version + "+g" + commit[:12], commit, "release" if args.release_version else "ci-preview") - elif args.command == "check-tag": - result = check_tag(args.tag, args.expected_commit) + elif args.command == "plan": + result = plan(args.commit) elif args.command == "assemble": result = assemble(args.source, args.output, args.version, args.commit, args.channel) else: - result = create_draft(args.repository, args.tag, args.commit, args.assets) - if args.command in ("identity", "check-tag") and os.environ.get("GITHUB_OUTPUT"): + notes = release_notes(args.changelog.read_bytes().decode(), args.tag) + result = publish(args.repository, args.tag, args.commit, args.assets, notes) + if args.command in ("identity", "plan") and os.environ.get("GITHUB_OUTPUT"): with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - for key in ("version", "commit", "channel"): - output.write(f"{key}={result[key]}\n") + for key in ("version", "commit", "channel", "release"): + if key in result: + output.write(f"{key}={result[key]}\n") print(json.dumps(result, sort_keys=True)) diff --git a/scripts/tests/test_release.py b/scripts/tests/test_release.py index 690a11e..160c0c7 100644 --- a/scripts/tests/test_release.py +++ b/scripts/tests/test_release.py @@ -50,7 +50,7 @@ def fixture(root): return source -class VersionAndTagTests(unittest.TestCase): +class VersionTests(unittest.TestCase): def test_versions_fail_closed(self): for value in ('v1.2.3', VERSION, 'v1.2.3-rc.1'): self.assertEqual(release.release_version(value), value) @@ -63,43 +63,89 @@ def test_versions_fail_closed(self): with self.assertRaises(ValueError): release.identity(VERSION + '+g' + 'b' * 12, COMMIT, 'ci-preview') - def test_real_git_tag_binding(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - def git(*args): - return subprocess.check_output(['git', '-c', 'commit.gpgsign=false', '-c', 'tag.gpgsign=false', - '-c', 'core.hooksPath=' + str(root / 'empty-hooks'), *args], - cwd=root, stderr=subprocess.DEVNULL, text=True).strip() - git('init', '--initial-branch=main') - git('config', 'user.name', 'Synthetic release test') - git('config', 'user.email', 'release-test@example.invalid') - git('config', 'core.autocrlf', 'false') - (root / 'VERSION').write_bytes((VERSION + '\n').encode()) - git('add', 'VERSION') - git('commit', '-m', 'synthetic release version') - commit = git('rev-parse', 'HEAD') - git('update-ref', 'refs/remotes/origin/main', commit) - git('tag', '-a', VERSION, '-m', 'synthetic annotated tag') - self.assertEqual(release.check_tag(VERSION, commit, root)['commit'], commit) - with self.assertRaises(ValueError): - release.check_tag(VERSION, 'b' * 40, root) - git('tag', 'v9.0.0') - with self.assertRaises(ValueError): - release.check_tag('v9.0.0', cwd=root) - with self.assertRaises(subprocess.CalledProcessError): - release.check_tag('v9.0.1', cwd=root) - (root / 'VERSION').write_bytes(b'v1.0.0\n') - git('commit', '-am', 'unmerged version') - git('tag', 'v1.0.0') - with self.assertRaises(subprocess.CalledProcessError): - release.check_tag('v1.0.0', cwd=root) - (root / '.github/workflows').mkdir(parents=True) - (root / '.github/workflows/change.yml').write_bytes(b'name: changed\n') - git('add', '.github') - git('commit', '-m', 'workflow changes on main') - git('update-ref', 'refs/remotes/origin/main', 'HEAD') - with self.assertRaises(subprocess.CalledProcessError): - release.check_tag(VERSION, cwd=root) + def test_semver_precedence(self): + ordered = ['v0.1.0', 'v0.2.0-alpha', 'v0.2.0-alpha.1', 'v0.2.0-alpha.2', 'v0.2.0-alpha.10', + 'v0.2.0-alpha.beta', 'v0.2.0-beta', 'v0.2.0-beta.2', 'v0.2.0-beta.11', 'v0.2.0-rc.1', + 'v0.2.0', 'v0.2.1', 'v0.10.0', 'v1.0.0'] + self.assertEqual(sorted(reversed(ordered), key=release.version_key), ordered) + with self.assertRaises(ValueError): + release.version_key('0.2.0') + + def test_release_notes_take_exactly_one_section(self): + changelog = ('# Changelog\n\n## v0.4.0-alpha.10\n\n- later\n\n' + '## v0.4.0-alpha.1 - 2026-10-17\n\n- one\n\n### Known limits\n\n- two\n\n' + '## v0.2.0-alpha.1\n\n- old\n') + self.assertEqual(release.release_notes(changelog, 'v0.4.0-alpha.1'), '- one\n\n### Known limits\n\n- two\n') + self.assertEqual(release.release_notes(changelog, 'v0.2.0-alpha.1'), '- old\n') + for text, message in (('## v0.4.0-alpha.10\n\n- later\n', 'exactly one'), + ('## v0.4.0-alpha.1\n- a\n## v0.4.0-alpha.1\n- b\n', 'exactly one'), + ('## v0.4.0-alpha.1x\n- a\n', 'exactly one'), + ('## v0.4.0-alpha.1\n\n\n## v0.2.0\n- a\n', 'empty')): + with self.subTest(text=text), self.assertRaisesRegex(ValueError, message): + release.release_notes(text, 'v0.4.0-alpha.1') + + +class PlanTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.git('init', '--initial-branch=main') + self.git('config', 'user.name', 'Synthetic release test') + self.git('config', 'user.email', 'release-test@example.invalid') + self.git('config', 'core.autocrlf', 'false') + + def git(self, *args): + return subprocess.check_output(['git', '-c', 'commit.gpgsign=false', '-c', 'tag.gpgsign=false', + '-c', 'core.hooksPath=' + str(self.root / 'empty-hooks'), *args], + cwd=self.root, stderr=subprocess.DEVNULL, text=True).strip() + + def commit(self, version, notes=None, **files): + (self.root / 'VERSION').write_bytes((version + '\n').encode()) + changelog = '# Changelog\n' + ''.join(f'\n## {v}\n\n- {text}\n' for v, text in (notes or {}).items()) + (self.root / 'CHANGELOG.md').write_bytes(changelog.encode()) + for name, content in files.items(): + path = self.root / name.replace('__', '/') + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + self.git('add', '-A') + self.git('commit', '-m', 'synthetic ' + version) + commit = self.git('rev-parse', 'HEAD') + self.git('update-ref', 'refs/remotes/origin/main', commit) + return commit + + def plan(self, commit): + return release.plan(commit, self.root) + + def test_only_a_new_version_releases(self): + first = self.commit('v0.2.0-alpha.1', {'v0.2.0-alpha.1': 'first'}) + self.git('tag', '-a', 'v0.2.0-alpha.1', '-m', 'synthetic annotated tag') + self.git('tag', 'vnext') # Not a release version; ignored. + same = self.commit('v0.2.0-alpha.1', {'v0.2.0-alpha.1': 'first'}, README=b'docs only\n') + self.assertEqual(self.plan(same), {'commit': same, 'version': 'v0.2.0-alpha.1', 'channel': 'release', 'release': 'false'}) + # A rerun on the tagged commit itself finishes that release. + self.assertEqual(self.plan(first)['release'], 'true') + bumped = self.commit('v0.4.0-alpha.1', {'v0.2.0-alpha.1': 'first'}) + with self.assertRaisesRegex(ValueError, 'CHANGELOG.md needs exactly one section'): + self.plan(bumped) + noted = self.commit('v0.4.0-alpha.1', {'v0.4.0-alpha.1': 'second', 'v0.2.0-alpha.1': 'first'}) + self.assertEqual(self.plan(noted), {'commit': noted, 'version': 'v0.4.0-alpha.1', 'channel': 'release', 'release': 'true'}) + older = self.commit('v0.2.0-alpha.0', {'v0.2.0-alpha.0': 'older'}) + with self.assertRaisesRegex(ValueError, 'newer than every release tag'): + self.plan(older) + with self.assertRaisesRegex(ValueError, 'full source commit'): + self.plan(noted[:12]) + + def test_off_main_or_changed_workflows_fail_closed(self): + base = self.commit('v0.4.0-alpha.1', {'v0.4.0-alpha.1': 'notes'}) + branch = self.commit('v0.4.0-alpha.2', {'v0.4.0-alpha.2': 'notes'}) + self.git('update-ref', 'refs/remotes/origin/main', base) + with self.assertRaises(subprocess.CalledProcessError): + self.plan(branch) + self.git('reset', '--hard', base) + self.commit('v0.4.0-alpha.1', {'v0.4.0-alpha.1': 'notes'}, **{'.github__workflows__change.yml': b'name: changed\n'}) + with self.assertRaises(subprocess.CalledProcessError): + self.plan(base) class PackageTests(unittest.TestCase): @@ -144,48 +190,150 @@ def test_complete_assembly_and_corruption(self): self.assertFalse((root / 'incomplete').exists()) -class DraftTests(unittest.TestCase): +class FakeGitHub: + """Hold one repository's tags and releases, and record every request.""" + + def __init__(self, uploaded): + self.refs = {} # tag -> (object type, sha) + self.tag_objects = {} # tag object sha -> commit + self.releases = [] + self.uploaded = uploaded + self.calls = [] + self.on_upload = None + + def tag_at(self, tag, commit): + self.tag_objects['c' * 40] = commit + self.refs[tag] = ('tag', 'c' * 40) + + def writes(self): + return [(method, endpoint, body) for endpoint, body, upload, method in self.calls + if body is not None or upload is not None] + + def __call__(self, endpoint, body=None, upload=None, method='POST'): + self.calls.append((endpoint, body, upload, method if body is not None or upload is not None else 'GET')) + prefix = 'repos/example/repo/' + if upload is not None: + asset = {'name': upload.name, 'state': 'uploaded', 'digest': 'sha256:' + package.sha256(upload.read_bytes())} + self.uploaded.append(asset) + if self.on_upload: + self.on_upload() + return asset + path = endpoint[len(prefix):] + if path.startswith('releases?per_page='): + return list(self.releases) + if path.startswith('git/matching-refs/tags/'): + name = path.rsplit('/', 1)[1] + return [{'ref': 'refs/tags/' + tag} for tag in self.refs if tag.startswith(name)] + if path.startswith('git/ref/tags/'): + kind, sha = self.refs[path.rsplit('/', 1)[1]] + return {'object': {'type': kind, 'sha': sha}} + if path == 'git/tags': + self.tag_objects['d' * 40] = body['object'] + return {'sha': 'd' * 40, 'tag': body['tag'], 'object': {'sha': body['object'], 'type': 'commit'}} + if path.startswith('git/tags/'): + return {'object': {'type': 'commit', 'sha': self.tag_objects[path.rsplit('/', 1)[1]]}} + if path == 'git/refs': + self.refs[body['ref'].removeprefix('refs/tags/')] = ('tag', body['sha']) + return {'ref': body['ref'], 'object': {'type': 'tag', 'sha': body['sha']}} + if path == 'releases': + self.releases.append({'id': 7, 'draft': True, 'tag_name': body['tag_name'], 'prerelease': body['prerelease']}) + return dict(self.releases[-1]) + if path != 'releases/7': + raise AssertionError('unexpected request ' + endpoint) + current = self.releases[0] + if method == 'PATCH' and body is not None: + current['draft'] = body['draft'] + return dict(current, assets=list(self.uploaded), html_url='https://github.com/example/repo/releases/tag/' + VERSION) + + +class PublishTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) root = Path(self.temp.name) self.assets = root / 'release' release.assemble(fixture(root), self.assets, VERSION, COMMIT, 'release') - self.calls = [] self.uploaded = [] + self.github = FakeGitHub(self.uploaded) + main_line = patch.object(release, 'main_line') + self.main_line = main_line.start() + self.addCleanup(main_line.stop) - def api(self, endpoint, body=None, upload=None): - self.calls.append((endpoint, body, upload)) - if '?per_page=' in endpoint: - return [] - if body is not None: - return {'id': 7, 'draft': True} - if upload is not None: - asset = {'name': upload.name, 'state': 'uploaded', 'digest': 'sha256:' + package.sha256(upload.read_bytes())} - self.uploaded.append(asset) - return asset - return {'draft': True, 'tag_name': VERSION, 'assets': self.uploaded, 'html_url': 'https://github.com/example/repo/releases/tag/' + VERSION} - - def create(self): - return release.create_draft('example/repo', VERSION, COMMIT, self.assets) - - def test_draft_only_and_exact_uploaded_digests(self): - with patch.object(release, 'remote_tag', return_value=COMMIT), patch.object(release, 'gh_json', side_effect=self.api): - self.assertTrue(self.create()['draft']) - writes = [body for _, body, _ in self.calls if body is not None] - self.assertEqual(len(writes), 1) - self.assertIs(writes[0]['draft'], True) - self.assertIs(writes[0]['prerelease'], True) - self.assertEqual(writes[0]['make_latest'], 'false') + def publish(self): + with patch.object(release, 'gh_json', side_effect=self.github): + return release.publish('example/repo', VERSION, COMMIT, self.assets, '- synthetic notes\n') + + def test_tags_then_drafts_and_publishes_last(self): + # A longer tag sharing the prefix is not this release's tag. + self.github.refs[VERSION + '.1'] = ('commit', 'b' * 40) + result = self.publish() + self.assertIs(result['draft'], False) + writes = self.github.writes() + self.assertEqual([(method, endpoint) for method, endpoint, _ in writes[:3]], + [('POST', 'repos/example/repo/git/tags'), ('POST', 'repos/example/repo/git/refs'), + ('POST', 'repos/example/repo/releases')]) + self.assertEqual(writes[0][2], {'tag': VERSION, 'message': 'pt cli ' + VERSION, 'object': COMMIT, 'type': 'commit'}) + draft = writes[2][2] + self.assertIs(draft['draft'], True) + self.assertIs(draft['prerelease'], True) + self.assertEqual(draft['make_latest'], 'false') + self.assertTrue(draft['body'].startswith('- synthetic notes\n\n---\n\n')) + self.assertIn(COMMIT, draft['body']) + self.assertEqual(len(writes), 9) self.assertEqual(len(self.uploaded), 5) + self.assertEqual(writes[-1], ('PATCH', 'repos/example/repo/releases/7', {'draft': False, 'make_latest': 'false'})) + self.main_line.assert_called_once() + + def test_reuses_a_tag_already_on_the_commit(self): + self.github.tag_at(VERSION, COMMIT) + self.assertIs(self.publish()['draft'], False) + endpoints = [endpoint for _, endpoint, _ in self.github.writes()] + self.assertNotIn('repos/example/repo/git/tags', endpoints) + self.assertNotIn('repos/example/repo/git/refs', endpoints) + + def test_refuses_a_tag_on_another_commit(self): + self.github.tag_at(VERSION, 'b' * 40) + with self.assertRaisesRegex(ValueError, 'another commit'): + self.publish() + self.assertEqual(self.github.writes(), []) def test_existing_release_never_modified(self): for is_draft in (False, True): - with patch.object(release, 'remote_tag', return_value=COMMIT), patch.object(release, 'gh_json', return_value=[{'tag_name': VERSION, 'draft': is_draft}]) as api: - with self.assertRaisesRegex(ValueError, 'already exists'): - self.create() - self.assertEqual(api.call_count, 1) - self.assertIn('/releases?per_page=100&page=1', api.call_args.args[0]) + self.github.calls.clear() + self.github.releases = [{'tag_name': VERSION, 'draft': is_draft}] + with self.assertRaisesRegex(ValueError, 'already exists'): + self.publish() + self.assertEqual(len(self.github.calls), 1) + self.assertIn('/releases?per_page=100&page=1', self.github.calls[0][0]) + + def test_bad_assets_or_branch_precede_any_request(self): + self.main_line.side_effect = subprocess.CalledProcessError(1, 'git') + with self.assertRaises(subprocess.CalledProcessError): + self.publish() + self.main_line.side_effect = None + (self.assets / 'SHA256SUMS').unlink() + with self.assertRaises(ValueError): + self.publish() + self.assertEqual(self.github.calls, []) + + def test_partial_upload_never_publishes(self): + def interrupt(): + if len(self.uploaded) == 2: + raise TimeoutError('synthetic upload interruption') + self.github.on_upload = interrupt + with self.assertRaises(TimeoutError): + self.publish() + self.assertNotIn('PATCH', [method for method, _, _ in self.github.writes()]) + self.assertIs(self.github.releases[0]['draft'], True) + + def test_tag_moved_during_upload_never_publishes(self): + def move(): + if len(self.uploaded) == 5: + self.github.refs[VERSION] = ('commit', 'b' * 40) + self.github.on_upload = move + with self.assertRaisesRegex(ValueError, 'moved during upload'): + self.publish() + self.assertNotIn('PATCH', [method for method, _, _ in self.github.writes()]) def test_existing_draft_on_later_page(self): old = [{'tag_name': 'v0.0.' + str(i)} for i in range(100)] @@ -200,40 +348,19 @@ def test_annotated_remote_tag(self): with patch.object(release, 'gh_json', side_effect=responses): self.assertEqual(release.remote_tag('example/repo', VERSION), COMMIT) - def test_bad_assets_and_moved_tag_precede_writes(self): - with patch.object(release, 'remote_tag', return_value='b' * 40), patch.object(release, 'gh_json') as api: - with self.assertRaisesRegex(ValueError, 'moved'): - self.create() - api.assert_not_called() - (self.assets / 'SHA256SUMS').unlink() - with patch.object(release, 'gh_json') as api, patch.object(release, 'remote_tag') as tag: - with self.assertRaises(ValueError): - self.create() - api.assert_not_called() - tag.assert_not_called() - - def test_partial_upload_does_not_publish_or_retry(self): - def fail(endpoint, **kwargs): - if kwargs.get('upload') and self.uploaded: - raise TimeoutError('synthetic upload interruption') - return self.api(endpoint, **kwargs) - with patch.object(release, 'remote_tag', return_value=COMMIT), patch.object(release, 'gh_json', side_effect=fail): - with self.assertRaises(TimeoutError): - self.create() - self.assertEqual(len(self.uploaded), 1) - self.assertEqual([body['draft'] for _, body, _ in self.calls if body], [True]) - def test_gh_errors_are_not_all_treated_as_absent(self): for status in (401, 403, 404, 500): result = subprocess.CompletedProcess([], 1, '', f'gh: failure (HTTP {status})') with patch.object(release.subprocess, 'run', return_value=result), self.assertRaises(ValueError): - release.gh_json('repos/example/repo/releases?per_page=100&page=1') + release.gh_json('repos/example/repo/git/matching-refs/tags/' + VERSION) - def test_tag_moves_after_upload_remains_draft(self): - with patch.object(release, 'remote_tag', side_effect=[COMMIT, 'b' * 40]), patch.object(release, 'gh_json', side_effect=self.api): - with self.assertRaisesRegex(ValueError, 'moved during upload'): - self.create() - self.assertEqual([body['draft'] for _, body, _ in self.calls if body], [True]) + def test_gh_json_sends_the_requested_method(self): + result = subprocess.CompletedProcess([], 0, '{}', '') + with patch.object(release.subprocess, 'run', return_value=result) as run: + release.gh_json('repos/example/repo/releases/7', body={'draft': False}, method='PATCH') + command = run.call_args.args[0] + self.assertEqual(command[command.index('--method') + 1], 'PATCH') + self.assertEqual(json.loads(run.call_args.kwargs['input']), {'draft': False}) if __name__ == '__main__':