mirror of
https://github.com/TheFunny/TelegramTwitterMediaBot.git
synced 2026-09-24 23:42:18 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8063777962
|
||
|
|
ac10b8715c
|
||
|
|
517e1362a5
|
||
|
|
50299bacbb
|
||
|
|
9d40f3bc50
|
||
|
|
2045c3cea1
|
||
|
|
09656810fe
|
||
|
|
786bafca42
|
||
|
|
18da6e97c2
|
||
|
|
7b816d4153
|
||
|
|
d8b9a06453
|
||
|
|
4e0f1b834e
|
||
|
|
21437d1843
|
||
|
|
a54029c19b
|
||
|
|
c6120b7cc0
|
||
|
|
7b4e273533
|
||
|
|
6a87583cc0
|
||
|
|
1ba64e858d
|
||
|
|
008d31b9bd
|
||
|
|
66ec14662c
|
||
|
|
8ae7d9947d
|
||
|
|
28e8fec68d
|
||
|
|
b2b01721b2
|
||
|
|
85c3be5ef5
|
||
|
|
5e7a87c0dd
|
||
|
|
6a2ba6a50a
|
||
|
|
fb354c9434
|
||
|
|
bc7f249c20
|
||
|
|
403b84996f
|
||
|
|
f08b187964
|
||
|
|
8428468712
|
||
|
|
412359e84c
|
||
|
|
438ced278f
|
||
|
|
704b14f05a
|
||
|
|
1f9da14772
|
||
|
|
4694e60ee3
|
||
|
|
88dc0ccb9e
|
||
|
|
b563b949bb
|
||
|
|
e7855b02fe
|
||
|
|
5e265f2413
|
||
|
|
5060b760ba
|
||
|
|
7019f34801
|
||
|
|
d05450d88a
|
||
|
|
053ae0ec25
|
||
|
|
d1f2ae09b2
|
||
|
|
715d6a59b0
|
||
|
|
ef8a1dae15
|
||
|
|
ac34759b02
|
||
|
|
c420c95165
|
||
|
|
4d6ec7924b
|
||
|
|
9bae46eb9a
|
||
|
|
cb91913088
|
||
|
|
2b6cb506c7
|
||
|
|
c49e2175a1
|
||
|
|
2ec13a0624
|
||
|
|
0765b7deec
|
||
|
|
e72cb1b98f
|
||
|
|
9fc5533676
|
||
|
|
46bbe8639d
|
||
|
|
2ff213e22f
|
||
|
|
2c45b3491d
|
||
|
|
a3d03cf30f
|
||
|
|
e64b48a453
|
||
|
|
022f63916c
|
||
|
|
f984428169
|
||
|
|
85fb12edc7
|
||
|
|
7bdf760c7b
|
||
|
|
3dbcb45899
|
||
|
|
aee1cf35ae
|
||
|
|
7b50ad82b0
|
||
|
|
a49bb1d1af
|
||
|
|
e99f8b0bc0
|
||
|
|
3fd04e4420
|
||
|
|
0e91753402
|
||
|
|
8f254c3779
|
||
|
|
e9dd3aece2
|
||
|
|
67b6bd3038
|
||
|
|
3fb6b3b4da
|
||
|
|
e6800fd27b
|
||
|
|
38e65a3791
|
||
|
|
eecd4320f8
|
||
|
|
d774f0b37c
|
||
|
|
5d44946690
|
||
|
|
33b1f04f0e
|
||
|
|
4c1fa857c4
|
||
|
|
3ebc1e4a8f
|
||
|
|
20a0cf3ea3
|
||
|
|
f6523e021d
|
||
|
|
c549a6d35e
|
||
|
|
9e5b6df21c
|
||
|
|
aa70b45ae6
|
||
|
|
70d4f2ec88
|
||
|
|
b7763a6572
|
||
|
|
459bfe5803
|
||
|
|
01e097a8b6
|
||
|
|
435c8c4cc4
|
||
|
|
df8fd77d29
|
||
|
|
f7179d65ee
|
||
|
|
65c9aa6c5c
|
||
|
|
c58202e683
|
||
|
|
ea63dbb9f9
|
||
|
|
9db1a6093b
|
||
|
|
bd98001d42
|
||
|
|
90663a51cc
|
||
|
|
7ecb61399d
|
||
|
|
40ab07882d
|
||
|
|
676b4bc2ba
|
||
|
|
2d50440bf1
|
||
|
|
6b4da18be5
|
||
|
|
5222cfa1cb
|
||
|
|
dd98a90a45
|
||
|
|
26581cfca1
|
||
|
|
d9f3ee99c1
|
||
|
|
f21570f579
|
||
|
|
7a61077d80
|
||
|
|
7dd0e8f2d6
|
||
|
|
c8a32d49c9
|
||
|
|
4e42855c59
|
||
|
|
9a7cda05c9
|
||
|
|
5630a86d88
|
||
|
|
b9dd1f4d08
|
||
|
|
9aed6f4a24
|
||
|
|
3d377f68fb
|
||
|
|
5166d97545
|
||
|
|
ebe7b8bdd7
|
||
|
|
a5187981c7
|
||
|
|
10a672787a
|
||
|
|
9eb865bb02
|
||
|
|
74ffe66884
|
||
|
|
f8796913e5
|
||
|
|
d60f849864
|
||
|
|
a981256b11
|
||
|
|
8c085bea35
|
||
|
|
670351d436
|
||
|
|
64cf43dc01
|
||
|
|
62507d3a01
|
||
|
|
667f523c8b
|
||
|
|
507c8ac317
|
||
|
|
670a7bd02b
|
||
|
|
5ff921222a
|
||
|
|
0edaef56bd
|
||
|
|
994734b001
|
||
|
|
a501a17519
|
||
|
|
edf4dab26d
|
||
|
|
818a44d697
|
||
|
|
e31bf92df7
|
||
|
|
a1c452f19d
|
||
|
|
362eb9e729
|
||
|
|
35074bab67
|
||
|
|
1fb7837255
|
||
|
|
4e723e1657
|
||
|
|
cd8b5ac67b
|
||
|
|
bd5a6846e8
|
||
|
|
da8fde6a4e
|
||
|
|
3b946b1eab
|
||
|
|
d540fc31e9
|
||
|
|
024dfd50b3
|
||
|
|
3828d5b483
|
||
|
|
39dbd0f3a2
|
||
|
|
d3560dca52
|
||
|
|
24cbfc2f27
|
||
|
|
4cdf618c25
|
||
|
|
0a82ca5a42
|
||
|
|
4cf793cd7e
|
||
|
|
36e5e8afe6
|
||
|
|
3f9821d475
|
||
|
|
9e873131d4
|
||
|
|
5b77d14497
|
||
|
|
d4c36feb9a
|
||
|
|
5d0acdac01
|
||
|
|
d6707133cc
|
||
|
|
fb601f4d5d
|
||
|
|
d8dd4fa91e
|
||
|
|
af96caff40
|
||
|
|
52184ba6fb
|
||
|
|
0eb4e5c78d
|
||
|
|
5c51de217a
|
||
|
|
c1f5d3ca54
|
||
|
|
1bb6968108 | ||
|
|
14b444d109
|
||
|
|
de3105d4cd | ||
|
|
c46103a23f | ||
|
|
9529f64b41
|
||
|
|
d0de17329d | ||
|
|
9af37e92b4 | ||
|
|
e68a1dbd30 | ||
|
|
b9c6d16ff0
|
@@ -0,0 +1,83 @@
|
||||
# Copy to `.env` (gitignored) and fill in:
|
||||
#
|
||||
# cp .env.example .env
|
||||
#
|
||||
# `docker compose` reads it for the `${VAR}` substitutions in
|
||||
# docker-compose.yml, and `cargo run` reads it through dotenv. Every variable is
|
||||
# described in README.md ("环境变量说明" / "Environment variables") — this file
|
||||
# only shows the shape, with the defaults the code would use anyway.
|
||||
|
||||
# --- required -------------------------------------------------------------
|
||||
# Token from @BotFather. Without it the bot exits at startup.
|
||||
TELOXIDE_TOKEN=
|
||||
|
||||
# --- sites (all optional) -------------------------------------------------
|
||||
# Pixiv: refresh token. Unset = pixiv links answer "support is disabled".
|
||||
PIXIV_REFRESH_TOKEN=
|
||||
# Twitter/X: the `auth_token` cookie of a logged-in session, used only for
|
||||
# NSFW tweets that the public syndication endpoint withholds.
|
||||
TWITTER_AUTH_TOKEN=
|
||||
# bilibili: the whole cookie string; only needed when the egress IP stays
|
||||
# risk-controlled (device cookies are fetched automatically).
|
||||
BILIBILI_COOKIE=
|
||||
|
||||
# --- bot behaviour --------------------------------------------------------
|
||||
# Admin chat IDs, comma-separated: start/stop notices, admin-only commands.
|
||||
BOT_ADMIN=
|
||||
# Log level. Leave the line commented out for the default
|
||||
# (`info,hyper_util=warn,reqwest=warn`); do not set it to an empty value.
|
||||
# RUST_LOG=info,xmedia_bot=debug,x_media=debug
|
||||
# Edit-before-forward record TTL (seconds).
|
||||
EDIT_MESSAGE_TTL_SECONDS=86400
|
||||
# Link-result cache TTL (seconds).
|
||||
LINK_CACHE_TTL_SECONDS=604800
|
||||
# Wrap a post's text in a collapsible blockquote from this many characters on;
|
||||
# 0 disables the wrap.
|
||||
CAPTION_QUOTE_TEXT_CHARS=200
|
||||
# State directory (local runs only — the container uses /app/data).
|
||||
DATA_DIR=data
|
||||
|
||||
# --- network --------------------------------------------------------------
|
||||
# HTTP proxy for the Bot API and site fetches. Two traps: teloxide panics on a
|
||||
# *blank* value, so comment the line out rather than leaving it empty; and
|
||||
# inside a container the proxy must be reachable from there (use
|
||||
# host.docker.internal, not 127.0.0.1 — that is the container itself).
|
||||
# docker-compose.yml does not pass this variable unless you add it to the bot
|
||||
# service's `environment:` block.
|
||||
# TELOXIDE_PROXY=http://127.0.0.1:10808
|
||||
|
||||
# --- webhook deployment (docker-compose.yml) ------------------------------
|
||||
# false = long polling (no public URL needed). true = webhook behind the
|
||||
# bundled nginx-proxy — and then WEBHOOK_LISTEN/PORT/URL are required.
|
||||
# The compose healthcheck probes the listener only when this is true.
|
||||
WEBHOOK=false
|
||||
# WEBHOOK_LISTEN=0.0.0.0
|
||||
# WEBHOOK_PORT=8443
|
||||
# WEBHOOK_URL=https://your.domain/
|
||||
# Validation token Telegram echoes back as X-Telegram-Bot-Api-Secret-Token.
|
||||
# Required when WEBHOOK=true: the bot refuses to start without one (use a
|
||||
# random value of 16+ chars — without it the listener accepts any request).
|
||||
# WEBHOOK_SECRET_TOKEN=
|
||||
# Self-signed certificate path, used only for Telegram-side validation (TLS is
|
||||
# terminated by the reverse proxy); unneeded with acme-companion. Not passed by
|
||||
# docker-compose.yml — add the line there if this deployment needs it.
|
||||
# WEBHOOK_CERT=/app/cert/cert.pem
|
||||
|
||||
# --- reverse proxy (docker-compose.yml) -----------------------------------
|
||||
# Public domain or IP that nginx-proxy routes for; empty = do not route.
|
||||
VIRTUAL_HOST=
|
||||
# Port inside the bot container nginx-proxy forwards to.
|
||||
VIRTUAL_PORT=8443
|
||||
# Certificate notification address for acme-companion.
|
||||
DEFAULT_EMAIL=
|
||||
# UID the container runs as; it must be able to write ./data on the host.
|
||||
# The entrypoint's default (and the README's) is 9001 — keep them equal so
|
||||
# the file owner on the host matches what you expect. Must be a non-zero
|
||||
# numeric uid: the entrypoint refuses 0 (the bot would keep root through the
|
||||
# privilege drop) and anything non-numeric.
|
||||
LOCAL_USER_ID=9001
|
||||
# Uncomment (here and the matching line in docker-compose.yml) to have
|
||||
# acme-companion issue the certificate for VIRTUAL_HOST.
|
||||
# ACME_HOST=
|
||||
# Send requests with an unknown Host to this vhost (needed for plain-IP access).
|
||||
# DEFAULT_HOST=
|
||||
@@ -4,6 +4,8 @@ name: CI
|
||||
# job that exercises the real source sites and the token-gated pixiv tests.
|
||||
#
|
||||
# Layering:
|
||||
# changes — decides whether anything but documentation changed; a docs-only
|
||||
# push/PR skips `test` (which then reports as skipped, not missing).
|
||||
# test — fmt + clippy + the full offline unit suite + a release-profile
|
||||
# build + cargo-audit dependency gate. Runs on every push and PR,
|
||||
# including forks (it needs no secrets).
|
||||
@@ -26,6 +28,7 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
tags: ['v*']
|
||||
pull_request:
|
||||
schedule:
|
||||
# Weekly probe of the live endpoints, so external API changes surface.
|
||||
@@ -46,7 +49,53 @@ env:
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
jobs:
|
||||
# Docs-only changes skip the heavy job: a README edit does not need a four
|
||||
# minute Rust build (and it cannot break one). A gate job rather than a
|
||||
# workflow-level `paths` filter — that leaves the run without a `test` check
|
||||
# at all, and a required status check then waits for something that will
|
||||
# never be reported, while a *skipped* job reports as neutral.
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
code: ${{ steps.diff.outputs.code }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
fetch-depth: 0 # the diff below needs the pushed range
|
||||
- id: diff
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
zero=0000000000000000000000000000000000000000
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
base="origin/${{ github.base_ref }}"
|
||||
git fetch --quiet --no-tags origin "${{ github.base_ref }}"
|
||||
changed="$(git diff --name-only "$base...HEAD")"
|
||||
else
|
||||
before="${{ github.event.before }}"
|
||||
if [ -z "$before" ] || [ "$before" = "$zero" ]; then
|
||||
# New branch or force push: no usable base to compare against,
|
||||
# so the full suite runs. Same for schedule/dispatch, which have
|
||||
# no `before` at all.
|
||||
changed=""
|
||||
else
|
||||
changed="$(git diff --name-only "$before..${{ github.sha }}")"
|
||||
fi
|
||||
fi
|
||||
# Only a change that is *entirely* markdown may skip the job;
|
||||
# anything else — and an empty diff, i.e. a re-run of the same
|
||||
# commit — counts as code.
|
||||
code=true
|
||||
if [ -n "$changed" ] && ! grep -qvE '\.md$' <<<"$changed"; then
|
||||
code=false
|
||||
fi
|
||||
echo "changed: ${changed:-<no diff>}"
|
||||
echo "code=$code" >> "$GITHUB_OUTPUT"
|
||||
|
||||
test:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.code == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
# Generous on purpose: the release-profile build below is cold on the very
|
||||
# first run (thin LTO + codegen-units = 1 across every dependency), and a
|
||||
@@ -92,15 +141,29 @@ jobs:
|
||||
env:
|
||||
PIXIV_REFRESH_TOKEN: ${{ secrets.PIXIV_REFRESH_TOKEN }}
|
||||
TWITTER_AUTH_TOKEN: ${{ secrets.TWITTER_AUTH_TOKEN }}
|
||||
BILIBILI_COOKIE: ${{ secrets.BILIBILI_COOKIE }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
# Everything network- or secret-gated lives in x-media, and the bot
|
||||
# crate's suite (MockSender + tempdir stores, no network) already ran in
|
||||
# the `test` job — rebuilding it here bought nothing.
|
||||
- name: Run token-gated tests
|
||||
run: cargo test -p x-media --locked
|
||||
# The live-network tests, by the "live" name filter (all #[ignore]d).
|
||||
- name: Run live-network tests
|
||||
run: cargo test -p x-media --locked -- --ignored live
|
||||
# All #[ignore]d live tests, by the "live" name filter, in both crates:
|
||||
# the bot crate has two of its own (repair refetch, text-only link)
|
||||
# whose fetches are network-bound but whose sends go through MockSender.
|
||||
# --show-output keeps each test's stdout — the SKIP lines printed by a
|
||||
# skipped test are what the summary step below greps, so a skip stays
|
||||
# distinguishable from a pass.
|
||||
- name: Run live-network tests (x-media)
|
||||
run: cargo test -p x-media --locked -- --ignored live --show-output 2>&1 | tee live-x-media.log
|
||||
- name: Run live-network tests (xmedia-bot)
|
||||
run: cargo test -p xmedia-bot --locked -- --ignored live --show-output 2>&1 | tee live-bot.log
|
||||
# A green live run must not be able to mean "nothing actually ran"
|
||||
# (pixiv without its secret, bilibili risk-controlling the runner IP):
|
||||
# collect every SKIP line into the run summary.
|
||||
- name: Surface skipped live tests
|
||||
if: always()
|
||||
run: |
|
||||
skips=$(grep -h '^SKIP ' live-*.log 2>/dev/null || true)
|
||||
if [ -n "$skips" ]; then
|
||||
echo "::warning::live job skipped tests, see the job summary"
|
||||
{ echo "### Live tests skipped"; echo "$skips" | sed 's/^/- /'; } >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
@@ -21,7 +21,10 @@ on:
|
||||
- Cargo.toml
|
||||
- Cargo.lock
|
||||
- .github/workflows/docker.yml
|
||||
- 'crates/**/Cargo.toml'
|
||||
# Any crate source, not just manifests: the stub/touch layering only
|
||||
# breaks against real source structure, which a manifest-only PR never
|
||||
# exercises.
|
||||
- 'crates/**'
|
||||
|
||||
env:
|
||||
APP_NAME: telegram-twitter-media-bot
|
||||
@@ -39,7 +42,9 @@ concurrency:
|
||||
jobs:
|
||||
# A tag push and a branch push to the same commit fire two workflow runs;
|
||||
# build only once. Tag runs always build; master runs build only when the
|
||||
# pushed commit is not already tagged (the tag run covers it).
|
||||
# pushed commit is not already tagged (the tag run covers it). That check
|
||||
# can only see tags that already exist on the remote — see the check step's
|
||||
# re-fetch and the one-push release flow in AGENTS.md.
|
||||
should-build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
@@ -73,13 +78,44 @@ jobs:
|
||||
- id: check
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "$GITHUB_REF_TYPE" = "branch" ] && git tag --points-at "$GITHUB_SHA" | grep -q .; then
|
||||
echo "commit already tagged; the tag run builds the image"
|
||||
echo "build=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "build=true" >> "$GITHUB_OUTPUT"
|
||||
zero=0000000000000000000000000000000000000000
|
||||
if [ "$GITHUB_REF_TYPE" = "branch" ]; then
|
||||
# A branch run can start before the release tag for its commit
|
||||
# reaches the remote — pushing master first is the usual way to hit
|
||||
# it — and then `git tag --points-at` legitimately finds nothing
|
||||
# and this run builds the same commit the tag run is building: two
|
||||
# docker builds, one release. (Seen on v1.9.0 and v1.9.1: the
|
||||
# branch run's checkout had every tag *except* the one being
|
||||
# pushed.) Re-fetching here, immediately before the decision,
|
||||
# shrinks the window to "the tag was pushed after this step ran";
|
||||
# pushing the branch and the tag together
|
||||
# (`git push origin master vX.Y.Z`) removes it.
|
||||
git fetch --tags --force --quiet origin
|
||||
if git tag --points-at "$GITHUB_SHA" | grep -q .; then
|
||||
echo "commit already tagged; the tag run builds the image"
|
||||
echo "build=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
# Nothing the image is made of changed — a documentation or
|
||||
# workflow-only commit — so there is no new image to publish. The
|
||||
# PR trigger's path list plus the crate sources, which the image
|
||||
# compiles into the binary.
|
||||
before="${{ github.event.before }}"
|
||||
if [ -n "$before" ] && [ "$before" != "$zero" ] \
|
||||
&& ! git diff --name-only "$before..$GITHUB_SHA" \
|
||||
| grep -qE '^(Dockerfile|docker-entrypoint\.sh|\.dockerignore|Cargo\.toml|Cargo\.lock|\.github/workflows/docker\.yml|crates/)'; then
|
||||
echo "no build input changed; skipping the image build"
|
||||
echo "build=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
echo "build=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# No `actions/checkout` here on purpose: `docker/build-push-action` defaults
|
||||
# to the Git context (`https://github.com/<owner>/<repo>.git#<ref>`), so
|
||||
# BuildKit clones the repo itself and authenticates with the automatic
|
||||
# github.token. Adding `context: .` below without a checkout step would hand
|
||||
# BuildKit an empty workspace.
|
||||
docker:
|
||||
needs: should-build
|
||||
if: needs.should-build.outputs.build == 'true'
|
||||
@@ -117,9 +153,11 @@ jobs:
|
||||
# would give every new tag a cold cache on release builds. PR runs only
|
||||
# read it (cache-to is empty) so they cannot evict the release cache.
|
||||
#
|
||||
# FFMPEG_URL/FFMPEG_SHA256 come from repository variables when set, so a
|
||||
# release can pin an exact ffmpeg build (the Dockerfile default follows
|
||||
# the project's `/redirect/latest/` URL, which has no sha256 sidecar).
|
||||
# FFMPEG_URL/FFMPEG_SHA256 come from repository variables when set —
|
||||
# both or neither: the Dockerfile checks the sha256 unconditionally, so
|
||||
# a URL without its matching hash fails the build. The fallbacks pin the
|
||||
# same 9.0.2 release the Dockerfile defaults to (keep the three in step
|
||||
# when bumping).
|
||||
#
|
||||
# Single-arch (amd64) on purpose: adding arm64 means re-adding
|
||||
# `docker/setup-qemu-action`, `platforms: linux/amd64,linux/arm64`, and
|
||||
@@ -131,8 +169,8 @@ jobs:
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
build-args: |
|
||||
APP_NAME=${{ env.APP_NAME }}
|
||||
FFMPEG_URL=${{ vars.FFMPEG_URL || 'https://ffmpeg.martin-riedl.de/redirect/latest/linux/amd64/release/ffmpeg.zip' }}
|
||||
FFMPEG_SHA256=${{ vars.FFMPEG_SHA256 }}
|
||||
FFMPEG_URL=${{ vars.FFMPEG_URL || 'https://ffmpeg.martin-riedl.de/download/linux/amd64/1789931100_9.0.2/ffmpeg.zip' }}
|
||||
FFMPEG_SHA256=${{ vars.FFMPEG_SHA256 || 'fa8ecf4abbd290d98f7d188b8649cc6b391ae209a98452be955a15aab1909d7f' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha,scope=tgxmb-build
|
||||
|
||||
@@ -6,8 +6,6 @@ nginx-certs/
|
||||
nginx-vhost.d/
|
||||
nginx-html/
|
||||
nginx-acme/
|
||||
docker-compose.yml
|
||||
|
||||
.env
|
||||
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
## Project Overview
|
||||
|
||||
Telegram bot (teloxide) that turns post links from X/Twitter, Pixiv, Bluesky, and Misskey (misskey.io) into media messages (images, video, GIF) with the post's title, author, and tags. It supports batch media splitting, retry with persistence, inline queries, forward-channel rebinding with caption templates, and Pixiv ugoira→MP4 transcoding. README is in Chinese; user-facing bot strings are in English. The project is a Rust port of a Python predecessor (see `queue.rs` comments referencing `utils/task_queue.py`).
|
||||
Telegram bot (teloxide) that turns post links from X/Twitter, Pixiv, Bluesky, Misskey (misskey.io), and Bilibili dynamics into media messages (images, video, GIF) with the post's title, author, and tags. It supports batch media splitting, retry with persistence, inline queries, forward-channel rebinding with caption templates, and Pixiv ugoira→MP4 transcoding. README is in Chinese; user-facing bot strings are in English. The project is a Rust port of a Python predecessor (see `queue.rs` comments referencing `utils/task_queue.py`).
|
||||
|
||||
Two-crate Cargo workspace (both v1.6.0, edition 2024, resolver 3):
|
||||
Two-crate Cargo workspace (both v1.9.2, edition 2024, resolver 3):
|
||||
|
||||
- **`crates/x-media`** — library that fetches and normalizes media from the four sites. Pure, no Telegram knowledge.
|
||||
- **`crates/xmedia-bot`** — the bot binary: teloxide dispatcher, SQLite-backed chat state, persistent task queue.
|
||||
@@ -18,31 +18,37 @@ Telegram update → Dispatcher (polling or axum webhook) → dptree branches
|
||||
└─ callback_query → "forward" (copy to channel) / "template|<name>" (apply caption template)
|
||||
```
|
||||
|
||||
Message flow: `message_handler` extracts URLs (from `url`/`text_link` entities, text + caption, deduped) → `x_media::site::fetch(url)` → `Fetched` → builds a `Task` → `send::send_media_sequence` (media groups ≤ 9, caption on first item) or `send::send_animation`. On Telegram URL-fetch failure or size error (`send_batch_via_upload`): download via `x_media::site::download_media` to a temp file (≤ 10 MiB), sniff magic bytes (`sniff_ext`), upload via multipart; oversized items fall back to `fallback_url`. On failure: `enqueue_retry` persists resume-state `Task` into the SQLite queue → workers lease (120 s lock TTL) → retry with exponential backoff (≤ 30 s, `MAX_RETRIES = 2`) → dead-letter → `notify_failure`. Success → `post_send_actions`: edit-before-forward prompt with inline buttons, or `copy_messages` to the bound forward channel.
|
||||
Message flow: `message_handler` extracts URLs (from `url`/`text_link` entities, text + caption, deduped) → `x_media::site::fetch(url)` → `Fetched` → builds a `Task` → `send::send_media_sequence` (media groups ≤ 10, caption on first item) or `send::send_animation`. On Telegram URL-fetch failure or size error (`send_batch_via_upload`): download via `x_media::site::download_media_limited` to a temp file (≤ 10 MiB), sniff magic bytes (`sniff_ext`), upload via multipart; oversized items fall back to `fallback_url`. On failure: `enqueue_retry` persists resume-state `Task` into the SQLite queue (it reports whether the row was really written, and only then does the user get the "retrying in Ns" notice — an enqueue that fails says so instead) → workers lease (120 s lock TTL) → retry with exponential backoff (≤ 30 s for the bot's own delays, `MAX_RETRIES = 2`) → dead-letter → `notify_failure`. Success → `post_send_actions`: edit-before-forward prompt with inline buttons, or `copy_messages` to the bound forward channel.
|
||||
|
||||
Debug command: `/debug <url>` runs the same `x_media::site::fetch` and replies with `debug_report` (`handlers/commands.rs`) — site id, normalized cache key, source URL, title/author/tags, sensitive flag, caption and the media list — nothing is sent, cached or forwarded; the report is capped at 4000 chars and sent with HTML parse mode: raw fields are escaped, and the caption is wrapped in a `<blockquote>` so it renders exactly like the sent media caption (escaped text and links included).
|
||||
Debug command: `/debug <url>` runs the same `x_media::site::fetch` and replies with `debug_report` (`handlers/commands.rs`) — site id, normalized cache key, source URL, title/author/tags, sensitive flag, caption and the media list — nothing is sent, cached or forwarded; the report is capped at 4000 chars and sent with HTML parse mode: raw fields are escaped, and the caption is wrapped in a `<blockquote>` so it renders exactly like the sent media caption (escaped text and links included). The caption it shows is `preview_caption`'s: the chat's per-site format override plus the long-post quoting, i.e. exactly what the send paths produce — showing the raw built-in caption made `/set_format` look like a no-op, and the `/set_format` success reply points users at `/debug` to preview.
|
||||
|
||||
The `/test <url>` command runs the ordinary link pipeline (`urls::url_media`) with `PostSend::Suppressed`: the media is sent and cached like any other link, but the chat's `forward_channel_id`/`edit_before_forward` are ignored, so a test never forwards to the channel and never opens the edit prompt (retries and dead-letter notifications behave as usual). Both commands use a custom `parse_arg_remainder` parser (whole remainder, trimmed) because teloxide's built-in `split` parser takes exactly one space-separated token.
|
||||
User-facing failure text is a function of the error class, never one generic sentence: `urls::fetch_error_message` maps `FetchError::NotFound` (post gone), `Sensitive` (withheld, needs `TWITTER_AUTH_TOKEN`), `Blocked` (source risk control), `Disabled { site }` (a registered site switched off — pixiv without a token, the one case `fetch` answers `Err` instead of `Ok(None)`) and `Transient`/`Http` (source down) apart. The same distinction drives the group hint: a supported link posted in a group (not a channel) gets one `GROUP_LINK_HINT` reply, because the link pipeline is private-chat only.
|
||||
|
||||
The `x-media` library: `site::fetch(url)` dispatches through the `SITES` registry (per-site `impl Site`, in order twitter → bsky → misskey → pixiv) and returns `Ok(None)` for unmatched URLs. `Fetched { source_url, caption, title, media: Vec<Media>, sensitive, site_id, … }`; `caption_with(format)` substitutes `{url} {author} {author_url} {title} {tags}`.
|
||||
The `/test <url>` command runs the ordinary link pipeline (`urls::url_media`) with `PostSend::Suppressed`: the media is sent and cached like any other link, but the chat's `forward_channel_id`/`edit_before_forward` are ignored, so a test never forwards to the channel and never opens the edit prompt (retries and dead-letter notifications behave as usual). `/test`, `/debug`, `/set_format` and `/clear_cache` use the custom `parse_arg_remainder` parser (whole remainder, trimmed) because teloxide's built-in `split` parser takes exactly one space-separated token per field: `/set_format <site> <format>` never parsed with it (and `/clear_cache` without an argument did not either), and a command that fails to parse falls through to the URL flow in silence. `commands::tests::every_documented_invocation_parses` pins every documented form against exactly that.
|
||||
|
||||
The inline path (`handlers/inline.rs`) answers from the **link cache** first: a post already sent somewhere answers with `InlineQueryResultCached*` built from its Telegram file ids, so no fetch happens and — unlike a URL result — media Telegram could never fetch itself still works (pixiv's pximg.net, a locally encoded ugoira/bsky MP4). Only a cache miss fetches (`fetch_once`), and then the media URLs go straight to Telegram, which fetches them itself and cannot send site-specific headers — so `x_media::site::needs_media_headers(url)` (true exactly where a site's `media_headers` is non-empty, i.e. pixiv's pximg.net) marks the media that must be skipped instead of shipped broken; locally produced media (ugoira MP4, bsky remux) fails `Url::parse` and is skipped the same way. A degraded cache entry keeps only URLs, so it takes the same URL path (a video with no poster is skipped there, Telegram has no thumbnail to show). A query whose every item was skipped is answered *empty* (with a cache window) rather than left unanswered — an unanswered query keeps the client spinning and, through the debounce's release, re-runs the fetch on every keystroke. The answer goes through `MediaSender::answer_inline_query` (the trait carries it so the path is mock-testable; `inline.rs`'s own tests cover the cache and degraded-entry answers offline).
|
||||
|
||||
`url_media` is a thin wrapper over `url_media_inner`: `run_with_chat_action` sends the chat action, then re-sends it every `ACTION_REFRESH` (4 s) while the pipeline future is pending, because Telegram drops an action after ~5 s and a fetch (ugoira encode, HLS remux) plus an upload routinely outlasts that. The pipeline flips the shared `ActionHint` from `Typing` to `UploadPhoto`/`UploadVideo` once the media kinds are known. The `select!` is `biased` on the pipeline branch so a finished pipeline never emits a stray action.
|
||||
|
||||
The `x-media` library: `site::fetch(url)` dispatches through the `SITES` registry (per-site `impl Site`, in order twitter → bsky → misskey → pixiv → bilibili) and returns `Ok(None)` for unmatched URLs (`Err(FetchError::Disabled { site })` when the URL matches a registered site whose `enabled()` is false — see `disabled_site`). `Fetched { source_url, caption, title, content, media: Vec<Media>, sensitive, site_id, … }` (title and content are split per platform: a pixiv artwork's title and description, a bilibili headline and body, and text-only posts whose text is all `content`); `caption_with(format)` substitutes `{url} {author} {author_url} {title} {content} {tags}`.
|
||||
|
||||
## Key Directories
|
||||
|
||||
| Path | Purpose |
|
||||
|---|---|
|
||||
| `crates/x-media/src/` | Fetch library. `site/mod.rs` = dispatcher + `Fetched`/`FetchError`/`download_media`/`media_size`; `media.rs` = `Media` enum; `examples/fetch.rs` = end-to-end usage sample |
|
||||
| `crates/x-media/src/site/<twitter\|pixiv\|bsky\|misskey>/` | One directory per site: `mod.rs` (re-exports), `interface.rs` (PATTERN, `enabled()`, `fetch_from_url()`, `cache_key`/`is_retryable`/`media_headers`, unit struct `<Name>Site` implementing `site::Site`, `From<SiteStruct> for Fetched`), `model.rs` (serde DTOs). Pixiv adds `api.rs` (auth + transport); twitter adds `auth.rs` (logged-in GraphQL `TweetDetail` fallback for NSFW tweets, gated on `TWITTER_AUTH_TOKEN`). Misskey targets misskey.io only (`POST /api/notes/show`, 400+`NO_SUCH_NOTE` → NotFound). Twitter's `from_syndication_json` HTML-decodes the API text — syndication and GraphQL `full_text` both arrive pre-escaped (`>` `<` `&` `'`) — so the stored text is raw and the caption escapes exactly once |
|
||||
| `crates/xmedia-bot/src/main.rs` | Entry point: env/log init, command registration (`register_commands`), shared `send::BOT` force-init, queue worker start, site login validation (`site::validate_all`), 300 s edit-expiry sweep, dptree handler tree, webhook vs polling dispatch |
|
||||
| `crates/x-media/src/` | Fetch library. `site/mod.rs` = dispatcher + `Fetched`/`FetchError`/`download_media*` (the streaming `download_media_to_file` and the capped `download_media_limited`, which is where a download's size and its total time budget are enforced); `media.rs` = `Media` enum; `examples/fetch.rs` = end-to-end usage sample |
|
||||
| `crates/x-media/src/site/<twitter\|pixiv\|bsky\|misskey\|bilibili>/` | One directory per site: `mod.rs` (re-exports), `interface.rs` (`PATTERN`, `fetch_from_url()`, `cache_key`, the unit struct `<Name>Site` implementing `site::Site` — the trait supplies the `enabled`/`is_retryable`/`media_headers` defaults unless the site differs, as pixiv does — and `From<SiteStruct> for Fetched`), `model.rs` (serde DTOs). Pixiv adds `api.rs` (auth + transport); twitter adds `auth.rs` (logged-in GraphQL `TweetDetail` fallback for NSFW tweets, gated on `TWITTER_AUTH_TOKEN`; without the token a withheld tweet stays `FetchError::Sensitive` and the bot reports it as age-restricted instead of "no media"). Misskey targets misskey.io only (`POST /api/notes/show`, 400+`NO_SUCH_NOTE` → NotFound). Bilibili fetches dynamics (images/animated images only — an attached video degrades to its cover, and its title stands in for the post text, which AV dynamics do not have) from `/x/polymer/web-dynamic/v1/detail` sent with `features=itemOpusStyle` (without that flag the legacy serialization drops an image/text post's body and headline entirely — `desc` comes back `null`; the adapter still parses the legacy `major.draw`/`desc`/`archive` shapes as a fallback). No WBI signature is involved; device cookies `buvid3`/`buvid4` are fetched automatically from `/x/frontend/finger/spi` because bilibili's `-352` risk control starts rejecting plain requests, `BILIBILI_COOKIE` is the escalation when an IP stays blocked; `b23.tv` short links are deliberately unmatched. Twitter's `from_syndication_value` HTML-decodes the API text — syndication and GraphQL `full_text` both arrive pre-escaped (`>` `<` `&` `'`) — so the stored text is raw and the caption escap…
|
||||
| `crates/xmedia-bot/src/main.rs` | Entry point: env/log init, command registration (`register_commands` — `setMyCommands` plus the profile description texts), shared `send::BOT` force-init, startup sweep of this project's leftover temp files (`x_media::TEMP_FILE_PREFIX` + an age gate, since a killed process runs no destructors), startup repair of queued retries whose local media did not survive a restart (`handlers::repair_lost_local_media`, before any worker can lease: those rows are re-fetched from their `source_url`), queue worker start, site login validation (`site::validate_all`), `periodic_sweep` (`SWEEP_INTERVAL` 300 s): expired prompts are rewritten in place to `EDIT_PROMPT_EXPIRED_TEXT` with an empty keyboard — an edit, never a new message, so a background timer cannot wake a chat — plus the link-cache prune, the idle rate-limit buckets and the idle inline-query entries, and the queue backlog line (only when non-empty). Takes its collaborators rather than the statics so its loop is testable with a paused clock, dptree handler tree, webhook vs polling dispatch |
|
||||
| `crates/xmedia-bot/src/config.rs` | Manual env parsing into `Config` |
|
||||
| `crates/xmedia-bot/src/db.rs` | `DbPool`: one shared SQLite connection pool (`POOL_SIZE = 4`, WAL, busy_timeout) for all three tables over `$DATA_DIR/task_queue.db` (default `data/`) — the three stores share it; `open_store` creates file + schema, `with_conn` runs all rusqlite I/O in `spawn_blocking` |
|
||||
| `crates/xmedia-bot/src/handlers/` | Handler modules: `mod.rs` (message entry point, `reply`, `log_key`), `commands.rs` (teloxide `BotCommands` enum + command executor, incl. `/test <url>` (send-only) / `/debug <url>` (parse-only) and the admin-only `/bot_dict` state dump), `urls.rs` (URL extraction + bounded job channel (256) drained by `URL_WORKERS = 8` workers (`start_url_workers`) — backpressure instead of unbounded spawns; teloxide's per-chat workers are sequential — batch-forwards need concurrency), `inline.rs`/`callback.rs` (inline queries / edit-before-forward buttons), `statics.rs` (global statics) |
|
||||
| `crates/xmedia-bot/src/state.rs` | `ChatStore`: parking_lot `Mutex<HashMap>` cache + SQLite write-through (`chat_state` table) |
|
||||
| `crates/xmedia-bot/src/link_cache.rs` | `LinkCache`: SQLite-backed cache (`link_cache` table) of successfully sent posts — raw caption fields + Telegram `file_id`s; repeat links re-send locally (no fetch/upload), TTL + prune, invalidated on permanent send failure |
|
||||
| `crates/xmedia-bot/src/queue.rs` | `PersistentTaskQueue`: SQLite-backed queue (`tasks` table), `QUEUE_WORKERS = 4` concurrent workers (lease via `BEGIN IMMEDIATE` + `locked_until` TTL), retry→dead-letter, `notify_one` worker wakeup plus a separate `Notify` for the 30 s lease-expiry sweep (a shared one let the sweep steal the workers' wakeup permit), `busy_timeout` on all connections |
|
||||
| `crates/xmedia-bot/src/ctx.rs` | `AppContext`: the injected collaborators (`sender` + `ChatStore`/`PersistentTaskQueue`/`LinkCache`/`Config`), `from_statics` for production and the `CONTEXT` static the worker closures hold. `test_support::TestStores` backs handler tests with a tempdir store set |
|
||||
| `crates/xmedia-bot/src/send/` | `send/mod.rs`: `Task`/`MediaItemPayload` payloads, `SendError`/`Classification`, `send_media_sequence`/`send_animation`/`forward_messages`; `send/input_media.rs`: payload → `InputFile`/`InputMedia` + `build_media_group` (caption on the first item only); `send/upload.rs`: the download-and-reupload fallback (`prepare_upload_item`/`send_batch_via_upload`, photo downscale handoff); `send/post_send.rs`: link-cache write, `KEEP_ALIVE` registry, `settle_task`, `post_send_actions`, `handle_task`/`dead_letter_notify` |
|
||||
| `crates/xmedia-bot/src/media_sender.rs` | `MediaSender` trait: the user-flow surface (`send_media_group`/`send_animation`/`copy_messages`/`send_message`/`answer_callback_query`/`edit_message_caption`/`delete_message`/`send_chat_action`) implemented by teloxide `Bot` (per-chat rate-limited) and by a recording `MockSender` in tests. Admin/setup APIs (`get_chat`, `set_my_commands`, …) stay on the concrete `Bot` |
|
||||
| `crates/xmedia-bot/src/rate_limit.rs` | Per-chat token bucket (`CAPACITY = 20`, ~20 msg/min refill) paced before sends reach the API so batch forwards don't trip flood control |
|
||||
| `crates/xmedia-bot/src/db.rs` | `DbPool`: one shared SQLite connection pool (`POOL_SIZE = 16`, WAL, busy_timeout) for all three tables over `$DATA_DIR/task_queue.db` (default `data/`) — the three stores share it; `open_store` creates file + schema and then applies the `PRAGMA user_version` migration chain (`MIGRATIONS` + `migrate` — append-only; `schema_init` is the version-0 baseline and must not gain columns an existing database would never receive — `db.rs`'s tests pin a pre-migration database upgrading intact, the shipped migration text frozen (appending is the only allowed change) and a fresh database landing at the latest version), `with_conn` runs all rusqlite I/O in `spawn_blocking` |
|
||||
| `crates/xmedia-bot/src/handlers/` | Handler modules: `mod.rs` (message entry point, `reply`, `log_key`, the group-only `GROUP_LINK_HINT` for a supported link posted outside a private chat), `url_workers.rs`/`repair.rs` (worker pool; startup repair), `commands.rs` (teloxide `BotCommands` enum + command executor, incl. `/test <url>` (send-only) / `/debug <url>` (parse-only) and the admin-only `/bot_dict` state dump; `/set_format` rejects unknown `{…}` placeholders and resets with `-`), `urls.rs` (URL extraction + the per-URL pipeline; one *shared* in-flight fetch per cache key (`shared_fetch`+`IN_FLIGHT_FETCHES`: a second chat, a batch forward or a retry asking for the same post meanwhile waits for the first caller's result, the entry is dropped the moment the fetch settles so nothing is ever answered from an old fetch, and a waiter whose sharer was cancelled fetches for itself); plus the startup repair `repair_lost_local_media`, whose decision (`needs_refetch`) and rewrite (`apply_refresh`) are pure and tested while the fetch itself is a live test), `url_workers.rs` (the bounded job channel (256) and its `URL_WORKERS = 8` supervised workers, `start_url_workers`/`stop_url_workers` — backpressure instead of unbounded spawns; teloxide's per-chat workers are sequential, so batch-forwards need this concurrency), `repair.rs` (startup `repair_lost_local_media` with its `needs_refetch`/`apply_refresh`/`refetch`), `inline.rs`/`callback.rs` (inline queries / edit-before-forward buttons, incl. `skip`; a forward that fails retryably is both queued *and* settles the prompt — the queued row carries the message ids itself, and a prompt left live let a second Confirm copy the same messages twice and let Skip answer "nothing was forwarded" while the row still delivered), `statics.rs` (global statics) |
|
||||
| `crates/xmedia-bot/src/state.rs` | `ChatStore`: parking_lot `Mutex<HashMap>` cache + SQLite write-through (`chat_state` table); the 300 s sweep's `prune_expired` evicts any chat with no live edit-before-forward prompt, so the cache (and the per-chat lock map) stays bounded to active prompts — durable settings reload from the DB on next use |
|
||||
| `crates/xmedia-bot/src/link_cache.rs` | `LinkCache`: SQLite-backed cache (`link_cache` table) of successfully sent posts — raw caption fields + the source media URLs + Telegram `file_id`s; repeat links re-send locally (no fetch/upload), TTL + prune; a permanent send failure *degrades* the entry instead of dropping it (the file ids go, the URLs stay, so the next request re-sends from those without a fetch), and a degraded entry that fails again is removed |
|
||||
| `crates/xmedia-bot/src/queue.rs` | `PersistentTaskQueue`: SQLite-backed queue (`tasks` table), `QUEUE_WORKERS = 4` concurrent workers (lease via `BEGIN IMMEDIATE` + `locked_until` TTL), retry→dead-letter, a `lease_token` fence: `lease_next` stamps a random token and every write-back (heartbeat, `delete`, `reschedule`, `mark_done`) is guarded by it, so a lease that expired and was re-leased cannot be written by its former holder — a lost lease stops the attempt instead; a finished row's `DELETE`/reschedule retried and a failed delete falling back to a `done` tombstone (the lease query and the sweep only look at `pending`/`in_progress`, so a task that already ran cannot be resurrected and re-run), `runnable_rows`/`replace_payload` (the startup repair's read/rewrite path: it runs before the workers exist, which is why it needs no lease token), `notify_one` worker wakeup plus a separate `Notify` for the 30 s lease-expiry sweep (a shared one let the sweep steal the workers' wakeup permit; the sweep does notify the workers after it actually recovered a row, since a recovered task is due immediately while every worker may be parked on `notify` with no pending row to sleep on), `busy_timeout` on all connections |
|
||||
| `crates/xmedia-bot/src/ctx.rs` | `AppContext`: the injected collaborators (`sender` + `ChatStore`/`PersistentTaskQueue`/`LinkCache`/`Config`), `from_statics` for production and the `CONTEXT` static the worker closures hold. `test_support::TestStores` backs handler tests with a tempdir store set, and the module also carries the fixtures those tests share — the canonical cached post (`cached_photo`), the edit-before-forward prompt (`seed_prompt` with its `PROMPT_ID`/`FORWARDED_ID`) and a scripted API error (`api_error`) — so no two test modules keep their own copies |
|
||||
| `crates/xmedia-bot/src/send/` | `send/mod.rs`: `Task`/`MediaItemPayload` payloads (`media: MediaRef`, i.e. `Source` URL-or-path vs `FileId` — one field used to carry both with a flag), `send_media_sequence`/`send_animation`/`forward_messages`; `send/error.rs`: the Bot API error policy (`SendError`/`Classification`, `classify_request_error`, the media-fetch/size markers); `send/input_media.rs`: payload → `InputFile`/`InputMedia` + `build_media_group` (caption on the first item only); `send/upload.rs`: the download-and-reupload fallback (`prepare_upload_item`/`send_batch_via_upload`, photo downscale handoff); `send/post_send.rs`: link-cache write, `KEEP_ALIVE` registry, `settle_task`, `post_send_actions`, `handle_task`/`dead_letter_notify` |
|
||||
| `crates/xmedia-bot/src/media_sender/{mod.rs,test_support.rs}` | `MediaSender` trait: the user-flow surface (`send_media_group`/`send_animation`/`copy_messages`/`send_message`/`answer_callback_query`/`edit_message_text`/`edit_message_caption`/`delete_message`/`send_chat_action`/`answer_inline_query`) implemented by teloxide `Bot` (per-chat rate-limited) and by a recording `MockSender` in tests. Admin/setup APIs (`get_chat`, `set_my_commands`, …) stay on the concrete `Bot`. `test_support.rs` (cfg(test)-only) holds the scripted `MockSender` and `fake_api` (the stand-in API the real-`Bot` tests drive) |
|
||||
| `crates/xmedia-bot/src/rate_limit.rs` | Two token buckets paced before sends reach the API so batch forwards don't trip flood control: one per chat (`CAPACITY = 20`, ~20 msg/min refill) and one bot-wide (`acquire_global`, 30/s — Telegram's per-bot ceiling, invisible to any per-chat bucket and only binding when a batch fans out over many chats). `prune_idle` drops the per-chat buckets that refilled while unheld |
|
||||
|
||||
## Development Commands
|
||||
|
||||
@@ -50,7 +56,7 @@ The `x-media` library: `site::fetch(url)` dispatches through the `SITES` registr
|
||||
export TELOXIDE_TOKEN=<token> # required; PIXIV_REFRESH_TOKEN optional (Pixiv disabled without it)
|
||||
cargo run -p xmedia-bot # run the bot (polling by default)
|
||||
cargo run -p x-media --example fetch -- <url> # test a link through the fetch library
|
||||
cargo test --workspace # full test suite (no CI test step exists — run locally)
|
||||
cargo test --workspace # full test suite (CI runs the same, with --locked)
|
||||
cargo build --release -p xmedia-bot # release build (Dockerfile does this)
|
||||
cargo clippy --workspace --all-targets # lint (Clippy is the configured IDE linter)
|
||||
cargo fmt --check # formatting
|
||||
@@ -60,29 +66,29 @@ Docker: `docker build -t tgxmb .` then `docker run --rm -d --name tgxmb --env-fi
|
||||
|
||||
## Code Conventions & Common Patterns
|
||||
|
||||
- **Errors via `thiserror` derive** (no anyhow): the public, stringified errors — `FetchError` (`Http`/`Json`/`Pixiv`/`Site`/`NotFound`/`Blocked`) and `PixivError` — derive `thiserror::Error` with `#[from]` conversions; `Display`/`source()` come from the derive. The internal control-flow enums — `QueueError` (`Retryable { delay_seconds, payload }` / `Permanent`), `SendError` (Retryable/Permanent), `Classification`, `FallbackError` — carry no `Display` and are handled by direct variant matching. New errors should follow the same split: stringified/public errors derive `thiserror`, internal flow enums stay plain.
|
||||
- **Errors via `thiserror` derive** (no anyhow): the public, stringified errors — `FetchError` (`Http`/`Json`/`Pixiv`/`Site`/`NotFound`/`Blocked`/`Disabled`/`Sensitive`/`TooLarge`/`MediaPrep`/`Transient`/`RateLimited`/`Io`) and `PixivError` — derive `thiserror::Error` with `#[from]` conversions; `Display`/`source()` come from the derive. The internal control-flow enums — `QueueError` (`Retryable { delay_seconds, payload }` / `Permanent`), `SendError` (Retryable/Permanent), `Classification`, `FallbackError` — carry no `Display` and are handled by direct variant matching. New errors should follow the same split: stringified/public errors derive `thiserror`, internal flow enums stay plain.
|
||||
- **Global state via `std::sync::LazyLock` statics**, not DI: `CONFIG`, `CHAT_STORE`, `TASK_QUEUE` in `handlers/statics.rs`; shared reqwest `CLIENT` in `x-media/src/site/mod.rs`. `Bot` is passed/cloned into handlers; queue workers share the process-wide `send::BOT` (`LazyLock<Bot>`, force-initialized in `main` so a missing token fails at startup).
|
||||
- **Async**: tokio multi-thread runtime (`#[tokio::main]` default). All rusqlite I/O inside `tokio::task::spawn_blocking`. Long loops use `tokio::select!` with `tokio::sync::{watch, Notify}` stop/wake channels. No streams.
|
||||
- **Blocking sync primitives**: `parking_lot::Mutex` for hot caches, `tokio::sync::Mutex` for async-shared state (pixiv token cache), `AtomicBool` for feature gates.
|
||||
- **Site adapter convention**: each site module exports `PATTERN: LazyLock<Regex>`, `enabled() -> bool`, `fetch_from_url(url) -> Result<Fetched, FetchError>`, plus `cache_key`/`is_retryable`/`media_headers`, and a unit struct `<Name>Site` implementing `site::Site`; the central dispatcher (`site/mod.rs`) only iterates the `SITES` registry. Adding a site = new `site/<name>/{mod.rs,interface.rs,model.rs}` + one `Box::new(...)` entry in `SITES` — the bot crate never lists sites (SetFormat whitelist, cache-key site lookup and startup validation all derive from the registry). Async trait methods return `SiteFuture` (a boxed `Pin<Box<dyn Future + Send>>`) because `async fn` in traits is not dyn-compatible.
|
||||
- **Site adapter convention**: each site module exports `PATTERN: LazyLock<Regex>`, `fetch_from_url(url) -> Result<Fetched, FetchError>` and `cache_key`, plus a unit struct `<Name>Site` implementing `site::Site`; `enabled`/`is_retryable`/`media_headers` come from the trait's defaults unless the site overrides them (only pixiv does); the central dispatcher (`site/mod.rs`) only iterates the `SITES` registry. Adding a site = new `site/<name>/{mod.rs,interface.rs,model.rs}` + one `Box::new(...)` entry in `SITES` — the bot crate never lists sites (SetFormat whitelist, cache-key site lookup and startup validation all derive from the registry). Async trait methods return `SiteFuture` (a boxed `Pin<Box<dyn Future + Send>>`) because `async fn` in traits is not dyn-compatible.
|
||||
- **Serde**: per-site `model.rs` are pure `Deserialize` DTOs mirroring API JSON; site structs in `interface.rs` have private fields, a `caption()` builder, and `impl From<SiteStruct> for Fetched`. Persisted payloads use internally-tagged enums (`#[serde(tag = "kind")]` / `type`).
|
||||
- **Naming**: module-per-concern, snake_case files, `CamelCase` types, `snake_case` fns. `//!` module docs and `///` docs on non-obvious logic (syndication token, ugoira encoding, `display_text_range`).
|
||||
- **Retries**: only `x-media::site::fetch` retries (3 attempts, `1 << attempt` backoff, HTTP errors only); `site::fetch_once` is the same code path with a single attempt, used by inline queries whose answer window is shorter than the backoff. Queue retries are explicit `QueueError::Retryable` with computed delay (`retry_delay_seconds`).
|
||||
- Logging via `log` macros (`pretty_env_logger`, level from `RUST_LOG`). Level convention: `info` = lifecycle + per-post business results (`sent`/`forwarded`/`copied`), admin/operator actions and anomalies (fallback, retry enqueue, dead-letter is `error`); `debug` = per-request detail (message/command/URL extraction, `fetching`/`fetched`, batch sends, queue processing, photo processing, inline queries). Full user-submitted URLs and message text only appear at `debug`; at `info` and above links are printed via the normalized cache key (`handlers::log_key`, e.g. `[key=twitter:123...]`) so logs stay short and do not echo user data.
|
||||
- **Retries**: only `x-media::site::fetch` retries (3 attempts, a doubling backoff widened by a random slice of itself so workers that failed together do not recover together, with a 429's `Retry-After` honored up to `MAX_RETRY_AFTER_SECS` = 60 s, over HTTP errors only); `site::fetch_once` is the same code path with a single attempt, used by inline queries whose answer window is shorter than the backoff. A status a site answers with is classified by what a *retry* can change: 404/410 are `NotFound` and 401/403 are `Blocked` (permanent, reported at once), 429/5xx are `Transient` and retried. Queue retries are explicit `QueueError::Retryable` with computed delay (`retry_delay_seconds`), scaled per attempt by `scaled_retry_delay` — which only ever scales **up**, so a delay the server asked for (Telegram `retry_after`) is never shortened. `send::classify_request_error` is the send-side counterpart: `RetryAfter` and `Network` are retryable, and so is a 5xx — teloxide sleeps 10 s on a server error and then parses the body, so by then the HTTP status is gone and the condition is recognised by shape instead (a JSON server-error description, or an `InvalidJson` whose raw body is not JSON, i.e. a proxy/error page).
|
||||
- Logging via `log` macros (`pretty_env_logger`, level from `RUST_LOG`). `main.rs` initializes the **timed** builder with a default filter of `info,hyper_util=warn,reqwest=warn` when `RUST_LOG` is unset: the plain `init` had no timestamps and fell back to `error`, so a deployment that forgot the variable logged nothing at all, and at `debug` the HTTP client's own lines outnumbered the bot's two to one. An explicit `RUST_LOG` overrides the default wholesale. Level convention: `info` = lifecycle + per-post business results (`sent`/`forwarded`/`copied`, with `chat=` and the total `ms`), admin/operator actions and anomalies (the upload fallback and other user-served degradations are `warn`; retry enqueue and dead-letter are `error`); `debug` = per-request detail (URL extraction, `fetching`/`fetched` with the fetch duration, batch sends, queue processing with the row's `chat=`/`key=` and per-attempt `ms`, photo processing, inline queries); `trace` = user data (the full URL, the message text, the inline query). At `debug` and above links are printed via the normalized cache key (`handlers::log_key`, e.g. `[key=twitter:123...]`), so a `debug` log can be shared without echoing what users pasted; user-supplied text that does reach a line (display names, callback data, channel handles) goes through `handlers::log_escape`, whose escapes keep a crafted value from splitting or forging a log entry, and degradations that leave the user served (a failed cache read/write, a failed chat action) are `warn`, not `error`. The only queue/sweep aggregate is the 300 s sweep's queue line, and it speaks only when the queue is non-empty.
|
||||
|
||||
## Important Files
|
||||
|
||||
| File | Why it matters |
|
||||
|---|---|
|
||||
| `crates/xmedia-bot/src/main.rs` | Startup sequence, webhook vs polling, graceful shutdown (SIGINT via teloxide ctrlc / SIGTERM via `stop_token` for docker, → sweep stop → admin msg → queue stop) |
|
||||
| `crates/xmedia-bot/src/handlers/` | `statics.rs` = `CHAT_STORE`/`TASK_QUEUE`/`CONFIG` singletons (open `$DATA_DIR/task_queue.db`, default `data/` **relative to CWD**, dir auto-created); `commands.rs` = command dispatch (incl. `/test <url>` send-only, `/debug <url>` parse-only, and the admin-only `/bot_dict` state dump); `urls.rs` = URL extraction + the per-URL pipeline (`url_media` takes a `PostSend` mode: chat settings vs `/test`'s suppressed actions); `inline.rs` = debounced inline queries; `callback.rs` = edit-before-forward buttons (dptree entry + testable `handle_callback` core) |
|
||||
| `crates/xmedia-bot/src/send/` | `mod.rs`: constants `MAX_MEDIA_GROUP = 9`; `classify_request_error`; the senders. `upload.rs`: download-and-reupload fallback triggered only by Telegram API errors (`is_media_fetch_failure` / `is_size_error`). `post_send.rs`: settlement (`settle_task`), cache write, post-send actions, queue handlers. `input_media.rs`: payload → `InputMedia` |
|
||||
| `crates/xmedia-bot/src/photo.rs` | Pure-Rust photo processing (no ffmpeg): `png` (image-png) decode/encode + `zune-jpeg` decode + `fast_image_resize` Lanczos3 downscale + `jpeg-encoder`. Photos over Telegram's limits (width + height > 10000 px → `PHOTO_INVALID_DIMENSIONS`; bytes > 10 MiB) are decoded, downscaled keeping the format, PNG bit depth > 24 (RGBA 32-bit / 16-bit per channel) reduced to 24-bit RGB with alpha flattened white (≤24-bit untouched, never upconverted), and transcoded to JPEG only if still over the cap; memory budget guarded, otherwise the item's smaller fallback URL |
|
||||
| `crates/x-media/src/site/mod.rs` | Dispatcher, `Fetched`/`FetchError`, shared `CLIENT`, `download_media` (adds `Referer: https://www.pixiv.net/` for `pximg.net` hotlink protection) |
|
||||
| `crates/xmedia-bot/src/handlers/` | `statics.rs` = `CHAT_STORE`/`TASK_QUEUE`/`CONFIG` singletons (open `$DATA_DIR/task_queue.db`, default `data/` **relative to CWD**, dir auto-created); `mod.rs` also holds `apply_caption_edit`, the one place a caption edit is applied and its failure classified: a short retryable delay is retried once, anything else is reported to the user instead of being swallowed (`callback.rs`'s template button answers its toast with the failure and leaves the record alone); `commands.rs` = command dispatch (incl. `/test <url>` send-only, `/debug <url>` parse-only, the read-only `/settings` every chat member can read — unlike the admin-only `/bot_dict` raw dump — and template removal; `/start`/`/help` carry the guidance teloxide's `descriptions()` cannot render, and `/set_format` rejects unknown `{…}` placeholders, resetting with `-`; `/set_template` enforces 50 templates per chat, 55 UTF-8-byte names, and 1024-character escaped bodies; `/settings` output is capped at 4000 characters); `urls.rs` = URL extraction + the per-URL pipeline (`url_media` takes a `PostSend` mode: chat settings vs `/test`'s suppressed actions); `inline.rs` = debounced inline queries (hotlink-protected and local media skipped); `callback.rs` = edit-before-forward buttons (dptree entry + testable `handle_callback` core, incl. `skip`) |
|
||||
| `crates/xmedia-bot/src/send/` | `mod.rs`: constants `MAX_MEDIA_GROUP = 10` and the senders; `error.rs`: `classify_request_error` (5xx/non-JSON bodies retry, see the Retries bullet) and the media-fetch markers that route a URL send into the reupload fallback — including `failed to get HTTP url content`, the description single-media URL sends answer with. `upload.rs`: download-and-reupload fallback triggered only by Telegram API errors (`is_media_fetch_failure` / `is_size_error`), the per-kind upload cap (`MAX_MEDIA_UPLOAD_BYTES` = 50 MB for video/animation/other, Telegram's multipart limit; `photo::MAX_UPLOAD_BYTES` stays the 10 MiB photo one) with a download's class from `classify_download_error` (transport/429/5xx retry; 4xx is permanent — the media itself is gone or refused — and a temp-file *write* failure retries, being resource exhaustion far more often than a broken temp dir). Item preparation is bounded **process-wide** (`PREP_SLOTS` in `upload.rs`: URL workers and queue workers can each be inside a batch, so a per-batch bound is not a memory bound), and the check that routes an oversized item to `fallback_url` is the download's own declared-Content-Length abort (`FetchError::TooLarge` → `MediaTooLarge`) — there is no separate size probe, which used to cost a second request per item. `post_send.rs`: settlement (`settle_task`), cache write, post-send actions (dead-letter text via `failure_text`: post key + cause, since the raw error alone does not say which link died), queue handlers. `input_media.rs`: payload → `InputMedia` |
|
||||
| `crates/xmedia-bot/src/photo.rs` | Pure-Rust photo processing (no ffmpeg): `png` (image-png) decode/encode + `zune-jpeg` decode + `fast_image_resize` Lanczos3 downscale + `jpeg-encoder`. Photos over Telegram's limits (width + height > 10000 px → `PHOTO_INVALID_DIMENSIONS`; bytes > 10 MiB) are decoded, downscaled keeping the format, PNG bit depth > 24 (RGBA 32-bit / 16-bit per channel) reduced to 24-bit RGB with alpha flattened white (≤24-bit untouched, never upconverted), and transcoded to JPEG only if still over the cap; memory budget guarded, otherwise the item's smaller fallback URL. Two budgets, not one: `MAX_PHOTO_DOWNLOAD_BYTES` (32 MiB) caps the *download* in the send fallback — the whole body is buffered, once per prep slot — while `MAX_DECODE_BYTES` (512 MiB) stays the pre-allocation guard that decides whether a decoded photo can be processed at all; over either one the item degrades to its smaller URL |
|
||||
| `crates/x-media/src/site/{mod,download}.rs` | `mod.rs`: dispatcher, `Fetched`/`FetchError`, `needs_media_headers` (the per-site rule, asked by the inline path to skip what Telegram cannot fetch). `download.rs`: the media-download stack — the metadata vs. media HTTP clients, the host-network guard (applied to the start URL and every redirect hop) and `download_media_limited`/`download_media_to_file` (which add the site's headers, e.g. `Referer: https://www.pixiv.net/` for `pximg.net`) |
|
||||
| `crates/x-media/src/site/pixiv/api.rs` | OAuth token exchange (hardcoded app client id/secret), access-token cache, ugoira zip→MP4 via ffmpeg in `spawn_blocking` |
|
||||
| `Dockerfile` | Multi-stage: cached dep layer via stub sources + `touch *.rs` mtime bump (cargo's freshness is mtime-based and `cargo clean -p` removes 0 files — the touch is what forces the real sources to rebuild while deps stay cached), static ffmpeg from ffmpeg.martin-riedl.de (`FFMPEG_URL` arg, optional `FFMPEG_SHA256` checksum, `unzip -t` integrity check), `debian:bookworm-slim` runtime, entrypoint. Runtime ships **no libssl/libcrypto/CA bundle** — rustls webpki-roots handles all TLS, and the static ffmpeg only processes local files (downloads go through reqwest) |
|
||||
| `docker-entrypoint.sh` | Privilege drop: `useradd` with `LOCAL_USER_ID` (default 9001) + `setpriv` (no gosu on bookworm-slim) |
|
||||
| `docker-compose.yml.example` | Deployment env reference (real `docker-compose.yml` is gitignored). Ships nginx-proxy + acme-companion: webhook mode needs TLS termination in front (teloxide's axum listener is HTTP-only; `WEBHOOK_CERT` only feeds `set_webhook`), bot exposes `VIRTUAL_HOST`/`VIRTUAL_PORT` on the shared `proxy` network, no host port; container names `nginx-proxy`/`acme-companion`/`tgxmb`, start order via `depends_on` (proxy → acme → bot) |
|
||||
|`docker-entrypoint.sh` | Privilege drop: `useradd` with `LOCAL_USER_ID` (default 9001) + `setpriv` (no gosu on bookworm-slim); rejects a non-numeric or `0` `LOCAL_USER_ID`, which would otherwise survive the drop and run the bot root |
|
||||
| `docker-compose.yml` | The deployment composition, committed as-is: every instance value (token, admins, site credentials, domain) is a `${VAR}` substitution read from the gitignored `.env` beside it, so the file needs no per-deployment edit — and a variable not listed in a service's `environment:` never reaches that container. Ships nginx-proxy + acme-companion: webhook mode needs TLS termination in front (teloxide's axum listener is HTTP-only; `WEBHOOK_CERT` only feeds `set_webhook`), bot exposes `VIRTUAL_HOST`/`VIRTUAL_PORT` on the shared `proxy` network, no host port; container names `nginx-proxy`/`acme-companion`/`tgxmb`, start order via `depends_on` (proxy → acme → bot) |
|
||||
| `.github/workflows/docker.yml` | CI: build+push to Docker Hub on tag `v*`/master, plus a build-only check on PRs touching the build inputs; **no test step**; verifies a release tag matches both crate versions; buildx gha cache (`cache-from` always, `cache-to` except on PRs, scope `tgxmb-build`, `mode=max`) so cargo deps + ffmpeg layers are restored across runs; `FFMPEG_URL`/`FFMPEG_SHA256` come from repo variables when set |
|
||||
| `README.md` | Feature docs + command table (Chinese) |
|
||||
|
||||
@@ -90,19 +96,19 @@ Docker: `docker build -t tgxmb .` then `docker run --rm -d --name tgxmb --env-fi
|
||||
|
||||
- **Rust, stable, edition 2024**, workspace resolver 3. No `rust-version`/MSRV pin, no `rust-toolchain.toml` — recent stable is assumed. No nightly features.
|
||||
- Package manager: **Cargo** (workspace with path dep `x-media` ← `xmedia-bot`). No `[workspace.package]`/shared deps — each crate lists deps independently.
|
||||
- **TLS is rustls end-to-end** (no native-tls/openssl in the tree, no libssl in the Docker runtime image): `teloxide` is declared `default-features = false` with `["webhooks-axum", "macros", "rustls", "ctrlc_handler"]` (the removed `default` also carried `native-tls` and `ctrlc_handler` — the latter must stay); x-media's reqwest is `default-features = false` with `["json", "rustls-tls"]` (webpki-roots baked in, so the image ships no CA bundle). One reqwest 0.12.28 in the lock.
|
||||
- **Versioning**: bump the version in all three places (`crates/x-media/Cargo.toml`, `crates/xmedia-bot/Cargo.toml`, `Cargo.lock`) and **keep `README.md`, `README.en.md` and `AGENTS.md` in sync with the code on every bump**, then commit (`chore: bump version to X.Y.Z`), create an annotated tag `vX.Y.Z`, and push branch + tag (the tag push triggers the Docker Hub build). The tag must equal both crate versions: `.github/workflows/docker.yml` verifies that before building, and `--locked` verifies the lock file.
|
||||
- Config is **environment-variable driven** (dotenv loads `.env`, gitignored; no `.env.example` exists). Key vars: `TELOXIDE_TOKEN` (required), `PIXIV_REFRESH_TOKEN`, `TWITTER_AUTH_TOKEN` (optional; x.com `auth_token` cookie — enables the logged-in GraphQL fallback that fetches NSFW tweets syndication withholds), `BOT_ADMIN` (comma-separated ids), `EDIT_MESSAGE_TTL_SECONDS` (default 86400), `LINK_CACHE_TTL_SECONDS` (default 604800), `DATA_DIR` (default `data`, CWD-relative; the SQLite dir, auto-created), `WEBHOOK`/`WEBHOOK_URL`/`WEBHOOK_LISTEN`/`WEBHOOK_PORT`/`WEBHOOK_CERT`/`WEBHOOK_SECRET_TOKEN` (webhook mode requires URL/listen/port, `.expect`ed; `WEBHOOK_CERT` is Telegram-facing self-signed validation only — TLS must be terminated by a reverse proxy), `RUST_LOG`, `TELOXIDE_PROXY`, `LOCAL_USER_ID` (entrypoint only).
|
||||
- SQLite via `rusqlite` with `bundled` feature (no system libsqlite needed). DB file `$DATA_DIR/task_queue.db` (default `data/task_queue.db`, CWD-relative — run from the workspace root, or `/app` in Docker; set `DATA_DIR` to pin state anywhere). Mount `./data` and `./cert` volumes.
|
||||
- `.gitattributes` enforces LF for `*.sh` (CRLF breaks shebangs in containers). `.gitignore`: `.env`, `data/`, `cert/`, `docker-compose.yml`, `/target`, `.idea/`.
|
||||
- **TLS is rustls end-to-end** (no native-tls/openssl in the tree, no libssl in the Docker runtime image): `teloxide` is declared `default-features = false` with `["webhooks-axum", "macros", "rustls", "ctrlc_handler"]` (the removed `default` also carried `native-tls` and `ctrlc_handler` — the latter must stay); x-media's reqwest is `default-features = false` with `["json", "rustls-tls", "gzip", "http2"]` (webpki-roots baked in, so the image ships no CA bundle; `gzip` because the site APIs answer their JSON compressed — twitter's syndication body is 4469 bytes identity vs 1066 gzipped — and `http2` because every site CDN here negotiates h2). One reqwest 0.12.28 in the lock.
|
||||
- **Versioning**: bump the version in all three places (`crates/x-media/Cargo.toml`, `crates/xmedia-bot/Cargo.toml`, `Cargo.lock`) and **keep `README.md`, `README.en.md` and `AGENTS.md` in sync with the code on every bump**, then commit (`chore: bump version to X.Y.Z`), create an annotated tag `vX.Y.Z`, and push branch + tag **in one push** (`git push origin master vX.Y.Z`; the tag push triggers the Docker Hub build). Pushing them separately with the branch first makes the master run of `docker.yml` build the same commit as the tag run — its duplicate check can only see the tags that already exist on the remote. The tag must equal both crate versions: `.github/workflows/docker.yml` verifies that before building, and `--locked` verifies the lock file.
|
||||
- Config is **environment-variable driven** (dotenv loads `.env`, which is gitignored; `.env.example` is the tracked template — `cp .env.example .env` — and is also the file `docker compose` substitutes `${VAR}` from, so every variable the compose passes must be documented there). Key vars: `TELOXIDE_TOKEN` (required), `PIXIV_REFRESH_TOKEN`, `TWITTER_AUTH_TOKEN` (optional; x.com `auth_token` cookie — enables the logged-in GraphQL fallback that fetches NSFW tweets syndication withholds), `BILIBILI_COOKIE` (optional; whole bilibili cookie string — bilibili dynamics fetch anonymously and add their own device cookies, this only rescues an egress IP that bilibili has hard-flagged with `-352`/412), `BOT_ADMIN` (comma-separated ids), `EDIT_MESSAGE_TTL_SECONDS` (default 86400), `LINK_CACHE_TTL_SECONDS` (default 604800), `CAPTION_QUOTE_TEXT_CHARS` (default 200; a post whose text — the `title` plus `content` joined, see `site::compose_text` — reaches this length gets that text wrapped in an expandable blockquote inside its caption, the URL and author line staying outside; `0` disables it. Applied at the send boundary in `send::quote_long_caption`, which locates the text as what follows the author link, so a `/set_format` that moves `{title}`/`{content}` elsewhere and pixiv's title-inside-a-link layout opt out; `copy_messages` forwards and queued retries inherit the wrap, while the edit-before-forward rewrite stays unquoted by design), `DATA_DIR` (default `data`, CWD-relative; the SQLite dir, auto-created), `WEBHOOK`/`WEBHOOK_URL`/`WEBHOOK_LISTEN`/`WEBHOOK_PORT`/`WEBHOOK_CERT`/`WEBHOOK_SECRET_TOKEN` (webhook mode requires URL/listen/port **and the secret token**, all `.expect`ed — a listener without a secret accepts unauthenticated updates; `WEBHOOK_CERT` is Telegram-facing self-signed validation only — TLS must be terminated by a reverse proxy), `RUST_LOG`, `TELOXIDE_PROXY`, `LOCAL_USER_ID` (entrypoint only).
|
||||
- SQLite via `rusqlite` with `bundled` feature (no system libsqlite needed). DB file `$DATA_DIR/task_queue.db` (default `data/task_queue.db`, CWD-relative — run from the workspace root, or `/app` in Docker; set `DATA_DIR` to pin state anywhere). Mount the `./data` volume (the shipped compose mounts only that); `./cert` matters solely for a self-signed `WEBHOOK_CERT` you wire in yourself — add both its mount and the env line to compose then, as the template's own comment says.
|
||||
- `.gitattributes` enforces LF for `*.sh` (CRLF breaks shebangs in containers). `.gitignore`: `.env`, `data/`, `cert/`, `nginx-*` (proxy state), `/target`, `.idea/` (the compose file is tracked; only `.env` carries the deployment's own values).
|
||||
- Docs are in Chinese (README, AGENTS.md); user-facing bot strings are in English. Keep that split when editing user-facing strings and docs.
|
||||
|
||||
## Testing & QA
|
||||
|
||||
- **~135 tests, all inline `#[cfg(test)] mod tests`** — no `tests/` integration directories. Framework: built-in Rust test + `#[tokio::test]` (dev-deps only in `x-media`: tokio macros/rt-multi-thread, dotenv).
|
||||
- No mocking framework anywhere (no mockito/wiremock/mockall). Conventions: pure-function units (regex parsing, serde round-trips, chunking, retry math) tested synchronously; async tests use real dependencies — file-backed SQLite via `tempfile` (`queue.rs::new_queue()` helper), live network fetches.
|
||||
- Live-network tests exist in `site/twitter/interface.rs` (5), `site/bsky/interface.rs` (2), `site/misskey/interface.rs` (1), `site/pixiv/api.rs` (1); `photo.rs` adds one `#[ignore = "heavy: …"]` test. `site/mod.rs` also has a **token-gated but not `#[ignore]`d** pixiv download test (`download_media_pixiv_original_with_referer`): it hits `i.pximg.net` whenever `PIXIV_REFRESH_TOKEN` is set, so a local `cargo test --workspace` is not fully offline and can flake on a pixiv CDN body timeout. Test gating convention (enforced by `.github/workflows/ci.yml`): pure unit tests always run; live-network tests carry `#[ignore = "live network: ..."]` (run via `cargo test --workspace -- --ignored live`); token-gated pixiv tests early-return when `PIXIV_REFRESH_TOKEN` is absent **or empty** (an unset GitHub secret arrives as `""` — `is_err()` alone would run them tokenless and fail). Run the full offline suite with `cargo test --workspace`.
|
||||
- **~180 tests, all inline `#[cfg(test)] mod tests`** — no `tests/` integration directories. Framework: built-in Rust test + `#[tokio::test]` (dev-deps only in `x-media`: tokio macros/rt-multi-thread, dotenv).
|
||||
- No mocking framework anywhere (no mockito/wiremock/mockall). Conventions: pure-function units (regex parsing, serde round-trips, chunking, retry math) tested synchronously; async tests use real dependencies — file-backed SQLite via `tempfile` (`queue.rs::new_queue()` helper), live network fetches. Tests that must go through a **real `Bot`** (its URL/multipart building, the per-chat limiter and the bot-wide budget) talk to a stand-in API instead (`media_sender::test_support::fake_api::FakeApi`, a `tokio` TCP listener that records every call and answers the smallest result each method needs — teloxide keys methods by payload type, so the recorded name is `SendMediaGroup`, not `sendMediaGroup`): a media group, the edit-before-forward prompt through the real callback path, and `handlers::handle_message` (the context-taking body of `message_handler`, split out for exactly this).
|
||||
- Live-network tests exist in `site/twitter/interface.rs` (5), `site/bsky/interface.rs` (1), `site/misskey/interface.rs` (1), `site/bilibili/interface.rs` (5), `site/pixiv/api.rs` (1) and `site/download.rs` (1: the pixiv download below); the bot crate adds one live test each in `handlers/repair.rs` and `handlers/urls.rs`; `photo.rs` adds one `#[ignore = "heavy: …"]` test. `site/download.rs`'s pixiv download test (`live_download_media_pixiv_original_with_referer`) is gated **both ways** — `#[ignore = "live network: …"]` *and* an early return without `PIXIV_REFRESH_TOKEN` — so a local `cargo test --workspace` stays fully offline and the pixiv CDN flake surfaces only in the live job. `disabled_site_is_reported_not_ignored` (same file) is gated the other way round: it asserts `fetch` answers `FetchError::Disabled { site: "pixiv" }` for a pixiv link and early-returns when `PIXIV_REFRESH_TOKEN` **is** set (the site is then enabled). Test gating convention (enforced by `.github/workflows/ci.yml`): pure unit tests always run; live-network tests carry `#[ignore = "live network: ..."]` (run via `cargo test --workspace -- --ignored live`); token-gated pixiv tests early-return when `PIXIV_REFRESH_TOKEN` is absent **or empty** (an unset GitHub secret arrives as `""` — `is_err()` alone would run them tokenless and fail), and the bilibili live tests early-return when the API answers risk control (`-352`, which bilibili applies per IP by request volume). Run the full offline suite with `cargo test --workspace`.
|
||||
- Fixtures are inline `serde_json::json!` builder fns (`fixture()`, `thread_json()`, `illust_json()`), not files. The shared `CLIENT` sets `pool_max_idle_per_host(0)` under `#[cfg(test)]` to avoid cross-runtime `DispatchGone`.
|
||||
- **CI** — `.github/workflows/ci.yml` (actions pinned to commit SHAs, `--locked` on every cargo invocation, `concurrency` cancels superseded runs, `RUST_BACKTRACE=1`) runs `cargo fmt --check` + `cargo clippy --workspace --all-targets --locked -- -D warnings` + `cargo test --workspace --locked` + a release-profile `cargo build --release --locked` + an `actions-rust-lang/audit` dependency-vulnerability gate (offline, no secrets, on every push/PR) and a `live` job (schedule/manual/tag only, `-p x-media` since every network/secret-gated test lives there, `continue-on-error`) for the `#[ignore]`d live + token tests. `.github/workflows/docker.yml` builds and pushes the image on master/tag and runs a **build-only check on pull requests touching the build inputs** (`Dockerfile`, entrypoint, manifests, `.dockerignore`); a release tag must match both crate versions or the build stops, and `FFMPEG_URL`/`FFMPEG_SHA256` are taken from repository variables when set (a release can pin an exact ffmpeg build). `.github/dependabot.yml` keeps crates, the pinned actions and the Docker base images current.
|
||||
- Untested and hard to test without a mock seam: `main.rs`, `config.rs`, `db.rs`, `handlers/statics.rs`, `media_sender.rs` (holds the `MockSender` itself); in `x-media`: `media.rs`, `lib.rs`, all `model.rs`. The `commands.rs` *executor* needs a real `Bot` (only its pure report builder is tested). Everything else — `handlers/{mod,callback,inline,urls}.rs`, `send/*`, `ctx.rs`, `state.rs`, `queue.rs`, `link_cache.rs`, `rate_limit.rs` — is driven through `TestStores`/`ctx::test_support` and the scripted `MockSender`.
|
||||
- **CI** — `.github/workflows/ci.yml` (actions pinned to commit SHAs, `--locked` on every cargo invocation, `concurrency` cancels superseded runs, `RUST_BACKTRACE=1`) runs (behind a `changes` gate job, so a push/PR whose entire diff is markdown skips it instead of burning four minutes on nothing) `cargo fmt --check` + `cargo clippy --workspace --all-targets --locked -- -D warnings` + `cargo test --workspace --locked` + a release-profile `cargo build --release --locked` + an `actions-rust-lang/audit` dependency-vulnerability gate (offline, no secrets, on every push/PR) and a `live` job (schedule/manual/tag only, `continue-on-error`) that runs the `#[ignore]`d `live` tests in **both** crates — `PIXIV_REFRESH_TOKEN`/`TWITTER_AUTH_TOKEN`/`BILIBILI_COOKIE` pass through as secrets, and a summary step lists every `SKIP` a test printed so a green live run cannot mean zero coverage. `.github/workflows/docker.yml` builds and pushes the image on master/tag and runs a **build-only check on pull requests touching the build inputs**; its `should-build` gate skips a branch push that is already tagged (`git tag --points-at` — the tag run builds it, so push both refs together) or that touched no build input at all, while a tag push always builds (`Dockerfile`, entrypoint, manifests, `.dockerignore`); a release tag must match both crate versions or the build stops, and `FFMPEG_URL`/`FFMPEG_SHA256` are taken from repository variables when set (a release can pin an exact ffmpeg build). `.github/dependabot.yml` keeps crates, the pinned actions and the Docker base images current.
|
||||
- Untested and hard to test without a mock seam: `handlers/statics.rs`; `config.rs` only partly (the webhook truth table, TTL fallback and blank-secret parsing are pinned, the rest of the env parsing is not); `db.rs` is covered for the migration chain but not for pool behaviour under contention; `main.rs` is covered where it was split out (`periodic_sweep`, `sweep_temp_dir`) but not for startup/shutdown or its `dptree` branch tree (the handlers themselves are, through the stand-in API); in `x-media`: `media.rs`, `lib.rs`, all `model.rs` (their serde shapes are exercised indirectly by the adapter fixtures that deserialize into them). Everything else — `handlers/{mod,callback,inline,urls}.rs`, `send/*`, `ctx.rs`, `state.rs`, `queue.rs`, `link_cache.rs`, `rate_limit.rs`, `commands.rs` (its executor, through scripted outcomes) — is driven through `TestStores`/`ctx::test_support` and the scripted `MockSender`.
|
||||
- No coverage tracking.
|
||||
|
||||
Generated
+217
-223
@@ -10,25 +10,13 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
version = "0.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"version_check",
|
||||
"zerocopy",
|
||||
"cpubits",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -73,12 +61,15 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.4.2"
|
||||
name = "async-compression"
|
||||
version = "0.4.43"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
|
||||
checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
"compression-codecs",
|
||||
"compression-core",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -171,11 +162,12 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"hybrid-array",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -199,12 +191,6 @@ version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.12.1"
|
||||
@@ -213,21 +199,11 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||
|
||||
[[package]]
|
||||
name = "bzip2"
|
||||
version = "0.5.2"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
|
||||
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
|
||||
dependencies = [
|
||||
"bzip2-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bzip2-sys"
|
||||
version = "0.1.13+1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"libbz2-rs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -261,7 +237,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"cpufeatures",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
@@ -279,28 +255,57 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "colored"
|
||||
version = "3.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.3.1"
|
||||
name = "compression-codecs"
|
||||
version = "0.4.38"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
|
||||
checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
|
||||
dependencies = [
|
||||
"compression-core",
|
||||
"flate2",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compression-core"
|
||||
version = "0.4.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
@@ -309,13 +314,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
@@ -326,21 +328,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
version = "3.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
|
||||
dependencies = [
|
||||
"crc-catalog",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc-catalog"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -351,19 +338,21 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
name = "ctutils"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -446,17 +435,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "1.0.0"
|
||||
@@ -480,13 +458,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
"ctutils",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -573,7 +553,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -632,6 +612,18 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
@@ -729,16 +721,6 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
@@ -752,20 +734,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
@@ -775,11 +743,30 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
"r-efi",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"fnv",
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"http",
|
||||
"indexmap 2.14.2",
|
||||
"slab",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
@@ -788,11 +775,11 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -800,14 +787,17 @@ name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.9.1"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
|
||||
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
|
||||
dependencies = [
|
||||
"hashbrown 0.14.5",
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -830,9 +820,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
@@ -894,6 +884,15 @@ version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.11.1"
|
||||
@@ -904,6 +903,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
@@ -1132,11 +1132,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1153,7 +1153,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1252,6 +1252,12 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libbz2-rs-sys"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
@@ -1260,9 +1266,9 @@ checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.30.1"
|
||||
version = "0.38.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
|
||||
checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
@@ -1309,24 +1315,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
|
||||
|
||||
[[package]]
|
||||
name = "lzma-rs"
|
||||
version = "0.3.0"
|
||||
name = "lzma-rust2"
|
||||
version = "0.16.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e"
|
||||
checksum = "ca93e534d1142d1d0dcca6d25fe302508a5dfb40b302802904577725ea0b695b"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"crc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lzma-sys"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1443,9 +1437,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pbkdf2"
|
||||
version = "0.12.2"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
|
||||
checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"hmac",
|
||||
@@ -1532,6 +1526,12 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppmd-rust"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
@@ -1644,7 +1644,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1656,12 +1656,6 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
@@ -1801,6 +1795,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
@@ -1857,10 +1852,20 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.32.1"
|
||||
name = "rsqlite-vfs"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
|
||||
checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
|
||||
dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.40.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"fallible-iterator",
|
||||
@@ -1868,6 +1873,7 @@ dependencies = [
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
"sqlite-wasm-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1886,7 +1892,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2067,12 +2073,23 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.7"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
@@ -2120,6 +2137,18 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlite-wasm-rs"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"js-sys",
|
||||
"rsqlite-vfs",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
@@ -2289,7 +2318,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2328,6 +2357,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"js-sys",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
@@ -2451,12 +2481,17 @@ version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
@@ -2502,6 +2537,12 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "typed-path"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
@@ -2568,12 +2609,6 @@ version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.1"
|
||||
@@ -2589,15 +2624,6 @@ version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.4+wasi-0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.128"
|
||||
@@ -2701,7 +2727,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2845,12 +2871,6 @@ version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -2859,13 +2879,13 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
|
||||
[[package]]
|
||||
name = "x-media"
|
||||
version = "1.6.0"
|
||||
version = "1.9.2"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dotenv",
|
||||
"html-escape",
|
||||
"log",
|
||||
"rand 0.8.8",
|
||||
"rand 0.10.2",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"serde",
|
||||
@@ -2879,7 +2899,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "xmedia-bot"
|
||||
version = "1.6.0"
|
||||
version = "1.9.2"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dotenv",
|
||||
@@ -2890,7 +2910,7 @@ dependencies = [
|
||||
"parking_lot",
|
||||
"png",
|
||||
"pretty_env_logger",
|
||||
"rand 0.8.8",
|
||||
"rand 0.10.2",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2902,15 +2922,6 @@ dependencies = [
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xz2"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2"
|
||||
dependencies = [
|
||||
"lzma-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.3"
|
||||
@@ -2980,20 +2991,6 @@ name = "zeroize"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
|
||||
dependencies = [
|
||||
"zeroize_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize_derive"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
@@ -3030,29 +3027,26 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "2.4.2"
|
||||
version = "8.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
|
||||
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"arbitrary",
|
||||
"bzip2",
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
"crossbeam-utils",
|
||||
"deflate64",
|
||||
"displaydoc",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"hmac",
|
||||
"indexmap 2.14.2",
|
||||
"lzma-rs",
|
||||
"lzma-rust2",
|
||||
"memchr",
|
||||
"pbkdf2",
|
||||
"ppmd-rust",
|
||||
"sha1",
|
||||
"thiserror",
|
||||
"time",
|
||||
"xz2",
|
||||
"typed-path",
|
||||
"zeroize",
|
||||
"zopfli",
|
||||
"zstd",
|
||||
|
||||
+28
-24
@@ -8,20 +8,36 @@ ARG APP_NAME=telegram-twitter-media-bot
|
||||
# encoding. Served from https://ffmpeg.martin-riedl.de (Cloudflare CDN,
|
||||
# built on Debian 12 — glibc-compatible with the bookworm-slim runtime).
|
||||
# johnvansickle.com throttles datacenter IPs and served garbage from GitHub
|
||||
# runners. `/redirect/latest/` floats to the newest release build; each build
|
||||
# also ships a .sha256. Swap `amd64` for `arm64` when building arm64 images.
|
||||
ARG FFMPEG_URL=https://ffmpeg.martin-riedl.de/redirect/latest/linux/amd64/release/ffmpeg.zip
|
||||
# Arm64 images need this URL swapped for the `linux/arm64` build (currently
|
||||
# hardcoded amd64; the workflow builds amd64 only — see docker.yml).
|
||||
# Optional sha256 of ffmpeg.zip (pinned releases only): set to verify the
|
||||
# download. The mirror publishes .sha256 sidecars next to pinned builds, e.g.
|
||||
# https://ffmpeg.martin-riedl.de/download/linux/amd64/<id>_9.0/ffmpeg.zip.sha256
|
||||
# (the /redirect/latest/ URL itself has no sidecar — pin the effective URL).
|
||||
ARG FFMPEG_SHA256=
|
||||
# runners.
|
||||
#
|
||||
# Pinned to one release build instead of `/redirect/latest/`: the floating
|
||||
# URL changes under every build and ships no sha256 sidecar, while this pair
|
||||
# (zip + the sha256 the mirror publishes beside it, `<url>.sha256`) is
|
||||
# verified on every run. Bump both together — the site lists the current
|
||||
# ids, e.g. https://ffmpeg.martin-riedl.de. Swap `amd64` for `arm64` when
|
||||
# building arm64 images (the workflow builds amd64 only — see docker.yml).
|
||||
ARG FFMPEG_URL=https://ffmpeg.martin-riedl.de/download/linux/amd64/1789931100_9.0.2/ffmpeg.zip
|
||||
# sha256 of that zip, checked unconditionally: an FFMPEG_URL override must
|
||||
# pair with the new zip's sha256 or the build fails here, so an unverifiable
|
||||
# binary never reaches the image.
|
||||
ARG FFMPEG_SHA256=fa8ecf4abbd290d98f7d188b8649cc6b391ae209a98452be955a15aab1909d7f
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# 1. Rust dependencies first: only the manifests plus stub sources, so the
|
||||
# 1. Static ffmpeg first: only the two ARGs above invalidate this layer, so a
|
||||
# manifest or source edit never re-downloads it. The zip contains a single
|
||||
# `ffmpeg` binary at the root. `unzip -t` verifies the archive before
|
||||
# extraction so a bad download fails loudly here instead of a cryptic
|
||||
# later error.
|
||||
RUN wget -q -O /tmp/ffmpeg.zip "$FFMPEG_URL" \
|
||||
&& echo "$FFMPEG_SHA256 /tmp/ffmpeg.zip" | sha256sum -c - \
|
||||
&& unzip -tq /tmp/ffmpeg.zip \
|
||||
&& unzip -q /tmp/ffmpeg.zip -d /usr/local/bin \
|
||||
&& chmod +x /usr/local/bin/ffmpeg \
|
||||
&& rm /tmp/ffmpeg.zip \
|
||||
&& /usr/local/bin/ffmpeg -version >/dev/null
|
||||
|
||||
# 2. Rust dependencies next: only the manifests plus stub sources, so the
|
||||
# expensive dependency fetch + compile lives in a layer invalidated only by
|
||||
# manifest/lock changes.
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
@@ -32,21 +48,9 @@ RUN mkdir -p crates/x-media/src crates/xmedia-bot/src \
|
||||
&& : > crates/x-media/src/lib.rs \
|
||||
&& cargo build --release --locked -p xmedia-bot
|
||||
|
||||
# 2. Static ffmpeg next (cached unless FFMPEG_URL changes), so source edits
|
||||
# never re-download it. The zip contains a single `ffmpeg` binary at the
|
||||
# root. `unzip -t` verifies the archive before extraction so a bad
|
||||
# download fails loudly here instead of a cryptic later error.
|
||||
RUN wget -q -O /tmp/ffmpeg.zip "$FFMPEG_URL" \
|
||||
&& if [ -n "$FFMPEG_SHA256" ]; then echo "$FFMPEG_SHA256 /tmp/ffmpeg.zip" | sha256sum -c -; fi \
|
||||
&& unzip -tq /tmp/ffmpeg.zip \
|
||||
&& unzip -q /tmp/ffmpeg.zip -d /usr/local/bin \
|
||||
&& chmod +x /usr/local/bin/ffmpeg \
|
||||
&& rm /tmp/ffmpeg.zip \
|
||||
&& /usr/local/bin/ffmpeg -version >/dev/null
|
||||
|
||||
# 3. Real sources last: only our crates recompile on source changes. Cargo's
|
||||
# freshness check is mtime-based; the COPY'd host files usually predate the
|
||||
# step-1 stub build, so cargo would consider the stub up to date and never
|
||||
# stub build, so cargo would consider the stub up to date and never
|
||||
# compile the real sources. `touch` makes every .rs newer than the stub
|
||||
# artifacts, forcing a rebuild of just the two crates while the compiled
|
||||
# dependency layer stays cached. (`cargo clean -p` does NOT work here — it
|
||||
|
||||
+35
-21
@@ -1,14 +1,18 @@
|
||||
# TelegramXMediaBot
|
||||
|
||||
A Telegram bot that turns post links from X / Twitter, Pixiv, Bluesky, and Misskey (misskey.io) into media messages (images, video, GIF) with the post's title, author, and tags.
|
||||
A Telegram bot that turns post links from X / Twitter, Pixiv, Bluesky, Misskey (misskey.io), and Bilibili dynamics into media messages (images, video, GIF) with the post's title, author, and tags.
|
||||
|
||||
## Features
|
||||
|
||||
- Sending a link in a private chat fetches and sends the images, videos and GIFs automatically; oversized media is split into batches
|
||||
- Text-only posts report "no media"; unsupported links are silently ignored
|
||||
- Inline queries (`@bot <link>`)
|
||||
- Bind a forward channel for automatic forwarding; edit the caption before forwarding and apply custom templates
|
||||
- Failed sends are retried automatically with persistence; the user is notified after retries are exhausted
|
||||
- Sending a link in a private chat fetches and sends the images, videos and GIFs automatically; oversized media is split into batches (10 items per group)
|
||||
- Text-only posts report "no media"; unsupported links are silently ignored. Fetch failures name the reason (post gone / content withheld / source risk control / site not enabled)
|
||||
- Long posts (text ≥ `CAPTION_QUOTE_TEXT_CHARS`, default 200) show **the text part** of their caption inside a collapsible blockquote, with the link and author line left outside it
|
||||
- Inline queries (`@bot <link>`) — except Pixiv images and locally transcoded animations, which Telegram cannot fetch (no Referer) and would show broken, so they are skipped (such a query answers empty rather than spinning or re-fetching); a supported link posted in a group gets a one-line hint to use the private chat or inline mode (channels stay silent)
|
||||
- `/start` explains the supported sites and how to use it; `/help` lists the commands plus argument syntax, the caption placeholders and the private-chat rule; the bot's profile description texts are set at startup
|
||||
- `/settings` shows this chat's configuration (forward channel, edit-before-forward, per-site caption formats, saved templates); templates are added with `/set_template` and removed with `/remove_template`
|
||||
- Bind a forward channel for automatic forwarding; edit the caption before forwarding and apply custom templates (the prompt carries Confirm / Skip buttons, states its expiry, and is marked expired in place once it lapses)
|
||||
- Failed sends are retried automatically with persistence; the notice names which link failed, how long the retry waits, or the final cause
|
||||
- The chat action stays on screen for the whole fetch, so long jobs (ugoira transcode, large uploads) do not look stalled
|
||||
- Pixiv ugoira animations are transcoded to MP4; Bluesky videos are remuxed (HLS stream → MP4)
|
||||
- Photos exceeding Telegram's size/dimension limits are compressed automatically (original format kept, JPEG fallback only when needed)
|
||||
- Link-result cache: after a successful send the Telegram file ids and caption fields are cached locally, so a repeated link is re-sent from local state — no source-site request, no media file stored (expiry controlled by `LINK_CACHE_TTL_SECONDS`, default 7 days)
|
||||
@@ -23,24 +27,29 @@ export PIXIV_REFRESH_TOKEN=<token>
|
||||
cargo run -p xmedia-bot
|
||||
```
|
||||
|
||||
Docker deployment (see `docker-compose.yml.example`):
|
||||
Docker deployment (`docker-compose.yml` in this repo is the orchestration; instance values live in the `.env` next to it, and compose substitutes every `${VAR}` from there):
|
||||
|
||||
```bash
|
||||
cp .env.example .env # fill in TELOXIDE_TOKEN and the rest; every line is commented
|
||||
docker build -t tgxmb .
|
||||
docker run --rm -d --name tgxmb --env-file .env -v ./data:/app/data tgxmb
|
||||
# or use the bundled orchestration (nginx-proxy + acme-companion):
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Environment variables: `TELOXIDE_TOKEN` (required), `PIXIV_REFRESH_TOKEN`, `BOT_ADMIN`, `EDIT_MESSAGE_TTL_SECONDS`, `LINK_CACHE_TTL_SECONDS`, `RUST_LOG`, `TELOXIDE_PROXY`, `WEBHOOK*`, `TWITTER_AUTH_TOKEN` (optional).
|
||||
Environment variables: `TELOXIDE_TOKEN` (required), `PIXIV_REFRESH_TOKEN`, `BOT_ADMIN`, `EDIT_MESSAGE_TTL_SECONDS`, `LINK_CACHE_TTL_SECONDS`, `RUST_LOG`, `TELOXIDE_PROXY`, `WEBHOOK*`, `TWITTER_AUTH_TOKEN` (optional), `BILIBILI_COOKIE` (optional).
|
||||
|
||||
NSFW tweets: the public syndication endpoint does not return sensitive content. Setting `TWITTER_AUTH_TOKEN` (the `auth_token` cookie value of a logged-in x.com session) lets the bot fetch NSFW media in the logged-in state only when it hits a withheld tweet; without it, the bot reports no media.
|
||||
NSFW tweets: the public syndication endpoint does not return sensitive content. Setting `TWITTER_AUTH_TOKEN` (the `auth_token` cookie value of a logged-in x.com session) lets the bot fetch NSFW media in the logged-in state only when it hits a withheld tweet; without it the bot answers that the post's media is withheld and needs `TWITTER_AUTH_TOKEN`.
|
||||
|
||||
Bilibili dynamics are fetched anonymously by default (no login; the bot fetches bilibili's anonymous `buvid3`/`buvid4` device cookies itself to raise the success rate). If the server's egress IP gets hard-flagged by bilibili (persistent `risk control (-352)` log lines or HTTP 412), set `BILIBILI_COOKIE` (the whole cookie string from a logged-in browser, e.g. `SESSDATA=…; bili_jct=…`) to restore access. Only a dynamic's images and animations are sent; an attached video degrades to its cover image.
|
||||
|
||||
### Webhook deployment (needs a reverse proxy)
|
||||
|
||||
`docker-compose.yml.example` ships an [nginx-proxy](https://github.com/nginx-proxy/nginx-proxy) + [acme-companion](https://github.com/nginx-proxy/acme-companion) reverse-proxy orchestration. Pick one deployment shape:
|
||||
`docker-compose.yml` ships an [nginx-proxy](https://github.com/nginx-proxy/nginx-proxy) + [acme-companion](https://github.com/nginx-proxy/acme-companion) reverse-proxy orchestration. The committed file needs **no editing**: domain, tokens and admins are instance values and live in the `.env` beside it (compose reads and substitutes `${VAR}` at startup). Pick one deployment shape:
|
||||
|
||||
**With a domain**
|
||||
1. Point a DNS A record at the server
|
||||
2. In compose set `VIRTUAL_HOST` and `WEBHOOK_URL` to the domain, and uncomment `ACME_HOST` (set it to the domain)
|
||||
2. In `.env` set `VIRTUAL_HOST` and `WEBHOOK_URL` to the domain; to have acme-companion issue the certificate, also uncomment the `ACME_HOST` line in `docker-compose.yml` and set `ACME_HOST` in `.env`
|
||||
3. acme-companion issues and renews certificates automatically — nothing manual
|
||||
|
||||
**IP only**
|
||||
@@ -68,7 +77,7 @@ Let's Encrypt can issue certificates for public IPs (available since 2026, valid
|
||||
--key-file /acme.sh/<SERVER_IP>.key \
|
||||
--reloadcmd "curl --unix-socket /var/run/docker.sock -X POST http://localhost/containers/nginx-proxy/kill?signal=HUP"
|
||||
```
|
||||
3. In compose set `VIRTUAL_HOST: '<SERVER_IP>'` and `WEBHOOK_URL: 'https://<SERVER_IP>/'`; no `WEBHOOK_CERT` needed. Renewal is handled by the acme.sh daemon (`--days 3` = renew every 3 days, buffer against the 7-day validity), and a successful renewal HUP-notifies nginx-proxy to load the new certificate.
|
||||
3. In `.env` set `VIRTUAL_HOST=<SERVER_IP>` and `WEBHOOK_URL=https://<SERVER_IP>/`; no `WEBHOOK_CERT` needed. Renewal is handled by the acme.sh daemon (`--days 3` = renew every 3 days, buffer against the 7-day validity), and a successful renewal HUP-notifies nginx-proxy to load the new certificate.
|
||||
|
||||
Limitations: certificate validity ~7 days; only http-01/tls-alpn-01 validation (port 80 must be publicly reachable); no DNS-01, private IPs or IP ranges; at most 5 certificates per 168 hours for the same IP set. It is recommended to trial-issue with `--server letsencrypt_test` first, then switch to the production server.
|
||||
|
||||
@@ -80,15 +89,18 @@ Telegram only accepts ports 443/80/88/8443.
|
||||
| Variable | Description |
|
||||
|---|---|
|
||||
| `TELOXIDE_TOKEN` | Bot token (required) |
|
||||
| `PIXIV_REFRESH_TOKEN` | Pixiv refresh token; Pixiv is disabled without it |
|
||||
| `PIXIV_REFRESH_TOKEN` | Pixiv refresh token; Pixiv is disabled without it (a pixiv link then gets an explicit "site not enabled" reply instead of silence) |
|
||||
| `TWITTER_AUTH_TOKEN` | Optional; the `auth_token` cookie of a logged-in x.com session, used only to fetch NSFW tweets' media |
|
||||
| `BILIBILI_COOKIE` | Optional bilibili cookie string (`SESSDATA=…; bili_jct=…`); only needed when the egress IP stays risk-controlled (device cookies are fetched automatically) |
|
||||
| `BOT_ADMIN` | Admin chat IDs, comma-separated; receives start/stop notifications |
|
||||
| `EDIT_MESSAGE_TTL_SECONDS` | Edit-before-forward record expiry in seconds, default 86400 |
|
||||
| `EDIT_MESSAGE_TTL_SECONDS` | Edit-before-forward record expiry in seconds, default 86400; once lapsed the prompt is rewritten in place to "expired — nothing was forwarded" (no extra message) |
|
||||
| `LINK_CACHE_TTL_SECONDS` | Link-result cache expiry in seconds, default 604800 (7 days) |
|
||||
| `CAPTION_QUOTE_TEXT_CHARS` | **The text part** of the caption (the joined `{title}` + `{content}`) is wrapped in a collapsible blockquote once it reaches this many characters, default 200; `0` disables |
|
||||
| `DATA_DIR` | Data directory (where the SQLite `task_queue.db` lives), default `data` (relative to the working directory, created automatically) |
|
||||
| `RUST_LOG` | Log level |
|
||||
| `TELOXIDE_PROXY` | HTTP proxy (e.g. `http://127.0.0.1:10808`); applies to both the Telegram Bot API and site fetches — required on restricted networks (e.g. behind the GFW) |
|
||||
| `RUST_LOG` | Log level, default `info,hyper_util=warn,reqwest=warn` (an unset variable no longer silences the log). Recipes: `info,xmedia_bot=debug,x_media=debug` (app detail, no dependency noise) / `debug,hyper_util=off` (everything) / `trace` (also prints full links and message text — **user data**) |
|
||||
| `TELOXIDE_PROXY` | HTTP proxy (e.g. `http://127.0.0.1:10808`); applies to both the Telegram Bot API and site fetches — required on restricted networks (e.g. behind the GFW). **Never leave it blank** (`TELOXIDE_PROXY=`) — teloxide panics on a value it cannot parse; omit the line when unused. `docker-compose.yml` deliberately does not pass it to the container (a `127.0.0.1` proxy there is the container itself): add the line and use `host.docker.internal:<port>` when a deployment needs one |
|
||||
| `LOCAL_USER_ID` | UID the container runs as, default 9001 |
|
||||
| `VIRTUAL_HOST` | Public domain or IP; nginx-proxy routes by this |
|
||||
| `VIRTUAL_HOST` | Public domain or IP; nginx-proxy routes by this (set it in `.env`, which compose reads) |
|
||||
| `VIRTUAL_PORT` | Port the bot listens on inside the container; nginx-proxy's forwarding target |
|
||||
| `ACME_HOST` | Domain deployment: when set to the domain, acme-companion issues/renews certificates automatically |
|
||||
| `DEFAULT_HOST` | nginx-proxy routes requests with unknown Host headers to this vhost (needed for IP access) |
|
||||
@@ -109,15 +121,17 @@ Telegram only accepts ports 443/80/88/8443.
|
||||
| `/help` | List all commands and usage (this command table) |
|
||||
| `/set_forward_channel <channel>` | Set the forward channel: `@channel` or channel ID; media messages are forwarded to it automatically afterwards |
|
||||
| `/remove_forward_channel` | Remove the forward channel |
|
||||
| `/edit_before_forward` | Toggle "edit before forward": when enabled, the bot posts a prompt after forwarding; replying to it edits the first forwarded message's caption (or taps a template button to apply one) |
|
||||
| `/set_template <name>` | Reply to a message containing `[]` to save it as a named template; `[]` is replaced by the original post link when forwarding (used with "edit before forward") |
|
||||
| `/set_format <site> <format>` | Customize the caption format for one site. Sites: `twitter` / `bsky` / `pixiv` / `misskey`. Placeholders: `{url}` `{author}` `{author_url}` `{title}` `{tags}` |
|
||||
| `/edit_before_forward` | Toggle "edit before forward": when enabled, the bot posts a prompt after forwarding; replying to it edits the first forwarded message's caption (or tapping a template button applies one), then `↩️ Confirm` forwards and `🛑 Skip` drops this forward; the prompt states its expiry and is marked expired in place when it lapses (nothing is forwarded) |
|
||||
| `/set_template <name>` | Reply to a message containing `[]` to save it as a named template; `[]` is replaced by the original post link when forwarding (used with "edit before forward"). Names are limited to 55 UTF-8 bytes, bodies to 1024 escaped characters, and 50 templates per chat |
|
||||
| `/remove_template <name>` | Remove a template (names are listed by `/settings`; the prompt's keyboard shows at most 60) |
|
||||
| `/settings` | Show this chat's configuration: forward channel, edit-before-forward, per-site caption formats, saved templates |
|
||||
| `/set_format <site> <format>` | Customize the caption format for one site. Sites: `twitter` / `bsky` / `pixiv` / `misskey` / `bilibili`. Placeholders: `{url}` `{author}` `{author_url}` `{title}` `{content}` `{tags}`; unknown placeholders are rejected with the list of valid ones, and `-` restores the site's built-in format (preview with `/debug <link>`) |
|
||||
| `/clear_cache [link]` | Clear the link cache (admin only); with a link only that entry, otherwise everything |
|
||||
| `/bot_dict` | Show the current chat state (debugging; admin only) |
|
||||
| `/test <link>` | Parse a link and send its media; no channel forward, no edit-before-forward prompt (send only) |
|
||||
| `/debug <link>` | Debug: parse a link and report the parse result only (site, title, author, tags, media list) — no media is sent |
|
||||
|
||||
Link processing works only in private chats; commands work in any chat.
|
||||
Link processing works only in private chats; commands work in any chat. A supported link posted in a group gets a one-line hint to use the private chat or inline mode; channels stay silent.
|
||||
|
||||
## Notes
|
||||
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
# TelegramXMediaBot
|
||||
|
||||
Telegram 机器人,将 X / Twitter、Pixiv、Bluesky、Misskey (misskey.io) 的帖子链接转换为媒体消息发送,附带帖子标题、作者与标签。
|
||||
Telegram 机器人,将 X / Twitter、Pixiv、Bluesky、Misskey (misskey.io)、Bilibili 动态的帖子链接转换为媒体消息发送,附带帖子标题、作者与标签。
|
||||
|
||||
## 功能
|
||||
|
||||
- 私聊发送链接后自动抓取并发送图片、视频与 GIF,超量图片自动分批
|
||||
- 纯文字帖提示无媒体;不支持的链接静默忽略
|
||||
- 支持内联查询(`@机器人 <链接>`)
|
||||
- 可绑定转发频道自动转发;支持转发前编辑 caption 与自定义模板
|
||||
- 发送失败自动重试并持久化,重试耗尽后通知用户
|
||||
- 私聊发送链接后自动抓取并发送图片、视频与 GIF,超量图片自动分批(每批 10 张)
|
||||
- 纯文字帖提示无媒体;不支持的链接静默忽略。抓取失败会按原因分别提示(帖子已删除 / 内容受限 / 源站风控 / 站点未启用)
|
||||
- 长帖(正文 ≥ `CAPTION_QUOTE_TEXT_CHARS`,默认 200)的**正文部分**用可折叠引用块展示,链接与作者行留在引用块外
|
||||
- 支持内联查询(`@机器人 <链接>`;Pixiv 图片与本地转码的动图不支持内联 —— Telegram 取图时无法携带 Referer,会显示破图,因此跳过;这类查询直接返回空结果,不会一直转圈或反复请求);在群聊里发链接会提示改用私聊或内联查询(频道内保持静默)
|
||||
- `/start` 说明支持的站点与用法,`/help` 列出命令、参数格式、caption 占位符与私聊限制;bot 资料页(description / short description)启动时一并设置
|
||||
- `/settings` 查看本聊天配置(转发频道、转发前编辑开关、各站点 caption 格式、模板列表);模板可用 `/set_template` 增、`/remove_template` 删
|
||||
- 可绑定转发频道自动转发;支持转发前编辑 caption 与自定义模板(提示消息带 Confirm / Skip 按钮并写明过期时间,过期后就地标记为已过期)
|
||||
- 发送失败自动重试并持久化,重试耗尽后通知用户;提示会写明是哪条链接、重试等待多久、或最终失败的原因
|
||||
- 抓取期间持续显示"正在输入 / 正在发送"状态,长任务(ugoira 转码、大图上传)不会看起来卡死
|
||||
- Pixiv ugoira 动图自动转码为 MP4;Bluesky 视频自动转码(HLS 流 → MP4)
|
||||
- 超过 Telegram 尺寸/大小限制的图片自动压缩(保持原格式,必要时转 JPEG)
|
||||
- 链接结果本地缓存:成功发送后缓存 Telegram file id 与 caption 等,再次收到相同链接直接本地重发,不再请求源站、不保存媒体文件(`LINK_CACHE_TTL_SECONDS` 控制过期,默认 7 天)
|
||||
@@ -23,24 +27,29 @@ export PIXIV_REFRESH_TOKEN=<token>
|
||||
cargo run -p xmedia-bot
|
||||
```
|
||||
|
||||
Docker 部署(参考 `docker-compose.yml.example`):
|
||||
Docker 部署(编排见仓库里的 `docker-compose.yml`,实例相关的值写在同目录的 `.env`,compose 会自动替换其中的 `${VAR}`):
|
||||
|
||||
```bash
|
||||
cp .env.example .env # 填 TELOXIDE_TOKEN 等,逐项都有注释
|
||||
docker build -t tgxmb .
|
||||
docker run --rm -d --name tgxmb --env-file .env -v ./data:/app/data tgxmb
|
||||
# 或者用仓库里的编排(含 nginx-proxy + acme-companion):
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
环境变量:`TELOXIDE_TOKEN`(必填)、`PIXIV_REFRESH_TOKEN`、`BOT_ADMIN`、`EDIT_MESSAGE_TTL_SECONDS`、`LINK_CACHE_TTL_SECONDS`、`RUST_LOG`、`TELOXIDE_PROXY`、`WEBHOOK*`、`TWITTER_AUTH_TOKEN`(可选)。
|
||||
环境变量:`TELOXIDE_TOKEN`(必填)、`PIXIV_REFRESH_TOKEN`、`BOT_ADMIN`、`EDIT_MESSAGE_TTL_SECONDS`、`LINK_CACHE_TTL_SECONDS`、`RUST_LOG`、`TELOXIDE_PROXY`、`WEBHOOK*`、`TWITTER_AUTH_TOKEN`(可选)、`BILIBILI_COOKIE`(可选)。
|
||||
|
||||
NSFW 推文:公开的 syndication 接口不返回敏感内容。设置 `TWITTER_AUTH_TOKEN`(登录 x.com 后浏览器 Cookie 里的 `auth_token` 值)后,bot 会仅在遇到 NSFW 推文时以登录态获取媒体;未设置则提示无媒体。
|
||||
NSFW 推文:公开的 syndication 接口不返回敏感内容。设置 `TWITTER_AUTH_TOKEN`(登录 x.com 后浏览器 Cookie 里的 `auth_token` 值)后,bot 会仅在遇到 NSFW 推文时以登录态获取媒体;未设置则回复该推文内容受限(需要配置 `TWITTER_AUTH_TOKEN`)。
|
||||
|
||||
Bilibili 动态默认匿名抓取(无需登录,bot 会自动从 B 站的匿名指纹接口取 `buvid3`/`buvid4` 设备 cookie 以提高成功率)。若服务器出口 IP 被 B 站重度风控(日志里的 `risk control (-352)` 或 HTTP 412,且持续出现),设置 `BILIBILI_COOKIE`(登录后浏览器里整条 Cookie 串,如 `SESSDATA=…; bili_jct=…`)可恢复访问。当前只发送动态里的图片与动图,动态内嵌视频发送其封面。
|
||||
|
||||
### Webhook 部署(需要反向代理)
|
||||
|
||||
`docker-compose.yml.example` 内置了 [nginx-proxy](https://github.com/nginx-proxy/nginx-proxy) + [acme-companion](https://github.com/nginx-proxy/acme-companion) 反向代理编排,按部署环境二选一:
|
||||
`docker-compose.yml` 内置了 [nginx-proxy](https://github.com/nginx-proxy/nginx-proxy) + [acme-companion](https://github.com/nginx-proxy/acme-companion) 反向代理编排,仓库里的这份文件**不需要改动**:域名、令牌、管理员等实例相关的值都写在同目录的 `.env` 里(compose 启动时自动读取并替换 `${VAR}`)。按部署环境二选一:
|
||||
|
||||
**有域名**
|
||||
1. DNS A 记录指向服务器
|
||||
2. compose 里设 `VIRTUAL_HOST`、`WEBHOOK_URL` 为域名,并取消注释 `ACME_HOST`(设为域名)
|
||||
2. `.env` 里设 `VIRTUAL_HOST`、`WEBHOOK_URL` 为域名;要由 acme-companion 自动签发证书时,再取消 `docker-compose.yml` 里 `ACME_HOST` 那行的注释,并在 `.env` 里把 `ACME_HOST` 设为域名
|
||||
3. acme-companion 自动签发与续期证书,无需手动处理
|
||||
|
||||
**只有 IP**
|
||||
@@ -68,7 +77,7 @@ Let's Encrypt 支持为公网 IP 签发证书(2026 年起可用,有效期约
|
||||
--key-file /acme.sh/<SERVER_IP>.key \
|
||||
--reloadcmd "curl --unix-socket /var/run/docker.sock -X POST http://localhost/containers/nginx-proxy/kill?signal=HUP"
|
||||
```
|
||||
3. compose 里设 `VIRTUAL_HOST: '<SERVER_IP>'`、`WEBHOOK_URL: 'https://<SERVER_IP>/'`,无需 `WEBHOOK_CERT`。续期由 acme.sh daemon 自动完成(`--days 3` = 每 3 天续一次,证书 7 天有效有缓冲),续期成功后自动 HUP 通知 nginx-proxy 加载新证书。
|
||||
3. `.env` 里设 `VIRTUAL_HOST=<SERVER_IP>`、`WEBHOOK_URL=https://<SERVER_IP>/`,无需 `WEBHOOK_CERT`。续期由 acme.sh daemon 自动完成(`--days 3` = 每 3 天续一次,证书 7 天有效有缓冲),续期成功后自动 HUP 通知 nginx-proxy 加载新证书。
|
||||
|
||||
限制:证书约 7 天有效;验证仅支持 http-01/tls-alpn-01(80 端口必须公网可达);不支持 DNS-01、私有 IP 与 IP 段;同一 IP 集合每 168 小时限签发 5 张。建议先用 `--server letsencrypt_test` 试签,成功后再切正式服务器。
|
||||
|
||||
@@ -80,15 +89,18 @@ Telegram 只接受 443/80/88/8443 端口。
|
||||
| 变量 | 说明 |
|
||||
|---|---|
|
||||
| `TELOXIDE_TOKEN` | Bot token(必填) |
|
||||
| `PIXIV_REFRESH_TOKEN` | Pixiv 刷新令牌;未设置则禁用 Pixiv |
|
||||
| `PIXIV_REFRESH_TOKEN` | Pixiv 刷新令牌;未设置则禁用 Pixiv(此时收到 pixiv 链接会明确回复「站点未启用」,不会静默忽略) |
|
||||
| `TWITTER_AUTH_TOKEN` | 可选;登录 x.com 后浏览器 Cookie 里的 `auth_token`,仅在遇到 NSFW 推文时以登录态获取媒体 |
|
||||
| `BILIBILI_COOKIE` | 可选的 B 站 Cookie 串(`SESSDATA=…; bili_jct=…`),仅在出口 IP 被持续风控时才需要(设备 cookie 由 bot 自动获取) |
|
||||
| `BOT_ADMIN` | 管理员聊天 ID,逗号分隔;接收启动/停止通知 |
|
||||
| `EDIT_MESSAGE_TTL_SECONDS` | 转发前编辑记录过期秒数,默认 86400 |
|
||||
| `EDIT_MESSAGE_TTL_SECONDS` | 转发前编辑记录过期秒数,默认 86400;过期后提示消息会被就地改写为「已过期,未转发」(不额外发消息打扰) |
|
||||
| `LINK_CACHE_TTL_SECONDS` | 链接结果缓存过期秒数,默认 604800(7 天) |
|
||||
| `CAPTION_QUOTE_TEXT_CHARS` | 正文(`{title}` + `{content}` 合计)达到该长度(字符)时,caption 的**正文部分**用可折叠引用块包裹,默认 200;`0` 关闭 |
|
||||
| `DATA_DIR` | 数据目录(SQLite 数据库 `task_queue.db` 所在目录),默认 `data`(相对工作目录,会自动创建) |
|
||||
| `RUST_LOG` | 日志级别 |
|
||||
| `TELOXIDE_PROXY` | HTTP 代理(如 `http://127.0.0.1:10808`);同时作用于 Telegram Bot API 与站点抓取请求,网络受限环境(如 GFW)必需 |
|
||||
| `RUST_LOG` | 日志级别,默认 `info,hyper_util=warn,reqwest=warn`(未设置也**不会**哑掉)。排障配方:`info,xmedia_bot=debug,x_media=debug`(应用细节,无依赖噪音)/ `debug,hyper_util=off`(全量)/ `trace`(额外打印完整链接与消息原文,**含用户数据**) |
|
||||
| `TELOXIDE_PROXY` | HTTP 代理(如 `http://127.0.0.1:10808`);同时作用于 Telegram Bot API 与站点抓取请求,网络受限环境(如 GFW)必需。**不要留空值**(`TELOXIDE_PROXY=`)——teloxide 对无法解析的值会直接 panic;不用代理就别写这一行。容器里要用代理时,`docker-compose.yml` 的 `environment` 里默认没有它(容器内的 `127.0.0.1` 是容器自己),需要时手动加上并把地址换成 `host.docker.internal:<port>` |
|
||||
| `LOCAL_USER_ID` | 容器内运行用户 UID,默认 9001 |
|
||||
| `VIRTUAL_HOST` | 对外域名或 IP,nginx-proxy 按此路由 |
|
||||
| `VIRTUAL_HOST` | 对外域名或 IP,nginx-proxy 按此路由(写在 `.env`,compose 读取) |
|
||||
| `VIRTUAL_PORT` | bot 容器内监听端口,nginx-proxy 的转发目标 |
|
||||
| `ACME_HOST` | 域名部署:设为域名时由 acme-companion 自动签发/续期证书 |
|
||||
| `DEFAULT_HOST` | nginx-proxy 将未知 Host 的请求路由到该 vhost(IP 访问时需要) |
|
||||
@@ -109,15 +121,17 @@ Telegram 只接受 443/80/88/8443 端口。
|
||||
| `/help` | 查看全部命令及用法(即本文档的命令表) |
|
||||
| `/set_forward_channel <频道>` | 设置转发频道,参数为 `@频道名` 或频道 ID;设置后发送的媒体消息会自动转发到该频道 |
|
||||
| `/remove_forward_channel` | 取消转发频道 |
|
||||
| `/edit_before_forward` | 开关「转发前编辑」:开启后,转发成功后 bot 会发一条提示消息,回复它可修改第一条转发消息的 caption(或点击模板按钮套用模板) |
|
||||
| `/set_template <名称>` | 回复一条含 `[]` 的消息,将其保存为命名模板;转发时 `[]` 会被替换为原帖链接(配合「转发前编辑」使用) |
|
||||
| `/set_format <站点> <格式>` | 自定义某站点的 caption 格式。站点:`twitter` / `bsky` / `pixiv` / `misskey`。占位符:`{url}` `{author}` `{author_url}` `{title}` `{tags}` |
|
||||
| `/edit_before_forward` | 开关「转发前编辑」:开启后,转发成功后 bot 会发一条提示消息,回复它可修改第一条转发消息的 caption(或点击模板按钮套用模板),再点 `↩️ Confirm` 才会真正转发,`🛑 Skip` 放弃本次转发;提示消息写明过期时间,过期后原地标记为已过期且不会转发 |
|
||||
| `/set_template <名称>` | 回复一条含 `[]` 的消息,将其保存为命名模板;转发时 `[]` 会被替换为原帖链接(配合「转发前编辑」使用)。模板名称最长 55 个 UTF-8 字节、正文最长 1024 个转义后字符,每聊天最多 50 个模板 |
|
||||
| `/remove_template <名称>` | 删除某个模板(名称见 `/settings`;提示消息的模板按钮最多显示 60 个) |
|
||||
| `/settings` | 查看本聊天配置:转发频道、转发前编辑开关、各站点 caption 格式、模板列表 |
|
||||
| `/set_format <站点> <格式>` | 自定义某站点的 caption 格式。站点:`twitter` / `bsky` / `pixiv` / `misskey` / `bilibili`。占位符:`{url}` `{author}` `{author_url}` `{title}` `{content}` `{tags}`;未识别的占位符会被拒绝并列出可用项,格式填 `-` 恢复站点默认格式(可用 `/debug <链接>` 预览效果) |
|
||||
| `/clear_cache [链接]` | 清空链接缓存(仅管理员);带链接只清该条,否则清空全部 |
|
||||
| `/bot_dict` | 查看当前聊天状态(调试用;仅管理员) |
|
||||
| `/test <链接>` | 解析链接并发送媒体;不转发到频道、不弹转发前编辑提示(仅发送) |
|
||||
| `/debug <链接>` | 调试:只解析链接并返回解析结果(站点、标题、作者、标签、媒体列表),不发送任何媒体 |
|
||||
|
||||
链接处理仅限私聊;命令在任意聊天可用。
|
||||
链接处理仅限私聊;命令在任意聊天可用。在群聊里发受支持的链接会回复一条提示(改用私聊或内联查询),频道内保持静默。
|
||||
|
||||
## 备注
|
||||
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
[package]
|
||||
name = "x-media"
|
||||
version = "1.6.0"
|
||||
version = "1.9.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "gzip", "http2"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
regex = "1.12"
|
||||
html-escape = "0.2"
|
||||
url = "2.5.2"
|
||||
bytes = "1"
|
||||
zip = "2"
|
||||
zip = "8"
|
||||
tempfile = "3"
|
||||
thiserror = "2"
|
||||
rand = "0.8"
|
||||
rand = "0.10"
|
||||
log = "0.4"
|
||||
tokio = { version = "1.40", features = ["time"] }
|
||||
tokio = { version = "1.40", features = ["time", "rt", "fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.40", features = ["macros", "rt-multi-thread"] }
|
||||
|
||||
@@ -1,2 +1,9 @@
|
||||
pub mod media;
|
||||
pub mod site;
|
||||
|
||||
/// Prefix every temp file and temp dir this project creates, so a startup
|
||||
/// sweep can recognise its own leftovers: a killed process leaves them behind
|
||||
/// (`TempDir`/`NamedTempFile` clean up on drop, and a killed process runs no
|
||||
/// destructors), and without a marker the only safe assumption about the OS
|
||||
/// temp directory is "not mine".
|
||||
pub const TEMP_FILE_PREFIX: &str = "tgxmb-";
|
||||
|
||||
@@ -37,18 +37,15 @@ impl Media {
|
||||
#[derive(Debug)]
|
||||
pub enum Media {
|
||||
Illustration {
|
||||
title: Option<String>,
|
||||
url: String,
|
||||
thumbnail_url: Option<String>,
|
||||
fallback_url: Option<String>,
|
||||
},
|
||||
Video {
|
||||
title: Option<String>,
|
||||
url: String,
|
||||
thumbnail_url: String,
|
||||
},
|
||||
Animated {
|
||||
title: Option<String>,
|
||||
url: String,
|
||||
thumbnail_url: String,
|
||||
},
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
mod interface;
|
||||
mod model;
|
||||
|
||||
pub use interface::{BilibiliSite, PATTERN, cache_key, fetch_from_url};
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Serde DTOs for the Bilibili dynamic detail endpoint
|
||||
//! (`/x/polymer/web-dynamic/v1/detail`), mirroring live responses
|
||||
//! (field paths verified 2026-09-17). Every field is optional so an API
|
||||
//! shape change degrades to "no media" instead of a parse failure.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Detail {
|
||||
/// Business code: `0` = OK, `-352`/`-412` = risk control, `500`/`4101147`
|
||||
/// = gone.
|
||||
pub(crate) code: i64,
|
||||
#[serde(default)]
|
||||
pub(crate) message: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) data: Option<Data>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Data {
|
||||
#[serde(default)]
|
||||
pub(crate) item: Option<Box<Item>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Item {
|
||||
/// The dynamic id, same numeric id as in the URL.
|
||||
#[serde(default)]
|
||||
pub(crate) id_str: String,
|
||||
#[serde(default)]
|
||||
pub(crate) modules: Option<Modules>,
|
||||
/// The quoted dynamic when this item is a forward. A forward shell often
|
||||
/// carries no media of its own — the original holds it.
|
||||
#[serde(default)]
|
||||
pub(crate) orig: Option<Box<Item>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Modules {
|
||||
#[serde(default)]
|
||||
pub(crate) module_author: Option<Author>,
|
||||
#[serde(default)]
|
||||
pub(crate) module_dynamic: Option<Dynamic>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Author {
|
||||
#[serde(default)]
|
||||
pub(crate) name: String,
|
||||
#[serde(default)]
|
||||
pub(crate) mid: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Dynamic {
|
||||
#[serde(default)]
|
||||
pub(crate) desc: Option<Desc>,
|
||||
#[serde(default)]
|
||||
pub(crate) major: Option<Major>,
|
||||
/// A single topic (`{"id":…,"name":…}`), the dynamic's only tag source.
|
||||
#[serde(default)]
|
||||
pub(crate) topic: Option<Topic>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Desc {
|
||||
#[serde(default)]
|
||||
pub(crate) text: String,
|
||||
}
|
||||
|
||||
/// `major` is a tagged union: `type` (`MAJOR_TYPE_DRAW` / `_OPUS` /
|
||||
/// `_ARCHIVE` / …) plus one payload object per type. Only the three payloads
|
||||
/// this adapter reads are modeled; an unknown major simply yields no media.
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Major {
|
||||
#[serde(default)]
|
||||
pub(crate) draw: Option<Draw>,
|
||||
#[serde(default)]
|
||||
pub(crate) opus: Option<Opus>,
|
||||
#[serde(default)]
|
||||
pub(crate) archive: Option<Archive>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Draw {
|
||||
#[serde(default)]
|
||||
pub(crate) items: Vec<Pic>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Pic {
|
||||
/// `major.draw` image URL.
|
||||
#[serde(default)]
|
||||
pub(crate) src: Option<String>,
|
||||
/// `major.opus.pics` image URL — the opus shape names the field
|
||||
/// differently while carrying the same image.
|
||||
#[serde(default)]
|
||||
pub(crate) url: Option<String>,
|
||||
}
|
||||
|
||||
impl Pic {
|
||||
/// The image URL, whichever key this serialization put it under.
|
||||
pub(crate) fn url(&self) -> Option<&str> {
|
||||
self.src.as_deref().or(self.url.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
/// `major.opus`: the serialization of an image/text post the web client asks
|
||||
/// for (`features=itemOpusStyle`). It carries the parts the legacy shape drops
|
||||
/// entirely — the document title and body of an opus post, whose
|
||||
/// `module_dynamic.desc` comes back `null`.
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Opus {
|
||||
/// Document headline; often absent.
|
||||
#[serde(default)]
|
||||
pub(crate) title: Option<String>,
|
||||
/// Document body (untruncated: a 307-char sample came back whole).
|
||||
#[serde(default)]
|
||||
pub(crate) summary: Option<Desc>,
|
||||
#[serde(default)]
|
||||
pub(crate) pics: Vec<Pic>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Archive {
|
||||
/// The attached video's cover — the only image an AV dynamic has (the
|
||||
/// video itself is deliberately not resolved, see the module docs).
|
||||
#[serde(default)]
|
||||
pub(crate) cover: Option<String>,
|
||||
/// The video's title. An AV dynamic has no body of its own (`desc` comes
|
||||
/// back `null`), so this card title is the post's content.
|
||||
#[serde(default)]
|
||||
pub(crate) title: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Topic {
|
||||
#[serde(default)]
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
/// Response of the anonymous fingerprint endpoint (`/x/frontend/finger/spi`),
|
||||
/// the source of the adapter's device cookies.
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct Fingerprint {
|
||||
#[serde(default)]
|
||||
pub(crate) data: Option<FingerprintData>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub(crate) struct FingerprintData {
|
||||
/// Sent as the `buvid3` cookie.
|
||||
#[serde(default, rename = "b_3")]
|
||||
pub(crate) buvid3: String,
|
||||
/// Sent as the `buvid4` cookie.
|
||||
#[serde(default, rename = "b_4")]
|
||||
pub(crate) buvid4: String,
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::model;
|
||||
use crate::media::Media;
|
||||
use crate::site::{FetchError, Fetched, Site, SiteFuture};
|
||||
use html_escape::{encode_double_quoted_attribute, encode_text};
|
||||
use html_escape::encode_text;
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
@@ -30,10 +30,6 @@ pub static PATTERN: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r"^(?:https?://)?bsky\.app/profile/([\w.\-:]+)/post/([\w.\-~]+)").unwrap()
|
||||
});
|
||||
|
||||
pub fn enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub async fn fetch_from_url(url: &str) -> Result<Fetched, FetchError> {
|
||||
let caps = PATTERN.captures(url).ok_or(FetchError::NotFound)?;
|
||||
let handle = caps
|
||||
@@ -51,6 +47,17 @@ pub async fn fetch_from_url(url: &str) -> Result<Fetched, FetchError> {
|
||||
// encode path — the temp file stays alive via `_keep_alive`). On any
|
||||
// failure the video item is dropped and the post degrades to its text.
|
||||
let mut media = Vec::with_capacity(fetched.media.len());
|
||||
// The remux warnings below name the post, not the CDN URL they were
|
||||
// working on: the media URL is derived from what the user pasted, and
|
||||
// `warn` is a level operators share.
|
||||
let key = cache_key(url).unwrap_or_else(|| "?".into());
|
||||
// A failed remux is remembered: if it leaves the post with no media at
|
||||
// all, returning `Ok` would read as "this post has no media". It is
|
||||
// reported as `FetchError::MediaPrep` rather than a transient failure —
|
||||
// the download legs already got their own retry in place ([`fetch_hls`]),
|
||||
// and the fetch loop's retry would only download every segment again to
|
||||
// fail the same way.
|
||||
let mut remux_failure: Option<String> = None;
|
||||
for item in fetched.media {
|
||||
let is_hls = matches!(&item, Media::Video { url, .. }
|
||||
if url.contains("playlist") || url.ends_with(".m3u8"));
|
||||
@@ -66,16 +73,28 @@ pub async fn fetch_from_url(url: &str) -> Result<Fetched, FetchError> {
|
||||
_ => String::new(),
|
||||
};
|
||||
media.push(Media::Video {
|
||||
title: None,
|
||||
url: mp4_path.to_string_lossy().into_owned(),
|
||||
thumbnail_url,
|
||||
});
|
||||
fetched._keep_alive = Some(keep_alive);
|
||||
fetched._keep_alive = Some(std::sync::Arc::new(keep_alive));
|
||||
}
|
||||
// No ffmpeg: a deployment gap, not a bad moment — retrying it
|
||||
// would only waste the fetch budget, so the post degrades (and an
|
||||
// all-video post reports the media type as unsupported).
|
||||
Ok(None) => log::warn!("bsky video remux unavailable for [key={key}]"),
|
||||
Err(e) => {
|
||||
log::warn!("bsky video remux failed for [key={key}]: {e}");
|
||||
remux_failure = Some(e);
|
||||
}
|
||||
Ok(None) => log::warn!("bsky video remux unavailable for {url}"),
|
||||
Err(e) => log::warn!("bsky video remux failed for {url}: {e}"),
|
||||
}
|
||||
}
|
||||
if media.is_empty()
|
||||
&& let Some(reason) = remux_failure
|
||||
{
|
||||
return Err(FetchError::MediaPrep(format!(
|
||||
"bsky video remux failed: {reason}"
|
||||
)));
|
||||
}
|
||||
fetched.media = media;
|
||||
Ok(fetched)
|
||||
}
|
||||
@@ -88,15 +107,47 @@ pub fn cache_key(url: &str) -> Option<String> {
|
||||
.map(|caps| format!("bsky:{}/{}", &caps[1], &caps[2]))
|
||||
}
|
||||
|
||||
/// Bluesky's fetch-retry policy: transient classes only. Not-found, blocked
|
||||
/// and parse failures are permanent.
|
||||
pub fn is_retryable(err: &FetchError) -> bool {
|
||||
matches!(err, FetchError::Http(_) | FetchError::Transient(_))
|
||||
/// Segments fetched (and written) at once while remuxing an HLS video. Small
|
||||
/// on purpose: a segment can be up to 20 MiB and the whole playlist is capped
|
||||
/// at 256 MiB, so this is also what bounds the remux's peak memory.
|
||||
const SEGMENT_CONCURRENCY: usize = 4;
|
||||
|
||||
/// The ffmpeg concat list for the downloaded segments, **in segment order**.
|
||||
/// The downloads complete in completion order (`JoinSet`), and ffmpeg would
|
||||
/// happily concatenate them in whatever order the list holds: an out-of-order
|
||||
/// list produces a silently scrambled video, not an error.
|
||||
fn concat_list(files: &mut [(usize, std::path::PathBuf)]) -> String {
|
||||
files.sort_by_key(|(i, _)| *i);
|
||||
files
|
||||
.iter()
|
||||
.map(|(_, path)| format!("file '{}'\n", path.to_string_lossy()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// bsky media (cdn.bsky.app) needs no extra headers.
|
||||
pub fn media_headers(_url: &str) -> Option<Vec<(&'static str, String)>> {
|
||||
None
|
||||
/// One HLS fetch (a playlist or a segment) with an in-place retry for a
|
||||
/// retryable class (transport, 429/5xx). These used to get their retry from the
|
||||
/// outer fetch loop, which pays for it by replaying the whole post: master
|
||||
/// playlist, variant playlist and every segment again. A segment failing near
|
||||
/// the end of a 500-segment video meant downloading the entire thing twice
|
||||
/// more, so the second attempt belongs on the request that actually failed.
|
||||
async fn fetch_hls(url: &str, cap: u64) -> Result<bytes::Bytes, String> {
|
||||
match crate::site::download_media_limited(url, cap, crate::site::DOWNLOAD_TOTAL_TIMEOUT).await {
|
||||
Err(FetchError::RateLimited {
|
||||
retry_after_secs, ..
|
||||
}) => {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(retry_after_secs)).await;
|
||||
crate::site::download_media_limited(url, cap, crate::site::DOWNLOAD_TOTAL_TIMEOUT)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
Err(FetchError::Http(_) | FetchError::Transient(_)) => {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
crate::site::download_media_limited(url, cap, crate::site::DOWNLOAD_TOTAL_TIMEOUT)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
other => other.map_err(|e| e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads an HLS playlist (master or media) and remuxes its segments to a
|
||||
@@ -110,11 +161,10 @@ pub fn media_headers(_url: &str) -> Option<Vec<(&'static str, String)>> {
|
||||
async fn resolve_bsky_video(
|
||||
playlist_url: &str,
|
||||
) -> Result<Option<(std::path::PathBuf, tempfile::TempDir)>, String> {
|
||||
if !crate::site::ffmpeg_available() {
|
||||
crate::site::log_once_ffmpeg_missing();
|
||||
if crate::site::ffmpeg_missing() {
|
||||
return Ok(None);
|
||||
}
|
||||
let master = crate::site::download_media_limited(playlist_url, 1_048_576)
|
||||
let master = fetch_hls(playlist_url, 1_048_576)
|
||||
.await
|
||||
.map_err(|e| format!("bsky video master playlist: {e}"))?;
|
||||
let master = String::from_utf8_lossy(&master);
|
||||
@@ -149,7 +199,7 @@ async fn resolve_bsky_video(
|
||||
playlist_url.to_string()
|
||||
};
|
||||
|
||||
let variant = crate::site::download_media_limited(&playlist_url, 1_048_576)
|
||||
let variant = fetch_hls(&playlist_url, 1_048_576)
|
||||
.await
|
||||
.map_err(|e| format!("bsky video media playlist: {e}"))?;
|
||||
let variant = String::from_utf8_lossy(&variant);
|
||||
@@ -169,30 +219,59 @@ async fn resolve_bsky_video(
|
||||
return Err("bsky video has too many segments".to_string());
|
||||
}
|
||||
|
||||
let frames_dir = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||
let out_dir = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||
let frames_dir = tempfile::Builder::new()
|
||||
.prefix(crate::TEMP_FILE_PREFIX)
|
||||
.tempdir()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let out_dir = tempfile::Builder::new()
|
||||
.prefix(crate::TEMP_FILE_PREFIX)
|
||||
.tempdir()
|
||||
.map_err(|e| e.to_string())?;
|
||||
// Segments are fetched concurrently under a small bound, and written with
|
||||
// `tokio::fs` (a multi-megabyte `std::fs::write` blocks the executor
|
||||
// thread). Serially, a several-hundred-segment video made the user wait
|
||||
// for every round trip in turn — the dominant cost of a remux.
|
||||
let mut total: u64 = 0;
|
||||
let mut list = String::new();
|
||||
for (i, seg) in segments.iter().enumerate() {
|
||||
let bytes = crate::site::download_media_limited(seg, 20 * 1024 * 1024)
|
||||
.await
|
||||
.map_err(|e| format!("bsky segment {i}: {e}"))?;
|
||||
total += bytes.len() as u64;
|
||||
let mut written: Vec<(usize, std::path::PathBuf)> = Vec::with_capacity(segments.len());
|
||||
let mut next = 0;
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
loop {
|
||||
while set.len() < SEGMENT_CONCURRENCY && next < segments.len() {
|
||||
let i = next;
|
||||
next += 1;
|
||||
let seg = segments[i].clone();
|
||||
let path = frames_dir.path().join(format!("seg_{i:04}.ts"));
|
||||
set.spawn(async move {
|
||||
let bytes = fetch_hls(&seg, 20 * 1024 * 1024)
|
||||
.await
|
||||
.map_err(|e| format!("bsky segment {i}: {e}"))?;
|
||||
tokio::fs::write(&path, &bytes)
|
||||
.await
|
||||
.map_err(|e| format!("bsky segment {i}: {e}"))?;
|
||||
Ok::<_, String>((i, bytes.len() as u64, path))
|
||||
});
|
||||
}
|
||||
let Some(joined) = set.join_next().await else {
|
||||
break;
|
||||
};
|
||||
let (i, len, path) = joined.map_err(|e| format!("bsky segment task panicked: {e}"))??;
|
||||
total += len;
|
||||
if total > 256 * 1024 * 1024 {
|
||||
return Err("bsky video exceeds total size cap".to_string());
|
||||
}
|
||||
let path = frames_dir.path().join(format!("seg_{i:04}.ts"));
|
||||
std::fs::write(&path, &bytes).map_err(|e| e.to_string())?;
|
||||
list.push_str(&format!("file '{}'\n", path.to_string_lossy()));
|
||||
written.push((i, path));
|
||||
}
|
||||
let list = concat_list(&mut written);
|
||||
let list_path = frames_dir.path().join("list.txt");
|
||||
std::fs::write(&list_path, &list).map_err(|e| e.to_string())?;
|
||||
tokio::fs::write(&list_path, &list)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let output = out_dir.path().join("video.mp4");
|
||||
let list_str = list_path.to_string_lossy().into_owned();
|
||||
let output_str = output.to_string_lossy().into_owned();
|
||||
let status = tokio::task::spawn_blocking(move || {
|
||||
std::process::Command::new("ffmpeg")
|
||||
let mut child = std::process::Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-f",
|
||||
@@ -209,15 +288,30 @@ async fn resolve_bsky_video(
|
||||
])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.spawn()
|
||||
.map_err(|e| format!("ffmpeg spawn failed: {e}"))?;
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
|
||||
loop {
|
||||
match child
|
||||
.try_wait()
|
||||
.map_err(|e| format!("ffmpeg wait failed: {e}"))?
|
||||
{
|
||||
Some(status) => break Ok(status),
|
||||
None if std::time::Instant::now() >= deadline => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break Err("ffmpeg exceeded 300s".to_string());
|
||||
}
|
||||
None => std::thread::sleep(std::time::Duration::from_millis(50)),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("bsky remux worker panicked: {e}"))?;
|
||||
match status {
|
||||
Ok(s) if s.success() => Ok(Some((output, out_dir))),
|
||||
Ok(s) => Err(format!("ffmpeg exited with {s}")),
|
||||
Err(e) => Err(format!("ffmpeg spawn failed: {e}")),
|
||||
.map_err(|e| format!("bsky remux worker panicked: {e}"))??;
|
||||
if !status.success() {
|
||||
return Err(format!("ffmpeg exited with {status}"));
|
||||
}
|
||||
Ok(Some((output, out_dir)))
|
||||
}
|
||||
|
||||
/// Fetches a post thread by handle or DID (`at://` URIs work for both).
|
||||
@@ -233,12 +327,9 @@ pub async fn fetch(handle: &str, rkey: &str) -> Result<Post, FetchError> {
|
||||
// 404/410 = gone (permanent); 429/5xx = transient and retried by fetch.
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return match status.as_u16() {
|
||||
404 | 410 => Err(FetchError::NotFound),
|
||||
_ => Err(FetchError::Transient(format!("bsky status {status}"))),
|
||||
};
|
||||
return Err(crate::site::status_error("bsky", &response));
|
||||
}
|
||||
let text = response.text().await?;
|
||||
let text = crate::site::response_text(response, "bsky").await?;
|
||||
Post::from_json(&text, rkey.to_string())
|
||||
}
|
||||
|
||||
@@ -262,13 +353,7 @@ impl Post {
|
||||
}
|
||||
|
||||
pub fn caption(&self) -> String {
|
||||
format!(
|
||||
"{url}\n<a href=\"{author_url}\">{author}</a>: {text}",
|
||||
url = encode_double_quoted_attribute(&self.url()),
|
||||
author_url = encode_double_quoted_attribute(&self.author_url()),
|
||||
author = encode_text(&self.author),
|
||||
text = encode_text(&self.text),
|
||||
)
|
||||
crate::site::caption(&self.url(), &self.author_url(), &self.author, &self.text)
|
||||
}
|
||||
|
||||
pub fn from_json(raw_json: &str, id: String) -> Result<Self, FetchError> {
|
||||
@@ -284,7 +369,6 @@ impl Post {
|
||||
match embed {
|
||||
model::Media::Images { images } => {
|
||||
media.extend(images.into_iter().map(|image| Media::Illustration {
|
||||
title: None,
|
||||
url: image.fullsize,
|
||||
thumbnail_url: Some(image.thumb),
|
||||
fallback_url: None,
|
||||
@@ -295,7 +379,6 @@ impl Post {
|
||||
thumbnail,
|
||||
} => {
|
||||
media.push(Media::Video {
|
||||
title: None,
|
||||
url: playlist,
|
||||
thumbnail_url: thumbnail,
|
||||
});
|
||||
@@ -327,16 +410,18 @@ impl From<Post> for Fetched {
|
||||
let url = post.url();
|
||||
let author_url = post.author_url();
|
||||
let render_data = Some(crate::site::RenderData {
|
||||
url: url.clone(),
|
||||
author: encode_text(&post.author).into_owned(),
|
||||
author_url: author_url.clone(),
|
||||
title: encode_text(&post.text).into_owned(),
|
||||
// A post has no title: its text is all content.
|
||||
title: String::new(),
|
||||
content: encode_text(&post.text).into_owned(),
|
||||
tags: String::new(),
|
||||
});
|
||||
Fetched {
|
||||
source_url: url,
|
||||
caption: post.caption(),
|
||||
title: post.text.clone(),
|
||||
title: String::new(),
|
||||
content: post.text.clone(),
|
||||
media: post.media,
|
||||
sensitive: post.sensitive,
|
||||
site_id: "bsky",
|
||||
@@ -357,6 +442,22 @@ mod tests {
|
||||
serde_json::json!({ "thread": post_json })
|
||||
}
|
||||
|
||||
/// The downloads finish in completion order; ffmpeg concatenates whatever
|
||||
/// order `list.txt` holds, so an unsorted list is a scrambled video rather
|
||||
/// than an error.
|
||||
#[test]
|
||||
fn concat_list_is_in_segment_order() {
|
||||
let mut files = vec![
|
||||
(2, std::path::PathBuf::from("/t/seg_0002.ts")),
|
||||
(0, std::path::PathBuf::from("/t/seg_0000.ts")),
|
||||
(1, std::path::PathBuf::from("/t/seg_0001.ts")),
|
||||
];
|
||||
assert_eq!(
|
||||
concat_list(&mut files),
|
||||
"file '/t/seg_0000.ts'\nfile '/t/seg_0001.ts'\nfile '/t/seg_0002.ts'\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_matches_handle_and_did() {
|
||||
let cases = [
|
||||
@@ -389,6 +490,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A remux failure is a `MediaPrep`, which the fetch loop does not retry:
|
||||
/// replaying the post means downloading every HLS segment again, when the
|
||||
/// request that failed already got its second attempt in place
|
||||
/// ([`fetch_hls`]). The classes below are the ones still retried there.
|
||||
#[test]
|
||||
fn media_prep_failure_is_not_retried() {
|
||||
use crate::site::Site as _;
|
||||
assert!(!BskySite.is_retryable(&FetchError::MediaPrep(
|
||||
"bsky video remux failed: segment 400: 503".into()
|
||||
)));
|
||||
assert!(BskySite.is_retryable(&FetchError::Transient("429".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_json_images_with_missing_defaults() {
|
||||
let raw = thread_json(serde_json::json!({
|
||||
@@ -410,7 +524,8 @@ mod tests {
|
||||
fetched.source_url,
|
||||
"https://bsky.app/profile/user.bsky.social/post/3xxxx"
|
||||
);
|
||||
assert_eq!(fetched.title, "hello <world>");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "hello <world>");
|
||||
assert_eq!(fetched.media.len(), 1);
|
||||
assert!(!fetched.sensitive);
|
||||
// display_name absent -> empty fallback
|
||||
@@ -456,31 +571,18 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// The one live bsky check: a labelled post with photos — source URL,
|
||||
/// caption, media and the sensitive label all survive the parse. This
|
||||
/// replaced a second byte-identical live test whose URL is a *text-only*
|
||||
/// post, so neither copy pinned any media.
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to public.api.bsky.app"]
|
||||
async fn live_fetch_with_photos() {
|
||||
let fetched =
|
||||
fetch_from_url("https://bsky.app/profile/asagi0398.bsky.social/post/3mqkhrq5w6k2m")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fetched.source_url,
|
||||
"https://bsky.app/profile/asagi0398.bsky.social/post/3mqkhrq5w6k2m"
|
||||
);
|
||||
assert!(!fetched.caption.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to public.api.bsky.app"]
|
||||
async fn live_fetch_smoke() {
|
||||
let fetched =
|
||||
fetch_from_url("https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fetched.source_url,
|
||||
"https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224"
|
||||
);
|
||||
let url = "https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224";
|
||||
let fetched = fetch_from_url(url).await.unwrap();
|
||||
assert_eq!(fetched.source_url, url);
|
||||
assert!(!fetched.caption.is_empty());
|
||||
assert!(!fetched.media.is_empty(), "expected photos in {url}");
|
||||
assert!(fetched.sensitive, "expected a label on {url}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
mod interface;
|
||||
mod model;
|
||||
|
||||
pub use interface::{
|
||||
BskySite, PATTERN, Post, cache_key, enabled, fetch_from_url, is_retryable, media_headers,
|
||||
};
|
||||
pub use interface::{BskySite, PATTERN, Post, cache_key, fetch_from_url};
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
//! The media-download stack: the two HTTP clients (site metadata vs. media,
|
||||
//! which need different timeouts), the CDN allowlist that keeps a download
|
||||
//! out of the host's own network, and the two streaming entry points — a capped
|
||||
//! body in memory ([`download_media_limited`]) and a large one written as it
|
||||
//! arrives ([`download_media_to_file`]).
|
||||
//!
|
||||
//! Site-specific headers come from each adapter's `Site::media_headers`; no
|
||||
//! code here knows about a particular site.
|
||||
|
||||
use super::{FetchError, SITES};
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long a download may make no progress: the response head, and then each
|
||||
/// individual chunk, must arrive within this window. Not a total timeout — see
|
||||
/// [`DOWNLOAD_TOTAL_TIMEOUT`].
|
||||
const DOWNLOAD_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Absolute ceiling for one media download, on top of the idle window: a
|
||||
/// server that drips a byte every 29 s keeps [`next_chunk`] satisfied
|
||||
/// indefinitely, and a transfer that trickles forever holds whatever the
|
||||
/// caller pinned to it — a fetch permit for an in-flight post, a prep slot
|
||||
/// for the bot's upload fallback. Generous on purpose: the legitimate cases
|
||||
/// are big — an ugoira frame zip runs to hundreds of MB and an HLS remux
|
||||
/// pulls a whole video — so this is the budget for downloads *inside a
|
||||
/// fetch*, while the slot-holding fallback passes its own shorter one (see
|
||||
/// [`download_media_limited`]'s `total`). Checked between chunks, so a
|
||||
/// transfer that completes just over the budget is kept rather than thrown
|
||||
/// away.
|
||||
pub(crate) const DOWNLOAD_TOTAL_TIMEOUT: Duration = Duration::from_secs(600);
|
||||
|
||||
/// The error a download reports when it spends its whole budget without
|
||||
/// finishing. Retryable: the transfer may simply have been unlucky, and a retry
|
||||
/// of the post restarts the download.
|
||||
fn download_too_slow(total: Duration) -> FetchError {
|
||||
FetchError::Transient(format!("download exceeded {}s", total.as_secs()))
|
||||
}
|
||||
|
||||
/// Builds a client with the shared configuration (browser User-Agent, the
|
||||
/// Bot API's proxy, per-runtime pools under test). `total_timeout` is what
|
||||
/// differs between the two clients below.
|
||||
fn build_client(total_timeout: Option<Duration>) -> reqwest::Client {
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.user_agent("Mozilla/5.0")
|
||||
.connect_timeout(Duration::from_secs(10));
|
||||
// Redirects stay allowed for allowlisted CDN hops, but every hop goes
|
||||
// through the same policy as the initial URL; a third-party response must
|
||||
// not be able to introduce a new host.
|
||||
builder = builder.redirect(reqwest::redirect::Policy::custom(|attempt| {
|
||||
if !media_url_allowed(attempt.url()) {
|
||||
log::warn!("refusing a media redirect outside the CDN allowlist");
|
||||
return attempt.error(FetchError::Blocked);
|
||||
}
|
||||
if attempt.previous().len() >= 10 {
|
||||
return attempt.stop();
|
||||
}
|
||||
attempt.follow()
|
||||
}));
|
||||
if let Some(total) = total_timeout {
|
||||
// reqwest has no total timeout by default; a stalled connection
|
||||
// would otherwise pin a fetch/handler forever.
|
||||
builder = builder.timeout(total);
|
||||
}
|
||||
// Route site fetches through the same proxy the Bot API uses, so a
|
||||
// network that needs TELOXIDE_PROXY (e.g. behind the GFW) does not
|
||||
// leave site fetches dead while the bot itself works.
|
||||
if let Some(proxy) = std::env::var("TELOXIDE_PROXY")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
&& let Ok(p) = reqwest::Proxy::all(&proxy)
|
||||
{
|
||||
builder = builder.proxy(p);
|
||||
}
|
||||
// Each `#[tokio::test]` runs on its own runtime; the connection pool is
|
||||
// bound to the runtime that created it, so cross-runtime reuse of idle
|
||||
// connections fails with DispatchGone. In test builds every request uses
|
||||
// a fresh connection. Production runs on one runtime and keeps pooling.
|
||||
#[cfg(test)]
|
||||
let builder = builder.pool_max_idle_per_host(0);
|
||||
builder.build().expect("failed to build HTTP client")
|
||||
}
|
||||
|
||||
/// Shared HTTP client (browser User-Agent) for the site fetches — metadata
|
||||
/// requests, where 30s is generous.
|
||||
pub(crate) static CLIENT: LazyLock<reqwest::Client> =
|
||||
LazyLock::new(|| build_client(Some(Duration::from_secs(30))));
|
||||
|
||||
/// Client for media *downloads*, with no reqwest-level total timeout: a 10 MiB
|
||||
/// fallback download, or an ugoira frame zip that may be hundreds of MB,
|
||||
/// legitimately takes minutes on a slow link — a 30s total cap made those posts
|
||||
/// impossible to deliver at all (the size cap said 512 MiB, the clock said 30s).
|
||||
/// What a stalled connection cannot do is hang a worker: the head and every
|
||||
/// chunk are bounded by [`DOWNLOAD_IDLE_TIMEOUT`] (see [`next_chunk`]), and a
|
||||
/// transfer that keeps trickling but never finishes is bounded by the
|
||||
/// caller's total budget (see [`download_media_limited`]).
|
||||
static MEDIA_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| build_client(None));
|
||||
|
||||
/// The error a download reports when it stops making progress.
|
||||
fn download_stalled() -> FetchError {
|
||||
FetchError::Transient(format!(
|
||||
"download stalled for {}s",
|
||||
DOWNLOAD_IDLE_TIMEOUT.as_secs()
|
||||
))
|
||||
}
|
||||
|
||||
/// Sends a media-download request: the response head must arrive within the
|
||||
/// idle window, and a non-2xx status is classified by
|
||||
/// [`super::status_error`] with `"media"` as the name — the same table the
|
||||
/// site adapters use, so a dead URL and a bad moment read the same everywhere.
|
||||
/// A transport error never reaches that table — it fails in `send()` and
|
||||
/// stays [`FetchError::Http`].
|
||||
async fn send_download(request: reqwest::RequestBuilder) -> Result<reqwest::Response, FetchError> {
|
||||
let response = match tokio::time::timeout(DOWNLOAD_IDLE_TIMEOUT, request.send()).await {
|
||||
Ok(Ok(response)) => response,
|
||||
Ok(Err(e)) => return Err(e.into()),
|
||||
Err(_) => return Err(download_stalled()),
|
||||
};
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
Err(super::status_error("media", &response))
|
||||
}
|
||||
}
|
||||
|
||||
/// One body chunk, or `None` at the end. A body that stops delivering is a
|
||||
/// transient download error rather than a hang.
|
||||
async fn next_chunk(response: &mut reqwest::Response) -> Result<Option<bytes::Bytes>, FetchError> {
|
||||
match tokio::time::timeout(DOWNLOAD_IDLE_TIMEOUT, response.chunk()).await {
|
||||
Ok(Ok(chunk)) => Ok(chunk),
|
||||
Ok(Err(e)) => Err(e.into()),
|
||||
Err(_) => Err(download_stalled()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a successful API response body with a hard byte cap.
|
||||
pub(crate) async fn send_json_response(
|
||||
mut response: reqwest::Response,
|
||||
site: &'static str,
|
||||
) -> Result<bytes::Bytes, FetchError> {
|
||||
if let Some(len) = response.content_length()
|
||||
&& len > crate::site::MAX_SITE_JSON_BYTES as u64
|
||||
{
|
||||
return Err(FetchError::Site {
|
||||
site,
|
||||
error: "site response exceeds JSON size cap".into(),
|
||||
});
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = next_chunk(&mut response).await? {
|
||||
if body.len().saturating_add(chunk.len()) > crate::site::MAX_SITE_JSON_BYTES {
|
||||
return Err(FetchError::Site {
|
||||
site,
|
||||
error: "site response exceeds JSON size cap".into(),
|
||||
});
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(bytes::Bytes::from(body))
|
||||
}
|
||||
|
||||
/// `localhost` (and anything under it) plus the mDNS `.local` suffix.
|
||||
fn is_local_name(name: &str) -> bool {
|
||||
let name = name.trim_end_matches('.').to_ascii_lowercase();
|
||||
name == "localhost" || name.ends_with(".localhost") || name.ends_with(".local")
|
||||
}
|
||||
|
||||
/// Media is fetched only from the CDN families used by the site adapters.
|
||||
/// IP literals are rejected as well: a public IP is not a member of that
|
||||
/// allowlist, and accepting one would turn the bot into a generic proxy.
|
||||
fn media_host_allowed(name: &str) -> bool {
|
||||
let name = name.trim_end_matches('.').to_ascii_lowercase();
|
||||
name == "misskey.io"
|
||||
|| name.ends_with(".misskey.io")
|
||||
|| name == "misskeyusercontent.jp"
|
||||
|| name.ends_with(".misskeyusercontent.jp")
|
||||
|| name == "bsky.app"
|
||||
|| name.ends_with(".bsky.app")
|
||||
|| name == "twimg.com"
|
||||
|| name.ends_with(".twimg.com")
|
||||
|| name == "pximg.net"
|
||||
|| name.ends_with(".pximg.net")
|
||||
|| name == "hdslb.com"
|
||||
|| name.ends_with(".hdslb.com")
|
||||
}
|
||||
|
||||
fn media_url_allowed(url: &url::Url) -> bool {
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return false;
|
||||
}
|
||||
matches!(url.host(), Some(url::Host::Domain(name)) if !is_local_name(name) && media_host_allowed(name))
|
||||
}
|
||||
|
||||
/// Prepares a media download: refuses a URL outside the CDN allowlist
|
||||
/// ([`FetchError::Blocked`], permanent — the same URL would be refused again),
|
||||
/// then applies every site's media-header rule (pixiv's `Referer` for pximg.net
|
||||
/// hotlink protection; sites contribute via `media_headers(url)`, so the
|
||||
/// central download code carries no other per-site logic). One choke point so
|
||||
/// every download path gets both.
|
||||
fn media_request(url: &str) -> Result<reqwest::RequestBuilder, FetchError> {
|
||||
let parsed = url::Url::parse(url).map_err(|e| {
|
||||
log::warn!("media url is not a url: {e}");
|
||||
FetchError::Blocked
|
||||
})?;
|
||||
if !media_url_allowed(&parsed) {
|
||||
log::warn!("refusing media URL outside the CDN allowlist");
|
||||
return Err(FetchError::Blocked);
|
||||
}
|
||||
let mut request = MEDIA_CLIENT.get(parsed);
|
||||
for site in SITES.iter() {
|
||||
if let Some(headers) = site.media_headers(url) {
|
||||
for (name, value) in headers {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
/// Downloads a media file with a hard size cap: the body is streamed and the
|
||||
/// download aborts with [`FetchError::TooLarge`] the moment the cap is
|
||||
/// crossed (or when a declared Content-Length already exceeds it). Keeps the
|
||||
/// bot from buffering arbitrarily large bodies into memory — the size check
|
||||
/// the bot's upload fallback needs is the one here, not a probe of its own.
|
||||
///
|
||||
/// This is the bot's download path for the upload fallback: when Telegram
|
||||
/// cannot fetch a media URL itself (hotlink protection), the bot downloads
|
||||
/// the file and uploads it via multipart. Site-appropriate headers come from
|
||||
/// each site's `media_headers` (pixiv image hosts need `Referer`).
|
||||
///
|
||||
/// `total` is this caller's whole-transfer budget. The bot's upload fallback
|
||||
/// holds a prep slot (and its memory reservation) while this runs, so it
|
||||
/// passes a shorter one of its own; bsky's in-fetch segments take the
|
||||
/// generous [`super::DOWNLOAD_TOTAL_TIMEOUT`].
|
||||
pub async fn download_media_limited(
|
||||
url: &str,
|
||||
max_bytes: u64,
|
||||
total: Duration,
|
||||
) -> Result<bytes::Bytes, FetchError> {
|
||||
let response = send_download(media_request(url)?).await?;
|
||||
if let Some(len) = response.content_length()
|
||||
&& len > max_bytes
|
||||
{
|
||||
return Err(FetchError::TooLarge);
|
||||
}
|
||||
let mut response = response;
|
||||
let mut buf = Vec::new();
|
||||
let started = std::time::Instant::now();
|
||||
while let Some(chunk) = next_chunk(&mut response).await? {
|
||||
if started.elapsed() > total {
|
||||
return Err(download_too_slow(total));
|
||||
}
|
||||
buf.extend_from_slice(&chunk);
|
||||
if buf.len() as u64 > max_bytes {
|
||||
return Err(FetchError::TooLarge);
|
||||
}
|
||||
}
|
||||
Ok(bytes::Bytes::from(buf))
|
||||
}
|
||||
|
||||
/// Streams a download to `out`, aborting with [`FetchError::TooLarge`] the
|
||||
/// moment the body crosses `max_bytes` (or when a declared Content-Length
|
||||
/// already exceeds it). Unlike [`download_media_limited`] the body is never
|
||||
/// buffered in memory — used for large files (e.g. the pixiv ugoira frame
|
||||
/// zip, which can be hundreds of MB) that would otherwise spike RAM. Writes
|
||||
/// go through the tokio handle so a sync write never stalls an executor
|
||||
/// thread for the length of the download. Returns the number of bytes written.
|
||||
pub async fn download_media_to_file(
|
||||
url: &str,
|
||||
max_bytes: u64,
|
||||
out: &mut tokio::fs::File,
|
||||
) -> Result<u64, FetchError> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let response = send_download(media_request(url)?).await?;
|
||||
if let Some(len) = response.content_length()
|
||||
&& len > max_bytes
|
||||
{
|
||||
return Err(FetchError::TooLarge);
|
||||
}
|
||||
let mut response = response;
|
||||
let mut total: u64 = 0;
|
||||
let started = std::time::Instant::now();
|
||||
while let Some(chunk) = next_chunk(&mut response).await? {
|
||||
if started.elapsed() > DOWNLOAD_TOTAL_TIMEOUT {
|
||||
return Err(download_too_slow(DOWNLOAD_TOTAL_TIMEOUT));
|
||||
}
|
||||
total += chunk.len() as u64;
|
||||
if total > max_bytes {
|
||||
return Err(FetchError::TooLarge);
|
||||
}
|
||||
out.write_all(&chunk).await.map_err(FetchError::Io)?;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::site::{Fetched, pixiv};
|
||||
|
||||
#[test]
|
||||
fn media_urls_outside_the_allowlist_are_refused() {
|
||||
for url in [
|
||||
"http://127.0.0.1:9/x",
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://[::1]:9/x",
|
||||
"https://1.1.1.1/x",
|
||||
"https://[2606:4700::1111]/x",
|
||||
"https://localhost/",
|
||||
"https://prompt.localhost/x",
|
||||
"https://printer.local/x",
|
||||
"https://example.com/a",
|
||||
"https://evil.pximg.net.attacker.example/a",
|
||||
"file:///etc/passwd",
|
||||
"gopher://example.com/1",
|
||||
] {
|
||||
let parsed = url::Url::parse(url).unwrap();
|
||||
assert!(!media_url_allowed(&parsed), "{url}");
|
||||
}
|
||||
for url in [
|
||||
"https://i.pximg.net/img-original/img/1.jpg",
|
||||
"https://cdn.bsky.app/img/feed_thumbnail/plain/x",
|
||||
"https://pbs.twimg.com/media/1.jpg",
|
||||
"https://media.misskeyusercontent.jp/io/1.jpg",
|
||||
"https://i0.hdslb.com/bfs/1.jpg",
|
||||
] {
|
||||
let parsed = url::Url::parse(url).unwrap();
|
||||
assert!(media_url_allowed(&parsed), "{url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_download_from_a_refused_host_is_blocked() {
|
||||
// Refused on the URL alone: nothing has to be listening (or leaking) at
|
||||
// the metadata endpoint for this to hold, and the class is permanent so
|
||||
// the send path does not retry it.
|
||||
for url in [
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://127.0.0.1:9/secret",
|
||||
"http://8.8.8.8/x",
|
||||
] {
|
||||
let err = download_media_limited(url, u64::MAX, DOWNLOAD_TOTAL_TIMEOUT)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, FetchError::Blocked), "{url}: got {err:?}");
|
||||
}
|
||||
// A malformed URL is refused the same way instead of becoming a
|
||||
// retryable transport error.
|
||||
assert!(matches!(
|
||||
download_media_limited("not a url", u64::MAX, DOWNLOAD_TOTAL_TIMEOUT)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
FetchError::Blocked
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires PIXIV_REFRESH_TOKEN and i.pximg.net"]
|
||||
async fn live_download_media_pixiv_original_with_referer() {
|
||||
// Proves the Referer header is attached for i.pximg.net: a header-less
|
||||
// GET to a pixiv original URL is rejected with 403. `#[ignore]` as
|
||||
// well as the token gate: this hit the CDN on every `cargo test
|
||||
// --workspace` in a token-exported shell (and flaked on a CDN body
|
||||
// timeout there), and the `live_` name puts it inside the CI live
|
||||
// job's `--ignored live` filter. Empty-string check too: an unset CI
|
||||
// secret arrives as "" (GitHub Actions), which would otherwise run
|
||||
// the test tokenless and fail — the `SKIP` prefix is what the live
|
||||
// job greps to tell a skip from a pass.
|
||||
if std::env::var("PIXIV_REFRESH_TOKEN")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
.is_none()
|
||||
{
|
||||
eprintln!("SKIP (no PIXIV_REFRESH_TOKEN): not running the pixiv download test");
|
||||
return;
|
||||
}
|
||||
let illustration = pixiv::fetch(126839080).await.unwrap();
|
||||
let fetched: Fetched = illustration.into();
|
||||
let url = match fetched.media.first() {
|
||||
Some(crate::media::Media::Illustration { url, .. }) => url.clone(),
|
||||
other => panic!("expected illustration media, got {other:?}"),
|
||||
};
|
||||
assert!(url.contains("i.pximg.net"));
|
||||
let bytes = download_media_limited(&url, u64::MAX, DOWNLOAD_TOTAL_TIMEOUT)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!bytes.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::model;
|
||||
use crate::media::Media;
|
||||
use crate::site::{FetchError, Fetched, RenderData, Site, SiteFuture};
|
||||
use html_escape::{encode_double_quoted_attribute, encode_text};
|
||||
use html_escape::encode_text;
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
@@ -34,10 +34,6 @@ impl Site for MisskeySite {
|
||||
pub static PATTERN: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^(?:https?://)?misskey\.io/notes/([\w.\-~]+)").unwrap());
|
||||
|
||||
pub fn enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub async fn fetch_from_url(url: &str) -> Result<Fetched, FetchError> {
|
||||
let caps = PATTERN.captures(url).ok_or(FetchError::NotFound)?;
|
||||
let note_id = caps.get(1).ok_or(FetchError::NotFound)?.as_str();
|
||||
@@ -53,20 +49,10 @@ pub fn cache_key(url: &str) -> Option<String> {
|
||||
.map(|caps| format!("misskey:{}", &caps[1]))
|
||||
}
|
||||
|
||||
/// Misskey's fetch-retry policy: transient classes only. Not-found, blocked
|
||||
/// and parse failures are permanent.
|
||||
pub fn is_retryable(err: &FetchError) -> bool {
|
||||
matches!(err, FetchError::Http(_) | FetchError::Transient(_))
|
||||
}
|
||||
|
||||
/// misskey.io media hosts need no extra headers (verified: direct GET works).
|
||||
pub fn media_headers(_url: &str) -> Option<Vec<(&'static str, String)>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Fetches a note from misskey.io by id. The API answers client failures
|
||||
/// with HTTP 400 + `{"error":{"code":...}}` (NO_SUCH_NOTE → NotFound);
|
||||
/// everything else non-success is transient and retried by [`crate::site::fetch`].
|
||||
/// every other non-success status falls through to the shared classes in
|
||||
/// [`crate::site::status_error`] — persistent 4xx permanent, 429/5xx retried.
|
||||
pub async fn fetch(note_id: &str) -> Result<model::Note, FetchError> {
|
||||
let response = crate::site::CLIENT
|
||||
.post(API_URL)
|
||||
@@ -77,19 +63,19 @@ pub async fn fetch(note_id: &str) -> Result<model::Note, FetchError> {
|
||||
if !status.is_success() {
|
||||
return Err(match status.as_u16() {
|
||||
400 => not_found_or_invalid(response).await,
|
||||
_ => FetchError::Transient(format!("misskey status {status}")),
|
||||
// The local fallback used to disagree with the center: a misskey
|
||||
// 404 came back Transient here and was fetched three more times
|
||||
// for a note that is simply gone.
|
||||
_ => crate::site::status_error("misskey", &response),
|
||||
});
|
||||
}
|
||||
response.json().await.map_err(|e| FetchError::Site {
|
||||
site: "misskey",
|
||||
error: Box::new(e),
|
||||
})
|
||||
crate::site::response_json(response, "misskey").await
|
||||
}
|
||||
|
||||
/// Maps a 400 response: NO_SUCH_NOTE is permanent NotFound, any other 400 is
|
||||
/// a site error (permanent — retrying a rejected request cannot succeed).
|
||||
async fn not_found_or_invalid(response: reqwest::Response) -> FetchError {
|
||||
match response.json::<serde_json::Value>().await {
|
||||
match crate::site::response_json::<serde_json::Value>(response, "misskey").await {
|
||||
Ok(v) if v["error"]["code"] == "NO_SUCH_NOTE" => FetchError::NotFound,
|
||||
_ => FetchError::Site {
|
||||
site: "misskey",
|
||||
@@ -123,29 +109,31 @@ impl From<model::Note> for Fetched {
|
||||
let cw = content.cw.as_deref().unwrap_or_default();
|
||||
// Notes carry hashtags inline in the text (no structured tags array);
|
||||
// a CW note gets the marker prefixed so recipients see the spoiler.
|
||||
let mut title = cw.to_string();
|
||||
if !cw.is_empty() && !title.ends_with(' ') {
|
||||
title.push(' ');
|
||||
let mut text = cw.to_string();
|
||||
if !cw.is_empty() && !text.ends_with(' ') {
|
||||
text.push(' ');
|
||||
}
|
||||
title.push_str(content.text.as_deref().unwrap_or_default().trim());
|
||||
let title = title.trim().to_string();
|
||||
text.push_str(content.text.as_deref().unwrap_or_default().trim());
|
||||
let text = text.trim().to_string();
|
||||
|
||||
let caption = caption(&url, &author_url, &author, &title);
|
||||
let caption = crate::site::caption(&url, &author_url, &author, &text);
|
||||
let sensitive = content.cw.is_some() || content.files.iter().any(|f| f.is_sensitive);
|
||||
let media: Vec<Media> = content.files.iter().filter_map(media_from_file).collect();
|
||||
|
||||
Fetched {
|
||||
source_url: url.clone(),
|
||||
caption,
|
||||
title: title.clone(),
|
||||
// A note has no title: its text (CW marker included) is content.
|
||||
title: String::new(),
|
||||
content: text.clone(),
|
||||
media,
|
||||
sensitive,
|
||||
site_id: "misskey",
|
||||
render_data: Some(RenderData {
|
||||
url,
|
||||
author: encode_text(&author).into_owned(),
|
||||
author_url: author_url.clone(),
|
||||
title: encode_text(&title).into_owned(),
|
||||
title: String::new(),
|
||||
content: encode_text(&text).into_owned(),
|
||||
tags: String::new(),
|
||||
}),
|
||||
_keep_alive: None,
|
||||
@@ -153,38 +141,21 @@ impl From<model::Note> for Fetched {
|
||||
}
|
||||
}
|
||||
|
||||
fn caption(url: &str, author_url: &str, author: &str, text: &str) -> String {
|
||||
let url = encode_double_quoted_attribute(url);
|
||||
let author_url = encode_double_quoted_attribute(author_url);
|
||||
let author = encode_text(author);
|
||||
if text.is_empty() {
|
||||
return format!("{url}\n<a href=\"{author_url}\">{author}</a>");
|
||||
}
|
||||
format!(
|
||||
"{url}\n<a href=\"{author_url}\">{author}</a>: {text}",
|
||||
text = encode_text(text),
|
||||
)
|
||||
}
|
||||
|
||||
/// Maps a Misskey DriveFile to a [`Media`] item; unknown/audio/other types
|
||||
/// are skipped (twitter's `_ => {}` precedent). GIF must be matched before
|
||||
/// the generic image arm.
|
||||
fn media_from_file(file: &model::DriveFile) -> Option<Media> {
|
||||
let title = file.name.clone();
|
||||
match file.mime_type.as_str() {
|
||||
"image/gif" => Some(Media::Animated {
|
||||
title,
|
||||
url: file.url.clone(),
|
||||
thumbnail_url: file.thumbnail_url.clone().unwrap_or_default(),
|
||||
}),
|
||||
mime if mime.starts_with("image/") => Some(Media::Illustration {
|
||||
title,
|
||||
url: file.url.clone(),
|
||||
thumbnail_url: file.thumbnail_url.clone(),
|
||||
fallback_url: None,
|
||||
}),
|
||||
mime if mime.starts_with("video/") => Some(Media::Video {
|
||||
title,
|
||||
url: file.url.clone(),
|
||||
thumbnail_url: file.thumbnail_url.clone().unwrap_or_default(),
|
||||
}),
|
||||
@@ -234,11 +205,6 @@ mod tests {
|
||||
cache_key("https://misskey.io/notes/aotihl10lqrs015s"),
|
||||
Some("misskey:aotihl10lqrs015s".to_string())
|
||||
);
|
||||
assert_eq!(x_media_site_id("misskey:abc"), "misskey");
|
||||
}
|
||||
|
||||
fn x_media_site_id(key: &str) -> &'static str {
|
||||
crate::site::site_id_from_key(key)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -257,17 +223,16 @@ mod tests {
|
||||
"https://misskey.io/notes/aotihl10lqrs015s"
|
||||
);
|
||||
assert_eq!(fetched.site_id, "misskey");
|
||||
assert_eq!(fetched.title, "hello");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "hello");
|
||||
assert!(fetched.sensitive);
|
||||
assert_eq!(fetched.media.len(), 1);
|
||||
match &fetched.media[0] {
|
||||
Media::Illustration {
|
||||
title,
|
||||
url,
|
||||
thumbnail_url,
|
||||
fallback_url,
|
||||
} => {
|
||||
assert_eq!(title.as_deref(), Some("pic.webp"));
|
||||
assert_eq!(url, "https://media.misskeyusercontent.jp/io/a.webp");
|
||||
assert_eq!(
|
||||
thumbnail_url.as_deref(),
|
||||
@@ -308,7 +273,8 @@ mod tests {
|
||||
note["text"] = serde_json::json!("body");
|
||||
let fetched: Fetched = note_json(note).into();
|
||||
assert!(fetched.sensitive);
|
||||
assert_eq!(fetched.title, "spoiler body");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "spoiler body");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -341,7 +307,8 @@ mod tests {
|
||||
}
|
||||
});
|
||||
let fetched: Fetched = note_json(note).into();
|
||||
assert_eq!(fetched.title, "inner text");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "inner text");
|
||||
assert_eq!(fetched.media.len(), 1);
|
||||
// The source URL still points at the renote shell the user posted.
|
||||
assert_eq!(
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
mod interface;
|
||||
mod model;
|
||||
|
||||
pub use interface::{
|
||||
MisskeySite, PATTERN, cache_key, enabled, fetch_from_url, is_retryable, media_headers,
|
||||
};
|
||||
pub use interface::{MisskeySite, PATTERN, cache_key, fetch_from_url};
|
||||
|
||||
@@ -30,6 +30,4 @@ pub(crate) struct DriveFile {
|
||||
pub(crate) thumbnail_url: Option<String>,
|
||||
#[serde(default, rename = "isSensitive")]
|
||||
pub(crate) is_sensitive: bool,
|
||||
#[serde(default)]
|
||||
pub(crate) name: Option<String>,
|
||||
}
|
||||
|
||||
+509
-247
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@
|
||||
//! `app-api.pixiv.net`, deserialized with the kept `model.rs` types.
|
||||
|
||||
use super::interface::Illustration;
|
||||
use super::model::{IllustrationModel, TypeModel, UgoiraMetadataModel};
|
||||
use super::model::{IllustrationModel, UgoiraMetadataModel};
|
||||
use crate::media::Media;
|
||||
use crate::site::FetchError;
|
||||
use std::env;
|
||||
@@ -23,6 +23,19 @@ const APP_USER_AGENT: &str = "PixivIOSApp/7.13.3 (iOS 14.6; iPhone13,2)";
|
||||
/// Token refresh safe margin (seconds).
|
||||
const TOKEN_REFRESH_SAFE_MARGIN: u64 = 300;
|
||||
|
||||
const MAX_UGOIRA_FRAMES: usize = 5_000;
|
||||
const MAX_UGOIRA_UNPACKED_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
fn check_ugoira_archive_size(entries: usize, unpacked: u64) -> Result<(), &'static str> {
|
||||
if entries > MAX_UGOIRA_FRAMES {
|
||||
return Err("ugoira has too many frames");
|
||||
}
|
||||
if unpacked > MAX_UGOIRA_UNPACKED_BYTES {
|
||||
return Err("ugoira exceeds total unpacked size cap");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum PixivError {
|
||||
/// No refresh token available (PIXIV_REFRESH_TOKEN unset).
|
||||
@@ -39,6 +52,20 @@ pub enum PixivError {
|
||||
Status(u16),
|
||||
#[error("pixiv api error: {0}")]
|
||||
Api(String),
|
||||
/// A bad moment while preparing media: a transient download status
|
||||
/// (429 / 5xx), a stalled transfer or a temp-file write failure. A retry
|
||||
/// can change the answer, so the pixiv retry policy re-fetches these.
|
||||
#[error("transient pixiv error: {0}")]
|
||||
Transient(String),
|
||||
}
|
||||
|
||||
fn map_response_error(error: FetchError) -> PixivError {
|
||||
match error {
|
||||
FetchError::Http(e) => PixivError::Http(e),
|
||||
FetchError::Transient(message) => PixivError::Transient(message),
|
||||
FetchError::RateLimited { .. } => PixivError::Transient("rate limited".into()),
|
||||
other => PixivError::Api(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Native pixiv app-API client.
|
||||
@@ -76,7 +103,12 @@ impl PixivAPI {
|
||||
.header("User-Agent", AUTH_USER_AGENT)
|
||||
.send()
|
||||
.await?;
|
||||
let json: serde_json::Value = serde_json::from_str(&response.text().await?)?;
|
||||
if !response.status().is_success() {
|
||||
return Err(PixivError::Status(response.status().as_u16()));
|
||||
}
|
||||
let json: serde_json::Value = crate::site::response_json(response, "pixiv")
|
||||
.await
|
||||
.map_err(map_response_error)?;
|
||||
let access_token = json
|
||||
.get("access_token")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -115,7 +147,9 @@ impl PixivAPI {
|
||||
if !response.status().is_success() {
|
||||
return Err(PixivError::Status(response.status().as_u16()));
|
||||
}
|
||||
let json: serde_json::Value = serde_json::from_str(&response.text().await?)?;
|
||||
let json: serde_json::Value = crate::site::response_json(response, "pixiv")
|
||||
.await
|
||||
.map_err(map_response_error)?;
|
||||
if json.get("error").is_some() {
|
||||
let message = json
|
||||
.get("message")
|
||||
@@ -132,21 +166,26 @@ impl PixivAPI {
|
||||
pub async fn fetch(&self, illust_id: u64) -> Result<Illustration, FetchError> {
|
||||
let model = self.illust_detail(illust_id).await?;
|
||||
let mut illustration = Illustration::from_model(&model);
|
||||
if matches!(&model.r#type, TypeModel::Ugoira) {
|
||||
if model.r#type == "ugoira" {
|
||||
// Real ugoira support: download the frame zip and encode an MP4.
|
||||
// Without ffmpeg (or on encode failure) the post stays
|
||||
// unsupported (empty media, like Python).
|
||||
// Without ffmpeg the post stays unsupported (empty media, like
|
||||
// Python) — but a *failed* download/encode is reported instead:
|
||||
// a ugoira post has no static image to fall back to, so
|
||||
// swallowing it would present a transient zip-download error as
|
||||
// "this post has no media", with the retries skipped.
|
||||
match self.ugoira_video(illust_id).await {
|
||||
Ok(Some((mp4_path, _keep_alive))) => {
|
||||
illustration.media.push(Media::Video {
|
||||
title: None,
|
||||
url: mp4_path,
|
||||
thumbnail_url: model.image_urls.medium.clone(),
|
||||
});
|
||||
illustration._keep_alive = Some(_keep_alive);
|
||||
illustration._keep_alive = Some(std::sync::Arc::new(_keep_alive));
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => log::error!("ugoira encode failed for {illust_id}: {e}"),
|
||||
Err(e) => {
|
||||
log::error!("ugoira encode failed for {illust_id}: {e}");
|
||||
return Err(FetchError::Pixiv(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(illustration)
|
||||
@@ -168,7 +207,9 @@ impl PixivAPI {
|
||||
if !response.status().is_success() {
|
||||
return Err(PixivError::Status(response.status().as_u16()));
|
||||
}
|
||||
let json: serde_json::Value = serde_json::from_str(&response.text().await?)?;
|
||||
let json: serde_json::Value = crate::site::response_json(response, "pixiv")
|
||||
.await
|
||||
.map_err(map_response_error)?;
|
||||
if json.get("error").is_some() {
|
||||
let message = json
|
||||
.get("message")
|
||||
@@ -189,14 +230,15 @@ impl PixivAPI {
|
||||
&self,
|
||||
illust_id: u64,
|
||||
) -> Result<Option<(String, tempfile::TempDir)>, PixivError> {
|
||||
if !crate::site::ffmpeg_available() {
|
||||
crate::site::log_once_ffmpeg_missing();
|
||||
if crate::site::ffmpeg_missing() {
|
||||
return Ok(None);
|
||||
}
|
||||
let metadata = self.ugoira_metadata(illust_id).await?;
|
||||
if metadata.frames.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
check_ugoira_archive_size(metadata.frames.len(), 0)
|
||||
.map_err(|e| PixivError::Api(e.to_string()))?;
|
||||
let zip_url = metadata
|
||||
.zip_url
|
||||
.clone()
|
||||
@@ -207,25 +249,50 @@ impl PixivAPI {
|
||||
// Stream the frame zip to a temp file instead of buffering it in
|
||||
// memory: ugoira zips can be hundreds of MB, and the old
|
||||
// download_media_limited path spiked RAM up to the size cap.
|
||||
let mut zip_file = tempfile::Builder::new()
|
||||
let zip_file = tempfile::Builder::new()
|
||||
.prefix(crate::TEMP_FILE_PREFIX)
|
||||
.suffix(".zip")
|
||||
.tempfile()
|
||||
.map_err(|e| PixivError::Api(format!("temp zip failed: {e}")))?;
|
||||
crate::site::download_media_to_file(&zip_url, 512 * 1024 * 1024, zip_file.as_file_mut())
|
||||
// Stream through a tokio handle: a sync write per chunk would stall
|
||||
// an executor thread for the whole (up to 512 MiB) download. The
|
||||
// clone shares the file offset with `zip_file`, so the extraction
|
||||
// below reads what was written, and dropping it after the download
|
||||
// hands every byte to the OS.
|
||||
let mut zip_out = tokio::fs::File::from_std(
|
||||
zip_file
|
||||
.as_file()
|
||||
.try_clone()
|
||||
.map_err(|e| PixivError::Api(format!("temp zip clone failed: {e}")))?,
|
||||
);
|
||||
crate::site::download_media_to_file(&zip_url, 512 * 1024 * 1024, &mut zip_out)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
FetchError::Http(e) => PixivError::Http(e),
|
||||
// A bad moment (429/5xx, a stalled transfer, a temp-file
|
||||
// write failure) must stay retryable: folding it into Api
|
||||
// made one hiccup permanently fail the whole ugoira post,
|
||||
// while the bot's own upload downloads retry the same
|
||||
// classes.
|
||||
transient @ (FetchError::Transient(_)
|
||||
| FetchError::RateLimited { .. }
|
||||
| FetchError::Io(_)) => {
|
||||
PixivError::Transient(format!("frame zip download failed: {transient}"))
|
||||
}
|
||||
other => PixivError::Api(format!("frame zip download failed: {other}")),
|
||||
})?;
|
||||
drop(zip_out);
|
||||
let frame_delays = metadata.frames.iter().map(|f| f.delay).collect::<Vec<_>>();
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || -> Result<(String, tempfile::TempDir), String> {
|
||||
let frames_dir = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||
let out_dir = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||
|
||||
// Extract frames to canonical zero-padded names; pixiv ugoira
|
||||
// frames are uniformly jpg or png per artwork. The zip is read
|
||||
// from disk; `zip_file` stays alive for the whole extraction.
|
||||
let frames_dir = tempfile::Builder::new()
|
||||
.prefix(crate::TEMP_FILE_PREFIX)
|
||||
.tempdir()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let out_dir = tempfile::Builder::new()
|
||||
.prefix(crate::TEMP_FILE_PREFIX)
|
||||
.tempdir()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut archive = zip::ZipArchive::new(
|
||||
std::fs::File::open(zip_file.path()).map_err(|e| e.to_string())?,
|
||||
)
|
||||
@@ -233,33 +300,12 @@ impl PixivAPI {
|
||||
if archive.is_empty() {
|
||||
return Err("empty frame zip".to_string());
|
||||
}
|
||||
// Uniform jpg or png per artwork; sniff the first entry's
|
||||
// magic bytes instead of trusting its filename.
|
||||
let first = archive.by_index(0).map_err(|e| e.to_string())?;
|
||||
let mut first_bytes = Vec::new();
|
||||
first
|
||||
.take(64 * 1024 * 1024 + 1)
|
||||
.read_to_end(&mut first_bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if first_bytes.len() > 64 * 1024 * 1024 {
|
||||
return Err("frame exceeds size cap".to_string());
|
||||
}
|
||||
let extension = if first_bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
"jpg"
|
||||
} else if first_bytes.starts_with(b"\x89PNG") {
|
||||
"png"
|
||||
} else {
|
||||
"jpg"
|
||||
};
|
||||
check_ugoira_archive_size(archive.len(), 0)?;
|
||||
|
||||
let mut count = 0usize;
|
||||
{
|
||||
let path = frames_dir
|
||||
.path()
|
||||
.join(format!("img_{count:05}.{extension}"));
|
||||
std::fs::write(&path, &first_bytes).map_err(|e| e.to_string())?;
|
||||
count += 1;
|
||||
}
|
||||
for i in 1..archive.len() {
|
||||
let mut unpacked = 0u64;
|
||||
let mut extension = "jpg";
|
||||
for i in 0..archive.len() {
|
||||
let entry = archive.by_index(i).map_err(|e| e.to_string())?;
|
||||
if entry.size() > 64 * 1024 * 1024 {
|
||||
return Err(format!("frame {i} exceeds size cap"));
|
||||
@@ -272,6 +318,19 @@ impl PixivAPI {
|
||||
if bytes.len() > 64 * 1024 * 1024 {
|
||||
return Err(format!("frame {i} exceeds size cap"));
|
||||
}
|
||||
unpacked = unpacked
|
||||
.checked_add(bytes.len() as u64)
|
||||
.ok_or_else(|| "ugoira unpacked size overflow".to_string())?;
|
||||
check_ugoira_archive_size(archive.len(), unpacked)?;
|
||||
if i == 0 {
|
||||
extension = if bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
"jpg"
|
||||
} else if bytes.starts_with(b"\x89PNG") {
|
||||
"png"
|
||||
} else {
|
||||
"jpg"
|
||||
};
|
||||
}
|
||||
let path = frames_dir
|
||||
.path()
|
||||
.join(format!("img_{count:05}.{extension}"));
|
||||
@@ -281,7 +340,6 @@ impl PixivAPI {
|
||||
if count == 0 {
|
||||
return Err("empty frame zip".to_string());
|
||||
}
|
||||
|
||||
// Constant rate from the median frame delay (ms).
|
||||
let mut delays = frame_delays;
|
||||
delays.sort_unstable();
|
||||
@@ -289,7 +347,7 @@ impl PixivAPI {
|
||||
let framerate = 1000.0 / median as f64;
|
||||
|
||||
let output = out_dir.path().join("ugoira.mp4");
|
||||
let status = std::process::Command::new("ffmpeg")
|
||||
let mut child = std::process::Command::new("ffmpeg")
|
||||
.args([
|
||||
"-y",
|
||||
"-framerate",
|
||||
@@ -313,10 +371,27 @@ impl PixivAPI {
|
||||
])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.spawn()
|
||||
.map_err(|e| format!("ffmpeg spawn failed: {e}"))?;
|
||||
if !status.success() {
|
||||
return Err(format!("ffmpeg exited with {status}"));
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
|
||||
loop {
|
||||
match child
|
||||
.try_wait()
|
||||
.map_err(|e| format!("ffmpeg wait failed: {e}"))?
|
||||
{
|
||||
Some(status) => {
|
||||
if !status.success() {
|
||||
return Err(format!("ffmpeg exited with {status}"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
None if std::time::Instant::now() >= deadline => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err("ffmpeg exceeded 300s".to_string());
|
||||
}
|
||||
None => std::thread::sleep(std::time::Duration::from_millis(50)),
|
||||
}
|
||||
}
|
||||
Ok((output.to_string_lossy().into_owned(), out_dir))
|
||||
})
|
||||
@@ -335,16 +410,23 @@ impl PixivAPI {
|
||||
}
|
||||
}
|
||||
|
||||
/// pixiv3-rs replacement: `None` when `PIXIV_REFRESH_TOKEN` is unset.
|
||||
static PIXIV_CLIENT: LazyLock<Option<PixivAPI>> =
|
||||
LazyLock::new(|| env::var("PIXIV_REFRESH_TOKEN").ok().map(PixivAPI::new));
|
||||
/// pixiv3-rs replacement: `None` when `PIXIV_REFRESH_TOKEN` is unset or empty
|
||||
/// (compose injects an empty string for a blank `.env` value; an empty token
|
||||
/// must mean "not configured" instead of being sent to OAuth).
|
||||
static PIXIV_CLIENT: LazyLock<Option<PixivAPI>> = LazyLock::new(|| {
|
||||
env::var("PIXIV_REFRESH_TOKEN")
|
||||
.ok()
|
||||
.filter(|token| !token.is_empty())
|
||||
.map(PixivAPI::new)
|
||||
});
|
||||
|
||||
/// Set at startup when the login validation fails; pixiv stays disabled until
|
||||
/// the next process start.
|
||||
static DISABLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub fn enabled() -> bool {
|
||||
!DISABLED.load(Ordering::Relaxed) && env::var("PIXIV_REFRESH_TOKEN").is_ok()
|
||||
!DISABLED.load(Ordering::Relaxed)
|
||||
&& env::var("PIXIV_REFRESH_TOKEN").is_ok_and(|token| !token.is_empty())
|
||||
}
|
||||
|
||||
/// Permanently disables pixiv until the next process start.
|
||||
@@ -378,35 +460,56 @@ mod tests {
|
||||
use super::*;
|
||||
use dotenv::dotenv;
|
||||
|
||||
/// Skips when `PIXIV_REFRESH_TOKEN` is absent or empty (CI without the
|
||||
/// secret must stay green; GitHub Actions exposes an unset secret as an
|
||||
/// empty string, so `is_err()` alone is not enough).
|
||||
fn require_pixiv_token() -> bool {
|
||||
std::env::var("PIXIV_REFRESH_TOKEN")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fetch() {
|
||||
dotenv().ok();
|
||||
if !require_pixiv_token() {
|
||||
eprintln!("skipping: no PIXIV_REFRESH_TOKEN");
|
||||
return;
|
||||
/// An empty `PIXIV_REFRESH_TOKEN` (what compose injects for a blank
|
||||
/// `.env` value, and what an unset GitHub secret looks like) must read as
|
||||
/// "not configured", exactly like unset — otherwise a default deployment
|
||||
/// sends an empty refresh token to OAuth and fails login validation on
|
||||
/// every boot.
|
||||
#[test]
|
||||
fn empty_refresh_token_reads_as_unset() {
|
||||
// SAFETY: the value is restored before returning; `enabled()` keys on
|
||||
// this variable alone and no other test mutates it. Concurrent readers
|
||||
// see unset or empty, which this very fix makes the same answer.
|
||||
let previous = env::var("PIXIV_REFRESH_TOKEN").ok();
|
||||
unsafe { env::set_var("PIXIV_REFRESH_TOKEN", "") };
|
||||
let empty = enabled();
|
||||
unsafe { env::remove_var("PIXIV_REFRESH_TOKEN") };
|
||||
let unset = enabled();
|
||||
match previous {
|
||||
Some(value) => unsafe { env::set_var("PIXIV_REFRESH_TOKEN", value) },
|
||||
None => unsafe { env::remove_var("PIXIV_REFRESH_TOKEN") },
|
||||
}
|
||||
let result = fetch(126839080).await;
|
||||
assert!(result.is_ok());
|
||||
println!("{:#?}", result);
|
||||
assert!(!empty, "an empty token must not enable pixiv");
|
||||
assert_eq!(empty, unset, "empty must read exactly like unset");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to oauth.secure.pixiv.net"]
|
||||
async fn live_validate_with_bogus_token_fails() {
|
||||
dotenv().ok();
|
||||
// A bogus token must surface as Api error (invalid_grant), not panic.
|
||||
let client = PixivAPI::new("bogus_token_for_testing".to_string());
|
||||
let result = client.get_access_token().await;
|
||||
assert!(matches!(result, Err(PixivError::Api(_))), "got {result:?}");
|
||||
assert!(
|
||||
matches!(result, Err(PixivError::Status(code)) if (400..500).contains(&code)),
|
||||
"got {result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_read_transport_errors_stay_retryable() {
|
||||
let mapped = map_response_error(FetchError::Transient("reset".into()));
|
||||
assert!(matches!(mapped, PixivError::Transient(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ugoira_budget_rejects_too_many_frames() {
|
||||
assert!(check_ugoira_archive_size(MAX_UGOIRA_FRAMES, 0).is_ok());
|
||||
assert!(check_ugoira_archive_size(MAX_UGOIRA_FRAMES + 1, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ugoira_budget_rejects_too_many_unpacked_bytes() {
|
||||
assert!(check_ugoira_archive_size(1, MAX_UGOIRA_UNPACKED_BYTES).is_ok());
|
||||
assert!(check_ugoira_archive_size(1, MAX_UGOIRA_UNPACKED_BYTES + 1).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::model::{IllustrationModel, TypeModel};
|
||||
use super::model::{IllustrationModel, ImageUrlsModel};
|
||||
use crate::media::Media;
|
||||
use crate::site::{FetchError, Fetched, PixivError, Site, SiteFuture};
|
||||
use html_escape::{encode_double_quoted_attribute, encode_text};
|
||||
@@ -46,17 +46,25 @@ impl Site for PixivSite {
|
||||
}
|
||||
|
||||
fn validate(&self) -> SiteFuture<'static, (), String> {
|
||||
Box::pin(async {
|
||||
match super::api::validate().await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
// Keep the old behavior: a failed login disables pixiv
|
||||
// for the rest of this process.
|
||||
super::api::disable();
|
||||
Err(format!("{e}"))
|
||||
}
|
||||
}
|
||||
})
|
||||
Box::pin(async { startup_validation(super::api::validate().await) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns the startup token exchange's outcome into what the bot reports, and
|
||||
/// disables pixiv only for a rejected credential. A bad *moment* — a 5xx or a
|
||||
/// network error while the container comes up — must not disable it: disabling
|
||||
/// on any error turned every later pixiv link into "support is disabled".
|
||||
/// Separate from the network call so the decision is testable.
|
||||
fn startup_validation(result: Result<(), PixivError>) -> Result<(), String> {
|
||||
match result {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if pixiv_error_is_retryable(&e) => {
|
||||
Err(format!("{e} (transient — pixiv stays enabled)"))
|
||||
}
|
||||
Err(e) => {
|
||||
super::api::disable();
|
||||
Err(format!("{e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,19 +91,25 @@ pub fn cache_key(url: &str) -> Option<String> {
|
||||
/// API/auth errors, unparseable bodies and missing auth are not retried.
|
||||
pub fn is_retryable(err: &FetchError) -> bool {
|
||||
match err {
|
||||
FetchError::Http(_) | FetchError::Transient(_) => true,
|
||||
FetchError::Pixiv(e) => match e {
|
||||
PixivError::Http(_) => true,
|
||||
PixivError::Status(code) if *code == 429 || *code >= 500 => true,
|
||||
PixivError::Status(_)
|
||||
| PixivError::Api(_)
|
||||
| PixivError::Json(_)
|
||||
| PixivError::NoAuth => false,
|
||||
},
|
||||
FetchError::Http(_) | FetchError::Transient(_) | FetchError::RateLimited { .. } => true,
|
||||
FetchError::Pixiv(e) => pixiv_error_is_retryable(e),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixiv-specific half of the retry policy, shared with startup
|
||||
/// validation: a bad moment (429/5xx, a network error) is retryable, a
|
||||
/// rejected credential is not.
|
||||
fn pixiv_error_is_retryable(err: &PixivError) -> bool {
|
||||
match err {
|
||||
PixivError::Http(_) | PixivError::Transient(_) => true,
|
||||
PixivError::Status(code) if *code == 429 || *code >= 500 => true,
|
||||
PixivError::Status(_) | PixivError::Api(_) | PixivError::Json(_) | PixivError::NoAuth => {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// pximg.net is hotlink-protected: downloads must carry the pixiv Referer.
|
||||
/// The match is on the media host, not the site PATTERN — pixiv's PATTERN
|
||||
/// only matches `pixiv.net/artworks/...`, never `i.pximg.net`.
|
||||
@@ -107,17 +121,67 @@ pub fn media_headers(url: &str) -> Option<Vec<(&'static str, String)>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Flattens the app API's HTML description into plain text: `<br>` (and `<p>`)
|
||||
/// become line breaks, other tags are dropped, entities decoded, the ends
|
||||
/// trimmed. A caption shows text, not markup, so the author's `<a href>` links
|
||||
/// contribute their link text only.
|
||||
fn flatten_html(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
let mut chars = raw.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
// Only `<` followed by `/` or a letter opens a tag — a bare `<` in
|
||||
// prose ("2 < 3") is text.
|
||||
let opens_tag = c == '<'
|
||||
&& chars
|
||||
.peek()
|
||||
.is_some_and(|next| *next == '/' || next.is_ascii_alphabetic());
|
||||
if !opens_tag {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
let mut tag = String::new();
|
||||
let mut closed = false;
|
||||
for c in chars.by_ref() {
|
||||
if c == '>' {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
tag.push(c);
|
||||
}
|
||||
if !closed {
|
||||
// Unclosed `<…`: keep it as text rather than dropping the tail.
|
||||
out.push('<');
|
||||
out.push_str(&tag);
|
||||
break;
|
||||
}
|
||||
// `<br>`, `<br/>`, `<br />` with or without attributes, and both
|
||||
// halves of a paragraph break the line; everything else is dropped.
|
||||
let tag = tag
|
||||
.trim()
|
||||
.trim_start_matches('/')
|
||||
.trim_end_matches('/')
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
if tag == "p" || tag.starts_with("br") {
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
html_escape::decode_html_entities(&out).trim().to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Illustration {
|
||||
id: String,
|
||||
title: String,
|
||||
/// The artwork's description, HTML flattened to plain text.
|
||||
content: String,
|
||||
author: String,
|
||||
author_id: String,
|
||||
tags: Vec<String>,
|
||||
pub(crate) media: Vec<Media>,
|
||||
nsfw: bool,
|
||||
/// Keeps a temp dir (ugoira MP4) alive until the send completes.
|
||||
pub(crate) _keep_alive: Option<tempfile::TempDir>,
|
||||
pub(crate) _keep_alive: Option<std::sync::Arc<tempfile::TempDir>>,
|
||||
}
|
||||
|
||||
impl Illustration {
|
||||
@@ -150,6 +214,7 @@ impl Illustration {
|
||||
pub fn from_model(model: &IllustrationModel) -> Self {
|
||||
let id = model.id.to_string();
|
||||
let title = model.title.clone();
|
||||
let content = flatten_html(&model.caption);
|
||||
let author = model.user.name.clone();
|
||||
let author_id = model.user.id.to_string();
|
||||
let mut tags: Vec<String> = model.tags.iter().map(|tag| tag.name.clone()).collect();
|
||||
@@ -160,39 +225,34 @@ impl Illustration {
|
||||
tags.insert(0, "AI".to_string());
|
||||
}
|
||||
let mut media = vec![];
|
||||
if matches!(&model.r#type, TypeModel::Ugoira) {
|
||||
if model.r#type == "ugoira" {
|
||||
// No static images for ugoira; the fetch path encodes an MP4 via
|
||||
// ffmpeg and appends it as a Video item (api.rs). This fallback
|
||||
// keeps media empty when encoding fails or ffmpeg is missing.
|
||||
} else if model.page_count > 1 {
|
||||
// Every page is kept: `original` is the only URL the API may leave
|
||||
// out (typically the restricted ones), and a page without it used
|
||||
// to be dropped whole — losing a page of the work while `large`
|
||||
// sat right there.
|
||||
media.extend(model.meta_pages.iter().filter_map(|page| {
|
||||
page.image_urls
|
||||
.original
|
||||
.clone()
|
||||
.map(|original| Media::Illustration {
|
||||
title: None,
|
||||
url: original,
|
||||
thumbnail_url: Some(page.image_urls.medium.clone()),
|
||||
fallback_url: Some(page.image_urls.large.clone()),
|
||||
})
|
||||
page_illustration(page.image_urls.original.clone(), &page.image_urls)
|
||||
}));
|
||||
} else if let Some(original) = model
|
||||
.meta_single_page
|
||||
.original_image_url
|
||||
.clone()
|
||||
.or(model.image_urls.original.clone())
|
||||
{
|
||||
media.push(Media::Illustration {
|
||||
title: None,
|
||||
url: original,
|
||||
thumbnail_url: Some(model.image_urls.medium.clone()),
|
||||
fallback_url: Some(model.image_urls.large.clone()),
|
||||
});
|
||||
} else {
|
||||
// The single page names its original in one of two places, and
|
||||
// `large` is the last resort.
|
||||
let urls = &model.image_urls;
|
||||
let original = model
|
||||
.meta_single_page
|
||||
.original_image_url
|
||||
.clone()
|
||||
.or_else(|| urls.original.clone());
|
||||
media.extend(page_illustration(original, urls));
|
||||
}
|
||||
let nsfw = model.sanity_level > 5;
|
||||
Self {
|
||||
id,
|
||||
title,
|
||||
content,
|
||||
author,
|
||||
author_id,
|
||||
tags,
|
||||
@@ -203,6 +263,21 @@ impl Illustration {
|
||||
}
|
||||
}
|
||||
|
||||
/// One artwork page as a media item: `original` when the API sent one, else the
|
||||
/// `large` variant (the same picture at a lower resolution), with `medium` as
|
||||
/// the thumbnail. `None` when the API gave no usable URL at all.
|
||||
fn page_illustration(original: Option<String>, urls: &ImageUrlsModel) -> Option<Media> {
|
||||
let url = original.unwrap_or_else(|| urls.large.clone());
|
||||
if url.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Media::Illustration {
|
||||
url,
|
||||
thumbnail_url: Some(urls.medium.clone()),
|
||||
fallback_url: Some(urls.large.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
impl From<Illustration> for Fetched {
|
||||
fn from(illustration: Illustration) -> Self {
|
||||
let url = illustration.url();
|
||||
@@ -214,16 +289,17 @@ impl From<Illustration> for Fetched {
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let render_data = Some(crate::site::RenderData {
|
||||
url: url.clone(),
|
||||
author: encode_text(&illustration.author).into_owned(),
|
||||
author_url: author_url.clone(),
|
||||
title: encode_text(&illustration.title).into_owned(),
|
||||
content: encode_text(&illustration.content).into_owned(),
|
||||
tags: encode_text(&tags).into_owned(),
|
||||
});
|
||||
Fetched {
|
||||
source_url: url,
|
||||
caption: illustration.caption(),
|
||||
title: illustration.title.clone(),
|
||||
content: illustration.content.clone(),
|
||||
media: illustration.media,
|
||||
sensitive: illustration.nsfw,
|
||||
site_id: "pixiv",
|
||||
@@ -262,6 +338,7 @@ mod tests {
|
||||
"illust": {
|
||||
"id": 123,
|
||||
"title": "Art <title>",
|
||||
"caption": "一行说明<br />二行 <a href=\"https://x.example/\">链接</a> & 结尾",
|
||||
"type": type_,
|
||||
"image_urls": {
|
||||
"medium": "medium.jpg",
|
||||
@@ -284,6 +361,44 @@ mod tests {
|
||||
Illustration::from_model(&model)
|
||||
}
|
||||
|
||||
/// The description arrives as HTML and becomes plain-text content: breaks
|
||||
/// kept, tags dropped (links keep their text), entities decoded.
|
||||
#[test]
|
||||
fn from_json_maps_description_to_content() {
|
||||
let v = illust_json("illust", 1, None, Some("o.jpg"), vec![], 0);
|
||||
let illustration = parse(v);
|
||||
assert_eq!(illustration.content, "一行说明\n二行 链接 & 结尾");
|
||||
|
||||
let fetched: Fetched = illustration.into();
|
||||
assert_eq!(fetched.title, "Art <title>");
|
||||
assert_eq!(fetched.content, "一行说明\n二行 链接 & 结尾");
|
||||
// The built-in caption keeps its layout: the description stays out of
|
||||
// it and is available through `{content}`.
|
||||
assert!(!fetched.caption.contains("一行说明"), "{}", fetched.caption);
|
||||
assert_eq!(
|
||||
fetched.render_fields().unwrap().3,
|
||||
"一行说明\n二行 链接 & 结尾"
|
||||
);
|
||||
assert!(
|
||||
fetched
|
||||
.caption_with("{title}: {content}")
|
||||
.ends_with("一行说明\n二行 链接 & 结尾")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_html_handles_common_markup() {
|
||||
assert_eq!(flatten_html(""), "");
|
||||
assert_eq!(flatten_html("plain"), "plain");
|
||||
assert_eq!(flatten_html("a<br />b<br/>c<br>d"), "a\nb\nc\nd");
|
||||
// A paragraph break is a blank line, exactly like `<br /><br />` —
|
||||
// writing it as one newline would flatten the author's paragraphs.
|
||||
assert_eq!(flatten_html("<p>one</p><p>two</p>"), "one\n\ntwo");
|
||||
assert_eq!(flatten_html("a & b <c>"), "a & b <c>");
|
||||
// Nothing to strip: angle brackets that are not a tag survive.
|
||||
assert_eq!(flatten_html("2 < 3"), "2 < 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_matches_all_forms() {
|
||||
let cases = [
|
||||
@@ -317,13 +432,48 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_validation_keeps_the_site_enabled_on_a_bad_moment() {
|
||||
use super::super::api;
|
||||
|
||||
// The startup decision, not the retry policy: a 5xx/429 while the
|
||||
// container comes up must leave pixiv enabled and say so in the message
|
||||
// the admin gets. The rejected-credential half is not exercised here —
|
||||
// it calls `disable()`, a process-wide flag with no reset, so a test
|
||||
// touching it would order-couple every other pixiv test (the predicate
|
||||
// it keys on is covered by the table below).
|
||||
for err in [
|
||||
PixivError::Status(429),
|
||||
PixivError::Status(503),
|
||||
PixivError::Transient("frame zip download failed: transient".into()),
|
||||
] {
|
||||
let enabled_before = api::enabled();
|
||||
let message = startup_validation(Err(err)).unwrap_err();
|
||||
assert!(message.contains("stays enabled"), "{message}");
|
||||
assert_eq!(
|
||||
api::enabled(),
|
||||
enabled_before,
|
||||
"a bad moment must not disable the site"
|
||||
);
|
||||
}
|
||||
assert!(startup_validation(Ok(())).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_retryable_classifies_transient_and_permanent() {
|
||||
// Transient: network errors, explicit transient, pixiv 429/5xx.
|
||||
// Transient: network errors, explicit transient, pixiv 429/5xx, and a
|
||||
// failed media download (the frame zip's own bad moment).
|
||||
assert!(is_retryable(&FetchError::Transient("429".into())));
|
||||
assert!(is_retryable(&FetchError::RateLimited {
|
||||
site: "pixiv",
|
||||
retry_after_secs: 30
|
||||
}));
|
||||
assert!(is_retryable(&FetchError::Pixiv(PixivError::Status(429))));
|
||||
assert!(is_retryable(&FetchError::Pixiv(PixivError::Status(500))));
|
||||
assert!(is_retryable(&FetchError::Pixiv(PixivError::Status(503))));
|
||||
assert!(is_retryable(&FetchError::Pixiv(PixivError::Transient(
|
||||
"frame zip download failed: transient: media status 429".into()
|
||||
))));
|
||||
// Permanent: pixiv 4xx (bad/expired token, forbidden, not found),
|
||||
// api/auth errors, unparseable bodies, not-found/blocked/sensitive.
|
||||
assert!(!is_retryable(&FetchError::Pixiv(PixivError::Status(400))));
|
||||
@@ -412,14 +562,19 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_page_without_any_original_is_empty() {
|
||||
fn single_page_without_any_original_falls_back_to_large() {
|
||||
let v = illust_json("illust", 1, None, None, vec![], 0);
|
||||
let fetched: Fetched = parse(v).into();
|
||||
assert!(fetched.media.is_empty());
|
||||
// Neither `meta_single_page.original_image_url` nor `image_urls.
|
||||
// original` is set: the work is still deliverable as `large`.
|
||||
match fetched.media.as_slice() {
|
||||
[Media::Illustration { url, .. }] => assert_eq!(url, "large.jpg"),
|
||||
other => panic!("expected the large variant, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_page_skips_pages_without_original() {
|
||||
fn multi_page_keeps_pages_without_original() {
|
||||
let v = illust_json(
|
||||
"illust",
|
||||
2,
|
||||
@@ -432,17 +587,27 @@ mod tests {
|
||||
0,
|
||||
);
|
||||
let fetched: Fetched = parse(v).into();
|
||||
assert_eq!(fetched.media.len(), 1);
|
||||
// Both pages arrive: the restricted one (no `original`) sends its
|
||||
// `large` instead of vanishing — a dropped page is a missing picture.
|
||||
let urls: Vec<&str> = fetched
|
||||
.media
|
||||
.iter()
|
||||
.map(|media| match media {
|
||||
Media::Illustration { url, .. } => url.as_str(),
|
||||
other => panic!("expected Illustration, got {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(urls, vec!["l1.jpg", "https://i.pximg.net/p2.jpg"]);
|
||||
match &fetched.media[0] {
|
||||
Media::Illustration {
|
||||
url,
|
||||
thumbnail_url,
|
||||
fallback_url,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(url, "https://i.pximg.net/p2.jpg");
|
||||
assert_eq!(thumbnail_url.as_deref(), Some("m2.jpg"));
|
||||
assert_eq!(fallback_url.as_deref(), Some("l2.jpg"));
|
||||
assert_eq!(thumbnail_url.as_deref(), Some("m1.jpg"));
|
||||
// `large` is the item itself here, so it is not also a
|
||||
// smaller variant of itself.
|
||||
assert_eq!(fallback_url.as_deref(), Some("l1.jpg"));
|
||||
}
|
||||
other => panic!("expected Illustration, got {other:?}"),
|
||||
}
|
||||
@@ -474,7 +639,7 @@ mod tests {
|
||||
);
|
||||
// Empty format falls back to the built-in caption.
|
||||
assert_eq!(fetched.caption_with(""), fetched.caption);
|
||||
assert_eq!(fetched.site_name(), "pixiv");
|
||||
assert_eq!(fetched.site_id, "pixiv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,7 +2,7 @@ mod api;
|
||||
mod interface;
|
||||
mod model;
|
||||
|
||||
pub use api::{PixivAPI, PixivError, disable, fetch, validate};
|
||||
pub use api::{PixivError, disable, fetch, validate};
|
||||
pub use interface::{
|
||||
Illustration, PATTERN, PixivSite, cache_key, enabled, fetch_from_url, is_retryable,
|
||||
media_headers,
|
||||
|
||||
@@ -6,7 +6,14 @@ use serde::Deserialize;
|
||||
pub struct IllustrationModel {
|
||||
pub id: u64,
|
||||
pub title: String,
|
||||
pub r#type: TypeModel,
|
||||
/// The artwork's description as the app API returns it — HTML in most
|
||||
/// works (`<br />`, `<a href>`, sometimes `<p>`), empty for many.
|
||||
#[serde(default)]
|
||||
pub caption: String,
|
||||
/// `"illust"` / `"manga"` / `"ugoira"`; only ugoira changes how the
|
||||
/// artwork is fetched (a zip of frames to encode), so the rest is kept as
|
||||
/// the string the API sent rather than as variants nothing matches.
|
||||
pub r#type: String,
|
||||
pub image_urls: ImageUrlsModel,
|
||||
pub user: UserInfoModel,
|
||||
pub tags: Vec<IllustrationTagModel>,
|
||||
@@ -18,16 +25,6 @@ pub struct IllustrationModel {
|
||||
pub meta_pages: Vec<MetaPageModel>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub enum TypeModel {
|
||||
#[serde(rename = "illust")]
|
||||
Illust,
|
||||
#[serde(rename = "manga")]
|
||||
Manga,
|
||||
#[serde(rename = "ugoira")]
|
||||
Ugoira,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UserInfoModel {
|
||||
pub id: u64,
|
||||
|
||||
@@ -130,14 +130,9 @@ pub async fn fetch(id: &str) -> Result<Tweet, FetchError> {
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
log::warn!("twitter auth fetch {id}: HTTP {status}");
|
||||
return match status.as_u16() {
|
||||
404 | 410 => Err(FetchError::NotFound),
|
||||
_ => Err(FetchError::Transient(format!(
|
||||
"twitter auth status {status}"
|
||||
))),
|
||||
};
|
||||
return Err(crate::site::status_error("twitter auth", &response));
|
||||
}
|
||||
let text = response.text().await?;
|
||||
let text = crate::site::response_text(response, "twitter auth").await?;
|
||||
let json: Value = serde_json::from_str(&text)?;
|
||||
let result = parse_tweet_result(&json, id)?;
|
||||
let syndication_shape = to_syndication_shape(&result).ok_or_else(|| {
|
||||
@@ -146,7 +141,7 @@ pub async fn fetch(id: &str) -> Result<Tweet, FetchError> {
|
||||
"missing tweet fields in GraphQL response",
|
||||
)))
|
||||
})?;
|
||||
Tweet::from_syndication_json(&syndication_shape.to_string()).map_err(FetchError::Json)
|
||||
Tweet::from_syndication_value(syndication_shape).map_err(FetchError::Json)
|
||||
}
|
||||
|
||||
/// Locates the tweet for `id` in a `TweetDetail` response and unwraps
|
||||
@@ -220,7 +215,7 @@ fn normalize_tweet_result(result: &Value) -> Result<Value, FetchError> {
|
||||
}
|
||||
|
||||
/// Maps a GraphQL `{core, legacy, ...}` tweet onto the syndication JSON
|
||||
/// shape [`Tweet::from_syndication_json`] parses, so the existing text /
|
||||
/// shape [`Tweet::from_syndication_value`] parses, so the existing text /
|
||||
/// media handling (t.co expansion, `name=orig`, mp4 variant) is reused.
|
||||
fn to_syndication_shape(tweet: &Value) -> Option<Value> {
|
||||
let legacy = tweet.get("legacy")?;
|
||||
@@ -305,7 +300,7 @@ mod tests {
|
||||
let json = conversation(tweet_result());
|
||||
let result = parse_tweet_result(&json, "2083868672721039569").unwrap();
|
||||
let shape = to_syndication_shape(&result).unwrap();
|
||||
let tweet = Tweet::from_syndication_json(&shape.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(shape).unwrap();
|
||||
let fetched: crate::site::Fetched = tweet.into();
|
||||
|
||||
assert!(fetched.sensitive);
|
||||
@@ -327,7 +322,8 @@ mod tests {
|
||||
"https://x.com/nsfw_author/status/2083868672721039569"
|
||||
);
|
||||
// The appended media short link (no URL-entity mapping) is stripped.
|
||||
assert_eq!(fetched.title, "nsfw content");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "nsfw content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::model;
|
||||
use crate::media::Media;
|
||||
use crate::site::{FetchError, Fetched, Site, SiteFuture};
|
||||
use html_escape::{decode_html_entities, encode_double_quoted_attribute, encode_text};
|
||||
use html_escape::{decode_html_entities, encode_text};
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
@@ -30,8 +30,12 @@ pub static PATTERN: LazyLock<Regex> = LazyLock::new(|| {
|
||||
Regex::new(r"^(?:https?://)?(?:www\.|mobile\.)?(?:x|twitter|fixvx|vxtwitter|fixupx|fxtwitter)\.com/[^.]+/status/(\d+)").unwrap()
|
||||
});
|
||||
|
||||
pub fn enabled() -> bool {
|
||||
true
|
||||
/// Cache key for a twitter URL: `"twitter:<id>"`. The prefix is the site id
|
||||
/// used for caption-format lookup and link-cache keys.
|
||||
pub fn cache_key(url: &str) -> Option<String> {
|
||||
PATTERN
|
||||
.captures(url)
|
||||
.map(|caps| format!("twitter:{}", &caps[1]))
|
||||
}
|
||||
|
||||
pub async fn fetch_from_url(url: &str) -> Result<Fetched, FetchError> {
|
||||
@@ -43,70 +47,31 @@ pub async fn fetch_from_url(url: &str) -> Result<Fetched, FetchError> {
|
||||
match fetch(id).await {
|
||||
Ok(tweet) => Ok(tweet.into()),
|
||||
// Syndication withholds NSFW/age-restricted tweets (empty `{}`).
|
||||
// Retry as the logged-in user when TWITTER_AUTH_TOKEN is set;
|
||||
// otherwise degrade to an empty result (the bot replies
|
||||
// "No media found").
|
||||
// Retry as the logged-in user when TWITTER_AUTH_TOKEN is set; without
|
||||
// the token the withholding is reported as `Sensitive`, so the bot can
|
||||
// answer "age-restricted / needs TWITTER_AUTH_TOKEN" instead of the
|
||||
// misleading "No media found".
|
||||
Err(FetchError::Sensitive) => {
|
||||
if super::auth::enabled() {
|
||||
match super::auth::fetch(id).await {
|
||||
Ok(tweet) => Ok(tweet.into()),
|
||||
// The tweet is genuinely gone (deleted / suspended /
|
||||
// tombstoned): report it instead of degrading to an
|
||||
// empty result ("No media found"). Only unexpected
|
||||
// fallback failures (network, parse) keep the NSFW
|
||||
// placeholder.
|
||||
Err(FetchError::NotFound) => Err(FetchError::NotFound),
|
||||
// Deleted/suspended (tombstoned) and unexpected fallback
|
||||
// failures keep their own class: the bot reports what
|
||||
// actually happened rather than "No media found".
|
||||
Err(e) => {
|
||||
log::warn!("twitter auth fallback failed for {id}: {e}");
|
||||
Ok(empty_fetched(url))
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::debug!("tweet {id} is sensitive; set TWITTER_AUTH_TOKEN to fetch NSFW media");
|
||||
Ok(empty_fetched(url))
|
||||
Err(FetchError::Sensitive)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache key for a twitter URL: `"twitter:<id>"`. The prefix is the site id
|
||||
/// used for caption-format lookup and link-cache keys.
|
||||
pub fn cache_key(url: &str) -> Option<String> {
|
||||
PATTERN
|
||||
.captures(url)
|
||||
.map(|caps| format!("twitter:{}", &caps[1]))
|
||||
}
|
||||
|
||||
/// Twitter's fetch-retry policy: transient classes only. Not-found, blocked,
|
||||
/// sensitive (NSFW withholding) and parse failures are permanent — retrying
|
||||
/// them only wastes attempts against the syndication endpoint.
|
||||
pub fn is_retryable(err: &FetchError) -> bool {
|
||||
matches!(err, FetchError::Http(_) | FetchError::Transient(_))
|
||||
}
|
||||
|
||||
/// twimg URLs need no extra headers (no hotlink protection).
|
||||
pub fn media_headers(_url: &str) -> Option<Vec<(&'static str, String)>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// A Fetched with no media for withheld tweets: the bot replies
|
||||
/// "No media found" and moves on instead of erroring.
|
||||
fn empty_fetched(url: &str) -> Fetched {
|
||||
Fetched {
|
||||
source_url: url.to_string(),
|
||||
// The raw user-supplied URL goes into an HTML caption; escape it so
|
||||
// crafted links cannot break the parse (Telegram 400).
|
||||
caption: encode_text(url).into_owned(),
|
||||
title: String::new(),
|
||||
media: vec![],
|
||||
sensitive: true,
|
||||
site_id: "twitter",
|
||||
render_data: None,
|
||||
_keep_alive: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches a tweet from the syndication endpoint. Deleted/blocked tweets
|
||||
/// surface as `FetchError::NotFound`; withheld content (empty tombstone,
|
||||
/// age-restricted) as `FetchError::Sensitive`.
|
||||
@@ -122,19 +87,19 @@ pub async fn fetch(id: &str) -> Result<Tweet, FetchError> {
|
||||
// 404/410 = gone (permanent); 429/5xx = transient and retried by fetch.
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return match status.as_u16() {
|
||||
404 | 410 => Err(FetchError::NotFound),
|
||||
_ => Err(FetchError::Transient(format!("twitter status {status}"))),
|
||||
};
|
||||
return Err(crate::site::status_error("twitter", &response));
|
||||
}
|
||||
let text = response.text().await?;
|
||||
// Classify before parsing the tweet (see [`parse_syndication_body`]).
|
||||
parse_syndication_body(&text)?;
|
||||
Tweet::from_syndication_json(&text).map_err(FetchError::Json)
|
||||
let text = crate::site::response_text(response, "twitter").await?;
|
||||
// Classify before building the tweet (see [`parse_syndication_body`]), and
|
||||
// build it from the value that classification already parsed: this used to
|
||||
// scan and allocate the whole body twice.
|
||||
let body = parse_syndication_body(&text)?;
|
||||
Tweet::from_syndication_value(body).map_err(FetchError::Json)
|
||||
}
|
||||
|
||||
/// Parses and classifies a syndication response body. `Ok` means the body is
|
||||
/// a real tweet payload; `Err` carries the permanent error class:
|
||||
/// Parses and classifies a syndication response body. `Ok` carries the parsed
|
||||
/// body on for the caller to build the tweet from — the same value, so the
|
||||
/// text is never parsed twice; `Err` carries the permanent error class:
|
||||
/// - `NotFound`: an `errors` array (deleted/blocked) or a `TweetTombstone`
|
||||
/// **with a reason** — "This Post was deleted by the Post author." /
|
||||
/// "This Post is from a suspended account." (the tweet is gone).
|
||||
@@ -165,7 +130,18 @@ fn parse_syndication_body(text: &str) -> Result<serde_json::Value, FetchError> {
|
||||
return Err(FetchError::NotFound);
|
||||
}
|
||||
if body.get("id_str").is_none() {
|
||||
return Err(FetchError::Sensitive);
|
||||
// Syndication answers an empty `{}` for withheld (NSFW /
|
||||
// age-restricted) tweets: the documented case, kept as `Sensitive`
|
||||
// because it is what triggers the logged-in auth fallback.
|
||||
if body.as_object().is_some_and(|object| object.is_empty()) {
|
||||
return Err(FetchError::Sensitive);
|
||||
}
|
||||
// Any other shape is not a tweet: an interstitial, a truncated body,
|
||||
// a change on their side. Reporting that as withheld content told the
|
||||
// user to set TWITTER_AUTH_TOKEN for something auth cannot fix.
|
||||
return Err(FetchError::Transient(
|
||||
"unexpected syndication body".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
@@ -223,17 +199,16 @@ impl Tweet {
|
||||
}
|
||||
|
||||
pub fn caption(&self) -> String {
|
||||
format!(
|
||||
"{url}\n<a href=\"{author_url}\">{author}</a>: {text}",
|
||||
url = encode_double_quoted_attribute(&self.url()),
|
||||
author_url = encode_double_quoted_attribute(&self.author_url()),
|
||||
author = encode_text(&self.author),
|
||||
text = encode_text(&self.text),
|
||||
)
|
||||
crate::site::caption(&self.url(), &self.author_url(), &self.author, &self.text)
|
||||
}
|
||||
|
||||
pub fn from_syndication_json(raw_json: &str) -> Result<Self, serde_json::Error> {
|
||||
let json: model::SyndicationTweet = serde_json::from_str(raw_json)?;
|
||||
/// Builds a tweet from an already-parsed syndication body. Takes the value
|
||||
/// rather than JSON text so a caller that had to parse it anyway (the
|
||||
/// fetch path classifies the raw shape; the auth fallback builds the shape
|
||||
/// itself) does not pay for a second scan — `from_value` moves the strings
|
||||
/// out instead.
|
||||
pub fn from_syndication_value(body: serde_json::Value) -> Result<Self, serde_json::Error> {
|
||||
let json: model::SyndicationTweet = serde_json::from_value(body)?;
|
||||
let id = json.id_str;
|
||||
// Expand the user's t.co short links to their real destinations and
|
||||
// strip the appended media short link, mirroring FxEmbed's linkFixer
|
||||
@@ -255,7 +230,6 @@ impl Tweet {
|
||||
for item in json.media_details {
|
||||
match item.media_type.as_str() {
|
||||
"photo" => media.push(Media::Illustration {
|
||||
title: None,
|
||||
url: original_twimg_url(&item.media_url_https),
|
||||
thumbnail_url: None,
|
||||
// The param-less base URL is a reduced-size variant;
|
||||
@@ -263,12 +237,10 @@ impl Tweet {
|
||||
fallback_url: Some(item.media_url_https.clone()),
|
||||
}),
|
||||
"video" => media.push(Media::Video {
|
||||
title: None,
|
||||
url: mp4_variant(&item),
|
||||
thumbnail_url: item.media_url_https,
|
||||
}),
|
||||
"animated_gif" => media.push(Media::Animated {
|
||||
title: None,
|
||||
url: mp4_variant(&item),
|
||||
thumbnail_url: item.media_url_https,
|
||||
}),
|
||||
@@ -352,17 +324,19 @@ impl From<Tweet> for Fetched {
|
||||
fn from(tweet: Tweet) -> Self {
|
||||
let url = tweet.url();
|
||||
let author_url = tweet.author_url();
|
||||
// A tweet has no title: its text is all content.
|
||||
let render_data = Some(crate::site::RenderData {
|
||||
url: url.clone(),
|
||||
author: encode_text(&tweet.author).into_owned(),
|
||||
author_url: author_url.clone(),
|
||||
title: encode_text(&tweet.text).into_owned(),
|
||||
title: String::new(),
|
||||
content: encode_text(&tweet.text).into_owned(),
|
||||
tags: String::new(),
|
||||
});
|
||||
Fetched {
|
||||
source_url: url,
|
||||
caption: tweet.caption(),
|
||||
title: tweet.text.clone(),
|
||||
title: String::new(),
|
||||
content: tweet.text.clone(),
|
||||
media: tweet.media,
|
||||
sensitive: tweet.sensitive,
|
||||
site_id: "twitter",
|
||||
@@ -432,12 +406,13 @@ mod tests {
|
||||
"entities": { "urls": [] },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
// The appended media short link is stripped, then entities decoded.
|
||||
assert_eq!(tweet.text, ">^ω^< & more 'quoted'");
|
||||
assert_eq!(tweet.author, "O'Brien");
|
||||
let fetched: Fetched = tweet.into();
|
||||
assert_eq!(fetched.title, ">^ω^< & more 'quoted'");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, ">^ω^< & more 'quoted'");
|
||||
// The caption escapes the raw text exactly once (encode_text covers
|
||||
// & < >; apostrophes stay literal — they are harmless in text).
|
||||
assert!(
|
||||
@@ -461,20 +436,6 @@ mod tests {
|
||||
assert_eq!(cache_key("https://example.com/1"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_retryable_classifies_transient_and_permanent() {
|
||||
// Transient: network errors and explicit transient statuses (the
|
||||
// `Http` arm shares this match arm with `Transient`).
|
||||
assert!(is_retryable(&FetchError::Transient("429".into())));
|
||||
// Permanent: gone, blocked, withheld, oversized, unparseable.
|
||||
assert!(!is_retryable(&FetchError::NotFound));
|
||||
assert!(!is_retryable(&FetchError::Blocked));
|
||||
assert!(!is_retryable(&FetchError::Sensitive));
|
||||
assert!(!is_retryable(&FetchError::TooLarge));
|
||||
let json_err = serde_json::from_str::<serde_json::Value>("x").unwrap_err();
|
||||
assert!(!is_retryable(&FetchError::Json(json_err)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_json_converts_to_fetched() {
|
||||
let raw = fixture(serde_json::json!([
|
||||
@@ -490,13 +451,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
]));
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
let fetched: Fetched = tweet.into();
|
||||
assert_eq!(
|
||||
fetched.source_url,
|
||||
"https://x.com/author_handle/status/861627479294746624"
|
||||
);
|
||||
assert_eq!(fetched.title, "a & b <c>");
|
||||
assert_eq!(fetched.title, "");
|
||||
assert_eq!(fetched.content, "a & b <c>");
|
||||
assert!(fetched.sensitive);
|
||||
assert_eq!(fetched.media.len(), 2);
|
||||
match &fetched.media[0] {
|
||||
@@ -524,14 +486,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_only_has_no_media() {
|
||||
let raw = fixture(serde_json::json!([]));
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let fetched: Fetched = tweet.into();
|
||||
assert!(fetched.media.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_gif_maps_to_animated() {
|
||||
let raw = fixture(serde_json::json!([
|
||||
@@ -543,61 +497,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
]));
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
assert!(matches!(&tweet.media[0], Media::Animated { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_strips_trailing_media_short_link() {
|
||||
// Real syndication shape: the appended media short link sits after the
|
||||
// visible text; the unmapped t.co link is stripped by content.
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": "hello world https://t.co/abc123",
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, "hello world");
|
||||
assert!(!tweet.caption().contains("t.co"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_strips_trailing_link_regardless_of_index_units() {
|
||||
// Real tweet 2084567054481571919: the visible text is 30 code points
|
||||
// but 41 UTF-16 units, and the two endpoints historically reported
|
||||
// display_text_range in different units (UTF-16 on syndication, code
|
||||
// points on GraphQL). The FxEmbed-style content-based strip ignores
|
||||
// the range entirely, so the appended media link is removed for any
|
||||
// response shape.
|
||||
let text = "妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero https://t.co/XnIi83EkEB";
|
||||
let visible = "妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero";
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "2084567054481571919",
|
||||
"text": text,
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, visible, "left a partial link");
|
||||
assert!(!tweet.caption().contains("t.co"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_strips_trailing_short_link_without_entities() {
|
||||
// No URL entities at all: the leftover t.co link is stripped by the
|
||||
// content regex.
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": "hello https://t.co/abc123",
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, "hello");
|
||||
// visible text and there are no URL entities, so the unmapped t.co link
|
||||
// is stripped by content alone. The second row is real tweet
|
||||
// 2084567054481571919 (30 code points but 41 UTF-16 units, and the two
|
||||
// endpoints historically reported `display_text_range` in different
|
||||
// units): a content-based strip cannot leave a partial link behind for
|
||||
// either unit system.
|
||||
for (text, visible) in [
|
||||
("hello world https://t.co/abc123", "hello world"),
|
||||
(
|
||||
"妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero https://t.co/XnIi83EkEB",
|
||||
"妄想𝑨𝒅𝒅𝒊𝒄𝒕𝒊𝒐𝒏…🩷💚❤️\n#ゼンゼロ #zzzero",
|
||||
),
|
||||
] {
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": text,
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
assert_eq!(tweet.text, visible, "left a partial link in {text:?}");
|
||||
assert!(!tweet.caption().contains("t.co"), "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -619,7 +549,7 @@ mod tests {
|
||||
},
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
assert_eq!(
|
||||
tweet.text,
|
||||
"Test Tweet with @mentionThis $twtr http://bit.ly/2pUk4be #hashtag"
|
||||
@@ -638,7 +568,7 @@ mod tests {
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
assert_eq!(tweet.text, "check #tag");
|
||||
}
|
||||
|
||||
@@ -661,28 +591,11 @@ mod tests {
|
||||
},
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
let tweet = Tweet::from_syndication_value(raw).unwrap();
|
||||
assert_eq!(tweet.text, "see for context");
|
||||
assert!(!tweet.caption().contains("t.co"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_text_keeps_multibyte_text() {
|
||||
// Text-only tweet: no short links, the multibyte text is untouched.
|
||||
let text = "コミティア落ちたので、明日は行きません。🙏ごめんなさい";
|
||||
let units: Vec<u16> = text.encode_utf16().collect();
|
||||
assert_eq!(units.len(), 28);
|
||||
let raw = serde_json::json!({
|
||||
"__typename": "Tweet",
|
||||
"id_str": "1",
|
||||
"text": text,
|
||||
"user": { "name": "N", "screen_name": "h" },
|
||||
"mediaDetails": []
|
||||
});
|
||||
let tweet = Tweet::from_syndication_json(&raw.to_string()).unwrap();
|
||||
assert_eq!(tweet.text, text, "full text kept intact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_twimg_url_rewrites_photo_urls() {
|
||||
assert_eq!(
|
||||
@@ -706,9 +619,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn syndication_token_matches_js_formula() {
|
||||
// JS: ((861627479294746624 / 1e15) * PI).toString(36) == "236.vrsocvda"
|
||||
let token = syndication_token(861627479294746624);
|
||||
assert!(token.starts_with("236.v"), "got {token}");
|
||||
// JS: ((861627479294746624 / 1e15) * PI).toString(36) == "236.vrsocvda".
|
||||
// This loop truncates ten base-36 fraction digits instead of rendering
|
||||
// the shortest round-tripping one, so it agrees with JS on the stem and
|
||||
// diverges in the tail (`…d9ui` vs `…da`). Pinned exactly, because the
|
||||
// token is a fixed function of the id: a stub or a wrong constant must
|
||||
// not pass. The endpoint currently serves public tweets regardless of
|
||||
// the token, which is why the tail is left as is.
|
||||
assert_eq!(syndication_token(861627479294746624), "236.vrsocvd9ui");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -776,6 +694,17 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_unexpected_shape_is_transient_not_withheld() {
|
||||
// A 200 that is not a tweet at all (an interstitial, a truncated
|
||||
// body) must not be reported as withheld content: that message tells
|
||||
// the user to set TWITTER_AUTH_TOKEN, which cannot fix it.
|
||||
match parse_syndication_body("{\"foo\":1}") {
|
||||
Err(FetchError::Transient(_)) => {}
|
||||
other => panic!("expected Transient, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn syndication_tweet_body_passes() {
|
||||
let raw = fixture(serde_json::json!([]));
|
||||
|
||||
@@ -2,6 +2,4 @@ mod auth;
|
||||
mod interface;
|
||||
mod model;
|
||||
|
||||
pub use interface::{
|
||||
PATTERN, Tweet, TwitterSite, cache_key, enabled, fetch_from_url, is_retryable, media_headers,
|
||||
};
|
||||
pub use interface::{PATTERN, Tweet, TwitterSite, cache_key, fetch_from_url};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "xmedia-bot"
|
||||
version = "1.6.0"
|
||||
version = "1.9.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -13,8 +13,8 @@ pretty_env_logger = "0.5"
|
||||
dotenv = "0.15"
|
||||
url = "2.5.2"
|
||||
html-escape = "0.2"
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
rand = "0.8"
|
||||
rusqlite = { version = "0.40", features = ["bundled"] }
|
||||
rand = "0.10"
|
||||
tempfile = "3"
|
||||
parking_lot = "0.12"
|
||||
bytes = "1"
|
||||
|
||||
+152
-31
@@ -1,5 +1,6 @@
|
||||
//! Central env handling. The only other places that read env are
|
||||
//! `Bot::from_env` (TELOXIDE_TOKEN) and x-media (PIXIV_REFRESH_TOKEN).
|
||||
//! `Bot::from_env` (TELOXIDE_TOKEN) and x-media (PIXIV_REFRESH_TOKEN,
|
||||
//! TWITTER_AUTH_TOKEN, BILIBILI_COOKIE).
|
||||
|
||||
use std::env;
|
||||
use std::net::IpAddr;
|
||||
@@ -12,6 +13,10 @@ pub struct Config {
|
||||
pub edit_message_ttl: Duration,
|
||||
/// LINK_CACHE_TTL_SECONDS, default 604800 (7 days).
|
||||
pub link_cache_ttl: Duration,
|
||||
/// CAPTION_QUOTE_TEXT_CHARS, default 200: a post whose text (title plus
|
||||
/// content) is at least this many characters gets that text wrapped in an
|
||||
/// expandable blockquote inside its caption. `0` disables the wrap.
|
||||
pub caption_quote_text_chars: usize,
|
||||
// Webhook settings (moved out of main; names/defaults unchanged).
|
||||
pub webhook_enabled: bool,
|
||||
pub webhook_url: Option<url::Url>,
|
||||
@@ -29,58 +34,60 @@ impl Config {
|
||||
fn parse_u64(name: &str, default: u64) -> u64 {
|
||||
match env::var(name) {
|
||||
Ok(v) => v.parse::<u64>().unwrap_or_else(|_| {
|
||||
log::warn!("invalid {name}={v:?}; using default {default}");
|
||||
log::warn!("invalid {name}; using default {default}");
|
||||
default
|
||||
}),
|
||||
Err(_) => default,
|
||||
}
|
||||
}
|
||||
|
||||
let admin_ids = match env::var("BOT_ADMIN") {
|
||||
Ok(s) => {
|
||||
let (ids, bad): (Vec<_>, Vec<_>) = s
|
||||
/// A setting that must parse when it is set: an unparseable value warns
|
||||
/// (naming the variable) and counts as unset.
|
||||
fn parse_opt<T: std::str::FromStr>(name: &str) -> Option<T> {
|
||||
env::var(name).ok().and_then(|s| {
|
||||
s.parse::<T>().ok().or_else(|| {
|
||||
log::warn!("invalid {name}");
|
||||
None
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
let admin_ids = env::var("BOT_ADMIN")
|
||||
.map(|s| {
|
||||
let mut bad = Vec::new();
|
||||
let ids: Vec<i64> = s
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|part| !part.is_empty())
|
||||
.partition(|part| part.parse::<i64>().is_ok());
|
||||
.filter_map(|part| match part.parse::<i64>() {
|
||||
Ok(id) => Some(id),
|
||||
Err(_) => {
|
||||
bad.push(part);
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !bad.is_empty() {
|
||||
log::warn!("BOT_ADMIN: ignoring non-numeric ids: {bad:?}");
|
||||
log::warn!("BOT_ADMIN: ignoring {} non-numeric id(s)", bad.len());
|
||||
}
|
||||
ids.into_iter()
|
||||
.filter_map(|p| p.parse::<i64>().ok())
|
||||
.collect()
|
||||
}
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
ids
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let edit_message_ttl =
|
||||
Duration::from_secs(parse_u64("EDIT_MESSAGE_TTL_SECONDS", 24 * 3600));
|
||||
let link_cache_ttl =
|
||||
Duration::from_secs(parse_u64("LINK_CACHE_TTL_SECONDS", 7 * 24 * 3600));
|
||||
let caption_quote_text_chars = parse_u64("CAPTION_QUOTE_TEXT_CHARS", 200) as usize;
|
||||
|
||||
let webhook_enabled = env::var("WEBHOOK")
|
||||
.is_ok_and(|v| matches!(v.to_lowercase().as_str(), "true" | "yes" | "1"));
|
||||
// The webhook settings are consumed by `.expect()` in main when
|
||||
// WEBHOOK=true, so an unparseable value fails fast at startup with a
|
||||
// clear message; still log here for the WEBHOOK=false case.
|
||||
let webhook_url = env::var("WEBHOOK_URL").ok().and_then(|s| {
|
||||
s.parse::<url::Url>().ok().or_else(|| {
|
||||
log::warn!("invalid WEBHOOK_URL={s:?}");
|
||||
None
|
||||
})
|
||||
});
|
||||
let webhook_listen = env::var("WEBHOOK_LISTEN").ok().and_then(|s| {
|
||||
s.parse::<IpAddr>().ok().or_else(|| {
|
||||
log::warn!("invalid WEBHOOK_LISTEN={s:?}");
|
||||
None
|
||||
})
|
||||
});
|
||||
let webhook_port = env::var("WEBHOOK_PORT").ok().and_then(|s| {
|
||||
s.parse::<u16>().ok().or_else(|| {
|
||||
log::warn!("invalid WEBHOOK_PORT={s:?}");
|
||||
None
|
||||
})
|
||||
});
|
||||
let webhook_url = parse_opt::<url::Url>("WEBHOOK_URL");
|
||||
let webhook_listen = parse_opt::<IpAddr>("WEBHOOK_LISTEN");
|
||||
let webhook_port = parse_opt::<u16>("WEBHOOK_PORT");
|
||||
// Empty strings count as unset (e.g. `-e WEBHOOK_CERT=` to disable a
|
||||
// value that would otherwise come from `.env`).
|
||||
let webhook_cert = env::var("WEBHOOK_CERT").ok().filter(|s| !s.is_empty());
|
||||
@@ -92,6 +99,7 @@ impl Config {
|
||||
admin_ids,
|
||||
edit_message_ttl,
|
||||
link_cache_ttl,
|
||||
caption_quote_text_chars,
|
||||
webhook_enabled,
|
||||
webhook_url,
|
||||
webhook_listen,
|
||||
@@ -101,3 +109,116 @@ impl Config {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The ids an operator's `BOT_ADMIN` yields: blanks dropped, non-numeric
|
||||
/// entries warned about and skipped, the rest kept in order. Parsed once —
|
||||
/// the split used to parse every entry twice.
|
||||
#[test]
|
||||
fn bot_admin_keeps_the_numeric_ids_in_order() {
|
||||
// SAFETY: no other test reads BOT_ADMIN, and the value is restored
|
||||
// before this test returns.
|
||||
let previous = env::var("BOT_ADMIN").ok();
|
||||
unsafe { env::set_var("BOT_ADMIN", " 7 ,abc,42, ,") };
|
||||
let ids = Config::load().admin_ids;
|
||||
match previous {
|
||||
Some(value) => unsafe { env::set_var("BOT_ADMIN", value) },
|
||||
None => unsafe { env::remove_var("BOT_ADMIN") },
|
||||
}
|
||||
assert_eq!(ids, vec![7, 42]);
|
||||
}
|
||||
|
||||
/// The webhook truth table: `Config::load` enables webhook mode only for
|
||||
/// a case-insensitive `true|yes|1`, and everything else — including the
|
||||
/// classic misspelling "on", which an operator would expect to work — is
|
||||
/// polling. Without this pin a typo silently ran a different transport
|
||||
/// (with P0's fail-fast secret check, or with no listener at all).
|
||||
#[test]
|
||||
fn webhook_flag_is_a_case_insensitive_truth_table() {
|
||||
// SAFETY: no other test *mutates* WEBHOOK, the value is restored
|
||||
// before this test returns, and concurrent Config::load callers in
|
||||
// other tests assert fields other than webhook_enabled.
|
||||
let previous = env::var("WEBHOOK").ok();
|
||||
for (value, expected) in [
|
||||
("true", true),
|
||||
("TRUE", true),
|
||||
("Yes", true),
|
||||
("1", true),
|
||||
("false", false),
|
||||
("on", false),
|
||||
("", false),
|
||||
] {
|
||||
unsafe { env::set_var("WEBHOOK", value) };
|
||||
assert_eq!(
|
||||
Config::load().webhook_enabled,
|
||||
expected,
|
||||
"WEBHOOK={value:?}"
|
||||
);
|
||||
}
|
||||
match previous {
|
||||
Some(value) => unsafe { env::set_var("WEBHOOK", value) },
|
||||
None => unsafe { env::remove_var("WEBHOOK") },
|
||||
}
|
||||
}
|
||||
|
||||
/// A malformed TTL warns and falls back to the default instead of being
|
||||
/// parsed as 0 — the difference between a 24h edit-prompt expiry and a
|
||||
/// prompt that expires instantly, which an operator would only notice
|
||||
/// when the buttons stop working.
|
||||
#[test]
|
||||
fn invalid_ttl_falls_back_to_the_default() {
|
||||
// SAFETY: no other test *mutates* EDIT_MESSAGE_TTL_SECONDS; restored
|
||||
// below, and no other test asserts the TTL field.
|
||||
let previous = env::var("EDIT_MESSAGE_TTL_SECONDS").ok();
|
||||
unsafe { env::set_var("EDIT_MESSAGE_TTL_SECONDS", "not-a-number") };
|
||||
let invalid = Config::load().edit_message_ttl;
|
||||
unsafe { env::set_var("EDIT_MESSAGE_TTL_SECONDS", "120") };
|
||||
let valid = Config::load().edit_message_ttl;
|
||||
match previous {
|
||||
Some(value) => unsafe { env::set_var("EDIT_MESSAGE_TTL_SECONDS", value) },
|
||||
None => unsafe { env::remove_var("EDIT_MESSAGE_TTL_SECONDS") },
|
||||
}
|
||||
assert_eq!(
|
||||
invalid,
|
||||
Duration::from_secs(24 * 3600),
|
||||
"an unparseable value falls back to the default"
|
||||
);
|
||||
assert_eq!(
|
||||
valid,
|
||||
Duration::from_secs(120),
|
||||
"a valid value is taken as-is"
|
||||
);
|
||||
}
|
||||
|
||||
/// A blank WEBHOOK_CERT / WEBHOOK_SECRET_TOKEN counts as unset — compose
|
||||
/// injects `${VAR:-}` as an empty string for a commented-out template
|
||||
/// line — while a present value is kept (the `-e VAR=` disable idiom).
|
||||
#[test]
|
||||
fn blank_webhook_cert_and_secret_count_as_unset() {
|
||||
// SAFETY: no other test *mutates* these two, both are restored
|
||||
// below, and no other test asserts them.
|
||||
let prev_cert = env::var("WEBHOOK_CERT").ok();
|
||||
let prev_secret = env::var("WEBHOOK_SECRET_TOKEN").ok();
|
||||
unsafe { env::set_var("WEBHOOK_CERT", "") };
|
||||
unsafe { env::set_var("WEBHOOK_SECRET_TOKEN", "") };
|
||||
let blank = Config::load();
|
||||
unsafe { env::set_var("WEBHOOK_CERT", "/x/cert.pem") };
|
||||
unsafe { env::set_var("WEBHOOK_SECRET_TOKEN", "s3cret") };
|
||||
let present = Config::load();
|
||||
match prev_cert {
|
||||
Some(value) => unsafe { env::set_var("WEBHOOK_CERT", value) },
|
||||
None => unsafe { env::remove_var("WEBHOOK_CERT") },
|
||||
}
|
||||
match prev_secret {
|
||||
Some(value) => unsafe { env::set_var("WEBHOOK_SECRET_TOKEN", value) },
|
||||
None => unsafe { env::remove_var("WEBHOOK_SECRET_TOKEN") },
|
||||
}
|
||||
assert_eq!(blank.webhook_cert, None, "blank must read as unset");
|
||||
assert_eq!(blank.webhook_secret_token, None, "blank must read as unset");
|
||||
assert_eq!(present.webhook_cert.as_deref(), Some("/x/cert.pem"));
|
||||
assert_eq!(present.webhook_secret_token.as_deref(), Some("s3cret"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,91 @@ pub static CONTEXT: LazyLock<AppContext<'static>> =
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
use crate::link_cache::{CachedMedia, CachedMediaKind, CachedPost};
|
||||
use crate::send::{MediaItemPayload, MediaRef};
|
||||
use crate::state::EditMessage;
|
||||
use std::sync::Arc;
|
||||
use teloxide::{ApiError, RequestError};
|
||||
|
||||
/// The edit-before-forward prompt's message id, and the message the prompt
|
||||
/// refers to (the one whose caption a reply swaps).
|
||||
pub(crate) const PROMPT_ID: i64 = 7;
|
||||
pub(crate) const FORWARDED_ID: i64 = 9;
|
||||
|
||||
/// A Telegram API error, for the tests that script a failure.
|
||||
pub(crate) fn api_error(message: &str) -> RequestError {
|
||||
RequestError::Api(ApiError::Unknown(message.to_string()))
|
||||
}
|
||||
|
||||
/// The API error a caption edit that changes nothing answers with — what
|
||||
/// the mocks script for a permanent send failure. A `fn` pointer, so it can
|
||||
/// be handed to `MockSender::scripted` as-is.
|
||||
pub(crate) fn permanent_error() -> RequestError {
|
||||
api_error("Bad Request: message is not modified")
|
||||
}
|
||||
|
||||
/// One photo payload item: `media` in the two flags the tests vary (no
|
||||
/// smaller variant, since that is the field most tests leave alone —
|
||||
/// `send`'s own tests build that case directly).
|
||||
pub(crate) fn photo_item(media: &str, has_spoiler: bool, file_id: bool) -> MediaItemPayload {
|
||||
MediaItemPayload::Photo {
|
||||
media: if file_id {
|
||||
MediaRef::FileId(media.to_string())
|
||||
} else {
|
||||
MediaRef::Source(media.to_string())
|
||||
},
|
||||
has_spoiler,
|
||||
fallback_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached post every test that touches the link cache starts from: one
|
||||
/// photo with a Telegram file id at the canonical URL (key `twitter:1`).
|
||||
/// Tests that need another field mutate the returned value.
|
||||
pub(crate) fn cached_photo() -> CachedPost {
|
||||
CachedPost {
|
||||
url: "https://x.com/u/status/1".into(),
|
||||
caption: "cap".into(),
|
||||
title: "t".into(),
|
||||
content: "c".into(),
|
||||
author: "a".into(),
|
||||
author_url: "au".into(),
|
||||
tags: String::new(),
|
||||
sensitive: false,
|
||||
media: vec![CachedMedia {
|
||||
kind: CachedMediaKind::Photo,
|
||||
file_id: "AgAC-file-id".into(),
|
||||
url: "https://pbs.twimg.com/media/photo.jpg".into(),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// Seeds the live prompt a post-send leaves behind in chat 1: the chat's
|
||||
/// template, a bound forward channel (the prompt's "forward" button
|
||||
/// branches on it) and the record for [`PROMPT_ID`] pointing at
|
||||
/// [`FORWARDED_ID`]. `template` is the record's template — what a reply
|
||||
/// swaps the caption through, `""` for none — and `created_at` backdates
|
||||
/// the record for the expiry cases.
|
||||
pub(crate) async fn seed_prompt(ctx: &AppContext<'_>, template: &str, created_at: i64) {
|
||||
ctx.chat_store
|
||||
.update(1, |data| {
|
||||
data.forward_channel_id = Some(2);
|
||||
data.template
|
||||
.insert("tpl".to_string(), "<b>[]</b>".to_string());
|
||||
data.edit_message.insert(
|
||||
PROMPT_ID,
|
||||
EditMessage {
|
||||
url: "https://x.com/u/status/1".into(),
|
||||
chat_id: 1,
|
||||
forward_message_ids: vec![FORWARDED_ID],
|
||||
template: template.to_string(),
|
||||
created_at,
|
||||
},
|
||||
);
|
||||
})
|
||||
.await
|
||||
.expect("seed prompt state");
|
||||
}
|
||||
|
||||
pub(crate) struct TestStores {
|
||||
_dir: tempfile::TempDir,
|
||||
@@ -88,10 +172,26 @@ pub(crate) mod test_support {
|
||||
&self.chat_store
|
||||
}
|
||||
|
||||
/// The parsed config, mutable so a test can pin a knob (e.g. the
|
||||
/// caption-quote threshold) instead of depending on the environment.
|
||||
pub(crate) fn config_mut(&mut self) -> &mut Config {
|
||||
&mut self.config
|
||||
}
|
||||
|
||||
pub(crate) fn link_cache(&self) -> &LinkCache {
|
||||
&self.link_cache
|
||||
}
|
||||
|
||||
pub(crate) fn task_queue(&self) -> &PersistentTaskQueue {
|
||||
&self.task_queue
|
||||
}
|
||||
|
||||
/// Path to the shared test database, for tests that need to corrupt or
|
||||
/// inspect schema through a separate connection.
|
||||
pub(crate) fn db_path(&self) -> &str {
|
||||
self.pool.path()
|
||||
}
|
||||
|
||||
/// Rows persisted in the task queue: what "queued for retry" looks like
|
||||
/// from the outside.
|
||||
pub(crate) async fn queued_tasks(&self) -> i64 {
|
||||
|
||||
+207
-16
@@ -17,9 +17,11 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Upper bound on pooled (reused) connections and on concurrent DB
|
||||
/// operations per store. Small on purpose: the queue's `BEGIN IMMEDIATE`
|
||||
/// leases serialize writes anyway, and WAL readers rarely need more.
|
||||
const POOL_SIZE: usize = 4;
|
||||
/// operations. Sized to cover every consumer at once — 4 queue workers +
|
||||
/// 8 URL workers, plus dispatcher handlers and the sweep — so the semaphore
|
||||
/// stops queueing operations behind each other; SQLite's single writer
|
||||
/// serializes writes regardless, and WAL readers rarely block.
|
||||
const POOL_SIZE: usize = 16;
|
||||
|
||||
/// A tiny connection pool for one SQLite file. Connections are checked out
|
||||
/// on a blocking thread and returned afterwards; `acquire` opens a new
|
||||
@@ -82,6 +84,26 @@ impl DbPool {
|
||||
pub fn path(&self) -> &str {
|
||||
&self.inner.path
|
||||
}
|
||||
|
||||
/// [`with_conn`] for the many callers that answer a failed statement with
|
||||
/// a default plus one log line: `what` names the operation and `level`
|
||||
/// says how bad it is (`Error` when the failure loses work the caller
|
||||
/// expected, `Warn` when the user is still served).
|
||||
///
|
||||
/// [`with_conn`]: DbPool::with_conn
|
||||
pub async fn with_conn_or<T, F>(&self, level: log::Level, what: &str, default: T, f: F) -> T
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&mut Connection) -> rusqlite::Result<T> + Send + 'static,
|
||||
{
|
||||
match self.with_conn(f).await {
|
||||
Ok(value) => value,
|
||||
Err(e) => {
|
||||
log::log!(level, "{what}: {e}");
|
||||
default
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PoolInner {
|
||||
@@ -115,31 +137,60 @@ pub fn open_db(path: &str) -> rusqlite::Result<Connection> {
|
||||
|
||||
/// Opens the shared DB file, runs the merged schema for all three tables and
|
||||
/// returns a pool for it. One call per process in production (the stores
|
||||
/// share the returned pool); tests call it per tempdir.
|
||||
/// share the returned pool); tests call it per tempdir. The file's directory
|
||||
/// must exist already — [`crate::handlers::db_path`] is what creates it, and
|
||||
/// it is the only caller that takes a path it did not get from a tempdir.
|
||||
pub fn open_store(path: &str) -> rusqlite::Result<Arc<DbPool>> {
|
||||
if let Some(parent) = std::path::Path::new(path).parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
{
|
||||
std::fs::create_dir_all(parent).map_err(rusqlite_error)?;
|
||||
}
|
||||
let conn = open_db(path)?;
|
||||
schema_init(&conn)?;
|
||||
migrate(&conn)?;
|
||||
Ok(Arc::new(DbPool::new(path)))
|
||||
}
|
||||
|
||||
fn rusqlite_error(e: std::io::Error) -> rusqlite::Error {
|
||||
rusqlite::Error::ToSqlConversionFailure(Box::new(e))
|
||||
/// Schema migrations, applied in order and tracked by `PRAGMA user_version`
|
||||
/// (the index in this array + 1 is the version a statement brings the
|
||||
/// database to). Append only — never edit or reorder an entry, or databases
|
||||
/// already past it would skip or repeat work.
|
||||
const MIGRATIONS: &[&str] = &[
|
||||
// 1: lease fencing. A worker's write-backs (`delete`/`reschedule`/the
|
||||
// lease heartbeat) are guarded by the token it was leased with, so a
|
||||
// lease that expired and was re-leased by another worker can no longer be
|
||||
// written by its former holder — which used to duplicate a send or drop
|
||||
// the new holder's retry state, silently.
|
||||
"ALTER TABLE tasks ADD COLUMN lease_token TEXT",
|
||||
// 2: the 300 s sweep prunes the link cache by `created_at`
|
||||
// (`DELETE FROM link_cache WHERE created_at < ?`). Without an index that
|
||||
// is a full scan of every post sent inside the TTL window — up to a week
|
||||
// of them — on every sweep; the `url` primary key cannot serve it.
|
||||
"CREATE INDEX IF NOT EXISTS idx_link_cache_created_at ON link_cache(created_at)",
|
||||
];
|
||||
|
||||
/// Brings an existing database up to [`MIGRATIONS`]. Idempotent: a database
|
||||
/// already at the latest version does no work.
|
||||
fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
|
||||
for (index, statement) in MIGRATIONS.iter().enumerate() {
|
||||
let target = index as i64 + 1;
|
||||
if version >= target {
|
||||
continue;
|
||||
}
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
tx.execute_batch(statement)?;
|
||||
tx.execute_batch(&format!("PRAGMA user_version = {target}"))?;
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates the `tasks`, `chat_state` and `link_cache` tables (idempotent).
|
||||
/// The three stores used to own their own schema; keeping it in one place
|
||||
/// means one initialization for the whole database file.
|
||||
///
|
||||
/// ⚠️ Schema-change reminder (deferred, see `docs/architecture-refactor.md`
|
||||
/// §5): this is a plain `CREATE TABLE IF NOT EXISTS` with no versioning.
|
||||
/// Before any column/table change that must migrate existing databases, land
|
||||
/// the `PRAGMA user_version` migration chain first (`MIGRATIONS: &[&str]` +
|
||||
/// `migrate(conn)`), then restructure this function.
|
||||
/// This is the **baseline** schema (version 0): a fresh database is created
|
||||
/// exactly like this, and anything that must *change* an existing one is
|
||||
/// appended to [`MIGRATIONS`] instead of being edited in here — otherwise a
|
||||
/// database created before the change would never gain the new column and a
|
||||
/// freshly created one would try to apply the migration a second time.
|
||||
pub fn schema_init(conn: &Connection) -> rusqlite::Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS tasks (id TEXT PRIMARY KEY, payload TEXT NOT NULL, \
|
||||
@@ -166,3 +217,143 @@ pub fn now_f64() -> f64 {
|
||||
pub fn unix_now() -> i64 {
|
||||
now_f64() as i64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rusqlite::Connection;
|
||||
|
||||
/// The schema as it shipped *before* the first migration: what an existing
|
||||
/// deployment has on disk when it starts on the new binary. Written out
|
||||
/// literally rather than derived from `schema_init`, so an edit to the
|
||||
/// baseline shows up here instead of being followed silently.
|
||||
const V0_SCHEMA: &str = "CREATE TABLE tasks (id TEXT PRIMARY KEY, payload TEXT NOT NULL, \
|
||||
run_after REAL NOT NULL, attempts INTEGER NOT NULL, status TEXT NOT NULL, \
|
||||
locked_until REAL NOT NULL, created_at REAL NOT NULL); \
|
||||
CREATE INDEX idx_tasks_pending ON tasks(status, run_after); \
|
||||
CREATE TABLE chat_state (chat_id TEXT PRIMARY KEY, payload TEXT NOT NULL); \
|
||||
CREATE TABLE link_cache (url TEXT PRIMARY KEY, payload TEXT NOT NULL, \
|
||||
created_at REAL NOT NULL);";
|
||||
|
||||
/// The migrations that have already shipped, verbatim. Appending is the only
|
||||
/// allowed change: editing one that a database has already applied leaves
|
||||
/// deployments on different schemas with nothing to notice it — the version
|
||||
/// counter says "done" and skips the new text.
|
||||
const SHIPPED_MIGRATIONS: &[&str] = &["ALTER TABLE tasks ADD COLUMN lease_token TEXT"];
|
||||
|
||||
fn columns(conn: &Connection, table: &str) -> Vec<String> {
|
||||
let mut stmt = conn
|
||||
.prepare(&format!("PRAGMA table_info({table})"))
|
||||
.unwrap();
|
||||
let mut names: Vec<String> = stmt
|
||||
.query_map([], |row| row.get::<_, String>(1))
|
||||
.unwrap()
|
||||
.map(Result::unwrap)
|
||||
.collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
fn user_version(conn: &Connection) -> i64 {
|
||||
conn.query_row("PRAGMA user_version", [], |row| row.get(0))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pre_migration_database_upgrades_and_keeps_its_rows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("old.db");
|
||||
{
|
||||
let conn = Connection::open(&path).unwrap();
|
||||
conn.execute_batch(V0_SCHEMA).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO tasks (id, payload, run_after, attempts, status, locked_until, created_at) \
|
||||
VALUES ('task_old', '{\"chat_id\":1}', 0, 0, 'pending', 0, 0)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(user_version(&conn), 0, "the fixture starts un-migrated");
|
||||
assert!(
|
||||
!columns(&conn, "tasks").contains(&"lease_token".to_string()),
|
||||
"the fixture is the pre-migration shape"
|
||||
);
|
||||
}
|
||||
|
||||
let pool = open_store(path.to_str().unwrap()).unwrap();
|
||||
pool.with_conn(|conn| {
|
||||
assert_eq!(user_version(conn), MIGRATIONS.len() as i64);
|
||||
let mut expected = vec![
|
||||
"id",
|
||||
"payload",
|
||||
"run_after",
|
||||
"attempts",
|
||||
"status",
|
||||
"locked_until",
|
||||
"created_at",
|
||||
"lease_token",
|
||||
];
|
||||
expected.sort();
|
||||
assert_eq!(
|
||||
columns(conn, "tasks"),
|
||||
expected,
|
||||
"an upgrade must add the migration's column and nothing else"
|
||||
);
|
||||
let payload: String = conn
|
||||
.query_row(
|
||||
"SELECT payload FROM tasks WHERE id = 'task_old'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(payload, "{\"chat_id\":1}", "rows survive the upgrade");
|
||||
// The link-cache prune's index arrives with the migrations (the
|
||||
// baseline schema has none): without it every sweep scans the
|
||||
// whole table.
|
||||
let index: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master \
|
||||
WHERE type = 'index' AND name = 'idx_link_cache_created_at'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(index, 1, "the migration's index must exist");
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shipped_migrations_are_frozen() {
|
||||
assert!(
|
||||
MIGRATIONS.len() >= SHIPPED_MIGRATIONS.len(),
|
||||
"migrations were removed or reordered, not appended"
|
||||
);
|
||||
for (index, (shipped, current)) in SHIPPED_MIGRATIONS.iter().zip(MIGRATIONS).enumerate() {
|
||||
assert_eq!(
|
||||
shipped,
|
||||
current,
|
||||
"migration {} already shipped: append a new one instead of editing it",
|
||||
index + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_fresh_database_lands_at_the_latest_version() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("fresh.db");
|
||||
let pool = open_store(path.to_str().unwrap()).unwrap();
|
||||
// Every migration is applied on creation, so a deployment that only ever
|
||||
// saw fresh databases is on the same schema as an upgraded one.
|
||||
pool.with_conn(|conn| {
|
||||
assert_eq!(user_version(conn), MIGRATIONS.len() as i64);
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// Opening the same file again is a no-op (the version gate skips it).
|
||||
open_store(path.to_str().unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ use teloxide::types::{CallbackQuery, CallbackQueryId, MessageId};
|
||||
|
||||
/// The `"forward"` button's data.
|
||||
const FORWARD: &str = "forward";
|
||||
/// The `"skip"` button's data: drop the prompt without forwarding.
|
||||
const SKIP: &str = "skip";
|
||||
/// Prefix of a template button's data: `"template|<name>"`.
|
||||
const TEMPLATE_PREFIX: &str = "template|";
|
||||
|
||||
@@ -57,7 +59,8 @@ async fn handle_callback(
|
||||
};
|
||||
// Lazy expiry: a stale record (past the TTL, not yet swept) is dropped.
|
||||
if edit.created_at + ttl_secs <= unix_now() {
|
||||
ctx.chat_store
|
||||
let _ = ctx
|
||||
.chat_store
|
||||
.update(chat_id, |data| {
|
||||
data.edit_message.remove(&prompt_message_id);
|
||||
})
|
||||
@@ -69,7 +72,34 @@ async fn handle_callback(
|
||||
return;
|
||||
}
|
||||
|
||||
log::info!("callback from {chat_id} on prompt {prompt_message_id}: {data}");
|
||||
log::debug!(
|
||||
"callback from {chat_id} on prompt {prompt_message_id}: {}",
|
||||
super::log_escape(data)
|
||||
);
|
||||
if data == SKIP {
|
||||
// Skip works with or without a forward channel: it is the explicit
|
||||
// "do not forward this" answer, and it drops the record so the forward
|
||||
// can never happen later.
|
||||
log::info!("edit-before-forward prompt {prompt_message_id} skipped");
|
||||
let _ = ctx
|
||||
.chat_store
|
||||
.update(chat_id, |data| {
|
||||
data.edit_message.remove(&prompt_message_id);
|
||||
})
|
||||
.await;
|
||||
let _ = ctx
|
||||
.sender
|
||||
.delete_message(ChatId(chat_id), MessageId(prompt_message_id as i32))
|
||||
.await;
|
||||
let _ = ctx
|
||||
.sender
|
||||
.answer_callback_query(
|
||||
callback_query_id,
|
||||
Some("Skipped — nothing was forwarded.".to_string()),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
if data == FORWARD {
|
||||
match chat_data.forward_channel_id {
|
||||
Some(channel_id) => {
|
||||
@@ -77,6 +107,7 @@ async fn handle_callback(
|
||||
from_chat_id: edit.chat_id,
|
||||
to_chat_id: channel_id,
|
||||
message_ids: edit.forward_message_ids.clone(),
|
||||
forward_offset: 0,
|
||||
notify_chat_id: Some(chat_id),
|
||||
notify_message_id: Some(prompt_message_id),
|
||||
};
|
||||
@@ -92,9 +123,24 @@ async fn handle_callback(
|
||||
delay_seconds,
|
||||
task,
|
||||
}) => {
|
||||
log::info!("forward queued for retry in {delay_seconds:.1}s");
|
||||
send::enqueue_retry(ctx.task_queue, *task, delay_seconds).await;
|
||||
("Forward queued for retry.".to_string(), false)
|
||||
// The queued row owns the forward from here (it carries
|
||||
// the message ids itself), so the prompt is settled
|
||||
// either way: leaving it live let a second Confirm copy
|
||||
// the same messages to the channel twice, and let Skip
|
||||
// answer "nothing was forwarded" while the row still
|
||||
// delivered it.
|
||||
let queued =
|
||||
send::enqueue_retry(ctx.task_queue, &task, delay_seconds).await;
|
||||
if queued {
|
||||
log::info!("forward queued for retry in {delay_seconds:.1}s");
|
||||
("Forward queued for retry.".to_string(), true)
|
||||
} else {
|
||||
log::error!("forward retry could not be queued");
|
||||
(
|
||||
"Forward failed and the retry could not be queued.".to_string(),
|
||||
true,
|
||||
)
|
||||
}
|
||||
}
|
||||
Err(send::SendError::Permanent { message, .. }) => {
|
||||
log::error!("forward failed permanently: {message}");
|
||||
@@ -107,7 +153,8 @@ async fn handle_callback(
|
||||
.sender
|
||||
.delete_message(ChatId(chat_id), MessageId(prompt_message_id as i32))
|
||||
.await;
|
||||
ctx.chat_store
|
||||
let _ = ctx
|
||||
.chat_store
|
||||
.update(chat_id, |data| {
|
||||
data.edit_message.remove(&prompt_message_id);
|
||||
})
|
||||
@@ -133,30 +180,50 @@ async fn handle_callback(
|
||||
}
|
||||
|
||||
if let Some(name) = data.strip_prefix(TEMPLATE_PREFIX) {
|
||||
let mut answer = None;
|
||||
if let Some(template_html) = chat_data.template.get(name).cloned()
|
||||
&& let Some(first_forward_id) = edit.forward_message_ids.first().copied()
|
||||
{
|
||||
// Raw template including the [] placeholder (Python parity).
|
||||
let _ = ctx
|
||||
.sender
|
||||
.edit_message_caption(
|
||||
ChatId(chat_id),
|
||||
MessageId(first_forward_id as i32),
|
||||
template_html,
|
||||
)
|
||||
.await;
|
||||
ctx.chat_store
|
||||
.update(chat_id, |data| {
|
||||
if let Some(entry) = data.edit_message.get_mut(&prompt_message_id) {
|
||||
entry.template = name.to_string();
|
||||
}
|
||||
})
|
||||
.await;
|
||||
log::info!("template '{name}' applied to prompt {prompt_message_id}");
|
||||
match super::apply_caption_edit(
|
||||
ctx.sender,
|
||||
ChatId(chat_id),
|
||||
MessageId(first_forward_id as i32),
|
||||
template_html,
|
||||
)
|
||||
.await
|
||||
{
|
||||
super::EditOutcome::Applied => {
|
||||
let _ = ctx
|
||||
.chat_store
|
||||
.update(chat_id, |data| {
|
||||
if let Some(entry) = data.edit_message.get_mut(&prompt_message_id) {
|
||||
entry.template = name.to_string();
|
||||
}
|
||||
})
|
||||
.await;
|
||||
log::info!(
|
||||
"template '{}' applied to prompt {prompt_message_id}",
|
||||
super::log_escape(name)
|
||||
);
|
||||
}
|
||||
// Nothing was applied, so nothing is recorded either: the
|
||||
// prompt keeps rendering through whatever it used before, and
|
||||
// the toast says why (a silently "successful" press left the
|
||||
// caption unchanged).
|
||||
super::EditOutcome::Failed(reason) => {
|
||||
log::error!(
|
||||
"template '{}' could not be applied: {}",
|
||||
super::log_escape(name),
|
||||
super::log_escape(&reason)
|
||||
);
|
||||
answer = Some(format!("Could not apply the template: {reason}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = ctx
|
||||
.sender
|
||||
.answer_callback_query(callback_query_id, None)
|
||||
.answer_callback_query(callback_query_id, answer)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -164,52 +231,22 @@ async fn handle_callback(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ctx::test_support::TestStores;
|
||||
use crate::ctx::test_support::{FORWARDED_ID, PROMPT_ID, TestStores, api_error, seed_prompt};
|
||||
use crate::media_sender::test_support::{MockSender, Outcome};
|
||||
use crate::state::EditMessage;
|
||||
use teloxide::ApiError;
|
||||
|
||||
/// The edit-before-forward prompt's message id in these tests.
|
||||
const PROMPT_ID: i64 = 7;
|
||||
/// The message the prompt refers to (the one whose caption is swapped).
|
||||
const FORWARDED_ID: i64 = 9;
|
||||
|
||||
fn api_error() -> RequestError {
|
||||
RequestError::Api(ApiError::Unknown("Bad Request: chat not found".into()))
|
||||
}
|
||||
/// The Telegram wording the mocks answer with: a chat the bot cannot reach.
|
||||
const API_ERROR: &str = "Bad Request: chat not found";
|
||||
|
||||
fn callback_id() -> CallbackQueryId {
|
||||
CallbackQueryId("cb-1".to_string())
|
||||
}
|
||||
|
||||
/// Seeds a live prompt record plus a forward channel and a template;
|
||||
/// `created_at` backdates the record for the expiry cases.
|
||||
async fn seed_prompt(ctx: &AppContext<'_>, created_at: i64) {
|
||||
ctx.chat_store
|
||||
.update(1, |data| {
|
||||
data.forward_channel_id = Some(2);
|
||||
data.template
|
||||
.insert("tpl".to_string(), "<b>[]</b>".to_string());
|
||||
data.edit_message.insert(
|
||||
PROMPT_ID,
|
||||
EditMessage {
|
||||
url: "https://x.com/u/status/1".into(),
|
||||
chat_id: 1,
|
||||
forward_message_ids: vec![FORWARDED_ID],
|
||||
template: String::new(),
|
||||
created_at,
|
||||
},
|
||||
);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn template_button_swaps_the_caption_and_records_the_choice() {
|
||||
let sender = MockSender::scripted(vec![Outcome::EditOk], api_error);
|
||||
let sender = MockSender::scripted(vec![Outcome::EditOk], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, crate::db::unix_now()).await;
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "template|tpl").await;
|
||||
|
||||
@@ -225,11 +262,35 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forward_button_copies_then_clears_the_prompt() {
|
||||
let sender = MockSender::scripted(vec![Outcome::CopyOk], api_error);
|
||||
async fn a_failed_template_swap_is_reported_in_the_toast() {
|
||||
let sender = MockSender::scripted(vec![Outcome::EditErr], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, crate::db::unix_now()).await;
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "template|tpl").await;
|
||||
|
||||
// The caption never changed, so the toast says so and the record does
|
||||
// not claim the template was applied.
|
||||
let toast = sender.answers().last().cloned().flatten();
|
||||
assert!(
|
||||
toast
|
||||
.as_deref()
|
||||
.is_some_and(|t| t.contains("Could not apply the template")),
|
||||
"{toast:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
ctx.chat_store.get(1).await.edit_message[&PROMPT_ID].template,
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forward_button_copies_then_clears_the_prompt() {
|
||||
let sender = MockSender::scripted(vec![Outcome::CopyOk], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "forward").await;
|
||||
|
||||
@@ -245,14 +306,67 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forward_without_a_channel_is_reported() {
|
||||
let sender = MockSender::scripted(vec![], api_error);
|
||||
async fn skip_drops_the_prompt_without_forwarding() {
|
||||
// "skip" needs no forward channel and no scripted outcomes: it deletes
|
||||
// the prompt and drops the record, so no forward can ever happen.
|
||||
let sender = MockSender::scripted(vec![], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, crate::db::unix_now()).await;
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "skip").await;
|
||||
|
||||
assert_eq!(
|
||||
sender.calls(),
|
||||
vec!["delete_message", "answer_callback_query"]
|
||||
);
|
||||
assert_eq!(
|
||||
sender.answers(),
|
||||
vec![Some("Skipped — nothing was forwarded.".to_string())]
|
||||
);
|
||||
assert!(
|
||||
ctx.chat_store.get(1).await.edit_message.is_empty(),
|
||||
"a skipped prompt must drop its record"
|
||||
);
|
||||
}
|
||||
|
||||
/// The whole callback path against a stand-in API through a real `Bot`:
|
||||
/// copy, delete, toast, carrying the ids the prompt held. The scripted
|
||||
/// mock records that a call happened; this records what the API received.
|
||||
#[tokio::test]
|
||||
async fn the_forward_button_talks_to_the_api_through_a_real_bot() {
|
||||
use crate::media_sender::test_support::fake_api::FakeApi;
|
||||
use teloxide::Bot;
|
||||
|
||||
let api = FakeApi::start().await;
|
||||
let bot = Bot::new("42:TEST").set_api_url(api.url());
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&bot);
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "forward").await;
|
||||
|
||||
assert_eq!(
|
||||
api.methods(),
|
||||
vec!["CopyMessages", "DeleteMessage", "AnswerCallbackQuery"]
|
||||
);
|
||||
let copy = api.body("CopyMessages");
|
||||
assert_eq!(copy["chat_id"], 2, "the prompt's channel");
|
||||
assert_eq!(copy["from_chat_id"], 1);
|
||||
assert_eq!(copy["message_ids"], serde_json::json!([FORWARDED_ID]));
|
||||
assert_eq!(api.body("AnswerCallbackQuery")["text"], "✅ Forwarded");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forward_without_a_channel_is_reported() {
|
||||
let sender = MockSender::scripted(vec![], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
ctx.chat_store
|
||||
.update(1, |data| data.forward_channel_id = None)
|
||||
.await;
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "forward").await;
|
||||
|
||||
@@ -264,39 +378,61 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retryable_forward_is_queued_and_keeps_the_prompt() {
|
||||
async fn retryable_forward_is_queued_and_settles_the_prompt() {
|
||||
use teloxide::types::Seconds;
|
||||
let sender = MockSender::scripted(vec![Outcome::CopyErr], || {
|
||||
RequestError::RetryAfter(Seconds::from_seconds(7))
|
||||
});
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, crate::db::unix_now()).await;
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "forward").await;
|
||||
|
||||
// The queued row carries the message ids itself, so it owns the
|
||||
// forward from here and the prompt is closed with it. Keeping it live
|
||||
// (the old behaviour) let a second Confirm copy the same messages to
|
||||
// the channel twice, and let Skip answer "nothing was forwarded" while
|
||||
// the row still delivered it.
|
||||
assert_eq!(
|
||||
sender.calls(),
|
||||
vec!["copy_messages", "answer_callback_query"]
|
||||
vec!["copy_messages", "delete_message", "answer_callback_query"]
|
||||
);
|
||||
assert_eq!(
|
||||
sender.answers(),
|
||||
vec![Some("Forward queued for retry.".to_string())]
|
||||
);
|
||||
assert_eq!(stores.queued_tasks().await, 1);
|
||||
// The prompt is not settled: the queued retry still needs the record.
|
||||
assert!(
|
||||
ctx.chat_store
|
||||
!ctx.chat_store
|
||||
.get(1)
|
||||
.await
|
||||
.edit_message
|
||||
.contains_key(&PROMPT_ID)
|
||||
.contains_key(&PROMPT_ID),
|
||||
"the record must be dropped so the prompt cannot be used again"
|
||||
);
|
||||
|
||||
// A second tap finds no record: it cannot enqueue a duplicate copy.
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "forward").await;
|
||||
assert_eq!(
|
||||
sender.calls(),
|
||||
vec![
|
||||
"copy_messages",
|
||||
"delete_message",
|
||||
"answer_callback_query",
|
||||
"answer_callback_query"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sender.answers().last().map(|a| a.as_deref()),
|
||||
Some(Some("Expired"))
|
||||
);
|
||||
assert_eq!(stores.queued_tasks().await, 1, "no second forward row");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_and_expired_prompts_answer_expired() {
|
||||
let sender = MockSender::scripted(vec![], api_error);
|
||||
let sender = MockSender::scripted(vec![], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
|
||||
@@ -306,7 +442,7 @@ mod tests {
|
||||
|
||||
// A record past its TTL (nothing swept it yet) is dropped on use.
|
||||
let stale = crate::db::unix_now() - ctx.config.edit_message_ttl.as_secs() as i64 - 1;
|
||||
seed_prompt(&ctx, stale).await;
|
||||
seed_prompt(&ctx, "", stale).await;
|
||||
handle_callback(&ctx, callback_id(), 1, PROMPT_ID, "forward").await;
|
||||
assert_eq!(
|
||||
sender.answers(),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,13 +3,16 @@
|
||||
//! inline cache instead of re-fetching.
|
||||
|
||||
use super::log_key;
|
||||
use crate::ctx::AppContext;
|
||||
use crate::link_cache::{CachedMediaKind, CachedPost};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
use teloxide::RequestError;
|
||||
use teloxide::prelude::*;
|
||||
use teloxide::types::{
|
||||
InlineQuery, InlineQueryResult, InlineQueryResultMpeg4Gif, InlineQueryResultPhoto,
|
||||
InlineQueryResultVideo, ParseMode,
|
||||
FileId, InlineQuery, InlineQueryResult, InlineQueryResultCachedMpeg4Gif,
|
||||
InlineQueryResultCachedPhoto, InlineQueryResultCachedVideo, InlineQueryResultMpeg4Gif,
|
||||
InlineQueryResultPhoto, InlineQueryResultVideo, ParseMode,
|
||||
};
|
||||
use x_media::media::Media;
|
||||
|
||||
@@ -20,6 +23,12 @@ use x_media::media::Media;
|
||||
/// post id. Only answer once the query has been stable for this long.
|
||||
const INLINE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(800);
|
||||
|
||||
/// How long a debounce entry is worth keeping: the window Telegram caches an
|
||||
/// inline answer for (`answer_inline_query` asks for `cache_time(300)`). Past
|
||||
/// it a repeat is sent to the bot again and has to be answered fresh, so the
|
||||
/// entry would only suppress a fetch the user is waiting for.
|
||||
const INLINE_STATE_TTL: std::time::Duration = std::time::Duration::from_secs(300);
|
||||
|
||||
/// Last seen inline query per user and whether it was already answered.
|
||||
/// Guards the debounce timer: a repeat of an answered query is served by
|
||||
/// Telegram's inline cache (see `cache_time`), not by another fetch. Keyed by
|
||||
@@ -27,110 +36,172 @@ const INLINE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(80
|
||||
/// different user's query) cancel another user's pending answer.
|
||||
struct InlineDebounceState {
|
||||
query: String,
|
||||
generation: u64,
|
||||
answered: bool,
|
||||
last_seen: std::time::Instant,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DebounceStates(HashMap<u64, InlineDebounceState>);
|
||||
struct DebounceStates {
|
||||
entries: HashMap<u64, InlineDebounceState>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl DebounceStates {
|
||||
/// Records `query` as the user's newest query. Returns false when it is a
|
||||
/// repeat whose answer already went out (Telegram's inline cache serves
|
||||
/// it; re-fetching would only hit the source site again).
|
||||
fn note(&mut self, user_id: u64, query: &str) -> bool {
|
||||
if let Some(prev) = self.0.get(&user_id)
|
||||
fn note(&mut self, user_id: u64, query: &str) -> (bool, u64) {
|
||||
if let Some(prev) = self.entries.get(&user_id)
|
||||
&& prev.query == query
|
||||
&& prev.answered
|
||||
{
|
||||
return false;
|
||||
return (false, prev.generation);
|
||||
}
|
||||
self.0.insert(
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
let generation = self.generation;
|
||||
self.entries.insert(
|
||||
user_id,
|
||||
InlineDebounceState {
|
||||
query: query.to_string(),
|
||||
generation,
|
||||
answered: false,
|
||||
last_seen: std::time::Instant::now(),
|
||||
},
|
||||
);
|
||||
true
|
||||
(true, generation)
|
||||
}
|
||||
|
||||
/// Claims the answer for the user's newest query; false when a newer query
|
||||
/// superseded it or the answer was already claimed.
|
||||
fn claim(&mut self, user_id: u64, query: &str) -> bool {
|
||||
let Some(state) = self.0.get_mut(&user_id) else {
|
||||
/// Drops entries no query has touched for `idle_for`. Split from the clock
|
||||
/// so the boundary is testable without ageing a monotonic instant.
|
||||
fn prune_idle_at(&mut self, now: std::time::Instant, idle_for: std::time::Duration) -> usize {
|
||||
let before = self.entries.len();
|
||||
self.entries
|
||||
.retain(|_, state| now.saturating_duration_since(state.last_seen) < idle_for);
|
||||
before - self.entries.len()
|
||||
}
|
||||
fn claim(&mut self, user_id: u64, query: &str, generation: u64) -> bool {
|
||||
let Some(state) = self.entries.get_mut(&user_id) else {
|
||||
return false;
|
||||
};
|
||||
if state.query != query || state.answered {
|
||||
if state.query != query || state.generation != generation || state.answered {
|
||||
return false;
|
||||
}
|
||||
state.answered = true;
|
||||
state.last_seen = std::time::Instant::now();
|
||||
true
|
||||
}
|
||||
|
||||
/// Releases a claimed-but-unsent answer so a repeat can retry the fetch.
|
||||
fn release(&mut self, user_id: u64, query: &str) {
|
||||
if let Some(state) = self.0.get_mut(&user_id)
|
||||
fn release(&mut self, user_id: u64, query: &str, generation: u64) {
|
||||
if let Some(state) = self.entries.get_mut(&user_id)
|
||||
&& state.query == query
|
||||
&& state.generation == generation
|
||||
{
|
||||
state.answered = false;
|
||||
state.last_seen = std::time::Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops debounce entries idle for [`INLINE_STATE_TTL`]; the 300 s sweep calls
|
||||
/// this next to the rate limiter's prune. Returns how many were dropped.
|
||||
pub(crate) fn prune_idle_states() -> usize {
|
||||
INLINE_DEBOUNCE_STATE
|
||||
.lock()
|
||||
.prune_idle_at(std::time::Instant::now(), INLINE_STATE_TTL)
|
||||
}
|
||||
|
||||
static INLINE_DEBOUNCE_STATE: LazyLock<parking_lot::Mutex<DebounceStates>> =
|
||||
LazyLock::new(|| parking_lot::Mutex::new(DebounceStates::default()));
|
||||
|
||||
pub async fn inline_query_handler(bot: Bot, query: InlineQuery) -> Result<(), RequestError> {
|
||||
if query.query.is_empty() {
|
||||
return respond(());
|
||||
let ctx = AppContext::from_statics(&bot);
|
||||
if query.query.is_empty() || x_media::site::cache_key(&query.query).is_none() {
|
||||
return answer_inline_query(&ctx, query).await.map(|_| ());
|
||||
}
|
||||
// Only run a fetch for something that is actually a supported post URL.
|
||||
if x_media::site::cache_key(&query.query).is_none() {
|
||||
return respond(());
|
||||
}
|
||||
// Debounce: record the query and answer only after it has been stable for
|
||||
// INLINE_DEBOUNCE (the timer below). An already-answered repeat of the
|
||||
// same query is left to Telegram's inline cache instead of re-fetching.
|
||||
let user_id = query.from.id.0;
|
||||
if !INLINE_DEBOUNCE_STATE.lock().note(user_id, &query.query) {
|
||||
let (should_answer, generation) = INLINE_DEBOUNCE_STATE.lock().note(user_id, &query.query);
|
||||
if !should_answer {
|
||||
return respond(());
|
||||
}
|
||||
let query_text = query.query.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(INLINE_DEBOUNCE).await;
|
||||
// Only the user's last query of a typing burst survives: earlier
|
||||
// timers see the query changed and give up without answering.
|
||||
if !INLINE_DEBOUNCE_STATE.lock().claim(user_id, &query_text) {
|
||||
if !INLINE_DEBOUNCE_STATE
|
||||
.lock()
|
||||
.claim(user_id, &query_text, generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
match answer_inline_query(bot, query).await {
|
||||
let ctx = AppContext::from_statics(&bot);
|
||||
match answer_inline_query(&ctx, query).await {
|
||||
Ok(true) => {}
|
||||
// No results produced (or nothing to answer): let a repeat of the
|
||||
// same query retry the fetch.
|
||||
Ok(false) | Err(_) => INLINE_DEBOUNCE_STATE.lock().release(user_id, &query_text),
|
||||
Ok(false) | Err(_) => {
|
||||
INLINE_DEBOUNCE_STATE
|
||||
.lock()
|
||||
.release(user_id, &query_text, generation);
|
||||
}
|
||||
}
|
||||
});
|
||||
respond(())
|
||||
}
|
||||
|
||||
/// Fetches the post behind an inline query and answers it. The caller has
|
||||
/// already applied the debounce. Returns `true` when an answer was sent.
|
||||
async fn answer_inline_query(bot: Bot, query: InlineQuery) -> Result<bool, RequestError> {
|
||||
log::debug!(
|
||||
"inline query: {} [key={}]",
|
||||
query.query,
|
||||
log_key(&query.query)
|
||||
);
|
||||
/// Answers the inline query behind a post URL. The caller has already applied
|
||||
/// the debounce. Returns `true` when an answer was sent.
|
||||
async fn answer_inline_query(
|
||||
ctx: &AppContext<'_>,
|
||||
query: InlineQuery,
|
||||
) -> Result<bool, RequestError> {
|
||||
// The query is user input: `debug` keeps only its normalized key, the
|
||||
// text itself is `trace` (same split as the message handler).
|
||||
log::debug!("inline query [key={}]", log_key(&query.query));
|
||||
log::trace!("inline query: {}", super::log_escape(&query.query));
|
||||
let Some(key) = x_media::site::cache_key(&query.query) else {
|
||||
answer(ctx.sender, query.id, Vec::new()).await?;
|
||||
return Ok(true);
|
||||
};
|
||||
// A post that was already sent to some chat is answered from the link
|
||||
// cache: its Telegram file ids make the answer instant, and — unlike a URL
|
||||
// result, which Telegram must fetch itself — they carry media that a
|
||||
// hotlink-protected host (pixiv's pximg.net) or a locally encoded file
|
||||
// (ugoira MP4, bsky remux) can never serve inline. That media used to be
|
||||
// skipped outright, so a pixiv link answered empty.
|
||||
if let Some(cached) = ctx.link_cache.get(&key, ctx.config.link_cache_ttl).await {
|
||||
let caption = inline_caption(&cached, ctx.config.caption_quote_text_chars);
|
||||
let results = cached_inline_results(&cached, &caption);
|
||||
answer(ctx.sender, query.id, results).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
// No retries: the debounce plus a 1s/2s backoff would outlast the inline
|
||||
// query the answer belongs to.
|
||||
match x_media::site::fetch_once(&query.query).await {
|
||||
Ok(Some(fetched)) => {
|
||||
let mut results: Vec<InlineQueryResult> = Vec::new();
|
||||
// Inline results have the same 1024-char caption limit as regular
|
||||
// messages; truncate once here for all items.
|
||||
// messages; truncate once here for all items, then apply the same
|
||||
// long-post quoting as the send paths. The built-in caption is what
|
||||
// an inline answer can use: there is no chat whose per-site format
|
||||
// could apply, so the render fields come from the fetch itself.
|
||||
let caption = x_media::site::truncate_caption(&fetched.caption);
|
||||
let text = fetched
|
||||
.render_fields()
|
||||
.map(|(_, _, title, content, _)| x_media::site::compose_text(title, content))
|
||||
.unwrap_or_default();
|
||||
let caption = crate::send::quote_long_caption(
|
||||
&caption,
|
||||
&text,
|
||||
ctx.config.caption_quote_text_chars,
|
||||
);
|
||||
let mut results: Vec<InlineQueryResult> = Vec::new();
|
||||
for (i, media) in fetched.media.iter().enumerate() {
|
||||
let id = format!("{i}");
|
||||
// Telegram fetches an inline result's URL itself and cannot
|
||||
// send site-specific headers, so hotlink-protected media
|
||||
// (pixiv's pximg.net) would render as a broken file there.
|
||||
// Locally produced media (ugoira MP4, bsky remux) is a local
|
||||
// path and does not parse as a URL at all — same skip.
|
||||
if x_media::site::needs_media_headers(media.url()) {
|
||||
log::debug!("inline: skipping hotlink-protected media {i}");
|
||||
continue;
|
||||
}
|
||||
let Some(url) = url::Url::parse(media.url()).ok() else {
|
||||
continue;
|
||||
};
|
||||
@@ -138,97 +209,382 @@ async fn answer_inline_query(bot: Bot, query: InlineQuery) -> Result<bool, Reque
|
||||
.thumbnail_url()
|
||||
.and_then(|t| url::Url::parse(t).ok())
|
||||
.unwrap_or_else(|| url.clone());
|
||||
let caption = caption.clone();
|
||||
let result = match media {
|
||||
Media::Illustration { .. } => {
|
||||
// Inline photo results have their own (smaller) size
|
||||
// cap; use the reduced variant when one exists.
|
||||
let photo_url = media
|
||||
.smaller_url()
|
||||
.and_then(|u| url::Url::parse(u).ok())
|
||||
.unwrap_or_else(|| url.clone());
|
||||
InlineQueryResult::Photo(
|
||||
InlineQueryResultPhoto::new(id, photo_url, thumbnail)
|
||||
.caption(caption)
|
||||
.parse_mode(ParseMode::Html),
|
||||
)
|
||||
}
|
||||
Media::Video { .. } => InlineQueryResult::Video(
|
||||
InlineQueryResultVideo::new(
|
||||
id,
|
||||
url,
|
||||
"video/mp4".parse().expect("valid mime"),
|
||||
thumbnail,
|
||||
fetched.title.clone(),
|
||||
)
|
||||
.caption(caption)
|
||||
.parse_mode(ParseMode::Html),
|
||||
),
|
||||
Media::Animated { .. } => InlineQueryResult::Mpeg4Gif(
|
||||
InlineQueryResultMpeg4Gif::new(id, url, thumbnail)
|
||||
.caption(caption)
|
||||
.parse_mode(ParseMode::Html),
|
||||
),
|
||||
};
|
||||
results.push(result);
|
||||
}
|
||||
if !results.is_empty() {
|
||||
// Explicit cache window: repeats of the same query within 5
|
||||
// minutes are served by Telegram without hitting the bot.
|
||||
bot.answer_inline_query(query.id, results)
|
||||
.cache_time(300)
|
||||
.await?;
|
||||
return Ok(true);
|
||||
// Inline photo results have their own (smaller) size cap; use
|
||||
// the reduced variant when one exists.
|
||||
let url = media
|
||||
.smaller_url()
|
||||
.and_then(|u| url::Url::parse(u).ok())
|
||||
.unwrap_or(url);
|
||||
results.push(url_result(
|
||||
i.to_string(),
|
||||
match media {
|
||||
Media::Illustration { .. } => CachedMediaKind::Photo,
|
||||
Media::Video { .. } => CachedMediaKind::Video,
|
||||
Media::Animated { .. } => CachedMediaKind::Animation,
|
||||
},
|
||||
url,
|
||||
thumbnail,
|
||||
fetched.title.clone(),
|
||||
caption.clone().into_owned(),
|
||||
));
|
||||
}
|
||||
answer(ctx.sender, query.id, results).await?;
|
||||
Ok(true)
|
||||
}
|
||||
Ok(None) | Err(_) => {
|
||||
if let Err(e) = answer(ctx.sender, query.id, Vec::new()).await {
|
||||
log::error!(
|
||||
"inline empty answer failed for [key={}]: {e}",
|
||||
log_key(&query.query)
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => log::error!("inline fetch {}: {e}", query.query),
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// The caption of an inline answer, from a cached post: the caption that was
|
||||
/// sent (the site's built-in one, truncated) plus the long-post quoting the
|
||||
/// send paths apply.
|
||||
fn inline_caption(cached: &CachedPost, quote_chars: usize) -> String {
|
||||
let text = x_media::site::compose_text(&cached.title, &cached.content);
|
||||
crate::send::quote_long_caption(
|
||||
&x_media::site::truncate_caption(&cached.caption),
|
||||
&text,
|
||||
quote_chars,
|
||||
)
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
/// One inline result pointing Telegram at a URL it fetches itself.
|
||||
fn url_result(
|
||||
id: String,
|
||||
kind: CachedMediaKind,
|
||||
url: url::Url,
|
||||
thumbnail: url::Url,
|
||||
title: String,
|
||||
caption: String,
|
||||
) -> InlineQueryResult {
|
||||
let parse_mode = ParseMode::Html;
|
||||
match kind {
|
||||
CachedMediaKind::Photo => InlineQueryResult::Photo(
|
||||
InlineQueryResultPhoto::new(id, url, thumbnail)
|
||||
.caption(caption)
|
||||
.parse_mode(parse_mode),
|
||||
),
|
||||
CachedMediaKind::Video => InlineQueryResult::Video(
|
||||
InlineQueryResultVideo::new(
|
||||
id,
|
||||
url,
|
||||
"video/mp4".parse().expect("valid mime"),
|
||||
thumbnail,
|
||||
title,
|
||||
)
|
||||
.caption(caption)
|
||||
.parse_mode(parse_mode),
|
||||
),
|
||||
CachedMediaKind::Animation => InlineQueryResult::Mpeg4Gif(
|
||||
InlineQueryResultMpeg4Gif::new(id, url, thumbnail)
|
||||
.caption(caption)
|
||||
.parse_mode(parse_mode),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// One inline result served from a Telegram file id.
|
||||
fn cached_result(
|
||||
id: String,
|
||||
kind: CachedMediaKind,
|
||||
file_id: String,
|
||||
title: String,
|
||||
caption: String,
|
||||
) -> InlineQueryResult {
|
||||
let parse_mode = ParseMode::Html;
|
||||
let file_id = FileId(file_id);
|
||||
match kind {
|
||||
CachedMediaKind::Photo => InlineQueryResult::CachedPhoto(
|
||||
InlineQueryResultCachedPhoto::new(id, file_id)
|
||||
.caption(caption)
|
||||
.parse_mode(parse_mode),
|
||||
),
|
||||
CachedMediaKind::Video => InlineQueryResult::CachedVideo(
|
||||
InlineQueryResultCachedVideo::new(id, file_id, title)
|
||||
.caption(caption)
|
||||
.parse_mode(parse_mode),
|
||||
),
|
||||
CachedMediaKind::Animation => InlineQueryResult::CachedMpeg4Gif(
|
||||
InlineQueryResultCachedMpeg4Gif::new(id, file_id)
|
||||
.caption(caption)
|
||||
.parse_mode(parse_mode),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The inline results a cached post answers with, one per media item: from the
|
||||
/// file id when the entry has one, else from the source URL (a degraded entry
|
||||
/// keeps only URLs). A URL item that needs site headers is skipped as in the
|
||||
/// fetch path; a *file id* needs no headers, which is what makes a pixiv post
|
||||
/// answerable inline.
|
||||
fn cached_inline_results(cached: &CachedPost, caption: &str) -> Vec<InlineQueryResult> {
|
||||
cached
|
||||
.media
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, media)| {
|
||||
let id = i.to_string();
|
||||
let caption = || caption.to_string();
|
||||
if !media.file_id.is_empty() {
|
||||
return Some(cached_result(
|
||||
id,
|
||||
media.kind,
|
||||
media.file_id.clone(),
|
||||
cached.title.clone(),
|
||||
caption(),
|
||||
));
|
||||
}
|
||||
if x_media::site::needs_media_headers(&media.url) {
|
||||
log::debug!("inline: skipping hotlink-protected cached media {i}");
|
||||
return None;
|
||||
}
|
||||
let url = url::Url::parse(&media.url).ok()?;
|
||||
if matches!(media.kind, CachedMediaKind::Video) {
|
||||
log::debug!("inline: skipping a cached video with no thumbnail {i}");
|
||||
return None;
|
||||
}
|
||||
Some(url_result(
|
||||
id,
|
||||
media.kind,
|
||||
url.clone(),
|
||||
url,
|
||||
cached.title.clone(),
|
||||
caption(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Answers with `results` (an empty vec is a real answer: it stops the client
|
||||
/// spinning and lets Telegram serve repeats itself) under the cache window
|
||||
/// [`INLINE_STATE_TTL`] mirrors.
|
||||
async fn answer(
|
||||
sender: &dyn crate::media_sender::MediaSender,
|
||||
id: teloxide::types::InlineQueryId,
|
||||
mut results: Vec<InlineQueryResult>,
|
||||
) -> Result<(), RequestError> {
|
||||
results.truncate(50);
|
||||
if results.is_empty() {
|
||||
log::debug!("inline: nothing Telegram can serve for the query; answering empty");
|
||||
}
|
||||
sender.answer_inline_query(id, results, 300).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::DebounceStates;
|
||||
use super::{DebounceStates, INLINE_STATE_TTL, answer_inline_query, cached_inline_results};
|
||||
use crate::ctx::test_support::{TestStores, api_error, cached_photo};
|
||||
use crate::link_cache::{CachedMedia, CachedMediaKind};
|
||||
use crate::media_sender::test_support::MockSender;
|
||||
use teloxide::types::InlineQuery;
|
||||
|
||||
const URL_A: &str = "https://x.com/a/status/1";
|
||||
const URL_B: &str = "https://x.com/b/status/2";
|
||||
|
||||
fn inline_query(url: &str) -> InlineQuery {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "42",
|
||||
"from": { "id": 5, "is_bot": false, "first_name": "u" },
|
||||
"query": url,
|
||||
"offset": "",
|
||||
}))
|
||||
.expect("a minimal inline query deserializes")
|
||||
}
|
||||
|
||||
/// A post already in the link cache is answered from its file ids: no
|
||||
/// fetch, and — unlike a URL result — media Telegram could never fetch
|
||||
/// itself (a pixiv pximg URL) can be served.
|
||||
#[tokio::test]
|
||||
async fn a_cached_post_answers_from_its_file_ids() {
|
||||
let sender = MockSender::scripted(vec![], || api_error("boom"));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
let mut entry = cached_photo();
|
||||
entry.media = vec![
|
||||
CachedMedia {
|
||||
kind: CachedMediaKind::Photo,
|
||||
file_id: "AgAC-photo".into(),
|
||||
url: "https://i.pximg.net/img-original/img/1.jpg".into(),
|
||||
},
|
||||
CachedMedia {
|
||||
kind: CachedMediaKind::Animation,
|
||||
file_id: "AgAC-gif".into(),
|
||||
url: "https://i.pximg.net/img-original/img/1.gif".into(),
|
||||
},
|
||||
];
|
||||
stores.link_cache().put("twitter:1", &entry).await;
|
||||
|
||||
let answered = answer_inline_query(&ctx, inline_query("https://x.com/u/status/1"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(answered);
|
||||
assert_eq!(
|
||||
sender.inline_answers(),
|
||||
vec![vec!["cached_photo:AgAC-photo", "cached_gif:AgAC-gif"]],
|
||||
"every item goes out as its cached file id, hotlink protection and all"
|
||||
);
|
||||
}
|
||||
|
||||
/// A degraded entry has no file ids left, so its URLs are used — and an
|
||||
/// item Telegram must not fetch (needs site headers) or cannot render (a
|
||||
/// video with no poster) is skipped. Nothing left means an *empty* answer:
|
||||
/// leaving the query unanswered makes the client spin and re-fetch on every
|
||||
/// keystroke.
|
||||
#[tokio::test]
|
||||
async fn a_degraded_cached_post_answers_with_urls_or_empty() {
|
||||
let sender = MockSender::scripted(vec![], || api_error("boom"));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
|
||||
let mut entry = cached_photo();
|
||||
entry.media = vec![
|
||||
CachedMedia {
|
||||
kind: CachedMediaKind::Photo,
|
||||
file_id: String::new(),
|
||||
url: "https://p/1.jpg".into(),
|
||||
},
|
||||
CachedMedia {
|
||||
kind: CachedMediaKind::Video,
|
||||
file_id: String::new(),
|
||||
url: "https://v/1.mp4".into(),
|
||||
},
|
||||
];
|
||||
stores.link_cache().put("twitter:1", &entry).await;
|
||||
answer_inline_query(&ctx, inline_query("https://x.com/u/status/1"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sender.inline_answers(),
|
||||
vec![vec!["photo:https://p/1.jpg"]],
|
||||
"the degradable photo goes out by URL, the poster-less video is skipped"
|
||||
);
|
||||
|
||||
// Nothing servable: a pixiv original needs a Referer Telegram does not
|
||||
// send.
|
||||
stores.link_cache().remove("twitter:1").await;
|
||||
let mut entry = cached_photo();
|
||||
entry.media = vec![CachedMedia {
|
||||
kind: CachedMediaKind::Photo,
|
||||
file_id: String::new(),
|
||||
url: "https://i.pximg.net/img-original/img/1.jpg".into(),
|
||||
}];
|
||||
stores.link_cache().put("twitter:1", &entry).await;
|
||||
answer_inline_query(&ctx, inline_query("https://x.com/u/status/1"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sender.inline_answers(),
|
||||
vec![vec!["photo:https://p/1.jpg".to_string()], Vec::new()],
|
||||
"a query with nothing servable is still answered, with no results"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_inline_query_answers_empty() {
|
||||
let sender = MockSender::scripted(vec![], || api_error("boom"));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
let answered = answer_inline_query(&ctx, inline_query("not a supported post"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(answered);
|
||||
assert_eq!(sender.inline_answers(), vec![Vec::<String>::new()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn answer_caps_cached_results_at_telegram_limit() {
|
||||
let sender = MockSender::scripted(vec![], || api_error("boom"));
|
||||
let mut entry = cached_photo();
|
||||
entry.media = (0..51)
|
||||
.map(|i| CachedMedia {
|
||||
kind: CachedMediaKind::Photo,
|
||||
file_id: format!("id-{i}"),
|
||||
url: format!("https://p/{i}.jpg"),
|
||||
})
|
||||
.collect();
|
||||
let results = cached_inline_results(&entry, "caption");
|
||||
assert!(results.len() > 50, "the builder itself may keep all items");
|
||||
super::answer(
|
||||
&sender,
|
||||
inline_query("https://x.com/u/status/1").id,
|
||||
results,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sender.inline_answers()[0].len(), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debounce_state_is_per_user() {
|
||||
let mut states = DebounceStates::default();
|
||||
// Two users query different links: both proceed, and neither timer
|
||||
// cancels the other (a single shared slot dropped one of them).
|
||||
assert!(states.note(1, URL_A));
|
||||
assert!(states.note(2, URL_B));
|
||||
assert!(states.claim(1, URL_A), "user 1's answer was cancelled");
|
||||
assert!(states.claim(2, URL_B), "user 2's answer was cancelled");
|
||||
assert!(states.note(1, URL_A).0);
|
||||
assert!(states.note(2, URL_B).0);
|
||||
let (_, generation_a) = states.note(1, URL_A);
|
||||
let (_, generation_b) = states.note(2, URL_B);
|
||||
assert!(states.claim(1, URL_A, generation_a));
|
||||
assert!(states.claim(2, URL_B, generation_b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answered_query_is_suppressed_per_user_only() {
|
||||
let mut states = DebounceStates::default();
|
||||
assert!(states.note(1, URL_A));
|
||||
assert!(states.claim(1, URL_A));
|
||||
// A repeat of the answered query by the same user is left to
|
||||
// Telegram's inline cache.
|
||||
assert!(!states.note(1, URL_A));
|
||||
// Another user pasting the same link still gets an answer.
|
||||
assert!(states.note(2, URL_A));
|
||||
assert!(states.claim(2, URL_A));
|
||||
assert!(states.note(1, URL_A).0);
|
||||
let (_, generation) = states.note(1, URL_A);
|
||||
assert!(states.claim(1, URL_A, generation));
|
||||
assert!(!states.note(1, URL_A).0);
|
||||
assert!(states.note(2, URL_A).0);
|
||||
let (_, generation) = states.note(2, URL_A);
|
||||
assert!(states.claim(2, URL_A, generation));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_states_are_pruned_and_live_ones_kept() {
|
||||
let mut states = DebounceStates::default();
|
||||
assert!(states.note(1, URL_A).0);
|
||||
let first = states.entries[&1].last_seen;
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
assert!(states.note(2, URL_B).0);
|
||||
|
||||
assert_eq!(
|
||||
states.prune_idle_at(first + INLINE_STATE_TTL, INLINE_STATE_TTL),
|
||||
1
|
||||
);
|
||||
assert!(!states.entries.contains_key(&1));
|
||||
assert!(states.entries.contains_key(&2));
|
||||
assert!(states.note(1, URL_A).0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_same_query_generation_cannot_claim_after_a_b_a() {
|
||||
let mut states = DebounceStates::default();
|
||||
assert!(states.note(1, URL_A).0);
|
||||
assert!(states.note(1, URL_B).0);
|
||||
let (_, stale_generation) = states.note(1, URL_A);
|
||||
let (_, current_generation) = states.note(1, URL_A);
|
||||
assert_ne!(stale_generation, current_generation);
|
||||
assert!(!states.claim(1, URL_A, stale_generation));
|
||||
assert!(states.claim(1, URL_A, current_generation));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_query_supersedes_and_failed_answer_is_released() {
|
||||
let mut states = DebounceStates::default();
|
||||
assert!(states.note(1, URL_A));
|
||||
assert!(states.note(1, URL_B));
|
||||
// The stale timer for the half-typed query gives up…
|
||||
assert!(!states.claim(1, URL_A));
|
||||
// …and the newest one answers.
|
||||
assert!(states.claim(1, URL_B));
|
||||
// No results → release so a repeat may retry the fetch.
|
||||
states.release(1, URL_B);
|
||||
assert!(states.claim(1, URL_B));
|
||||
assert!(states.note(1, URL_A).0);
|
||||
let (_, generation_a) = states.note(1, URL_B);
|
||||
assert!(!states.claim(1, URL_A, generation_a));
|
||||
let (_, generation_b) = states.note(1, URL_B);
|
||||
assert!(states.claim(1, URL_B, generation_b));
|
||||
states.release(1, URL_B, generation_b);
|
||||
assert!(states.claim(1, URL_B, generation_b));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,63 +9,124 @@
|
||||
mod callback;
|
||||
mod commands;
|
||||
mod inline;
|
||||
mod repair;
|
||||
mod statics;
|
||||
mod url_workers;
|
||||
mod urls;
|
||||
|
||||
pub use callback::callback_query_handler;
|
||||
pub use commands::register_commands;
|
||||
pub use inline::inline_query_handler;
|
||||
pub(crate) use inline::prune_idle_states;
|
||||
pub(crate) use repair::repair_lost_local_media;
|
||||
/// The resolved `$DATA_DIR/task_queue.db` path, for the startup config line.
|
||||
pub(crate) use statics::db_path;
|
||||
pub use statics::{CHAT_STORE, CONFIG, LINK_CACHE, TASK_QUEUE};
|
||||
pub use urls::{start_url_workers, stop_url_workers};
|
||||
pub use url_workers::{start_url_workers, stop_url_workers};
|
||||
|
||||
use crate::ctx::AppContext;
|
||||
use crate::media_sender::MediaSender;
|
||||
use commands::{Command, execute_command};
|
||||
use teloxide::RequestError;
|
||||
use teloxide::prelude::*;
|
||||
use teloxide::types::{ChatId, ChatKind, Message, MessageId, ParseMode, ReplyParameters};
|
||||
use teloxide::types::{ChatId, Message, MessageId};
|
||||
use teloxide::utils::command::BotCommands;
|
||||
use urls::{URL_JOBS, extract_urls};
|
||||
use url_workers::URL_JOBS;
|
||||
use urls::extract_urls;
|
||||
|
||||
/// Reply to a message by id, keeping the reply decoration even if the
|
||||
/// original was already deleted. Returns the reply's message id.
|
||||
/// original was already deleted.
|
||||
pub(crate) async fn reply(
|
||||
sender: &dyn MediaSender,
|
||||
chat_id: i64,
|
||||
reply_to: MessageId,
|
||||
text: impl Into<String>,
|
||||
) -> Result<i64, RequestError> {
|
||||
) -> Result<(), RequestError> {
|
||||
sender
|
||||
.send_message(ChatId(chat_id), text.into(), Some(reply_to), None)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reply to a message by id with HTML parse mode (same reply decoration as
|
||||
/// [`reply`]). Used by `/test`, whose report is an HTML message (the caption
|
||||
/// is wrapped in a `<blockquote>` to show it exactly as it will render).
|
||||
pub(crate) async fn reply_html(
|
||||
bot: &Bot,
|
||||
chat_id: i64,
|
||||
reply_to: MessageId,
|
||||
text: String,
|
||||
) -> Result<i64, RequestError> {
|
||||
// `<Bot as Requester>::` disambiguates from the MediaSender trait's
|
||||
// same-named method (see media_sender.rs).
|
||||
<Bot as Requester>::send_message(bot, ChatId(chat_id), text)
|
||||
.parse_mode(ParseMode::Html)
|
||||
.reply_parameters(ReplyParameters::new(reply_to).allow_sending_without_reply())
|
||||
.await
|
||||
.map(|message| message.id.0 as i64)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Log prefix tying the whole lifecycle of one link (fetch → send → cache →
|
||||
/// forward) together: the normalized cache key (`twitter:123…`, `pixiv:123`,
|
||||
/// `bsky:handle/rkey`) instead of the raw URL, so logs stay short and do not
|
||||
/// echo full user-submitted URLs at info level.
|
||||
/// `bsky:handle/rkey`, `bilibili:123…`) instead of the raw URL, so logs stay
|
||||
/// short and do not echo full user-submitted URLs at info level.
|
||||
pub fn log_key(url: &str) -> String {
|
||||
x_media::site::cache_key(url).unwrap_or_else(|| "<unsupported>".to_string())
|
||||
}
|
||||
|
||||
/// Makes user-supplied text (a display name, callback data, a channel handle)
|
||||
/// fit one log line: newlines and other control characters are escaped, so a
|
||||
/// crafted value cannot forge a second log entry or hide inside one. Tab is
|
||||
/// kept — it cannot break the line.
|
||||
pub(crate) fn log_escape(s: &str) -> std::borrow::Cow<'_, str> {
|
||||
if !s.chars().any(|c| c.is_control() && c != '\t') {
|
||||
return std::borrow::Cow::Borrowed(s);
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c if c != '\t' && c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(out)
|
||||
}
|
||||
|
||||
/// How long a caption edit may sleep before it gives up on retrying: the reply
|
||||
/// (or button press) that carried the text is already consumed, so the update
|
||||
/// must not stall the chat's queue behind a long flood-control wait — the user
|
||||
/// is told to send it again instead.
|
||||
const CAPTION_EDIT_MAX_RETRY_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Whether a caption edit landed.
|
||||
enum EditOutcome {
|
||||
Applied,
|
||||
/// The API's reason, for the message the user gets.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Applies a caption edit, retrying once when the API names a short retryable
|
||||
/// delay (`RetryAfter`/network/5xx). A failed edit used to be logged and
|
||||
/// swallowed while the record was updated anyway: the user saw nothing, the
|
||||
/// caption never changed, and the text they typed was gone. Callers report
|
||||
/// [`EditOutcome::Failed`] instead.
|
||||
async fn apply_caption_edit(
|
||||
sender: &dyn MediaSender,
|
||||
chat_id: ChatId,
|
||||
message_id: MessageId,
|
||||
caption: String,
|
||||
) -> EditOutcome {
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
match sender
|
||||
.edit_message_caption(chat_id, message_id, caption.clone())
|
||||
.await
|
||||
{
|
||||
Ok(()) => return EditOutcome::Applied,
|
||||
Err(e) => {
|
||||
let reason = e.to_string();
|
||||
if attempt == 0
|
||||
&& let crate::send::Classification::Retryable { delay_seconds } =
|
||||
crate::send::classify_request_error(&e)
|
||||
&& std::time::Duration::from_secs_f64(delay_seconds)
|
||||
<= CAPTION_EDIT_MAX_RETRY_WAIT
|
||||
{
|
||||
attempt = 1;
|
||||
log::debug!("caption edit failed ({reason}), retrying once");
|
||||
tokio::time::sleep(std::time::Duration::from_secs_f64(delay_seconds)).await;
|
||||
continue;
|
||||
}
|
||||
log::error!("edit_message_caption failed: {reason}");
|
||||
return EditOutcome::Failed(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit-before-forward: a reply to the prompt swaps the caption of the first
|
||||
/// forwarded message. Returns true when the message was consumed as an edit.
|
||||
/// Body of [`message_handler`]'s edit branch, without teloxide update types so
|
||||
@@ -80,6 +141,18 @@ async fn edit_message_handler(
|
||||
let Some(edit) = chat_data.edit_message.get(&reply_to_message_id) else {
|
||||
return false;
|
||||
};
|
||||
// Lazy expiry, the same rule a button press gets: a record past the TTL
|
||||
// (not yet swept) is dropped and the reply falls through to the normal
|
||||
// message flow instead of rewriting a caption from a dead prompt.
|
||||
if edit.created_at + ctx.config.edit_message_ttl.as_secs() as i64 <= crate::db::unix_now() {
|
||||
let _ = ctx
|
||||
.chat_store
|
||||
.update(chat_id, |data| {
|
||||
data.edit_message.remove(&reply_to_message_id);
|
||||
})
|
||||
.await;
|
||||
return false;
|
||||
}
|
||||
let Some(first_forward_id) = edit.forward_message_ids.first() else {
|
||||
return false;
|
||||
};
|
||||
@@ -97,25 +170,49 @@ async fn edit_message_handler(
|
||||
.map(|template| template.replace("[]", &link))
|
||||
.unwrap_or(link)
|
||||
};
|
||||
match ctx
|
||||
.sender
|
||||
.edit_message_caption(
|
||||
ChatId(chat_id),
|
||||
MessageId(*first_forward_id as i32),
|
||||
new_text,
|
||||
)
|
||||
.await
|
||||
match apply_caption_edit(
|
||||
ctx.sender,
|
||||
ChatId(chat_id),
|
||||
MessageId(*first_forward_id as i32),
|
||||
new_text,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => log::info!(
|
||||
EditOutcome::Applied => log::info!(
|
||||
"edit-before-forward: caption swapped on message {first_forward_id} for prompt {reply_to_message_id}"
|
||||
),
|
||||
Err(e) => log::error!("edit_message_caption failed: {e}"),
|
||||
// The reply was a caption for this prompt, so it stays consumed either
|
||||
// way — but the user is told the swap failed instead of losing it
|
||||
// silently (and can send it again).
|
||||
EditOutcome::Failed(reason) => {
|
||||
let _ = reply(
|
||||
ctx.sender,
|
||||
chat_id,
|
||||
MessageId(reply_to_message_id as i32),
|
||||
format!("Could not update the caption ({reason}). Send it again to retry."),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The `dptree` entry point: the process-wide context, plus the bot the
|
||||
/// dispatcher handed us (used for the replies this module sends itself).
|
||||
pub async fn message_handler(bot: Bot, message: Message) -> Result<(), RequestError> {
|
||||
let is_private = matches!(message.chat.kind, ChatKind::Private(_));
|
||||
handle_message(&AppContext::from_statics(&bot), &bot, message).await
|
||||
}
|
||||
|
||||
/// Body of [`message_handler`], taking its context. Every branch here — the
|
||||
/// edit-reply interception, the command path, the private-chat link enqueue and
|
||||
/// the group hint — is otherwise reachable only through the process-wide
|
||||
/// statics, which is why none of them had a test.
|
||||
pub(crate) async fn handle_message(
|
||||
ctx: &AppContext<'_>,
|
||||
bot: &Bot,
|
||||
message: Message,
|
||||
) -> Result<(), RequestError> {
|
||||
let is_private = message.chat.is_private();
|
||||
let sender = message
|
||||
.from
|
||||
.as_ref()
|
||||
@@ -125,41 +222,53 @@ pub async fn message_handler(bot: Bot, message: Message) -> Result<(), RequestEr
|
||||
.text()
|
||||
.map(|t| {
|
||||
let end = t.floor_char_boundary(120.min(t.len()));
|
||||
&t[..end]
|
||||
log_escape(&t[..end])
|
||||
})
|
||||
.unwrap_or("<no text>");
|
||||
// Per-request detail: debug only (message text is user data).
|
||||
.unwrap_or_else(|| std::borrow::Cow::Borrowed("<no text>"));
|
||||
// Per-request detail: who and where at `debug`; the message text itself is
|
||||
// user data and only ever appears at `trace`, so a `debug` log can be
|
||||
// shared without leaking what people pasted.
|
||||
log::debug!(
|
||||
"message from {sender} in {} (private={is_private}): {text_preview}",
|
||||
"message from {} in {} (private={is_private})",
|
||||
log_escape(&sender),
|
||||
message.chat.id
|
||||
);
|
||||
log::trace!("message text: {text_preview}");
|
||||
// URL/edit flows only run in private chats; commands run in any chat.
|
||||
if is_private
|
||||
&& let Some(reply) = message.reply_to_message()
|
||||
&& let Some(text) = message.text()
|
||||
&& edit_message_handler(
|
||||
&AppContext::from_statics(&bot),
|
||||
message.chat.id.0,
|
||||
reply.id.0 as i64,
|
||||
text,
|
||||
)
|
||||
.await
|
||||
&& edit_message_handler(ctx, message.chat.id.0, reply.id.0 as i64, text).await
|
||||
{
|
||||
return respond(());
|
||||
}
|
||||
if let Some(text) = message.text()
|
||||
&& let Ok(command) = Command::parse(text, "")
|
||||
{
|
||||
log::debug!("command from {}: {text_preview}", message.chat.id);
|
||||
execute_command(&bot, &message, command).await?;
|
||||
// The command name is what the operator needs at `debug`; its argument
|
||||
// may be a user-supplied URL, which stays at `trace`.
|
||||
log::debug!(
|
||||
"command from {}: {}",
|
||||
message.chat.id,
|
||||
log_escape(text.split_whitespace().next().unwrap_or("<empty>"))
|
||||
);
|
||||
log::trace!("command text: {text_preview}");
|
||||
execute_command(ctx, bot, &message, command).await?;
|
||||
return respond(());
|
||||
}
|
||||
if is_private {
|
||||
let urls = extract_urls(&message);
|
||||
// Only links a site adapter claims: an unsupported URL never gets a
|
||||
// media message, so enqueuing it would spend a queue slot, a worker
|
||||
// wake-up and (through `run_with_chat_action`) a Telegram call on
|
||||
// nothing. Same test the group branch below makes for its hint.
|
||||
let urls: Vec<String> = extract_urls(&message)
|
||||
.into_iter()
|
||||
.filter(|url| x_media::site::cache_key(url).is_some())
|
||||
.collect();
|
||||
if !urls.is_empty() {
|
||||
// Debug only, and echo the normalized keys instead of the raw URLs.
|
||||
let keys: Vec<String> = urls.iter().map(|u| log_key(u)).collect();
|
||||
log::debug!("extracted {} URL(s): {keys:?}", urls.len());
|
||||
log::debug!("queuing {} supported URL(s): {keys:?}", urls.len());
|
||||
}
|
||||
for url in urls {
|
||||
// Clone out of the lock: the parking_lot guard is !Send and must
|
||||
@@ -175,52 +284,79 @@ pub async fn message_handler(bot: Bot, message: Message) -> Result<(), RequestEr
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (message.chat.is_group() || message.chat.is_supergroup())
|
||||
&& extract_urls(&message)
|
||||
.iter()
|
||||
.any(|url| x_media::site::cache_key(url).is_some())
|
||||
{
|
||||
// A supported link in a group used to be dropped in silence, which
|
||||
// reads as a broken bot (the command menu is registered globally, so
|
||||
// the expectation is there). Unsupported links stay ignored; the hint
|
||||
// names the two paths that do work. Channels are excluded — the reply
|
||||
// would be posted into the channel itself.
|
||||
let _ = reply(ctx.sender, message.chat.id.0, message.id, GROUP_LINK_HINT).await;
|
||||
}
|
||||
respond(())
|
||||
}
|
||||
|
||||
/// Answer for a link posted where the pipeline does not run (a group): links
|
||||
/// are private-chat only, inline mode is the group path.
|
||||
const GROUP_LINK_HINT: &str =
|
||||
"Links are handled in private chat only — send me this link there, or use inline mode here.";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ctx::test_support::TestStores;
|
||||
use crate::ctx::test_support::{FORWARDED_ID, PROMPT_ID, TestStores, api_error, seed_prompt};
|
||||
use crate::media_sender::test_support::{MockSender, Outcome};
|
||||
use crate::state::EditMessage;
|
||||
use teloxide::ApiError;
|
||||
use teloxide::RequestError;
|
||||
|
||||
const PROMPT_ID: i64 = 7;
|
||||
const FORWARDED_ID: i64 = 9;
|
||||
/// The Telegram wording the mocks answer with: a message the bot cannot
|
||||
/// edit (the prompt was deleted).
|
||||
const API_ERROR: &str = "Bad Request: message not found";
|
||||
|
||||
fn api_error() -> RequestError {
|
||||
RequestError::Api(ApiError::Unknown("Bad Request: message not found".into()))
|
||||
#[test]
|
||||
fn log_escape_cannot_forge_a_second_log_line() {
|
||||
let forged = log_escape("alice\nINFO injected entry");
|
||||
assert!(!forged.contains('\n'), "no raw newline may survive");
|
||||
assert!(
|
||||
forged.contains("\\n"),
|
||||
"the break stays visible as an escape"
|
||||
);
|
||||
// The common case (clean input) borrows — logging must not allocate.
|
||||
assert!(matches!(
|
||||
log_escape("plain text"),
|
||||
std::borrow::Cow::Borrowed(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// Seeds a prompt record; `template` names the chat template used for it
|
||||
/// (empty = none, the caption gets the bare link).
|
||||
async fn seed_prompt(ctx: &AppContext<'_>, template: &str) {
|
||||
ctx.chat_store
|
||||
.update(1, |data| {
|
||||
data.template
|
||||
.insert("tpl".to_string(), "<b>[]</b>".to_string());
|
||||
data.edit_message.insert(
|
||||
PROMPT_ID,
|
||||
EditMessage {
|
||||
url: "https://x.com/u/status/1".into(),
|
||||
chat_id: 1,
|
||||
forward_message_ids: vec![FORWARDED_ID],
|
||||
template: template.to_string(),
|
||||
created_at: crate::db::unix_now(),
|
||||
},
|
||||
);
|
||||
})
|
||||
.await;
|
||||
#[tokio::test]
|
||||
async fn a_reply_to_an_expired_prompt_is_not_edited() {
|
||||
// 90 000 s ago: past the TTL under any config a test can hold.
|
||||
let sender = MockSender::scripted(vec![], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "tpl", crate::db::unix_now() - 90_000).await;
|
||||
|
||||
let consumed = edit_message_handler(&ctx, 1, PROMPT_ID, "new caption").await;
|
||||
|
||||
assert!(!consumed, "an expired prompt must not consume the reply");
|
||||
assert!(
|
||||
sender.captions().is_empty(),
|
||||
"no caption edit may reach a dead prompt"
|
||||
);
|
||||
assert!(
|
||||
stores.chat_store().get(1).await.edit_message.is_empty(),
|
||||
"the stale record must be dropped for good"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reply_to_a_prompt_swaps_the_caption_through_its_template() {
|
||||
let sender = MockSender::scripted(vec![Outcome::EditOk], api_error);
|
||||
let sender = MockSender::scripted(vec![Outcome::EditOk], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "tpl").await;
|
||||
seed_prompt(&ctx, "tpl", crate::db::unix_now()).await;
|
||||
|
||||
let consumed = edit_message_handler(&ctx, 1, PROMPT_ID, "new caption").await;
|
||||
|
||||
@@ -233,10 +369,10 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn reply_text_and_url_are_escaped_into_the_caption() {
|
||||
let sender = MockSender::scripted(vec![Outcome::EditOk], api_error);
|
||||
let sender = MockSender::scripted(vec![Outcome::EditOk], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "").await;
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
|
||||
edit_message_handler(&ctx, 1, PROMPT_ID, "<script>alert(1)</script>").await;
|
||||
|
||||
@@ -248,21 +384,62 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_caption_swap_still_consumes_the_reply() {
|
||||
let sender = MockSender::scripted(vec![Outcome::EditErr], api_error);
|
||||
async fn a_failed_caption_swap_is_reported_and_consumed() {
|
||||
// The script is per call, in order: the edit fails, the notice follows.
|
||||
let sender = MockSender::scripted(vec![Outcome::EditErr, Outcome::MessageOk], || {
|
||||
api_error(API_ERROR)
|
||||
});
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "tpl").await;
|
||||
seed_prompt(&ctx, "tpl", crate::db::unix_now()).await;
|
||||
|
||||
// The edit failed (message deleted etc.); the reply must still be
|
||||
// swallowed instead of being treated as a link to fetch.
|
||||
// swallowed instead of being treated as a link to fetch — and the user
|
||||
// must be told, because the text they sent is gone either way.
|
||||
assert!(edit_message_handler(&ctx, 1, PROMPT_ID, "new caption").await);
|
||||
assert_eq!(sender.calls(), vec!["edit_message_caption"]);
|
||||
assert_eq!(sender.calls(), vec!["edit_message_caption", "send_message"]);
|
||||
let notice = sender.messages().join(" ");
|
||||
assert!(notice.contains("Could not update the caption"), "{notice}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_short_retryable_caption_failure_is_retried_once() {
|
||||
use teloxide::types::Seconds;
|
||||
// A one-second flood-control wait is worth honouring: the retry lands
|
||||
// and the user never hears about it.
|
||||
let sender = MockSender::scripted(vec![Outcome::EditErr, Outcome::EditOk], || {
|
||||
RequestError::RetryAfter(Seconds::from_seconds(1))
|
||||
});
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "tpl", crate::db::unix_now()).await;
|
||||
|
||||
assert!(edit_message_handler(&ctx, 1, PROMPT_ID, "new caption").await);
|
||||
assert_eq!(
|
||||
sender.calls(),
|
||||
vec!["edit_message_caption", "edit_message_caption"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_long_retryable_caption_failure_is_not_retried() {
|
||||
use teloxide::types::Seconds;
|
||||
// A minute-long wait must not stall the chat's update queue behind it:
|
||||
// the user is told to send the caption again instead.
|
||||
let sender = MockSender::scripted(vec![Outcome::EditErr, Outcome::MessageOk], || {
|
||||
RequestError::RetryAfter(Seconds::from_seconds(60))
|
||||
});
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
seed_prompt(&ctx, "tpl", crate::db::unix_now()).await;
|
||||
|
||||
assert!(edit_message_handler(&ctx, 1, PROMPT_ID, "new caption").await);
|
||||
assert_eq!(sender.calls(), vec!["edit_message_caption", "send_message"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reply_to_an_unrelated_message_is_not_consumed() {
|
||||
let sender = MockSender::scripted(vec![], api_error);
|
||||
let sender = MockSender::scripted(vec![], || api_error(API_ERROR));
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&sender);
|
||||
|
||||
@@ -271,4 +448,100 @@ mod tests {
|
||||
assert!(!edit_message_handler(&ctx, 1, PROMPT_ID, "hello").await);
|
||||
assert!(sender.calls().is_empty());
|
||||
}
|
||||
|
||||
/// A reply driven through the real message entry point into a real `Bot`:
|
||||
/// the routing (reply-to-prompt → caption swap, before the command and URL
|
||||
/// branches) and the request teloxide builds.
|
||||
#[tokio::test]
|
||||
async fn a_prompt_reply_reaches_the_api_as_a_caption_edit() {
|
||||
use crate::media_sender::test_support::fake_api::FakeApi;
|
||||
use teloxide::Bot;
|
||||
|
||||
let api = FakeApi::start().await;
|
||||
let bot = Bot::new("42:TEST").set_api_url(api.url());
|
||||
let stores = TestStores::new();
|
||||
let ctx = stores.ctx(&bot);
|
||||
seed_prompt(&ctx, "", crate::db::unix_now()).await;
|
||||
let message: Message = serde_json::from_value(serde_json::json!({
|
||||
"message_id": PROMPT_ID + 1,
|
||||
"date": 0,
|
||||
"chat": { "id": 1, "type": "private" },
|
||||
"from": { "id": 5, "is_bot": false, "first_name": "u" },
|
||||
"reply_to_message": {
|
||||
"message_id": PROMPT_ID,
|
||||
"date": 0,
|
||||
"chat": { "id": 1, "type": "private" },
|
||||
"text": "prompt",
|
||||
},
|
||||
"text": "new caption",
|
||||
}))
|
||||
.expect("a minimal message deserializes");
|
||||
|
||||
handle_message(&ctx, &bot, message).await.unwrap();
|
||||
|
||||
assert_eq!(api.methods(), vec!["EditMessageCaption"]);
|
||||
let body = api.body("EditMessageCaption");
|
||||
assert_eq!(body["chat_id"], 1);
|
||||
assert_eq!(body["message_id"], FORWARDED_ID);
|
||||
assert_eq!(
|
||||
body["caption"],
|
||||
"<a href=\"https://x.com/u/status/1\">new caption</a>"
|
||||
);
|
||||
|
||||
// The other branch of the same entry point: a supported link in a group
|
||||
// gets the one explanatory reply (the link pipeline is private-chat only,
|
||||
// and dropping it in silence reads as a broken bot).
|
||||
let group: Message = serde_json::from_value(serde_json::json!({
|
||||
"message_id": 2,
|
||||
"date": 0,
|
||||
"chat": { "id": -100, "type": "group", "title": "g" },
|
||||
"from": { "id": 5, "is_bot": false, "first_name": "u" },
|
||||
"text": "https://x.com/u/status/1",
|
||||
"entities": [{ "type": "url", "offset": 0, "length": 24 }],
|
||||
}))
|
||||
.expect("a minimal group message deserializes");
|
||||
|
||||
handle_message(&ctx, &bot, group).await.unwrap();
|
||||
|
||||
assert_eq!(api.methods(), vec!["EditMessageCaption", "SendMessage"]);
|
||||
assert_eq!(api.body("SendMessage")["text"], GROUP_LINK_HINT);
|
||||
|
||||
// A channel stays silent: the hint reply would be posted into the
|
||||
// channel itself, so the same link must produce no further call.
|
||||
let channel: Message = serde_json::from_value(serde_json::json!({
|
||||
"message_id": 3,
|
||||
"date": 0,
|
||||
"chat": { "id": -1001234567890i64, "type": "channel", "title": "c" },
|
||||
"text": "https://x.com/u/status/1",
|
||||
"entities": [{ "type": "url", "offset": 0, "length": 24 }],
|
||||
}))
|
||||
.expect("a minimal channel message deserializes");
|
||||
|
||||
handle_message(&ctx, &bot, channel).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
api.methods(),
|
||||
vec!["EditMessageCaption", "SendMessage"],
|
||||
"a channel must not get the group hint"
|
||||
);
|
||||
|
||||
// And an *unsupported* link in a group stays silent too: the hint is
|
||||
// for links a site adapter claims (the branch's own filter).
|
||||
let unsupported: Message = serde_json::from_value(serde_json::json!({
|
||||
"message_id": 4,
|
||||
"date": 0,
|
||||
"chat": { "id": -100, "type": "group", "title": "g" },
|
||||
"text": "https://example.com/x",
|
||||
"entities": [{ "type": "url", "offset": 0, "length": 19 }],
|
||||
}))
|
||||
.expect("a minimal group message deserializes");
|
||||
|
||||
handle_message(&ctx, &bot, unsupported).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
api.methods(),
|
||||
vec!["EditMessageCaption", "SendMessage"],
|
||||
"an unsupported link must not get the hint"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Startup repair, run before any queue worker exists: a queued retry whose
|
||||
//! local media (a ugoira MP4, a bsky remux, a downloaded temp file) did not
|
||||
//! survive the restart can never succeed, because the registry that kept those
|
||||
//! files alive (`send::KEEP_ALIVE`) is in memory. Those rows are re-fetched
|
||||
//! from their post instead of dead-lettering the user's link.
|
||||
|
||||
use super::log_key;
|
||||
use super::urls::{cached_snapshot, media_to_payload};
|
||||
use crate::ctx::AppContext;
|
||||
use crate::link_cache::CachedPost;
|
||||
use crate::send::{self, Delivery, MediaItemPayload, Task};
|
||||
|
||||
// ── Startup repair: queued retries whose local media did not survive ───────
|
||||
|
||||
/// A post's fresh media plus the caption and cache snapshot that go with them:
|
||||
/// what [`refetch`] hands [`apply_refresh`]. Plain data, so the rewrite below
|
||||
/// can be tested without a network fetch (which cannot be faked here:
|
||||
/// [`x_media::site::Fetched`] keeps a private field and is not constructible
|
||||
/// outside its crate).
|
||||
struct Refetched {
|
||||
caption: String,
|
||||
items: Vec<MediaItemPayload>,
|
||||
cache_data: Option<CachedPost>,
|
||||
keep_alive: Option<std::sync::Arc<tempfile::TempDir>>,
|
||||
}
|
||||
|
||||
/// Whether a queued task should have its post re-fetched, because it still
|
||||
/// wants a local file (ugoira MP4, a bsky remux, a downloaded temp file) that is
|
||||
/// gone. Those files live in the system temp dir and the registry that keeps
|
||||
/// them alive for the retry (`send::KEEP_ALIVE`) is in memory, so a restart
|
||||
/// takes all of them — a retry that needs one can only dead-letter.
|
||||
///
|
||||
/// A partially delivered album is left alone: its remaining batches cannot be
|
||||
/// reconciled with a fresh media list without risking a second copy of what the
|
||||
/// user already received.
|
||||
fn needs_refetch(task: &Task) -> bool {
|
||||
if let Task::SendMediaSequence {
|
||||
batch_index,
|
||||
sent_message_ids,
|
||||
..
|
||||
} = task
|
||||
&& (*batch_index > 0 || !sent_message_ids.is_empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
task.local_media_paths().iter().any(|path| !path.exists())
|
||||
}
|
||||
|
||||
/// Rebuilds the task from the fresh media, keeping its delivery envelope (chat,
|
||||
/// reply, forward/edit settings, notify targets): the retry that was queued must
|
||||
/// still deliver the same way, whoever asked for it.
|
||||
fn apply_refresh(task: &Task, fresh: &Refetched) -> Option<Task> {
|
||||
let chat_id = task.chat_id()?;
|
||||
let (edit_before_forward, forward_channel_id) = match task {
|
||||
Task::SendMediaSequence {
|
||||
edit_before_forward,
|
||||
forward_channel_id,
|
||||
..
|
||||
}
|
||||
| Task::SendAnimation {
|
||||
edit_before_forward,
|
||||
forward_channel_id,
|
||||
..
|
||||
} => (*edit_before_forward, *forward_channel_id),
|
||||
Task::ForwardMessages { .. } => return None,
|
||||
};
|
||||
let reply_to_message_id = match task {
|
||||
Task::SendMediaSequence {
|
||||
reply_to_message_id,
|
||||
..
|
||||
}
|
||||
| Task::SendAnimation {
|
||||
reply_to_message_id,
|
||||
..
|
||||
} => *reply_to_message_id,
|
||||
Task::ForwardMessages { .. } => return None,
|
||||
};
|
||||
let (notify_chat_id, notify_message_id) = task.notify_target();
|
||||
Some(Task::from_items(
|
||||
Delivery {
|
||||
chat_id,
|
||||
reply_to_message_id,
|
||||
edit_before_forward,
|
||||
forward_channel_id,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
},
|
||||
task.source_url()?.to_string(),
|
||||
fresh.caption.clone(),
|
||||
fresh.items.clone(),
|
||||
fresh.cache_data.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Fetches the post again and maps it into [`Refetched`]: the same mapping the
|
||||
/// fresh-fetch path uses (per-site caption format from the chat, render fields
|
||||
/// for the link-cache snapshot), so a repaired task looks like a first send.
|
||||
async fn refetch(
|
||||
ctx: &AppContext<'_>,
|
||||
chat_id: i64,
|
||||
url: &str,
|
||||
) -> Result<Option<Refetched>, x_media::site::FetchError> {
|
||||
let Some(fetched) = x_media::site::fetch(url).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if fetched.media.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let chat_data = ctx.chat_store.get(chat_id).await;
|
||||
let format = chat_data.format_for(fetched.site_id);
|
||||
let caption = fetched.caption_with(&format);
|
||||
let cache_data = cached_snapshot(&fetched);
|
||||
let items: Vec<MediaItemPayload> = fetched
|
||||
.media
|
||||
.iter()
|
||||
.filter_map(|media| media_to_payload(media, fetched.sensitive))
|
||||
.collect();
|
||||
if items.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(Refetched {
|
||||
caption,
|
||||
items,
|
||||
cache_data,
|
||||
keep_alive: fetched.keep_alive(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Re-fetches every queued task whose local media did not survive the restart.
|
||||
/// This runs at startup before queue workers exist, so any SQLite error is
|
||||
/// returned to the caller and prevents workers from starting on unrepaired
|
||||
/// state.
|
||||
pub(crate) async fn repair_lost_local_media(
|
||||
ctx: &AppContext<'_>,
|
||||
) -> Result<usize, rusqlite::Error> {
|
||||
let rows = ctx.task_queue.runnable_rows().await?;
|
||||
let mut repaired = 0;
|
||||
for (id, payload) in rows {
|
||||
let Ok(task) = serde_json::from_str::<Task>(&payload) else {
|
||||
continue;
|
||||
};
|
||||
if !needs_refetch(&task) {
|
||||
continue;
|
||||
}
|
||||
let (Some(url), Some(chat_id)) = (task.source_url().map(str::to_string), task.chat_id())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
match refetch(ctx, chat_id, &url).await {
|
||||
Ok(Some(fresh)) => {
|
||||
let Some(updated) = apply_refresh(&task, &fresh) else {
|
||||
continue;
|
||||
};
|
||||
let updated = serde_json::to_value(&updated).expect("task serializes");
|
||||
match ctx.task_queue.replace_payload(&id, &updated).await {
|
||||
Ok(true) => {
|
||||
if let Some(dir) = fresh.keep_alive {
|
||||
send::KEEP_ALIVE.lock().push(dir);
|
||||
}
|
||||
repaired += 1;
|
||||
log::info!(
|
||||
"startup repair: re-fetched [key={}] for chat={chat_id}",
|
||||
log_key(&url)
|
||||
);
|
||||
}
|
||||
Ok(false) => {
|
||||
log::warn!("startup repair: queue row {id} disappeared before rewrite")
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("startup repair: queue row {id} rewrite failed: {e}");
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) | Err(_) => {
|
||||
let (notify_chat_id, notify_message_id) = task.notify_target();
|
||||
log::warn!(
|
||||
"startup repair: [key={}] for chat={chat_id} needed a re-fetch and none was possible",
|
||||
log_key(&url)
|
||||
);
|
||||
send::notify_failure(
|
||||
ctx.sender,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
&format!(
|
||||
"{} — the media held for retry was lost when the bot restarted and the post could not be fetched again. Please send the link again.",
|
||||
log_key(&url)
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(repaired)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ctx::test_support::{TestStores, permanent_error, photo_item};
|
||||
use crate::media_sender::test_support::MockSender;
|
||||
use crate::send::MediaRef;
|
||||
|
||||
fn queued_task(media: &str, batch_index: usize, sent: Vec<i64>) -> Task {
|
||||
Task::SendMediaSequence {
|
||||
chat_id: 1,
|
||||
reply_to_message_id: 2,
|
||||
caption: "cap".into(),
|
||||
media_batches: vec![vec![photo_item(media, false, false)]],
|
||||
batch_index,
|
||||
sent_message_ids: sent,
|
||||
source_url: "https://x.com/u/status/1".into(),
|
||||
edit_before_forward: true,
|
||||
forward_channel_id: Some(2),
|
||||
notify_chat_id: Some(1),
|
||||
notify_message_id: Some(2),
|
||||
cache_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_tasks_missing_a_local_file_need_a_refetch() {
|
||||
// A URL send needs nothing.
|
||||
assert!(!needs_refetch(&queued_task("https://cdn/1.jpg", 0, vec![])));
|
||||
// A local path that is still there (a survived temp file) needs nothing.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let alive = dir.path().join("ugoira.mp4");
|
||||
std::fs::write(&alive, b"x").unwrap();
|
||||
assert!(!needs_refetch(&queued_task(
|
||||
alive.to_str().unwrap(),
|
||||
0,
|
||||
vec![]
|
||||
)));
|
||||
// A local path the restart took away does.
|
||||
assert!(needs_refetch(&queued_task(
|
||||
"/nonexistent-ugoira.mp4",
|
||||
0,
|
||||
vec![]
|
||||
)));
|
||||
// A partially delivered album is left to its own retry path.
|
||||
assert!(!needs_refetch(&queued_task(
|
||||
"/nonexistent-ugoira.mp4",
|
||||
1,
|
||||
vec![7]
|
||||
)));
|
||||
assert!(!needs_refetch(&queued_task(
|
||||
"/nonexistent-ugoira.mp4",
|
||||
0,
|
||||
vec![7]
|
||||
)));
|
||||
// A channel copy holds no media.
|
||||
assert!(!needs_refetch(&Task::ForwardMessages {
|
||||
from_chat_id: 1,
|
||||
to_chat_id: 2,
|
||||
message_ids: vec![3],
|
||||
forward_offset: 0,
|
||||
notify_chat_id: None,
|
||||
notify_message_id: None,
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_refresh_keeps_the_delivery_envelope() {
|
||||
let task = queued_task("/nonexistent-ugoira.mp4", 0, vec![]);
|
||||
let fresh = Refetched {
|
||||
caption: "fresh caption".into(),
|
||||
items: vec![photo_item("https://cdn/fresh.jpg", true, false)],
|
||||
cache_data: None,
|
||||
keep_alive: None,
|
||||
};
|
||||
match apply_refresh(&task, &fresh).expect("a repairable task") {
|
||||
Task::SendMediaSequence {
|
||||
chat_id,
|
||||
reply_to_message_id,
|
||||
caption,
|
||||
media_batches,
|
||||
batch_index,
|
||||
sent_message_ids,
|
||||
source_url,
|
||||
edit_before_forward,
|
||||
forward_channel_id,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
..
|
||||
} => {
|
||||
// Same delivery: chat, reply, forward/edit settings, notify.
|
||||
assert_eq!((chat_id, reply_to_message_id), (1, 2));
|
||||
assert!(edit_before_forward);
|
||||
assert_eq!(forward_channel_id, Some(2));
|
||||
assert_eq!((notify_chat_id, notify_message_id), (Some(1), Some(2)));
|
||||
assert_eq!(source_url, "https://x.com/u/status/1");
|
||||
// Fresh media, and nothing of it counted as sent yet.
|
||||
assert_eq!(caption, "fresh caption");
|
||||
assert!(
|
||||
matches!(
|
||||
media_batches[0][0].media_ref(),
|
||||
MediaRef::Source(media) if media == "https://cdn/fresh.jpg"
|
||||
),
|
||||
"fresh media must replace the lost local file"
|
||||
);
|
||||
assert!(matches!(
|
||||
media_batches[0][0],
|
||||
MediaItemPayload::Photo {
|
||||
has_spoiler: true,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!((batch_index, sent_message_ids.len()), (0, 0));
|
||||
}
|
||||
other => panic!("expected a media sequence, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_queue_scan_error_is_reported_to_the_startup_caller() {
|
||||
let stores = TestStores::new();
|
||||
let sender = MockSender::scripted(vec![], permanent_error);
|
||||
let ctx = stores.ctx(&sender);
|
||||
let raw = rusqlite::Connection::open(stores.db_path()).unwrap();
|
||||
raw.execute_batch("DROP TABLE tasks").unwrap();
|
||||
|
||||
assert!(repair_lost_local_media(&ctx).await.is_err());
|
||||
}
|
||||
|
||||
/// The whole repair against a real post: a queued row whose media is a local
|
||||
/// file the restart took away is re-fetched from its `source_url` and
|
||||
/// rewritten in place, so the retry can still deliver it.
|
||||
#[tokio::test]
|
||||
#[ignore = "live network: requires outbound HTTPS to public.api.bsky.app"]
|
||||
async fn live_repair_refetches_a_lost_local_media_row() {
|
||||
let stores = TestStores::new();
|
||||
// An empty script: the repair must not need to tell the user anything.
|
||||
let sender = MockSender::scripted(vec![], permanent_error);
|
||||
let ctx = stores.ctx(&sender);
|
||||
let mut task = queued_task("/nonexistent-ugoira.mp4", 0, vec![]);
|
||||
if let Task::SendMediaSequence { source_url, .. } = &mut task {
|
||||
*source_url = "https://bsky.app/profile/fu-futa.bsky.social/post/3laoveufjv224".into();
|
||||
}
|
||||
stores
|
||||
.task_queue()
|
||||
.enqueue(serde_json::to_value(&task).unwrap(), crate::db::now_f64())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(repair_lost_local_media(&ctx).await, Ok(1));
|
||||
|
||||
let updated: Task = serde_json::from_value(stores.queued_payload().await).unwrap();
|
||||
match updated {
|
||||
Task::SendMediaSequence {
|
||||
media_batches,
|
||||
batch_index,
|
||||
sent_message_ids,
|
||||
caption,
|
||||
..
|
||||
} => {
|
||||
let media: Vec<&str> = media_batches
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|item| match item.media_ref() {
|
||||
MediaRef::Source(media) | MediaRef::FileId(media) => media.as_str(),
|
||||
})
|
||||
.collect();
|
||||
assert!(!media.is_empty(), "the fresh fetch yielded no media");
|
||||
assert!(
|
||||
media.iter().all(|m| m.starts_with("http")),
|
||||
"the retry must be uploadable from URLs again: {media:?}"
|
||||
);
|
||||
assert_eq!((batch_index, sent_message_ids.len()), (0, 0));
|
||||
assert!(!caption.is_empty());
|
||||
}
|
||||
other => panic!("expected a repaired media sequence, got {other:?}"),
|
||||
}
|
||||
// The post was re-read, not re-delivered: nothing was sent.
|
||||
assert!(sender.calls().is_empty(), "{:?}", sender.calls());
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,9 @@ static DB: LazyLock<Arc<db::DbPool>> = LazyLock::new(|| {
|
||||
/// create parent dirs, so the old hardcoded `data/task_queue.db` failed with
|
||||
/// a confusing error when started from a directory without `data/`, and a
|
||||
/// CWD-relative path is a footgun for systemd / cron deployments — `DATA_DIR`
|
||||
/// lets them pin the state anywhere.
|
||||
fn db_path() -> std::path::PathBuf {
|
||||
/// lets them pin the state anywhere. Also read by the startup config line, so
|
||||
/// the log says where the state actually landed.
|
||||
pub(crate) fn db_path() -> std::path::PathBuf {
|
||||
let dir = std::env::var("DATA_DIR").unwrap_or_else(|_| "data".to_string());
|
||||
let dir_path = std::path::Path::new(&dir);
|
||||
std::fs::create_dir_all(dir_path).expect("failed to create data directory");
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! The URL job channel and its worker pool: a bounded queue (backpressure
|
||||
//! instead of unbounded spawns) drained by [`URL_WORKERS`] supervised workers.
|
||||
//!
|
||||
//! teloxide's per-chat workers are sequential, so a batch forward needs its own
|
||||
//! concurrency: this is where a link handed over by `handlers::mod` actually
|
||||
//! reaches the pipeline.
|
||||
|
||||
use super::urls::{PostSend, url_media};
|
||||
use crate::ctx::CONTEXT;
|
||||
use std::sync::LazyLock;
|
||||
use teloxide::types::Message;
|
||||
|
||||
/// One URL job: the message + the extracted URL (the sender and stores come
|
||||
/// from the shared [`AppContext`], assembled from statics inside the worker).
|
||||
type UrlJob = (Message, String);
|
||||
/// Bounded channel of URL jobs drained by [`start_url_workers`]. The bound
|
||||
/// caps both queued memory and shutdown backlog; a full channel applies
|
||||
/// backpressure to the per-chat handler instead of spawning unbounded tasks.
|
||||
pub(crate) static URL_JOBS: LazyLock<
|
||||
parking_lot::Mutex<Option<tokio::sync::mpsc::Sender<UrlJob>>>,
|
||||
> = LazyLock::new(|| parking_lot::Mutex::new(None));
|
||||
/// Set by main's shutdown sequence; workers stop pulling new jobs.
|
||||
pub(crate) static URL_STOP: std::sync::atomic::AtomicBool =
|
||||
std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// JoinHandles of the URL workers, awaited by [`stop_url_workers`].
|
||||
static URL_WORKER_HANDLES: LazyLock<parking_lot::Mutex<Option<Vec<tokio::task::JoinHandle<()>>>>> =
|
||||
LazyLock::new(|| parking_lot::Mutex::new(None));
|
||||
|
||||
/// Worker count draining URL jobs; keeps the old 8-permit concurrency cap
|
||||
/// while bounding how many jobs can be queued at all.
|
||||
const URL_WORKERS: usize = 8;
|
||||
|
||||
/// Starts the URL job workers (called once from main after the queue starts).
|
||||
/// teloxide dispatches updates to a per-chat worker that handles them
|
||||
/// sequentially, so a batch-forward of many messages would otherwise be
|
||||
/// processed one at a time (fetch + send each, roughly a second per
|
||||
/// message); the workers add throughput, and FIFO order preserves per-message
|
||||
/// URL order.
|
||||
pub async fn start_url_workers() {
|
||||
let (tx, rx) = tokio::sync::mpsc::channel::<UrlJob>(256);
|
||||
*URL_JOBS.lock() = Some(tx);
|
||||
let rx = std::sync::Arc::new(tokio::sync::Mutex::new(rx));
|
||||
let mut handles = Vec::with_capacity(URL_WORKERS);
|
||||
for _ in 0..URL_WORKERS {
|
||||
let rx = std::sync::Arc::clone(&rx);
|
||||
handles.push(tokio::spawn(async move {
|
||||
// Supervised like the queue workers: a panic inside a worker
|
||||
// (a handler, a poisoned lock) used to kill it for good and
|
||||
// silently shrink the pool — the remaining workers keep the
|
||||
// channel drained, so nothing else surfaces the loss. The job the
|
||||
// panicking worker held is lost; the panic is not.
|
||||
while !URL_STOP.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
let rx = std::sync::Arc::clone(&rx);
|
||||
if let Err(e) = tokio::spawn(async move {
|
||||
while !URL_STOP.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
let job = rx.lock().await.recv().await;
|
||||
match job {
|
||||
Some((message, url)) => {
|
||||
url_media(
|
||||
&CONTEXT,
|
||||
message.chat.id.0,
|
||||
message.id.0 as i64,
|
||||
&url,
|
||||
PostSend::FromChat,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
log::error!("url worker panicked, restarting: {e}");
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
*URL_WORKER_HANDLES.lock() = Some(handles);
|
||||
}
|
||||
|
||||
/// Stops the URL workers: sets the stop flag, drops the job channel (so
|
||||
/// workers blocked in \`recv()\` wake with \`None\` and exit) and awaits the
|
||||
/// worker tasks. Each worker finishes its in-flight job first; jobs still
|
||||
/// queued in the channel are abandoned (the old implementation neither
|
||||
/// drained them nor woke blocked workers — it only set a flag checked
|
||||
/// between jobs).
|
||||
pub async fn stop_url_workers() {
|
||||
URL_STOP.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
// Dropping the sender makes every worker's recv() return None.
|
||||
*URL_JOBS.lock() = None;
|
||||
// Take the handles first so the lock guard drops before the awaits.
|
||||
let handles = URL_WORKER_HANDLES.lock().take();
|
||||
if let Some(handles) = handles {
|
||||
for handle in handles {
|
||||
if let Err(e) = handle.await {
|
||||
log::error!("url worker panicked at shutdown: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+141
-103
@@ -9,12 +9,13 @@
|
||||
//! by the periodic prune in `main`.
|
||||
|
||||
use crate::db::now_f64;
|
||||
use rusqlite::OptionalExtension;
|
||||
use rusqlite::params;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CachedMediaKind {
|
||||
Photo,
|
||||
@@ -26,6 +27,12 @@ pub enum CachedMediaKind {
|
||||
pub struct CachedMedia {
|
||||
pub kind: CachedMediaKind,
|
||||
pub file_id: String,
|
||||
/// The media URL the send used, kept so an entry whose file ids stopped
|
||||
/// working can still be re-sent without touching the source site (see the
|
||||
/// bot's `invalidate_cache`). Empty for entries written before this field
|
||||
/// existed — those can only be dropped and re-fetched.
|
||||
#[serde(default)]
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Everything needed to re-send a post without touching the source site:
|
||||
@@ -38,6 +45,10 @@ pub struct CachedPost {
|
||||
/// override).
|
||||
pub caption: String,
|
||||
pub title: String,
|
||||
/// The post's body text. Defaulted on read: entries written before the
|
||||
/// title/content split carry it inside `title`.
|
||||
#[serde(default)]
|
||||
pub content: String,
|
||||
pub author: String,
|
||||
pub author_url: String,
|
||||
pub tags: String,
|
||||
@@ -63,134 +74,159 @@ impl LinkCache {
|
||||
pub async fn get(&self, key: &str, ttl: Duration) -> Option<CachedPost> {
|
||||
let key = key.to_string();
|
||||
let ttl = ttl.as_secs_f64();
|
||||
let result = self
|
||||
.pool
|
||||
.with_conn(move |conn| {
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT payload, created_at FROM link_cache WHERE url = ?1")?;
|
||||
let mut rows = stmt.query(params![key])?;
|
||||
let Some(row) = rows.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let payload: String = row.get(0)?;
|
||||
let created_at: f64 = row.get(1)?;
|
||||
if now_f64() - created_at > ttl {
|
||||
conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key])?;
|
||||
return Ok(None);
|
||||
}
|
||||
match serde_json::from_str::<CachedPost>(&payload) {
|
||||
Ok(post) => Ok(Some(post)),
|
||||
Err(e) => {
|
||||
// Unreadable payload (e.g. an older schema): drop it
|
||||
// instead of re-failing the parse on every later hit.
|
||||
self.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"link cache read failed",
|
||||
None,
|
||||
move |conn| {
|
||||
let Some((payload, created_at)) = conn
|
||||
.query_row(
|
||||
"SELECT payload, created_at FROM link_cache WHERE url = ?1",
|
||||
params![key],
|
||||
|row| Ok((row.get::<_, String>(0)?, row.get::<_, f64>(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if now_f64() - created_at > ttl {
|
||||
conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key])?;
|
||||
Err(rusqlite::Error::ToSqlConversionFailure(Box::new(e)))
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::error!("link cache read failed: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
match serde_json::from_str::<CachedPost>(&payload) {
|
||||
Ok(post) => Ok(Some(post)),
|
||||
Err(e) => {
|
||||
// Unreadable payload (e.g. an older schema): drop it
|
||||
// instead of re-failing the parse on every later hit.
|
||||
conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key])?;
|
||||
Err(rusqlite::Error::ToSqlConversionFailure(Box::new(e)))
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn put(&self, key: &str, post: &CachedPost) {
|
||||
let key = key.to_string();
|
||||
let payload = serde_json::to_string(post).expect("cached post serializes");
|
||||
let result = self
|
||||
.pool
|
||||
.with_conn(move |conn| {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO link_cache (url, payload, created_at) VALUES (?1, ?2, ?3)",
|
||||
params![key, payload, now_f64()],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
self.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"link cache write failed",
|
||||
(),
|
||||
move |conn| {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO link_cache (url, payload, created_at) VALUES (?1, ?2, ?3)",
|
||||
params![key, payload, now_f64()],
|
||||
)?;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = result {
|
||||
log::error!("link cache write failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops an entry (e.g. a cached file id that turned out invalid).
|
||||
pub async fn remove(&self, key: &str) {
|
||||
let key = key.to_string();
|
||||
let result = self
|
||||
.pool
|
||||
.with_conn(move |conn| {
|
||||
conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key])?;
|
||||
Ok(())
|
||||
})
|
||||
self.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"link cache delete failed",
|
||||
(),
|
||||
move |conn| {
|
||||
conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key])?;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = result {
|
||||
log::error!("link cache delete failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes expired entries; returns how many were deleted.
|
||||
pub async fn prune(&self, ttl: Duration) -> usize {
|
||||
let cutoff = now_f64() - ttl.as_secs_f64();
|
||||
let result = self
|
||||
.pool
|
||||
.with_conn(move |conn| {
|
||||
conn.execute(
|
||||
"DELETE FROM link_cache WHERE created_at < ?1",
|
||||
params![cutoff],
|
||||
)
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
log::error!("link cache prune failed: {e}");
|
||||
0
|
||||
}
|
||||
}
|
||||
self.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"link cache prune failed",
|
||||
0,
|
||||
move |conn| {
|
||||
conn.execute(
|
||||
"DELETE FROM link_cache WHERE created_at < ?1",
|
||||
params![cutoff],
|
||||
)
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Deletes one entry (by normalized cache key) or the whole cache when
|
||||
/// `key` is `None`. Returns how many rows were removed.
|
||||
pub async fn clear(&self, key: Option<&str>) -> usize {
|
||||
let key = key.map(str::to_string);
|
||||
let result = self
|
||||
.pool
|
||||
.with_conn(move |conn| match &key {
|
||||
Some(key) => conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key]),
|
||||
None => conn.execute("DELETE FROM link_cache", []),
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
log::error!("link cache clear failed: {e}");
|
||||
0
|
||||
}
|
||||
}
|
||||
self.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"link cache clear failed",
|
||||
0,
|
||||
move |conn| match &key {
|
||||
Some(key) => {
|
||||
conn.execute("DELETE FROM link_cache WHERE url = ?1", params![key])
|
||||
}
|
||||
None => conn.execute("DELETE FROM link_cache", []),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ctx::test_support::cached_photo;
|
||||
|
||||
fn entry() -> CachedPost {
|
||||
CachedPost {
|
||||
url: "https://x.com/u/status/1".into(),
|
||||
caption: "cap".into(),
|
||||
title: "t".into(),
|
||||
author: "a".into(),
|
||||
author_url: "au".into(),
|
||||
tags: "".into(),
|
||||
sensitive: true,
|
||||
media: vec![CachedMedia {
|
||||
kind: CachedMediaKind::Photo,
|
||||
file_id: "AgAC...".into(),
|
||||
}],
|
||||
/// A payload written before the title/content split has no `content`
|
||||
/// field. It must still read back — the cache deletes what it cannot
|
||||
/// parse — with its text left where it was stored (`title`) and the
|
||||
/// caption it replays untouched. No migration: a self-hosted cache entry
|
||||
/// lives one TTL, and moving the text would only reshuffle `/set_format`
|
||||
/// placeholders until it expires.
|
||||
#[tokio::test]
|
||||
async fn pre_split_entry_still_parses() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = LinkCache::new(
|
||||
crate::db::open_store(dir.path().join("c.db").to_str().unwrap()).unwrap(),
|
||||
);
|
||||
let legacy = serde_json::json!({
|
||||
"url": "https://x.com/u/status/1",
|
||||
"caption": "https://x.com/u/status/1\n<a href=\"au\">a</a>: old text",
|
||||
"title": "old text",
|
||||
"author": "a",
|
||||
"author_url": "au",
|
||||
"tags": "",
|
||||
"sensitive": false,
|
||||
"media": [{"kind": "photo", "file_id": "AgAC..."}]
|
||||
});
|
||||
{
|
||||
let conn = rusqlite::Connection::open(dir.path().join("c.db")).unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO link_cache (url, payload, created_at) VALUES (?1, ?2, ?3)",
|
||||
params!["twitter:1", legacy.to_string(), now_f64()],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let got = cache
|
||||
.get("twitter:1", Duration::from_secs(3600))
|
||||
.await
|
||||
.expect("a pre-split payload must not be dropped");
|
||||
assert_eq!(got.title, "old text");
|
||||
assert_eq!(got.content, "");
|
||||
assert_eq!(
|
||||
got.caption,
|
||||
"https://x.com/u/status/1\n<a href=\"au\">a</a>: old text"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -199,12 +235,14 @@ mod tests {
|
||||
let cache = LinkCache::new(
|
||||
crate::db::open_store(dir.path().join("c.db").to_str().unwrap()).unwrap(),
|
||||
);
|
||||
cache.put("twitter:1", &entry()).await;
|
||||
cache.put("twitter:1", &cached_photo()).await;
|
||||
let got = cache.get("twitter:1", Duration::from_secs(3600)).await;
|
||||
assert!(got.is_some());
|
||||
let got = got.unwrap();
|
||||
assert_eq!(got.url, "https://x.com/u/status/1");
|
||||
assert_eq!(got.media[0].file_id, "AgAC...");
|
||||
assert_eq!(got.media[0].file_id, "AgAC-file-id");
|
||||
// The source URL rides along: it is what a degraded entry falls back to.
|
||||
assert_eq!(got.media[0].url, "https://pbs.twimg.com/media/photo.jpg");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -213,7 +251,7 @@ mod tests {
|
||||
let cache = LinkCache::new(
|
||||
crate::db::open_store(dir.path().join("c.db").to_str().unwrap()).unwrap(),
|
||||
);
|
||||
cache.put("twitter:1", &entry()).await;
|
||||
cache.put("twitter:1", &cached_photo()).await;
|
||||
// Force the row into the past so a 1s TTL expires it.
|
||||
{
|
||||
let conn = rusqlite::Connection::open(dir.path().join("c.db")).unwrap();
|
||||
@@ -266,8 +304,8 @@ mod tests {
|
||||
let cache = LinkCache::new(
|
||||
crate::db::open_store(dir.path().join("c.db").to_str().unwrap()).unwrap(),
|
||||
);
|
||||
cache.put("twitter:1", &entry()).await;
|
||||
cache.put("pixiv:2", &entry()).await;
|
||||
cache.put("twitter:1", &cached_photo()).await;
|
||||
cache.put("pixiv:2", &cached_photo()).await;
|
||||
cache.remove("twitter:1").await;
|
||||
assert!(
|
||||
cache
|
||||
@@ -301,8 +339,8 @@ mod tests {
|
||||
let cache = LinkCache::new(
|
||||
crate::db::open_store(dir.path().join("c.db").to_str().unwrap()).unwrap(),
|
||||
);
|
||||
cache.put("twitter:1", &entry()).await;
|
||||
cache.put("pixiv:2", &entry()).await;
|
||||
cache.put("twitter:1", &cached_photo()).await;
|
||||
cache.put("pixiv:2", &cached_photo()).await;
|
||||
// By key: only the matching row is removed.
|
||||
assert_eq!(cache.clear(Some("twitter:1")).await, 1);
|
||||
assert!(
|
||||
|
||||
+339
-45
@@ -1,4 +1,5 @@
|
||||
use dotenv::dotenv;
|
||||
use std::time::Duration;
|
||||
use teloxide::dptree::endpoint;
|
||||
use teloxide::prelude::*;
|
||||
use teloxide::stop::StopToken;
|
||||
@@ -20,7 +21,7 @@ mod send;
|
||||
mod state;
|
||||
|
||||
use ctx::CONTEXT;
|
||||
use handlers::{CHAT_STORE, CONFIG, LINK_CACHE, TASK_QUEUE};
|
||||
use handlers::{CONFIG, TASK_QUEUE};
|
||||
|
||||
/// Docker `stop` / `compose down` delivers SIGTERM, which teloxide's ctrlc
|
||||
/// handler (SIGINT only) never sees — without this the process would die
|
||||
@@ -40,12 +41,85 @@ fn spawn_sigterm_handler(stop_token: StopToken) {
|
||||
#[cfg(not(unix))]
|
||||
fn spawn_sigterm_handler(_stop_token: StopToken) {}
|
||||
|
||||
/// A leftover temp file must be at least this old before the startup sweep
|
||||
/// touches it. Orphans come from a *previous* run; anything younger could
|
||||
/// belong to a second instance sharing the temp directory (a misconfiguration,
|
||||
/// but one that must not cost it its in-flight download).
|
||||
const ORPHAN_TEMP_AGE: Duration = Duration::from_secs(3600);
|
||||
|
||||
/// Removes this project's own leftover temp entries (`x_media::TEMP_FILE_PREFIX`)
|
||||
/// from `dir` once they are older than `older_than`. Returns how many were
|
||||
/// removed. Entries that are not ours, or are too young, or cannot be dated,
|
||||
/// are left alone: the OS temp directory is shared, and the marker prefix plus
|
||||
/// the age gate are the only two things that make deleting here safe.
|
||||
fn sweep_temp_dir(dir: &std::path::Path, older_than: Duration) -> usize {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return 0;
|
||||
};
|
||||
let cutoff = std::time::SystemTime::now() - older_than;
|
||||
let mut removed = 0;
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name();
|
||||
if !name
|
||||
.to_string_lossy()
|
||||
.starts_with(x_media::TEMP_FILE_PREFIX)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let old_enough = entry
|
||||
.metadata()
|
||||
.and_then(|meta| meta.modified())
|
||||
.is_ok_and(|modified| modified < cutoff);
|
||||
if !old_enough {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let result = if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
std::fs::remove_dir_all(&path)
|
||||
} else {
|
||||
std::fs::remove_file(&path)
|
||||
};
|
||||
match result {
|
||||
Ok(()) => removed += 1,
|
||||
// Not worth a warning per entry: a file another process removed
|
||||
// first (or one we may not delete) is not a problem here.
|
||||
Err(e) => log::debug!("could not remove orphaned temp entry {path:?}: {e}"),
|
||||
}
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
dotenv().ok();
|
||||
pretty_env_logger::init();
|
||||
// Without RUST_LOG nothing at all was logged (env_logger falls back to
|
||||
// `error`), so a deployment that forgot the variable looked like a bot
|
||||
// with no logs; and at `debug` the HTTP client's own lines (hyper_util,
|
||||
// reqwest) outnumbered the bot's by two to one. The timed builder adds
|
||||
// the timestamp the plain `init` omitted, so a line can be compared with
|
||||
// a user's report. An explicit RUST_LOG still wins outright — but a blank
|
||||
// one (`RUST_LOG=` in `.env`, which is not "unset") must not silence the
|
||||
// log the way its absence used to.
|
||||
let filter = std::env::var("RUST_LOG")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or_else(|| "info,hyper_util=warn,reqwest=warn".to_string());
|
||||
pretty_env_logger::formatted_timed_builder()
|
||||
.parse_filters(&filter)
|
||||
.init();
|
||||
log::info!("Starting bot");
|
||||
|
||||
// Temp media (downloaded files, ugoira/remux dirs) is cleaned up by
|
||||
// `TempDir`/`NamedTempFile` on drop — which a killed process never runs.
|
||||
// Without this sweep every hard restart left its downloads behind (up to
|
||||
// hundreds of MB each) and nothing could tell them apart from a live
|
||||
// process's files or from anything else in the OS temp dir. See
|
||||
// [`sweep_temp_dir`] for why the age gate makes that safe.
|
||||
let orphans = sweep_temp_dir(&std::env::temp_dir(), ORPHAN_TEMP_AGE);
|
||||
if orphans > 0 {
|
||||
log::info!("swept {orphans} orphaned temp file(s) from a previous run");
|
||||
}
|
||||
|
||||
let bot = Bot::from_env();
|
||||
// Force the queue workers' shared Bot to initialize now so a missing
|
||||
// token fails at startup, not on the first queued task.
|
||||
@@ -56,11 +130,43 @@ async fn main() {
|
||||
log::warn!("failed to register commands: {e}");
|
||||
}
|
||||
|
||||
// The effective tunables, so an operator can see what the process actually
|
||||
// resolved (a mistyped DATA_DIR or a forgotten TTL override is otherwise
|
||||
// invisible until it bites). The proxy URL is never printed — it may embed
|
||||
// credentials — and admin ids are chat identifiers, so they stay at debug.
|
||||
let quote_chars = match CONFIG.caption_quote_text_chars {
|
||||
0 => "off".to_string(),
|
||||
n => format!("{n} chars"),
|
||||
};
|
||||
log::info!(
|
||||
"config: {} admin(s), edit-message TTL {}s",
|
||||
"config: {} admin(s), state {}, edit-message TTL {}s, link cache TTL {}s, caption quote {quote_chars}, proxy={}",
|
||||
CONFIG.admin_ids.len(),
|
||||
CONFIG.edit_message_ttl.as_secs()
|
||||
crate::handlers::db_path().display(),
|
||||
CONFIG.edit_message_ttl.as_secs(),
|
||||
CONFIG.link_cache_ttl.as_secs(),
|
||||
if std::env::var("TELOXIDE_PROXY").is_ok() {
|
||||
"yes"
|
||||
} else {
|
||||
"no"
|
||||
}
|
||||
);
|
||||
log::debug!("config: admin ids {:?}", CONFIG.admin_ids);
|
||||
|
||||
// Startup repair, before any worker runs: a queued retry whose media was a
|
||||
// local file (ugoira MP4, bsky remux, a downloaded temp file) can never
|
||||
// succeed after a restart — the registry that kept those files alive is in
|
||||
// memory — so those rows are re-fetched from their post instead of
|
||||
// dead-lettering the user's link.
|
||||
let repaired = match handlers::repair_lost_local_media(&CONTEXT).await {
|
||||
Ok(repaired) => repaired,
|
||||
Err(e) => {
|
||||
log::error!("startup repair failed: {e}; refusing to start queue workers");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if repaired > 0 {
|
||||
log::info!("startup repair: re-fetched {repaired} queued task(s)");
|
||||
}
|
||||
|
||||
// Queue worker: handles typed tasks, dead-letters failed sends to the
|
||||
// task's chat. Both closures use the shared context (the queue requires
|
||||
@@ -93,45 +199,17 @@ async fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Edit-expiry sweep: clears the prompt's buttons once the record expires.
|
||||
// Background sweep: expires the edit prompts and prunes what has aged out.
|
||||
log::info!(
|
||||
"edit-expiry sweep: every 300s, ttl {}",
|
||||
"edit-expiry sweep: every {}s, ttl {}",
|
||||
SWEEP_INTERVAL.as_secs(),
|
||||
CONFIG.edit_message_ttl.as_secs()
|
||||
);
|
||||
let (stop_tx, stop_rx) = watch::channel(false);
|
||||
{
|
||||
let bot = bot.clone();
|
||||
let mut stop_rx = stop_rx;
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = stop_rx.changed() => break,
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(300)) => {}
|
||||
}
|
||||
let ttl = CONFIG.edit_message_ttl;
|
||||
let removed = CHAT_STORE.prune_expired(ttl).await;
|
||||
let pruned = LINK_CACHE.prune(CONFIG.link_cache_ttl).await;
|
||||
if pruned > 0 {
|
||||
log::info!("link cache: pruned {pruned} expired entr(ies)");
|
||||
}
|
||||
let idle_limiters = crate::rate_limit::prune_idle();
|
||||
if idle_limiters > 0 {
|
||||
log::debug!("rate limiter: dropped {idle_limiters} idle bucket(s)");
|
||||
}
|
||||
for (chat_id, prompt_message_id) in removed {
|
||||
// If the prompt was already deleted, this fails with a
|
||||
// 400 "message to edit not found" — log and ignore.
|
||||
if let Err(e) = bot
|
||||
.edit_message_reply_markup(
|
||||
ChatId(chat_id),
|
||||
MessageId(prompt_message_id as i32),
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::info!("edit-expiry sweep: prompt message gone: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
periodic_sweep(crate::ctx::AppContext::from_statics(&bot), stop_rx).await;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -141,7 +219,6 @@ async fn main() {
|
||||
.branch(Update::filter_callback_query().branch(endpoint(handlers::callback_query_handler)));
|
||||
|
||||
let mut dispatcher = Dispatcher::builder(bot.clone(), handler)
|
||||
.dependencies(dptree::deps![""])
|
||||
.enable_ctrlc_handler()
|
||||
.build();
|
||||
|
||||
@@ -152,13 +229,16 @@ async fn main() {
|
||||
// secret token included) — no explicit registration here.
|
||||
let listen = CONFIG.webhook_listen.expect("WEBHOOK_LISTEN is not set");
|
||||
let port = CONFIG.webhook_port.expect("WEBHOOK_PORT is not set");
|
||||
let mut options = webhooks::Options::new((listen, port).into(), url);
|
||||
// No secret, no webhook: without one the axum listener accepts any
|
||||
// POST, and a forged update can impersonate anyone — admins included.
|
||||
let secret = CONFIG
|
||||
.webhook_secret_token
|
||||
.clone()
|
||||
.expect("WEBHOOK_SECRET_TOKEN is not set (required in webhook mode)");
|
||||
let mut options = webhooks::Options::new((listen, port).into(), url).secret_token(secret);
|
||||
if let Some(cert) = &CONFIG.webhook_cert {
|
||||
options = options.certificate(InputFile::file(cert));
|
||||
}
|
||||
if let Some(secret) = &CONFIG.webhook_secret_token {
|
||||
options = options.secret_token(secret.clone());
|
||||
}
|
||||
|
||||
let mut listener = webhooks::axum(bot.clone(), options)
|
||||
.await
|
||||
@@ -189,18 +269,19 @@ async fn main() {
|
||||
.await;
|
||||
}
|
||||
|
||||
// Graceful stop (Ctrl+C / SIGTERM): stop the sweep, notify the admin,
|
||||
// drain the queue. Bounded: a worker mid-download (30 s timeout) or a
|
||||
// long ugoira encode must not hold the shutdown hostage forever.
|
||||
// Graceful stop (Ctrl+C / SIGTERM): stop the queue first so no new
|
||||
// persistent task is leased while the URL workers drain. The two drains
|
||||
// share the bounded shutdown budget; URL work may legitimately outlive it,
|
||||
// but the queue must not be left running until process exit.
|
||||
log::info!("Stopping bot");
|
||||
const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
let shutdown = async {
|
||||
let _ = stop_tx.send(true);
|
||||
TASK_QUEUE.stop().await;
|
||||
handlers::stop_url_workers().await;
|
||||
if let Some(admin) = CONFIG.admin_ids.first() {
|
||||
let _ = bot.send_message(ChatId(*admin), "Shutting down...").await;
|
||||
}
|
||||
TASK_QUEUE.stop().await;
|
||||
};
|
||||
if tokio::time::timeout(SHUTDOWN_TIMEOUT, shutdown)
|
||||
.await
|
||||
@@ -211,3 +292,216 @@ async fn main() {
|
||||
log::info!("Bot stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/// How often [`periodic_sweep`] runs.
|
||||
const SWEEP_INTERVAL: Duration = Duration::from_secs(300);
|
||||
|
||||
/// The background sweep: rewrites the expired edit prompts in place, prunes the
|
||||
/// link cache, the idle rate-limit buckets and the idle inline-query entries,
|
||||
/// and reports the queue only when it is not empty.
|
||||
///
|
||||
/// Takes the shared [`crate::ctx::AppContext`] — the collaborators as one
|
||||
/// bundle, production assembling it from the statics and tests from tempdir
|
||||
/// stores — so a test can drive a tick with a paused clock: a sleeping task
|
||||
/// nothing drives is how the queue's own sweep kept a missing worker wake-up.
|
||||
async fn periodic_sweep(ctx: crate::ctx::AppContext<'_>, mut stop: watch::Receiver<bool>) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = stop.changed() => break,
|
||||
_ = tokio::time::sleep(SWEEP_INTERVAL) => {}
|
||||
}
|
||||
let removed = ctx
|
||||
.chat_store
|
||||
.prune_expired(ctx.config.edit_message_ttl)
|
||||
.await;
|
||||
let pruned = ctx.link_cache.prune(ctx.config.link_cache_ttl).await;
|
||||
if pruned > 0 {
|
||||
log::info!("link cache: pruned {pruned} expired entr(ies)");
|
||||
}
|
||||
let idle_limiters = crate::rate_limit::prune_idle();
|
||||
if idle_limiters > 0 {
|
||||
log::debug!("rate limiter: dropped {idle_limiters} idle bucket(s)");
|
||||
}
|
||||
// Entries past Telegram's own inline cache window: a repeat is sent to
|
||||
// the bot again anyway, so keeping them would suppress a fetch the user
|
||||
// is waiting for (and the map grew one entry per user, forever).
|
||||
let idle_inline = handlers::prune_idle_states();
|
||||
if idle_inline > 0 {
|
||||
log::debug!("inline queries: dropped {idle_inline} idle entry(ies)");
|
||||
}
|
||||
// Only speaks up when the queue is not empty: a healthy bot has nothing
|
||||
// to report, and a periodic "0 pending" line is noise that hides the
|
||||
// lines that matter.
|
||||
if let Some((pending, oldest_run_after)) = ctx.task_queue.pending_backlog().await {
|
||||
let overdue = crate::db::now_f64() - oldest_run_after;
|
||||
if overdue >= 0.0 {
|
||||
log::info!("queue: {pending} pending task(s), oldest {overdue:.0}s overdue");
|
||||
} else {
|
||||
log::info!(
|
||||
"queue: {pending} pending task(s), oldest retry in {:.0}s",
|
||||
-overdue
|
||||
);
|
||||
}
|
||||
}
|
||||
for (chat_id, prompt_message_id) in removed {
|
||||
// Rewritten in place, not announced: the sweep is a background
|
||||
// timer, and a fresh message would wake the chat up to a full TTL
|
||||
// later about a prompt the user already walked away from. The edit
|
||||
// drops the buttons too. If the prompt was already deleted this
|
||||
// fails with a 400 "message to edit not found" — log and ignore.
|
||||
if let Err(e) = ctx
|
||||
.sender
|
||||
.edit_message_text(
|
||||
ChatId(chat_id),
|
||||
MessageId(prompt_message_id as i32),
|
||||
send::EDIT_PROMPT_EXPIRED_TEXT.to_string(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::info!("edit-expiry sweep: prompt message gone: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sweep_removes_only_our_old_temp_entries() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = std::time::SystemTime::now() - Duration::from_secs(7200);
|
||||
let make = |name: &str, aged: bool| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, b"x").unwrap();
|
||||
if aged {
|
||||
let file = std::fs::File::options().write(true).open(&path).unwrap();
|
||||
file.set_modified(old).unwrap();
|
||||
}
|
||||
path
|
||||
};
|
||||
let ours_old = make(&format!("{}photo-old.jpg", x_media::TEMP_FILE_PREFIX), true);
|
||||
let ours_fresh = make(
|
||||
&format!("{}photo-new.jpg", x_media::TEMP_FILE_PREFIX),
|
||||
false,
|
||||
);
|
||||
let theirs = make("someone-elses-file", true);
|
||||
|
||||
assert_eq!(sweep_temp_dir(dir.path(), Duration::from_secs(3600)), 1);
|
||||
assert!(!ours_old.exists(), "an old leftover of ours is removed");
|
||||
assert!(ours_fresh.exists(), "a fresh file may belong to a live run");
|
||||
assert!(
|
||||
theirs.exists(),
|
||||
"files without our prefix are never touched"
|
||||
);
|
||||
|
||||
// A caller with no age gate also reaches the directory branch (aging a
|
||||
// *directory* is not portable, so the gate is what the first half
|
||||
// above proves): the fresh dir and file go, the unrelated file stays.
|
||||
let leftover_dir = dir
|
||||
.path()
|
||||
.join(format!("{}ugoira", x_media::TEMP_FILE_PREFIX));
|
||||
std::fs::create_dir(&leftover_dir).unwrap();
|
||||
std::fs::write(leftover_dir.join("frame.png"), b"x").unwrap();
|
||||
assert_eq!(sweep_temp_dir(dir.path(), Duration::ZERO), 2);
|
||||
assert!(
|
||||
!leftover_dir.exists(),
|
||||
"leftover dirs go with their contents"
|
||||
);
|
||||
assert!(!ours_fresh.exists(), "no age gate: ours, however fresh");
|
||||
assert!(theirs.exists());
|
||||
}
|
||||
|
||||
/// The sweep's tick: an expired prompt is rewritten in place (buttons
|
||||
/// dropped) while a live one is left alone. Driven through the loop's own
|
||||
/// timer on a paused clock — the loop is what a hand-called helper would
|
||||
/// leave untested, which is how the queue's sweep kept a missing wake-up.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_sweep_expires_only_the_prompts_past_their_ttl() {
|
||||
use crate::ctx::test_support::{
|
||||
FORWARDED_ID, PROMPT_ID, TestStores, api_error, seed_prompt,
|
||||
};
|
||||
use crate::media_sender::test_support::MockSender;
|
||||
use crate::state::EditMessage;
|
||||
|
||||
// The interval is pinned here because no assertion on the edits can see
|
||||
// it: a shorter interval produces the same single edit (the record is
|
||||
// gone after the first tick), and the paused clock can jump past the
|
||||
// boundary while a tick's DB work is in flight.
|
||||
assert_eq!(SWEEP_INTERVAL, Duration::from_secs(300));
|
||||
|
||||
let config = crate::config::Config::load();
|
||||
let stores = TestStores::new();
|
||||
let sender = MockSender::scripted(vec![], || {
|
||||
api_error("Bad Request: message to edit not found")
|
||||
});
|
||||
let ctx = stores.ctx(&sender);
|
||||
// Chat 1 holds a prompt past its ttl; chat 2 a live one.
|
||||
let stale = crate::db::unix_now() - config.edit_message_ttl.as_secs() as i64 - 1;
|
||||
seed_prompt(&ctx, "", stale).await;
|
||||
stores
|
||||
.chat_store()
|
||||
.update(2, |data| {
|
||||
data.edit_message.insert(
|
||||
PROMPT_ID,
|
||||
EditMessage {
|
||||
url: "https://x.com/u/status/1".into(),
|
||||
chat_id: 2,
|
||||
forward_message_ids: vec![FORWARDED_ID],
|
||||
template: String::new(),
|
||||
created_at: crate::db::unix_now(),
|
||||
},
|
||||
);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (stop_tx, stop_rx) = watch::channel(false);
|
||||
let sweep = periodic_sweep(stores.ctx(&sender), stop_rx);
|
||||
tokio::pin!(sweep);
|
||||
|
||||
// One second short of the interval: nothing has been touched. The
|
||||
// select is what polls the loop (a pinned future nobody awaits never
|
||||
// runs), and the paused clock makes this the loop's own timer.
|
||||
tokio::select! {
|
||||
_ = &mut sweep => unreachable!("the sweep only returns on stop"),
|
||||
_ = tokio::time::sleep(SWEEP_INTERVAL - Duration::from_secs(1)) => {}
|
||||
}
|
||||
assert!(
|
||||
sender.edited_texts().is_empty(),
|
||||
"the sweep ran before its interval"
|
||||
);
|
||||
|
||||
// The second that crosses the interval: the tick fires.
|
||||
tokio::select! {
|
||||
_ = &mut sweep => unreachable!("the sweep only returns on stop"),
|
||||
_ = tokio::time::sleep(Duration::from_secs(2)) => {}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
sender.edited_texts(),
|
||||
vec![(1, PROMPT_ID, send::EDIT_PROMPT_EXPIRED_TEXT.to_string())],
|
||||
"exactly the expired prompt, rewritten in place"
|
||||
);
|
||||
assert!(
|
||||
!ctx.chat_store
|
||||
.get(1)
|
||||
.await
|
||||
.edit_message
|
||||
.contains_key(&PROMPT_ID),
|
||||
"the expired record is gone"
|
||||
);
|
||||
assert!(
|
||||
ctx.chat_store
|
||||
.get(2)
|
||||
.await
|
||||
.edit_message
|
||||
.contains_key(&PROMPT_ID),
|
||||
"a live prompt keeps its record and its buttons"
|
||||
);
|
||||
|
||||
stop_tx.send(true).unwrap();
|
||||
sweep.await;
|
||||
}
|
||||
}
|
||||
|
||||
+95
-214
@@ -8,8 +8,8 @@ use teloxide::RequestError;
|
||||
use teloxide::prelude::Requester;
|
||||
use teloxide::prelude::*;
|
||||
use teloxide::types::{
|
||||
CallbackQueryId, ChatAction, ChatId, InlineKeyboardMarkup, InputFile, InputMedia, Message,
|
||||
MessageId, ParseMode, ReplyParameters,
|
||||
CallbackQueryId, ChatAction, ChatId, InlineKeyboardMarkup, InlineQueryId, InlineQueryResult,
|
||||
InputFile, InputMedia, Message, MessageId, ParseMode, ReplyParameters,
|
||||
};
|
||||
|
||||
/// Boxed, `Send` future returned by a [`MediaSender`] method (`async fn` in
|
||||
@@ -60,6 +60,25 @@ pub trait MediaSender: Send + Sync {
|
||||
reply_markup: Option<InlineKeyboardMarkup>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>>;
|
||||
|
||||
/// Sends an HTML-formatted plain message.
|
||||
fn send_html_message(
|
||||
&self,
|
||||
chat_id: ChatId,
|
||||
text: String,
|
||||
reply_to: Option<MessageId>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>>;
|
||||
|
||||
/// Answers an inline query with `results`, cached by Telegram for
|
||||
/// `cache_time` seconds. An empty `results` answers *empty*, which is a
|
||||
/// real answer: it stops the client spinning and lets Telegram serve a
|
||||
/// repeat itself instead of the bot re-running the query.
|
||||
fn answer_inline_query(
|
||||
&self,
|
||||
id: InlineQueryId,
|
||||
results: Vec<InlineQueryResult>,
|
||||
cache_time: u32,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>>;
|
||||
|
||||
/// Answers a callback query, optionally with a toast `text` shown to the
|
||||
/// user who pressed the button.
|
||||
fn answer_callback_query(
|
||||
@@ -68,6 +87,16 @@ pub trait MediaSender: Send + Sync {
|
||||
text: Option<String>,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>>;
|
||||
|
||||
/// Rewrites a message's text and drops its inline keyboard: the
|
||||
/// edit-expiry sweep rewriting a prompt whose record expired (a button left
|
||||
/// behind could only answer "Expired").
|
||||
fn edit_message_text(
|
||||
&self,
|
||||
chat_id: ChatId,
|
||||
message_id: MessageId,
|
||||
text: String,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>>;
|
||||
|
||||
/// Rewrites a message's caption, always with HTML parse mode (every caller
|
||||
/// in this bot renders escaped HTML: templates and edit-before-forward
|
||||
/// links).
|
||||
@@ -106,6 +135,9 @@ impl MediaSender for Bot {
|
||||
crate::rate_limit::limiter_for(chat_id.0)
|
||||
.acquire(items.len() as f64)
|
||||
.await;
|
||||
// Same spend against the bot-wide budget: a fan-out over chats is
|
||||
// invisible to the per-chat buckets.
|
||||
crate::rate_limit::acquire_global(items.len() as f64).await;
|
||||
// `<Bot as Requester>::` disambiguates from this trait's same-named
|
||||
// method (teloxide's API lives in the `Requester` trait).
|
||||
<Bot as Requester>::send_media_group(self, chat_id, items)
|
||||
@@ -124,6 +156,7 @@ impl MediaSender for Bot {
|
||||
) -> BoxFuture<'a, Result<Message, RequestError>> {
|
||||
Box::pin(async move {
|
||||
crate::rate_limit::limiter_for(chat_id.0).acquire(1.0).await;
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
let mut request = <Bot as Requester>::send_animation(self, chat_id, file)
|
||||
.caption(caption)
|
||||
.parse_mode(ParseMode::Html)
|
||||
@@ -147,6 +180,7 @@ impl MediaSender for Bot {
|
||||
crate::rate_limit::limiter_for(to.0)
|
||||
.acquire(ids.len() as f64)
|
||||
.await;
|
||||
crate::rate_limit::acquire_global(ids.len() as f64).await;
|
||||
<Bot as Requester>::copy_messages(self, to, from, ids).await
|
||||
})
|
||||
}
|
||||
@@ -159,6 +193,8 @@ impl MediaSender for Bot {
|
||||
reply_markup: Option<InlineKeyboardMarkup>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>> {
|
||||
Box::pin(async move {
|
||||
crate::rate_limit::limiter_for(chat_id.0).acquire(1.0).await;
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
let mut request = <Bot as Requester>::send_message(self, chat_id, text);
|
||||
if let Some(reply_to) = reply_to {
|
||||
request = request
|
||||
@@ -171,6 +207,39 @@ impl MediaSender for Bot {
|
||||
})
|
||||
}
|
||||
|
||||
fn send_html_message(
|
||||
&self,
|
||||
chat_id: ChatId,
|
||||
text: String,
|
||||
reply_to: Option<MessageId>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>> {
|
||||
Box::pin(async move {
|
||||
crate::rate_limit::limiter_for(chat_id.0).acquire(1.0).await;
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
let mut request =
|
||||
<Bot as Requester>::send_message(self, chat_id, text).parse_mode(ParseMode::Html);
|
||||
if let Some(reply_to) = reply_to {
|
||||
request = request
|
||||
.reply_parameters(ReplyParameters::new(reply_to).allow_sending_without_reply());
|
||||
}
|
||||
request.await.map(|message| message.id.0 as i64)
|
||||
})
|
||||
}
|
||||
|
||||
fn answer_inline_query(
|
||||
&self,
|
||||
id: InlineQueryId,
|
||||
results: Vec<InlineQueryResult>,
|
||||
cache_time: u32,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
<Bot as Requester>::answer_inline_query(self, id, results)
|
||||
.cache_time(cache_time)
|
||||
.await
|
||||
.map(|_| ())
|
||||
})
|
||||
}
|
||||
|
||||
fn answer_callback_query(
|
||||
&self,
|
||||
id: CallbackQueryId,
|
||||
@@ -185,6 +254,21 @@ impl MediaSender for Bot {
|
||||
})
|
||||
}
|
||||
|
||||
fn edit_message_text(
|
||||
&self,
|
||||
chat_id: ChatId,
|
||||
message_id: MessageId,
|
||||
text: String,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
crate::rate_limit::limiter_for(chat_id.0).acquire(1.0).await;
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
<Bot as Requester>::edit_message_text(self, chat_id, message_id, text)
|
||||
.reply_markup(InlineKeyboardMarkup::default())
|
||||
.await
|
||||
.map(|_| ())
|
||||
})
|
||||
}
|
||||
fn edit_message_caption(
|
||||
&self,
|
||||
chat_id: ChatId,
|
||||
@@ -192,6 +276,8 @@ impl MediaSender for Bot {
|
||||
caption: String,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
crate::rate_limit::limiter_for(chat_id.0).acquire(1.0).await;
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
<Bot as Requester>::edit_message_caption(self, chat_id, message_id)
|
||||
.caption(caption)
|
||||
.parse_mode(ParseMode::Html)
|
||||
@@ -206,6 +292,8 @@ impl MediaSender for Bot {
|
||||
message_id: MessageId,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
crate::rate_limit::limiter_for(chat_id.0).acquire(1.0).await;
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
<Bot as Requester>::delete_message(self, chat_id, message_id)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -218,6 +306,10 @@ impl MediaSender for Bot {
|
||||
action: ChatAction,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
// Same gap as send_message: actions count against the bot-wide
|
||||
// budget too (see there); the refresh loop behind
|
||||
// `run_with_chat_action` makes them frequent enough to matter.
|
||||
crate::rate_limit::acquire_global(1.0).await;
|
||||
// teloxide's `send_chat_action` returns `Result<True, _>` (its
|
||||
// unit marker type); map the success to `()`.
|
||||
<Bot as Requester>::send_chat_action(self, chat_id, action)
|
||||
@@ -227,216 +319,5 @@ impl MediaSender for Bot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Test support: a scripted [`MediaSender`] mock (no Telegram API involved).
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
/// One scripted outcome, consumed front-to-back; the last entry repeats
|
||||
/// for further calls of the same method kind.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Outcome {
|
||||
GroupOk,
|
||||
GroupErr,
|
||||
AnimationErr,
|
||||
CopyOk,
|
||||
CopyErr,
|
||||
/// An error from `send_message` (replies are fire-and-forget, so an
|
||||
/// error is fine for tests).
|
||||
MessageErr,
|
||||
/// A successful `send_message`, returning message id [`MockSender::SENT_ID`].
|
||||
MessageOk,
|
||||
EditOk,
|
||||
EditErr,
|
||||
}
|
||||
|
||||
/// Replays a script and records what was sent, so tests can assert the
|
||||
/// user-visible text a path produced.
|
||||
pub(crate) struct MockSender {
|
||||
script: Mutex<Vec<Outcome>>,
|
||||
cursor: Mutex<usize>,
|
||||
calls: Mutex<Vec<&'static str>>,
|
||||
messages: Mutex<Vec<String>>,
|
||||
captions: Mutex<Vec<String>>,
|
||||
answers: Mutex<Vec<Option<String>>>,
|
||||
/// Builds the error every `*Err` outcome returns (RequestError is not
|
||||
/// cloneable, so the factory recreates it per call).
|
||||
error: Box<dyn Fn() -> RequestError + Send + Sync>,
|
||||
}
|
||||
|
||||
impl MockSender {
|
||||
/// The message id a successful `send_message` reports.
|
||||
pub(crate) const SENT_ID: i64 = 1;
|
||||
|
||||
pub(crate) fn scripted(
|
||||
script: Vec<Outcome>,
|
||||
error: impl Fn() -> RequestError + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
MockSender {
|
||||
script: Mutex::new(script),
|
||||
cursor: Mutex::new(0),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
messages: Mutex::new(Vec::new()),
|
||||
captions: Mutex::new(Vec::new()),
|
||||
answers: Mutex::new(Vec::new()),
|
||||
error: Box::new(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Method names in call order (e.g. `["send_media_group",
|
||||
/// "send_media_group"]` proves the fallback re-sent).
|
||||
pub(crate) fn calls(&self) -> Vec<&'static str> {
|
||||
self.calls.lock().clone()
|
||||
}
|
||||
|
||||
/// Texts of the plain messages sent, in order.
|
||||
pub(crate) fn messages(&self) -> Vec<String> {
|
||||
self.messages.lock().clone()
|
||||
}
|
||||
|
||||
/// Captions passed to `edit_message_caption`, in order.
|
||||
pub(crate) fn captions(&self) -> Vec<String> {
|
||||
self.captions.lock().clone()
|
||||
}
|
||||
|
||||
/// Toast texts of the answered callback queries, in order.
|
||||
pub(crate) fn answers(&self) -> Vec<Option<String>> {
|
||||
self.answers.lock().clone()
|
||||
}
|
||||
|
||||
fn next(&self, kind: &'static str) -> Outcome {
|
||||
self.calls.lock().push(kind);
|
||||
let script = self.script.lock();
|
||||
let mut cursor = self.cursor.lock();
|
||||
if script.is_empty() {
|
||||
panic!("mock script exhausted: {kind}");
|
||||
}
|
||||
let idx = (*cursor).min(script.len() - 1);
|
||||
*cursor = idx + 1;
|
||||
script[idx]
|
||||
}
|
||||
|
||||
fn error(&self) -> RequestError {
|
||||
(self.error)()
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaSender for MockSender {
|
||||
fn send_media_group(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_reply_to: MessageId,
|
||||
_items: Vec<InputMedia>,
|
||||
) -> BoxFuture<'_, Result<Vec<Message>, RequestError>> {
|
||||
Box::pin(async move {
|
||||
match self.next("send_media_group") {
|
||||
Outcome::GroupOk => Ok(Vec::new()),
|
||||
Outcome::GroupErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_media_group"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_animation<'a>(
|
||||
&'a self,
|
||||
_chat_id: ChatId,
|
||||
_reply_to: MessageId,
|
||||
_caption: &'a str,
|
||||
_spoiler: bool,
|
||||
_file: InputFile,
|
||||
) -> BoxFuture<'a, Result<Message, RequestError>> {
|
||||
Box::pin(async move {
|
||||
match self.next("send_animation") {
|
||||
Outcome::AnimationErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_animation"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn copy_messages(
|
||||
&self,
|
||||
_to: ChatId,
|
||||
_from: ChatId,
|
||||
_ids: Vec<MessageId>,
|
||||
) -> BoxFuture<'_, Result<Vec<MessageId>, RequestError>> {
|
||||
Box::pin(async move {
|
||||
match self.next("copy_messages") {
|
||||
Outcome::CopyOk => Ok(vec![MessageId(1)]),
|
||||
Outcome::CopyErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for copy_messages"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_message(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
text: String,
|
||||
_reply_to: Option<MessageId>,
|
||||
_reply_markup: Option<InlineKeyboardMarkup>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.messages.lock().push(text);
|
||||
match self.next("send_message") {
|
||||
Outcome::MessageOk => Ok(MockSender::SENT_ID),
|
||||
Outcome::MessageErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_message"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn answer_callback_query(
|
||||
&self,
|
||||
_id: CallbackQueryId,
|
||||
text: Option<String>,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
// Always succeeds: the toast is cosmetic, so the script stays
|
||||
// focused on the outcomes a test cares about.
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("answer_callback_query");
|
||||
self.answers.lock().push(text);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn edit_message_caption(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_message_id: MessageId,
|
||||
caption: String,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.captions.lock().push(caption);
|
||||
match self.next("edit_message_caption") {
|
||||
Outcome::EditOk => Ok(()),
|
||||
Outcome::EditErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for edit_message_caption"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_message(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_message_id: MessageId,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
// Deletion is fire-and-forget in every caller; always succeeds.
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("delete_message");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn send_chat_action(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_action: ChatAction,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("send_chat_action");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) mod test_support;
|
||||
@@ -0,0 +1,537 @@
|
||||
//! Test support: a scripted [`MediaSender`] mock (no Telegram API involved)
|
||||
//! and the stand-in Telegram API the real-`Bot` tests talk to.
|
||||
//!
|
||||
//! [`MediaSender`]: super::MediaSender
|
||||
|
||||
use super::*;
|
||||
use parking_lot::Mutex;
|
||||
use teloxide::types::InlineQueryResult;
|
||||
|
||||
/// One scripted outcome, consumed front-to-back; the last entry repeats
|
||||
/// for further calls of the same method kind.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Outcome {
|
||||
GroupOk,
|
||||
GroupErr,
|
||||
AnimationOk,
|
||||
AnimationErr,
|
||||
CopyOk,
|
||||
CopyErr,
|
||||
/// An error from `send_message` (replies are fire-and-forget, so an
|
||||
/// error is fine for tests).
|
||||
MessageErr,
|
||||
/// A successful `send_message`, returning message id [`MockSender::SENT_ID`].
|
||||
MessageOk,
|
||||
EditOk,
|
||||
EditErr,
|
||||
}
|
||||
|
||||
/// A stand-in for `api.telegram.org` for the tests that must drive a real
|
||||
/// `Bot` — its request building, the per-chat limiter, the bot-wide budget
|
||||
/// — which the scripted mock bypasses entirely. Records every call and
|
||||
/// answers the smallest result each method needs.
|
||||
pub(crate) mod fake_api {
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
pub(crate) struct FakeApi {
|
||||
url: url::Url,
|
||||
calls: Arc<Mutex<Vec<(String, serde_json::Value)>>>,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl FakeApi {
|
||||
/// Binds an ephemeral port and serves until dropped.
|
||||
pub(crate) async fn start() -> FakeApi {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||
let recorded = Arc::clone(&calls);
|
||||
let server = tokio::spawn(async move {
|
||||
while let Ok((mut socket, _)) = listener.accept().await {
|
||||
let recorded = Arc::clone(&recorded);
|
||||
tokio::spawn(async move {
|
||||
let Some((method, body)) = read_request(&mut socket).await else {
|
||||
return;
|
||||
};
|
||||
recorded.lock().push((method.clone(), body));
|
||||
let payload = serde_json::json!({
|
||||
"ok": true,
|
||||
"result": canned_result(&method),
|
||||
})
|
||||
.to_string();
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
|
||||
content-length: {}\r\nconnection: close\r\n\r\n{}",
|
||||
payload.len(),
|
||||
payload
|
||||
);
|
||||
let _ = socket.write_all(response.as_bytes()).await;
|
||||
let _ = socket.flush().await;
|
||||
});
|
||||
}
|
||||
});
|
||||
FakeApi {
|
||||
// Trailing slash: teloxide appends `bot<token>/<method>`.
|
||||
url: url::Url::parse(&format!("http://{addr}/")).unwrap(),
|
||||
calls,
|
||||
server,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where to point a `Bot`: `Bot::new(token).set_api_url(api.url())`.
|
||||
pub(crate) fn url(&self) -> url::Url {
|
||||
self.url.clone()
|
||||
}
|
||||
|
||||
/// Method names in call order.
|
||||
pub(crate) fn methods(&self) -> Vec<String> {
|
||||
self.calls.lock().iter().map(|(m, _)| m.clone()).collect()
|
||||
}
|
||||
|
||||
/// The JSON body of the first call to `method` (`Null` for a body
|
||||
/// that is not JSON, i.e. a multipart upload).
|
||||
pub(crate) fn body(&self, method: &str) -> serde_json::Value {
|
||||
self.calls
|
||||
.lock()
|
||||
.iter()
|
||||
.find(|(m, _)| m == method)
|
||||
.map(|(_, body)| body.clone())
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FakeApi {
|
||||
fn drop(&mut self) {
|
||||
self.server.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest result teloxide can deserialize for a method. The names
|
||||
/// arrive as the payload type's own — `SendMediaGroup`, not
|
||||
/// `sendMediaGroup`: teloxide builds the URL from that, and the Bot API
|
||||
/// accepts the spelling.
|
||||
fn canned_result(method: &str) -> serde_json::Value {
|
||||
match method {
|
||||
"CopyMessages" => serde_json::json!([{ "message_id": 11 }]),
|
||||
"SendMediaGroup" => serde_json::json!([minimal_message()]),
|
||||
"SendMessage" | "SendAnimation" | "EditMessageCaption" => minimal_message(),
|
||||
_ => serde_json::Value::Bool(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn minimal_message() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"message_id": 1,
|
||||
"date": 0,
|
||||
"chat": { "id": 1, "type": "private" },
|
||||
})
|
||||
}
|
||||
|
||||
/// One HTTP/1.1 request: the head up to the blank line, then
|
||||
/// `content-length` bytes of body — JSON for most methods, multipart
|
||||
/// for the media ones (teloxide sends `SendMediaGroup` that way).
|
||||
async fn read_request(socket: &mut TcpStream) -> Option<(String, serde_json::Value)> {
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
let n = socket.read(&mut chunk).await.ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
let Some(headers_end) = find(&buf, b"\r\n\r\n") else {
|
||||
continue;
|
||||
};
|
||||
let head = String::from_utf8_lossy(&buf[..headers_end]).to_string();
|
||||
let length: usize = head
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
line.to_ascii_lowercase()
|
||||
.strip_prefix("content-length:")
|
||||
.and_then(|v| v.trim().parse().ok())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let body_start = headers_end + 4;
|
||||
while buf.len() < body_start + length {
|
||||
let n = socket.read(&mut chunk).await.ok()?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
let method = head
|
||||
.lines()
|
||||
.next()
|
||||
// `POST /bot<token>/<method>`
|
||||
.and_then(|line| line.split(' ').nth(1))
|
||||
.and_then(|path| path.rsplit('/').next())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let body = parse_body(&buf[body_start..], &head);
|
||||
return Some((method, body));
|
||||
}
|
||||
}
|
||||
|
||||
/// The request body as JSON: either the JSON body itself, or a
|
||||
/// multipart form flattened into an object (each part's value parsed as
|
||||
/// JSON when it is one, so `media` comes back as its array).
|
||||
fn parse_body(body: &[u8], head: &str) -> serde_json::Value {
|
||||
let content_type = head
|
||||
.lines()
|
||||
.find(|line| line.to_ascii_lowercase().starts_with("content-type:"))
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let Some(boundary) = content_type
|
||||
.split("boundary=")
|
||||
.nth(1)
|
||||
.map(|b| b.trim().trim_matches('"').to_string())
|
||||
else {
|
||||
return serde_json::from_slice(body).unwrap_or_default();
|
||||
};
|
||||
let text = String::from_utf8_lossy(body);
|
||||
let mut fields = serde_json::Map::new();
|
||||
for part in text.split(&format!("--{boundary}")).skip(1) {
|
||||
let Some((part_head, value)) = part.split_once("\r\n\r\n") else {
|
||||
continue;
|
||||
};
|
||||
let Some(name) = part_head
|
||||
.split("name=\"")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let value = value.trim_end_matches("\r\n");
|
||||
fields.insert(
|
||||
name.to_string(),
|
||||
serde_json::from_str(value).unwrap_or_else(|_| value.into()),
|
||||
);
|
||||
}
|
||||
serde_json::Value::Object(fields)
|
||||
}
|
||||
|
||||
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
haystack
|
||||
.windows(needle.len())
|
||||
.position(|window| window == needle)
|
||||
}
|
||||
}
|
||||
|
||||
/// Replays a script and records what was sent, so tests can assert the
|
||||
/// user-visible text a path produced.
|
||||
pub(crate) struct MockSender {
|
||||
script: Mutex<Vec<Outcome>>,
|
||||
cursor: Mutex<usize>,
|
||||
calls: Mutex<Vec<&'static str>>,
|
||||
messages: Mutex<Vec<String>>,
|
||||
captions: Mutex<Vec<String>>,
|
||||
answers: Mutex<Vec<Option<String>>>,
|
||||
/// `(chat, message, text)` of every text rewrite, in order.
|
||||
edited_texts: Mutex<Vec<(i64, i64, String)>>,
|
||||
/// What each `send_animation` handed Telegram: a URL or a file id as that
|
||||
/// string, an upload as `attach://<id>`.
|
||||
animation_files: Mutex<Vec<String>>,
|
||||
/// What every `answer_inline_query` answered with, one entry per result:
|
||||
/// `cached_photo:<file id>`, `photo:<url>`, and so on. An answer with no
|
||||
/// results is recorded as an empty inner vec.
|
||||
inline_answers: Mutex<Vec<Vec<String>>>,
|
||||
/// Builds the error every `*Err` outcome returns (RequestError is not
|
||||
/// cloneable, so the factory recreates it per call).
|
||||
error: Box<dyn Fn() -> RequestError + Send + Sync>,
|
||||
}
|
||||
|
||||
/// A one-string description of an inline result: the kind plus the file id it
|
||||
/// is served from, or the URL it points Telegram at.
|
||||
fn inline_result_tag(result: &InlineQueryResult) -> String {
|
||||
match result {
|
||||
InlineQueryResult::CachedPhoto(r) => format!("cached_photo:{}", r.photo_file_id.0),
|
||||
InlineQueryResult::CachedVideo(r) => format!("cached_video:{}", r.video_file_id.0),
|
||||
InlineQueryResult::CachedMpeg4Gif(r) => format!("cached_gif:{}", r.mpeg4_file_id.0),
|
||||
InlineQueryResult::Photo(r) => format!("photo:{}", r.photo_url),
|
||||
InlineQueryResult::Video(r) => format!("video:{}", r.video_url),
|
||||
InlineQueryResult::Mpeg4Gif(r) => format!("gif:{}", r.mpeg4_url),
|
||||
other => format!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest `Message` the send paths accept, for the outcomes that must
|
||||
/// report one (`send_animation` reads its id, and its media for the cache).
|
||||
pub(crate) fn mock_message(id: i64) -> Message {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"message_id": id,
|
||||
"date": 0,
|
||||
"chat": { "id": 1, "type": "private" },
|
||||
}))
|
||||
.expect("a minimal message deserializes")
|
||||
}
|
||||
|
||||
impl MockSender {
|
||||
/// The message id a successful `send_message` reports.
|
||||
pub(crate) const SENT_ID: i64 = 1;
|
||||
|
||||
pub(crate) fn scripted(
|
||||
script: Vec<Outcome>,
|
||||
error: impl Fn() -> RequestError + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
MockSender {
|
||||
script: Mutex::new(script),
|
||||
cursor: Mutex::new(0),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
messages: Mutex::new(Vec::new()),
|
||||
captions: Mutex::new(Vec::new()),
|
||||
answers: Mutex::new(Vec::new()),
|
||||
edited_texts: Mutex::new(Vec::new()),
|
||||
animation_files: Mutex::new(Vec::new()),
|
||||
inline_answers: Mutex::new(Vec::new()),
|
||||
error: Box::new(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Method names in call order (e.g. `["send_media_group",
|
||||
/// "send_media_group"]` proves the fallback re-sent).
|
||||
pub(crate) fn calls(&self) -> Vec<&'static str> {
|
||||
self.calls.lock().clone()
|
||||
}
|
||||
|
||||
/// Texts of the plain messages sent, in order.
|
||||
pub(crate) fn messages(&self) -> Vec<String> {
|
||||
self.messages.lock().clone()
|
||||
}
|
||||
|
||||
/// Captions passed to `edit_message_caption`, in order.
|
||||
pub(crate) fn captions(&self) -> Vec<String> {
|
||||
self.captions.lock().clone()
|
||||
}
|
||||
|
||||
/// Toast texts of the answered callback queries, in order.
|
||||
pub(crate) fn answers(&self) -> Vec<Option<String>> {
|
||||
self.answers.lock().clone()
|
||||
}
|
||||
|
||||
/// `(chat, message, text)` of every `edit_message_text`, in order.
|
||||
pub(crate) fn edited_texts(&self) -> Vec<(i64, i64, String)> {
|
||||
self.edited_texts.lock().clone()
|
||||
}
|
||||
|
||||
/// What every `send_animation` handed Telegram, in order.
|
||||
pub(crate) fn animation_files(&self) -> Vec<String> {
|
||||
self.animation_files.lock().clone()
|
||||
}
|
||||
|
||||
/// What every `answer_inline_query` answered with, in call order.
|
||||
pub(crate) fn inline_answers(&self) -> Vec<Vec<String>> {
|
||||
self.inline_answers.lock().clone()
|
||||
}
|
||||
|
||||
fn next(&self, kind: &'static str) -> Outcome {
|
||||
self.calls.lock().push(kind);
|
||||
let script = self.script.lock();
|
||||
let mut cursor = self.cursor.lock();
|
||||
if script.is_empty() {
|
||||
panic!("mock script exhausted: {kind}");
|
||||
}
|
||||
let idx = (*cursor).min(script.len() - 1);
|
||||
*cursor = idx + 1;
|
||||
script[idx]
|
||||
}
|
||||
|
||||
fn error(&self) -> RequestError {
|
||||
(self.error)()
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaSender for MockSender {
|
||||
fn send_media_group(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_reply_to: MessageId,
|
||||
items: Vec<InputMedia>,
|
||||
) -> BoxFuture<'_, Result<Vec<Message>, RequestError>> {
|
||||
Box::pin(async move {
|
||||
// Record the captions exactly as Telegram receives them (only
|
||||
// the first item of a group carries one), so tests can assert
|
||||
// what a recipient sees.
|
||||
self.captions
|
||||
.lock()
|
||||
.extend(items.iter().filter_map(|item| match item {
|
||||
InputMedia::Photo(photo) => photo.caption.clone(),
|
||||
InputMedia::Video(video) => video.caption.clone(),
|
||||
InputMedia::Animation(animation) => animation.caption.clone(),
|
||||
_ => None,
|
||||
}));
|
||||
match self.next("send_media_group") {
|
||||
Outcome::GroupOk => Ok(Vec::new()),
|
||||
Outcome::GroupErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_media_group"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_animation<'a>(
|
||||
&'a self,
|
||||
_chat_id: ChatId,
|
||||
_reply_to: MessageId,
|
||||
_caption: &'a str,
|
||||
_spoiler: bool,
|
||||
file: InputFile,
|
||||
) -> BoxFuture<'a, Result<Message, RequestError>> {
|
||||
// Record what Telegram was handed: a URL or a file id serializes as
|
||||
// that string, an upload as `attach://<id>`. Enough to tell a cached
|
||||
// send (which must not re-upload) from a fresh one.
|
||||
self.animation_files.lock().push(
|
||||
serde_json::to_value(&file)
|
||||
.ok()
|
||||
.and_then(|value| value.as_str().map(str::to_string))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
Box::pin(async move {
|
||||
match self.next("send_animation") {
|
||||
Outcome::AnimationOk => Ok(mock_message(MockSender::SENT_ID)),
|
||||
Outcome::AnimationErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_animation"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn copy_messages(
|
||||
&self,
|
||||
_to: ChatId,
|
||||
_from: ChatId,
|
||||
_ids: Vec<MessageId>,
|
||||
) -> BoxFuture<'_, Result<Vec<MessageId>, RequestError>> {
|
||||
Box::pin(async move {
|
||||
match self.next("copy_messages") {
|
||||
Outcome::CopyOk => Ok(vec![MessageId(1)]),
|
||||
Outcome::CopyErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for copy_messages"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_message(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
text: String,
|
||||
_reply_to: Option<MessageId>,
|
||||
_reply_markup: Option<InlineKeyboardMarkup>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.messages.lock().push(text);
|
||||
match self.next("send_message") {
|
||||
Outcome::MessageOk => Ok(MockSender::SENT_ID),
|
||||
Outcome::MessageErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_message"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn send_html_message(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
text: String,
|
||||
_reply_to: Option<MessageId>,
|
||||
) -> BoxFuture<'_, Result<i64, RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.messages.lock().push(text);
|
||||
match self.next("send_html_message") {
|
||||
Outcome::MessageOk => Ok(MockSender::SENT_ID),
|
||||
Outcome::MessageErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for send_html_message"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn answer_inline_query(
|
||||
&self,
|
||||
_id: InlineQueryId,
|
||||
results: Vec<InlineQueryResult>,
|
||||
cache_time: u32,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
// Records what the answer was made of, so a test can tell a cached
|
||||
// (file-id) result from a URL one. Always succeeds: the debounce's
|
||||
// release path is covered by `DebounceStates` directly.
|
||||
assert_eq!(
|
||||
cache_time, 300,
|
||||
"the inline cache window is what the tests pin"
|
||||
);
|
||||
self.calls.lock().push("answer_inline_query");
|
||||
self.inline_answers
|
||||
.lock()
|
||||
.push(results.iter().map(inline_result_tag).collect());
|
||||
Box::pin(async move { Ok(()) })
|
||||
}
|
||||
|
||||
fn answer_callback_query(
|
||||
&self,
|
||||
_id: CallbackQueryId,
|
||||
text: Option<String>,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
// Always succeeds: the toast is cosmetic, so the script stays
|
||||
// focused on the outcomes a test cares about.
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("answer_callback_query");
|
||||
self.answers.lock().push(text);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn edit_message_text(
|
||||
&self,
|
||||
chat_id: ChatId,
|
||||
message_id: MessageId,
|
||||
text: String,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
// Always succeeds: the only caller is the expiry sweep, which
|
||||
// tolerates a failure (a prompt the user already deleted), so the
|
||||
// script stays free for the call the test is about.
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("edit_message_text");
|
||||
self.edited_texts
|
||||
.lock()
|
||||
.push((chat_id.0, message_id.0 as i64, text));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn edit_message_caption(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_message_id: MessageId,
|
||||
caption: String,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.captions.lock().push(caption);
|
||||
match self.next("edit_message_caption") {
|
||||
Outcome::EditOk => Ok(()),
|
||||
Outcome::EditErr => Err(self.error()),
|
||||
other => panic!("unexpected outcome {other:?} for edit_message_caption"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn delete_message(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_message_id: MessageId,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
// Deletion is fire-and-forget in every caller; always succeeds.
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("delete_message");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn send_chat_action(
|
||||
&self,
|
||||
_chat_id: ChatId,
|
||||
_action: ChatAction,
|
||||
) -> BoxFuture<'_, Result<(), RequestError>> {
|
||||
Box::pin(async move {
|
||||
self.calls.lock().push("send_chat_action");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
+300
-42
@@ -12,6 +12,7 @@
|
||||
//! and 24-bit RGB have no alpha channel).
|
||||
|
||||
use std::io::Write;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use fast_image_resize as fir;
|
||||
use tempfile::NamedTempFile;
|
||||
@@ -22,13 +23,137 @@ use tempfile::NamedTempFile;
|
||||
pub const PHOTO_MAX_DIMENSION_SUM: u32 = 10000;
|
||||
/// Resize target with a safety margin so rounding cannot cross the cap.
|
||||
pub const PHOTO_TARGET_DIMENSION_SUM: u32 = 9900;
|
||||
/// Upload cap (bytes): files above this are not uploaded; the bot falls back
|
||||
/// to a smaller media URL instead.
|
||||
/// Photo upload cap (bytes): Telegram rejects a larger `sendPhoto`, so the bot
|
||||
/// falls back to a smaller media URL instead. Videos and animations have their
|
||||
/// own, larger cap — `send::upload::MAX_MEDIA_UPLOAD_BYTES` — and never become
|
||||
/// photos.
|
||||
pub const MAX_UPLOAD_BYTES: u64 = 10 * 1024 * 1024;
|
||||
/// Decode budget (bytes): a larger intermediate buffer is not worth the peak
|
||||
/// memory; the photo degrades to the smaller URL instead. Also the cap for
|
||||
/// downloading photos in the send fallback (they must be downloaded whole).
|
||||
/// memory; the photo degrades to the smaller URL instead.
|
||||
pub(crate) const MAX_DECODE_BYTES: u64 = 512 * 1024 * 1024;
|
||||
/// Cap for *downloading* a photo in the send fallback, kept separate from the
|
||||
/// decode budget above: the whole body is buffered before it is processed, once
|
||||
/// per download slot in flight, while the decode budget is about a single
|
||||
/// buffer. Telegram's *photo* upload cap is 10 MiB, so a photo this large can
|
||||
/// only be sent after a downscale that its reduced variant serves just as
|
||||
/// well — over the cap the item degrades to the smaller URL
|
||||
/// (`FallbackError::MediaTooLarge`), it is never an error.
|
||||
pub(crate) const MAX_PHOTO_DOWNLOAD_BYTES: u64 = 32 * 1024 * 1024;
|
||||
|
||||
/// Size of one memory-budget unit. Small enough that ordinary photos do not
|
||||
/// queue behind each other, coarse enough that the semaphore is not a counter
|
||||
/// per megabyte.
|
||||
const MEMORY_UNIT_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
/// Process-wide memory budget for photo preparation, in [`MEMORY_UNIT_BYTES`]
|
||||
/// units: 512 MiB. `PREP_SLOTS` bounds how many items are prepared at once but
|
||||
/// not how much memory they hold — one photo's decode buffer can be up to
|
||||
/// [`MAX_DECODE_BYTES`] (512 MiB), and the guard that refuses a bigger one is
|
||||
/// per photo, so six concurrent photos could peak near 3 GiB on a host sized
|
||||
/// for a fraction of that. Each item charges what it actually holds (its
|
||||
/// downloaded bytes plus the decode buffer its header predicts), so a 10-image
|
||||
/// album of ordinary photos still runs several at a time while huge ones
|
||||
/// serialize.
|
||||
const MEMORY_UNITS: u32 = 8;
|
||||
|
||||
static MEMORY_BUDGET: LazyLock<std::sync::Arc<tokio::sync::Semaphore>> =
|
||||
LazyLock::new(|| std::sync::Arc::new(tokio::sync::Semaphore::new(MEMORY_UNITS as usize)));
|
||||
|
||||
/// The buffer `w`×`h` needs in `channels` output channels — the one number the
|
||||
/// per-photo guards and the reservation below both use, so they cannot drift.
|
||||
fn decode_bytes(w: u32, h: u32, channels: usize) -> u64 {
|
||||
(w as u64) * (h as u64) * channels as u64
|
||||
}
|
||||
|
||||
fn memory_units(bytes: u64) -> u32 {
|
||||
bytes
|
||||
.div_ceil(MEMORY_UNIT_BYTES)
|
||||
.clamp(1, MEMORY_UNITS as u64) as u32
|
||||
}
|
||||
|
||||
/// Conservative peak estimate for one photo preparation. The source bytes,
|
||||
/// decoded pixels, any RGBA-to-RGB copy, resize output, and encoded output
|
||||
/// can coexist briefly; charging only `w*h*channels` under-counts the real
|
||||
/// process peak.
|
||||
fn processing_peak_bytes(downloaded: u64, decode: u64) -> u64 {
|
||||
downloaded
|
||||
.saturating_add(decode)
|
||||
.saturating_add(decode / 2)
|
||||
.saturating_add(decode)
|
||||
.saturating_add(MAX_UPLOAD_BYTES)
|
||||
}
|
||||
|
||||
/// Reserves `bytes` of the preparation budget until the returned permit drops.
|
||||
pub(crate) async fn reserve_memory(bytes: u64) -> tokio::sync::OwnedSemaphorePermit {
|
||||
reserve(std::sync::Arc::clone(&MEMORY_BUDGET), bytes).await
|
||||
}
|
||||
|
||||
/// [`reserve_memory`] against a caller-chosen budget; the tests pass their own
|
||||
/// so they do not fight over the process-wide one.
|
||||
async fn reserve(
|
||||
budget: std::sync::Arc<tokio::sync::Semaphore>,
|
||||
bytes: u64,
|
||||
) -> tokio::sync::OwnedSemaphorePermit {
|
||||
budget
|
||||
.acquire_many_owned(memory_units(bytes))
|
||||
.await
|
||||
.expect("memory budget semaphore closed")
|
||||
}
|
||||
|
||||
/// The processing decision for one downloaded photo, taken from its header
|
||||
/// alone — the one place the within-limits test and the decode-size guard
|
||||
/// live, so the memory reservation and the branch that acts on it cannot
|
||||
/// drift.
|
||||
enum PhotoPlan {
|
||||
/// Already within Telegram's limits (dimension sum and upload cap): the
|
||||
/// downloaded file is uploaded untouched, no decode buffer.
|
||||
AsIs,
|
||||
/// Needs processing: the decode buffer it will allocate, in bytes.
|
||||
Decode(u64),
|
||||
/// Processing would need a decode buffer over [`MAX_DECODE_BYTES`]: the
|
||||
/// caller falls back to the item's smaller URL.
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
/// [`PhotoPlan`] for a photo whose header said `w`×`h` in `channels` output
|
||||
/// channels, `len` bytes long.
|
||||
fn plan_photo(w: u32, h: u32, len: usize, channels: usize) -> PhotoPlan {
|
||||
if (w as u64) + (h as u64) <= PHOTO_MAX_DIMENSION_SUM as u64 && len as u64 <= MAX_UPLOAD_BYTES {
|
||||
return PhotoPlan::AsIs;
|
||||
}
|
||||
let bytes = decode_bytes(w, h, channels);
|
||||
if bytes > MAX_DECODE_BYTES {
|
||||
PhotoPlan::TooLarge
|
||||
} else {
|
||||
PhotoPlan::Decode(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// The memory budget for one photo preparation, from its header alone. The
|
||||
/// result includes the already-buffered download and the conservative decode,
|
||||
/// transform, resize, and encoding peak; the caller holds that reservation
|
||||
/// through the whole preparation.
|
||||
pub(crate) fn prepare_budget_bytes(bytes: &[u8]) -> u64 {
|
||||
let plan = if let Some((w, h, _depth, color)) = parse_png_header(bytes) {
|
||||
plan_photo(w, h, bytes.len(), output_channels(color))
|
||||
} else if let Some((w, h)) = jpeg_dims(bytes) {
|
||||
plan_photo(w, h, bytes.len(), 3)
|
||||
} else {
|
||||
PhotoPlan::AsIs
|
||||
};
|
||||
match plan {
|
||||
PhotoPlan::Decode(decode) => processing_peak_bytes(bytes.len() as u64, decode),
|
||||
PhotoPlan::AsIs | PhotoPlan::TooLarge => bytes.len() as u64,
|
||||
}
|
||||
}
|
||||
|
||||
/// JPEG dimensions from the headers, without decoding any pixels.
|
||||
fn jpeg_dims(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
let mut decoder = zune_jpeg::JpegDecoder::new(std::io::Cursor::new(bytes));
|
||||
decoder.decode_headers().ok()?;
|
||||
let info = decoder.info()?;
|
||||
Some((info.width as u32, info.height as u32))
|
||||
}
|
||||
/// JPEG output quality (1-100).
|
||||
const JPEG_QUALITY: u8 = 90;
|
||||
|
||||
@@ -80,31 +205,15 @@ pub fn prepare_photo(file: NamedTempFile, bytes: &[u8]) -> Result<PhotoPrep, Str
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the PNG IHDR (bytes 8..26: signature + length + "IHDR" + width +
|
||||
/// height + bit depth + color type).
|
||||
/// The PNG's IHDR as the crate reads it (signature through the first IDAT):
|
||||
/// width/height/depth/color decide the plan and the decode channels, without
|
||||
/// decoding any pixels.
|
||||
fn parse_png_header(bytes: &[u8]) -> Option<(u32, u32, png::BitDepth, png::ColorType)> {
|
||||
if !bytes.starts_with(b"\x89PNG\r\n\x1a\n") || bytes.len() < 26 {
|
||||
return None;
|
||||
}
|
||||
let w = u32::from_be_bytes(bytes.get(16..20)?.try_into().ok()?);
|
||||
let h = u32::from_be_bytes(bytes.get(20..24)?.try_into().ok()?);
|
||||
let depth = match *bytes.get(24)? {
|
||||
1 => png::BitDepth::One,
|
||||
2 => png::BitDepth::Two,
|
||||
4 => png::BitDepth::Four,
|
||||
8 => png::BitDepth::Eight,
|
||||
16 => png::BitDepth::Sixteen,
|
||||
_ => return None,
|
||||
};
|
||||
let color = match *bytes.get(25)? {
|
||||
0 => png::ColorType::Grayscale,
|
||||
2 => png::ColorType::Rgb,
|
||||
3 => png::ColorType::Indexed,
|
||||
4 => png::ColorType::GrayscaleAlpha,
|
||||
6 => png::ColorType::Rgba,
|
||||
_ => return None,
|
||||
};
|
||||
Some((w, h, depth, color))
|
||||
let reader = png::Decoder::new(std::io::Cursor::new(bytes))
|
||||
.read_info()
|
||||
.ok()?;
|
||||
let info = reader.info();
|
||||
Some((info.width, info.height, info.bit_depth, info.color_type))
|
||||
}
|
||||
|
||||
/// Output channels of a decoded frame for the given color type (post
|
||||
@@ -199,6 +308,7 @@ fn encode_jpeg(pix: &PixBuf, w: u32, h: u32) -> Result<Vec<u8>, String> {
|
||||
|
||||
fn write_temp(bytes: &[u8], ext: &str) -> Result<NamedTempFile, String> {
|
||||
let mut file = tempfile::Builder::new()
|
||||
.prefix(x_media::TEMP_FILE_PREFIX)
|
||||
.suffix(&format!(".{ext}"))
|
||||
.tempfile()
|
||||
.map_err(|e| format!("temp file failed: {e}"))?;
|
||||
@@ -209,7 +319,7 @@ fn write_temp(bytes: &[u8], ext: &str) -> Result<NamedTempFile, String> {
|
||||
}
|
||||
|
||||
fn target_dims(w: u32, h: u32) -> (u32, u32) {
|
||||
let scale = PHOTO_TARGET_DIMENSION_SUM as f64 / (w + h) as f64;
|
||||
let scale = PHOTO_TARGET_DIMENSION_SUM as f64 / ((w as u64) + (h as u64)) as f64;
|
||||
(
|
||||
((w as f64 * scale).round() as u32).max(1),
|
||||
((h as f64 * scale).round() as u32).max(1),
|
||||
@@ -221,17 +331,16 @@ fn target_dims(w: u32, h: u32) -> (u32, u32) {
|
||||
/// over the upload cap afterwards becomes JPEG.
|
||||
fn prepare_png(file: NamedTempFile, bytes: &[u8]) -> Result<PhotoPrep, String> {
|
||||
let (w, h, _bit_depth, color_type) = parse_png_header(bytes).ok_or("invalid PNG header")?;
|
||||
let size_over = bytes.len() as u64 > MAX_UPLOAD_BYTES;
|
||||
if w + h <= PHOTO_MAX_DIMENSION_SUM && !size_over {
|
||||
let channels = output_channels(color_type);
|
||||
let plan = plan_photo(w, h, bytes.len(), channels);
|
||||
if let PhotoPlan::AsIs = plan {
|
||||
return Ok(PhotoPrep::Upload(file));
|
||||
}
|
||||
log::debug!(
|
||||
"photo {w}x{h} ({_bit_depth:?} {color_type:?}, {} bytes) needs processing",
|
||||
bytes.len()
|
||||
);
|
||||
|
||||
let channels = output_channels(color_type);
|
||||
if (w as u64) * (h as u64) * channels as u64 > MAX_DECODE_BYTES {
|
||||
if let PhotoPlan::TooLarge = plan {
|
||||
log::warn!("photo decode buffer exceeds the memory budget; falling back to smaller media");
|
||||
return Ok(PhotoPrep::UseFallback);
|
||||
}
|
||||
@@ -267,7 +376,7 @@ fn prepare_png(file: NamedTempFile, bytes: &[u8]) -> Result<PhotoPrep, String> {
|
||||
};
|
||||
|
||||
let (mut w, mut h) = (out_w, out_h);
|
||||
if w + h > PHOTO_MAX_DIMENSION_SUM {
|
||||
if (w as u64) + (h as u64) > PHOTO_MAX_DIMENSION_SUM as u64 {
|
||||
let (nw, nh) = target_dims(w, h);
|
||||
pix = resize_pix(pix, w, h, nw, nh)?;
|
||||
(w, h) = (nw, nh);
|
||||
@@ -298,18 +407,18 @@ fn prepare_jpeg(file: NamedTempFile, bytes: &[u8]) -> Result<PhotoPrep, String>
|
||||
.map_err(|e| format!("jpeg headers: {e}"))?;
|
||||
let info = decoder.info().ok_or("jpeg info unavailable")?;
|
||||
let (w, h) = (info.width as u32, info.height as u32);
|
||||
let size_over = bytes.len() as u64 > MAX_UPLOAD_BYTES;
|
||||
if w + h <= PHOTO_MAX_DIMENSION_SUM && !size_over {
|
||||
let plan = plan_photo(w, h, bytes.len(), 3);
|
||||
if let PhotoPlan::AsIs = plan {
|
||||
return Ok(PhotoPrep::Upload(file));
|
||||
}
|
||||
if (w as u64) * (h as u64) * 3 > MAX_DECODE_BYTES {
|
||||
if let PhotoPlan::TooLarge = plan {
|
||||
log::warn!("photo decode buffer exceeds the memory budget; falling back to smaller media");
|
||||
return Ok(PhotoPrep::UseFallback);
|
||||
}
|
||||
let pixels = decoder.decode().map_err(|e| format!("jpeg decode: {e}"))?;
|
||||
let mut pix = PixBuf::Rgb(pixels);
|
||||
let (mut w, mut h) = (w, h);
|
||||
if w + h > PHOTO_MAX_DIMENSION_SUM {
|
||||
if (w as u64) + (h as u64) > PHOTO_MAX_DIMENSION_SUM as u64 {
|
||||
let (nw, nh) = target_dims(w, h);
|
||||
pix = resize_pix(pix, w, h, nw, nh)?;
|
||||
(w, h) = (nw, nh);
|
||||
@@ -326,15 +435,154 @@ fn prepare_jpeg(file: NamedTempFile, bytes: &[u8]) -> Result<PhotoPrep, String>
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
fn png_header(w: u32, h: u32, depth: u8, color: u8) -> Vec<u8> {
|
||||
let mut bytes = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".to_vec();
|
||||
bytes.extend(w.to_be_bytes());
|
||||
bytes.extend(h.to_be_bytes());
|
||||
bytes.extend([depth, color, 0, 0, 0]);
|
||||
// A correct IHDR CRC plus an IDAT chunk header: `png::Decoder` verifies
|
||||
// the CRC and `read_info` stops at the first IDAT — all the header
|
||||
// read needs. The hand-rolled parser this fixture used to feed stopped
|
||||
// four bytes earlier and checked neither.
|
||||
bytes.extend(crc32(&bytes[12..]).to_be_bytes());
|
||||
bytes.extend(0u32.to_be_bytes()); // IDAT payload length (never read)
|
||||
bytes.extend(b"IDAT");
|
||||
bytes
|
||||
}
|
||||
|
||||
/// CRC-32 as PNG chunks use it (IEEE, reflected).
|
||||
fn crc32(bytes: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in bytes {
|
||||
crc ^= b as u32;
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & (crc & 1).wrapping_neg());
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// The budget is a *process-wide* memory bound: `PREP_SLOTS` (6) caps how
|
||||
/// many photos are prepared at once, but six max-size photos would still
|
||||
/// hold six decode buffers of up to 512 MiB each.
|
||||
#[tokio::test]
|
||||
async fn huge_decodes_cannot_overlap_but_do_run_alone() {
|
||||
let budget = std::sync::Arc::new(tokio::sync::Semaphore::new(MEMORY_UNITS as usize));
|
||||
let max_photo = processing_peak_bytes(MAX_PHOTO_DOWNLOAD_BYTES, MAX_DECODE_BYTES);
|
||||
|
||||
// One max-size photo fits (clamped to the whole budget), so it can
|
||||
// never wait for budget that cannot exist.
|
||||
let first = tokio::time::timeout(
|
||||
Duration::from_millis(50),
|
||||
reserve(budget.clone(), max_photo),
|
||||
)
|
||||
.await
|
||||
.expect("a max-size photo must not wait");
|
||||
// A second one of the same size has to wait for the first to finish.
|
||||
assert!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(50),
|
||||
reserve(budget.clone(), max_photo)
|
||||
)
|
||||
.await
|
||||
.is_err(),
|
||||
"two max-size decodes overlapped"
|
||||
);
|
||||
drop(first);
|
||||
assert!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(50),
|
||||
reserve(budget.clone(), max_photo)
|
||||
)
|
||||
.await
|
||||
.is_ok(),
|
||||
"the budget was not released"
|
||||
);
|
||||
}
|
||||
|
||||
/// A 10-image album of ordinary photos must not serialize: the conservative
|
||||
/// peak still allows several small/medium photos to run together.
|
||||
#[tokio::test]
|
||||
async fn ordinary_photos_share_the_budget() {
|
||||
let budget = std::sync::Arc::new(tokio::sync::Semaphore::new(MEMORY_UNITS as usize));
|
||||
// A 4 MiB photo that decodes to ~36 MiB (4000x3000 RGB): its peak
|
||||
// costs two 64 MiB units, so four fit in the 512 MiB process budget.
|
||||
let ordinary = processing_peak_bytes(4 * 1024 * 1024, 36 * 1024 * 1024);
|
||||
assert_eq!(memory_units(ordinary), 2);
|
||||
let mut held = Vec::new();
|
||||
for i in 0..4 {
|
||||
held.push(
|
||||
tokio::time::timeout(Duration::from_millis(50), reserve(budget.clone(), ordinary))
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("ordinary photo {i} waited for budget")),
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), reserve(budget, ordinary))
|
||||
.await
|
||||
.is_err(),
|
||||
"the budget should reject a fifth two-unit photo"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_units_round_up_and_clamp() {
|
||||
assert_eq!(memory_units(1), 1);
|
||||
assert_eq!(memory_units(MEMORY_UNIT_BYTES), 1);
|
||||
assert_eq!(memory_units(MEMORY_UNIT_BYTES + 1), 2);
|
||||
// Never more than exists, or the item waits for itself forever.
|
||||
assert_eq!(memory_units(u64::MAX), MEMORY_UNITS);
|
||||
// One item's worst case (a max download plus a max decode) takes the
|
||||
// whole budget by itself.
|
||||
assert_eq!(
|
||||
memory_units(MAX_DECODE_BYTES + MAX_PHOTO_DOWNLOAD_BYTES),
|
||||
MEMORY_UNITS
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapping_dimension_sum_never_reads_as_within_limits() {
|
||||
// u32::MAX + 2 wraps to 1: the pre-u64 sum advertised AsIs here and
|
||||
// handed the absurd dimensions to Telegram untouched.
|
||||
assert!(matches!(
|
||||
plan_photo(u32::MAX, 2, 16, 3),
|
||||
PhotoPlan::TooLarge
|
||||
));
|
||||
}
|
||||
|
||||
/// What the reservation is charged is decided by the header, and it has to
|
||||
/// agree with what the pipeline does: a photo uploaded as-is costs only
|
||||
/// its buffered bytes, while a processed one costs its conservative peak.
|
||||
#[test]
|
||||
fn prepare_budget_follows_the_processing_decision() {
|
||||
// 9999x2 (sum 10001) is over the dimension cap → processed → charged.
|
||||
let oversized = png_header(9999, 2, 8, 2); // 8-bit RGB
|
||||
assert_eq!(
|
||||
prepare_budget_bytes(&oversized),
|
||||
processing_peak_bytes(oversized.len() as u64, 9999 * 2 * 3)
|
||||
);
|
||||
// Inside the limits (dimensions *and* bytes) → uploaded as-is.
|
||||
let small = png_header(100, 100, 8, 2);
|
||||
assert_eq!(prepare_budget_bytes(&small), small.len() as u64);
|
||||
// An unsupported format still keeps its already-buffered bytes alive.
|
||||
let unsupported = b"GIF89a not a photo";
|
||||
assert_eq!(prepare_budget_bytes(unsupported), unsupported.len() as u64);
|
||||
|
||||
// JPEG: 9999x2 is over the cap, so its RGB decode buffer is charged.
|
||||
let (w, h) = (9999u16, 2u16);
|
||||
let rgb = vec![90u8; w as usize * h as usize * 3];
|
||||
let mut bytes = Vec::new();
|
||||
jpeg_encoder::Encoder::new(&mut bytes, 90)
|
||||
.encode(&rgb, w, h, jpeg_encoder::ColorType::Rgb)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
prepare_budget_bytes(&bytes),
|
||||
processing_peak_bytes(bytes.len() as u64, 9999 * 2 * 3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_png_header() {
|
||||
let bytes = png_header(8979, 5316, 16, 6); // 16-bit RGBA
|
||||
@@ -459,7 +707,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn pipeline_resizes_oversized_jpeg() {
|
||||
// Build a small over-dimension JPEG with jpeg-encoder.
|
||||
// Build a small over-dimension JPEG with jpeg-encoder: 9999x2 sums to
|
||||
// one over the cap. The output's own headers are what must show the
|
||||
// resize — a copy-through is a perfectly valid JPEG, so magic bytes
|
||||
// and a non-empty buffer used to pass for nothing.
|
||||
let (w, h) = (9999u16, 2u16);
|
||||
let rgb = vec![90u8; (w as usize) * (h as usize) * 3];
|
||||
let mut bytes = Vec::new();
|
||||
@@ -475,8 +726,15 @@ mod tests {
|
||||
PhotoPrep::Upload(file) => {
|
||||
let out = std::fs::read(file.path()).unwrap();
|
||||
assert!(out.starts_with(&[0xFF, 0xD8]), "output must stay jpeg");
|
||||
// 9999x2 downscaled: the buffer length tells the new dims.
|
||||
assert!(out.len() > 100);
|
||||
let mut decoder = zune_jpeg::JpegDecoder::new(std::io::Cursor::new(out.as_slice()));
|
||||
decoder.decode_headers().unwrap();
|
||||
let info = decoder.info().unwrap();
|
||||
let (nw, nh) = (info.width as u32, info.height as u32);
|
||||
assert!(
|
||||
nw + nh <= PHOTO_MAX_DIMENSION_SUM,
|
||||
"still over the cap: {nw}x{nh}"
|
||||
);
|
||||
assert_ne!((nw, nh), (w as u32, h as u32), "output was not resized");
|
||||
}
|
||||
PhotoPrep::UseFallback => panic!("over-dimension JPEG should have been resized"),
|
||||
}
|
||||
|
||||
+704
-99
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,13 @@
|
||||
//! Per-chat token-bucket rate limiting.
|
||||
//!
|
||||
//! Telegram throttles bots that burst past a chat's message budget
|
||||
//! (roughly 20 messages/min for channels/groups); today the bot absorbs
|
||||
//! those 429s with queue retries. This limiter smooths the burst *before*
|
||||
//! it reaches the API: media sends to a chat consume one token per
|
||||
//! message, refilled at [`REFILL_PER_SEC`], so a batch forward paces itself
|
||||
//! instead of tripping flood control. The queue retry stays as the safety
|
||||
//! net for limits this bucket does not model (global per-bot limits etc.).
|
||||
//! Telegram throttles bots on two budgets: one per chat (roughly 20
|
||||
//! messages/min for channels/groups) and a bot-wide one (~30 messages per
|
||||
//! second). Both are smoothed here *before* the burst reaches the API — the
|
||||
//! per-chat bucket charges one token per message, and [`acquire_global`]
|
||||
//! charges the same spend against the bot-wide budget, which no per-chat
|
||||
//! bucket can see (a forward fanned out over many chats spends one token in
|
||||
//! each and nothing anywhere). The queue retry stays as the safety net for
|
||||
//! whatever neither bucket models.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
@@ -19,6 +20,12 @@ const CAPACITY: f64 = 20.0;
|
||||
/// Sustained refill: ~20 messages per minute.
|
||||
const REFILL_PER_SEC: f64 = 20.0 / 60.0;
|
||||
|
||||
/// The bot-wide budget: Telegram allows roughly 30 messages per second for a
|
||||
/// bot in total, independently of the per-chat limits. Set to the documented
|
||||
/// ceiling, so it only ever binds on a cross-chat burst.
|
||||
const GLOBAL_CAPACITY: f64 = 30.0;
|
||||
const GLOBAL_REFILL_PER_SEC: f64 = 30.0;
|
||||
|
||||
struct State {
|
||||
/// Current token balance; may go negative (debt from an acquire larger
|
||||
/// than the capacity, repaid by subsequent refills).
|
||||
@@ -84,12 +91,24 @@ impl TokenBucket {
|
||||
tokio::time::sleep(Duration::from_secs_f64(wait)).await;
|
||||
}
|
||||
|
||||
/// Current balance, refilled to now.
|
||||
fn balance(&self) -> f64 {
|
||||
let mut state = self.state.lock();
|
||||
self.refill(&mut state);
|
||||
state.tokens
|
||||
}
|
||||
|
||||
/// Current balance, for the tests that assert a call site charged the
|
||||
/// bucket (a charge is otherwise only observable as a delay).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn tokens(&self) -> f64 {
|
||||
self.balance()
|
||||
}
|
||||
|
||||
/// True when the bucket has refilled to capacity: no debt outstanding, so
|
||||
/// the chat has not sent anything recently.
|
||||
fn is_idle(&self) -> bool {
|
||||
let mut state = self.state.lock();
|
||||
self.refill(&mut state);
|
||||
state.tokens >= self.capacity
|
||||
self.balance() >= self.capacity
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +126,17 @@ pub fn limiter_for(chat_id: i64) -> Arc<TokenBucket> {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The one bucket every chat shares: Telegram's bot-wide budget.
|
||||
static GLOBAL_LIMITER: LazyLock<TokenBucket> =
|
||||
LazyLock::new(|| TokenBucket::new(GLOBAL_CAPACITY, GLOBAL_REFILL_PER_SEC));
|
||||
|
||||
/// Waits for `n` messages' worth of the bot-wide budget. Called by the send
|
||||
/// paths next to their per-chat [`limiter_for`]: at ~30/s it does not bind on
|
||||
/// a single chat, but a batch fanned out over many chats has no other guard.
|
||||
pub async fn acquire_global(n: f64) {
|
||||
GLOBAL_LIMITER.acquire(n).await;
|
||||
}
|
||||
|
||||
/// Drops limiters that are idle (refilled to capacity, so the chat has not
|
||||
/// sent recently) and are not still held by an in-flight sender. The map
|
||||
/// would otherwise keep one bucket per chat that ever sent media, forever.
|
||||
@@ -160,6 +190,21 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_global_budget_is_paced_and_shared() {
|
||||
// Drain the process-wide budget (no other test touches it: the send
|
||||
// paths that use it are mocked), then prove the next message waits for
|
||||
// the refill instead of going out instantly.
|
||||
acquire_global(GLOBAL_CAPACITY).await;
|
||||
let start = tokio::time::Instant::now();
|
||||
acquire_global(1.0).await;
|
||||
assert!(
|
||||
start.elapsed() >= Duration::from_secs_f64(1.0 / GLOBAL_REFILL_PER_SEC),
|
||||
"a fanned-out burst must be paced: elapsed {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn prune_idle_drops_full_unheld_buckets_only() {
|
||||
// Held by this task: kept even at full capacity, a sender has it.
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! The Telegram error policy: which failures the send paths retry, which are
|
||||
//! permanent, and which the download-and-reupload fallback owns. A status a
|
||||
//! *site* answers with is classified in `x_media::site`; this is the Bot API's
|
||||
//! side of the same question.
|
||||
|
||||
use super::upload::FallbackError;
|
||||
use super::{Task, retry_delay_seconds};
|
||||
use teloxide::{ApiError, RequestError};
|
||||
|
||||
/// Telegram's servers failed to fetch a media URL (hotlink protection etc.):
|
||||
/// these errors are handled by the download-and-reupload fallback, NOT by a
|
||||
/// queue retry (resending the URL cannot succeed).
|
||||
pub fn is_media_fetch_failure(e: &ApiError) -> bool {
|
||||
const MARKERS: [&str; 7] = [
|
||||
"webpage_media_empty",
|
||||
"media_empty",
|
||||
"empty_web_media",
|
||||
"webpage_curl_failed",
|
||||
"timeout",
|
||||
// Oversized photos (width + height > 10000 px) are rejected on URL
|
||||
// sends too; route them to the download-and-resize fallback.
|
||||
"photo_invalid_dimensions",
|
||||
// Telegram refused to fetch the URL it was handed. Single-media URL
|
||||
// sends answer with this one (the media-group verbs use the
|
||||
// `webpage_*`/`media_empty` markers above), and it is exactly the
|
||||
// case the download-and-reupload fallback exists for.
|
||||
"failed to get http url content",
|
||||
];
|
||||
let description = e.to_string().to_lowercase();
|
||||
MARKERS.iter().any(|marker| description.contains(marker))
|
||||
}
|
||||
|
||||
/// Telegram reported the media file as too large (HTTP 413 on multipart
|
||||
/// upload, or a "too large" message for URL-fetched media). These errors are
|
||||
/// handled by the size-check fallback (use a smaller media URL), NOT by a
|
||||
/// queue retry.
|
||||
pub fn is_size_error(e: &ApiError) -> bool {
|
||||
if matches!(e, ApiError::RequestEntityTooLarge) {
|
||||
return true;
|
||||
}
|
||||
let description = e.to_string().to_lowercase();
|
||||
["too large", "too big"]
|
||||
.iter()
|
||||
.any(|marker| description.contains(marker))
|
||||
}
|
||||
|
||||
/// Task-free classification of a Telegram request error. The callers attach
|
||||
/// the (updated) task when building a [`SendError`].
|
||||
pub enum Classification {
|
||||
Retryable {
|
||||
delay_seconds: f64,
|
||||
},
|
||||
Permanent {
|
||||
message: String,
|
||||
},
|
||||
/// Handled by the download fallback, not a queue retry.
|
||||
MediaFetchFailure,
|
||||
}
|
||||
|
||||
pub fn classify_request_error(e: &RequestError) -> Classification {
|
||||
match e {
|
||||
RequestError::RetryAfter(seconds) => Classification::Retryable {
|
||||
delay_seconds: seconds.seconds() as f64,
|
||||
},
|
||||
RequestError::Network(_) => Classification::Retryable {
|
||||
delay_seconds: retry_delay_seconds(0),
|
||||
},
|
||||
// A 5xx from the API — or from a proxy in front of it — is transient.
|
||||
// teloxide only sleeps 10s on a server error and then parses whatever
|
||||
// body came back, so by the time we see the error the HTTP status is
|
||||
// gone: a JSON 5xx body arrives as an unknown description, an HTML
|
||||
// error page as `InvalidJson`. Both used to be Permanent, which
|
||||
// dead-lettered a post over a Telegram-side blip.
|
||||
RequestError::Api(api) if is_server_error_text(&api.to_string()) => {
|
||||
Classification::Retryable {
|
||||
delay_seconds: retry_delay_seconds(0),
|
||||
}
|
||||
}
|
||||
RequestError::Api(api) if is_media_fetch_failure(api) => Classification::MediaFetchFailure,
|
||||
RequestError::Api(api) => Classification::Permanent {
|
||||
message: api.to_string(),
|
||||
},
|
||||
// An unparsable body can only come from something that is not the Bot
|
||||
// API (which always answers JSON): a 5xx/error page from an
|
||||
// intermediary, cut off mid-response. A JSON body that merely does not
|
||||
// match the expected type cannot be fixed by retrying, so that case
|
||||
// stays permanent.
|
||||
RequestError::InvalidJson { raw, .. } if !raw.trim_start().starts_with('{') => {
|
||||
Classification::Retryable {
|
||||
delay_seconds: retry_delay_seconds(0),
|
||||
}
|
||||
}
|
||||
RequestError::MigrateToChatId(_)
|
||||
| RequestError::InvalidJson { .. }
|
||||
| RequestError::Io(_) => Classification::Permanent {
|
||||
message: e.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Descriptions a 5xx carries when its body *is* JSON (teloxide keeps only the
|
||||
/// description text, never the status code). Matched like the media-fetch
|
||||
/// markers below; anything unmatched stays permanent, so a new permanent API
|
||||
/// error is not retried just because it is unfamiliar.
|
||||
fn is_server_error_text(description: &str) -> bool {
|
||||
const MARKERS: [&str; 4] = [
|
||||
"server error",
|
||||
"bad gateway",
|
||||
"gateway timeout",
|
||||
"service unavailable",
|
||||
];
|
||||
let description = description.to_lowercase();
|
||||
MARKERS.iter().any(|marker| description.contains(marker))
|
||||
}
|
||||
|
||||
/// Task boxed to keep the error size within `result_large_err` limits.
|
||||
#[derive(Debug)]
|
||||
pub enum SendError {
|
||||
Retryable { delay_seconds: f64, task: Box<Task> },
|
||||
Permanent { message: String, task: Box<Task> },
|
||||
}
|
||||
pub(crate) fn classify_to_send_error(
|
||||
e: &RequestError,
|
||||
task: Task,
|
||||
fetch_failure_label: &str,
|
||||
) -> SendError {
|
||||
match classify_request_error(e) {
|
||||
Classification::Retryable { delay_seconds } => SendError::Retryable {
|
||||
delay_seconds,
|
||||
task: Box::new(task),
|
||||
},
|
||||
Classification::Permanent { message } => SendError::Permanent {
|
||||
message,
|
||||
task: Box::new(task),
|
||||
},
|
||||
Classification::MediaFetchFailure => SendError::Permanent {
|
||||
message: fetch_failure_label.into(),
|
||||
task: Box::new(task),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl SendError {
|
||||
/// Attaches the (updated) task to a task-free [`FallbackError`] from the
|
||||
/// download/upload pipeline. [`FallbackError::MediaTooLarge`] never
|
||||
/// escapes the pipeline (it is handled by falling back to the smaller
|
||||
/// URL), so it is unreachable here.
|
||||
pub(super) fn from_fallback(f: FallbackError, task: Task) -> SendError {
|
||||
match f {
|
||||
FallbackError::Retryable { delay_seconds } => SendError::Retryable {
|
||||
delay_seconds,
|
||||
task: Box::new(task),
|
||||
},
|
||||
FallbackError::Permanent { message } => SendError::Permanent {
|
||||
message,
|
||||
task: Box::new(task),
|
||||
},
|
||||
FallbackError::MediaTooLarge => unreachable!("handled inside the upload fallback"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,20 +2,16 @@
|
||||
//! URL / local path), the per-kind `InputMedia` builders and the media-group
|
||||
//! assembly with its caption rule.
|
||||
|
||||
use super::MediaItemPayload;
|
||||
use super::{MediaItemPayload, MediaRef};
|
||||
use teloxide::types::{
|
||||
InputFile, InputMedia, InputMediaAnimation, InputMediaPhoto, InputMediaVideo, ParseMode,
|
||||
};
|
||||
|
||||
fn parse_media_url(s: &str) -> Result<url::Url, String> {
|
||||
url::Url::parse(s).map_err(|e| format!("invalid media URL: {e}"))
|
||||
}
|
||||
|
||||
/// The item's media string, whether it is a URL/path or a file id — callers
|
||||
/// that need the distinction match on [`MediaRef`] themselves.
|
||||
pub(super) fn item_url(item: &MediaItemPayload) -> &str {
|
||||
match item {
|
||||
MediaItemPayload::Photo { media, .. }
|
||||
| MediaItemPayload::Video { media, .. }
|
||||
| MediaItemPayload::Animation { media, .. } => media,
|
||||
match item.media_ref() {
|
||||
MediaRef::Source(media) | MediaRef::FileId(media) => media,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +19,8 @@ pub(super) fn item_url(item: &MediaItemPayload) -> &str {
|
||||
/// (e.g. a locally encoded ugoira MP4) is uploaded directly.
|
||||
pub(super) fn input_file_for(media: &str) -> Result<InputFile, String> {
|
||||
if media.starts_with("http://") || media.starts_with("https://") {
|
||||
Ok(InputFile::url(parse_media_url(media)?))
|
||||
let url = url::Url::parse(media).map_err(|e| format!("invalid media URL: {e}"))?;
|
||||
Ok(InputFile::url(url))
|
||||
} else if !std::path::Path::new(media).exists() {
|
||||
// A retried task may reference a temp file the original send's
|
||||
// TempDir already cleaned up; fail fast and permanent instead of
|
||||
@@ -38,59 +35,64 @@ impl MediaItemPayload {
|
||||
/// The input for a send: a cached file id goes out as `InputFile::file_id`
|
||||
/// (no fetch, no upload), URLs go to Telegram, anything else is a local
|
||||
/// path (transient upload fallback).
|
||||
fn input_file(&self) -> Result<InputFile, String> {
|
||||
match self {
|
||||
MediaItemPayload::Photo {
|
||||
media,
|
||||
file_id: true,
|
||||
..
|
||||
}
|
||||
| MediaItemPayload::Video {
|
||||
media,
|
||||
file_id: true,
|
||||
..
|
||||
}
|
||||
| MediaItemPayload::Animation {
|
||||
media,
|
||||
file_id: true,
|
||||
..
|
||||
} => Ok(InputFile::file_id(media.clone().into())),
|
||||
_ => input_file_for(item_url(self)),
|
||||
pub(super) fn input_file(&self) -> Result<InputFile, String> {
|
||||
match self.media_ref() {
|
||||
MediaRef::FileId(id) => Ok(InputFile::file_id(id.clone().into())),
|
||||
MediaRef::Source(media) => input_file_for(media),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn photo_media(file: InputFile, caption: Option<&str>, spoiler: bool) -> InputMedia {
|
||||
let mut photo = InputMediaPhoto::new(file).parse_mode(ParseMode::Html);
|
||||
if let Some(caption) = caption {
|
||||
photo = photo.caption(caption);
|
||||
/// Builds one media-group item around an already-selected file: the per-kind
|
||||
/// `InputMedia` (same spoiler/caption handling) plus the video's thumbnail,
|
||||
/// which Telegram takes as a separate upload/URL. The one place that dispatch
|
||||
/// is written; callers only choose the `InputFile`.
|
||||
pub(super) fn media_from(
|
||||
item: &MediaItemPayload,
|
||||
file: InputFile,
|
||||
caption: Option<&str>,
|
||||
) -> Result<InputMedia, String> {
|
||||
let media = match item {
|
||||
MediaItemPayload::Photo { has_spoiler, .. } => {
|
||||
let mut media = InputMediaPhoto::new(file).parse_mode(ParseMode::Html);
|
||||
if let Some(caption) = caption {
|
||||
media = media.caption(caption);
|
||||
}
|
||||
if *has_spoiler {
|
||||
media = media.spoiler();
|
||||
}
|
||||
InputMedia::Photo(media)
|
||||
}
|
||||
MediaItemPayload::Video { has_spoiler, .. } => {
|
||||
let mut media = InputMediaVideo::new(file).parse_mode(ParseMode::Html);
|
||||
if let Some(caption) = caption {
|
||||
media = media.caption(caption);
|
||||
}
|
||||
if *has_spoiler {
|
||||
media = media.spoiler();
|
||||
}
|
||||
InputMedia::Video(media)
|
||||
}
|
||||
MediaItemPayload::Animation { has_spoiler, .. } => {
|
||||
let mut media = InputMediaAnimation::new(file).parse_mode(ParseMode::Html);
|
||||
if let Some(caption) = caption {
|
||||
media = media.caption(caption);
|
||||
}
|
||||
if *has_spoiler {
|
||||
media = media.spoiler();
|
||||
}
|
||||
InputMedia::Animation(media)
|
||||
}
|
||||
};
|
||||
// The thumbnail comes off the item itself — every caller passed exactly
|
||||
// that, and only a video uses it (Telegram takes it as a separate
|
||||
// upload/URL).
|
||||
match (item.thumbnail_url(), media) {
|
||||
(Some(thumb), InputMedia::Video(video)) => {
|
||||
Ok(InputMedia::Video(video.thumbnail(input_file_for(thumb)?)))
|
||||
}
|
||||
(_, media) => Ok(media),
|
||||
}
|
||||
if spoiler {
|
||||
photo = photo.spoiler();
|
||||
}
|
||||
InputMedia::Photo(photo)
|
||||
}
|
||||
|
||||
pub(super) fn video_media(file: InputFile, caption: Option<&str>, spoiler: bool) -> InputMedia {
|
||||
let mut video = InputMediaVideo::new(file).parse_mode(ParseMode::Html);
|
||||
if let Some(caption) = caption {
|
||||
video = video.caption(caption);
|
||||
}
|
||||
if spoiler {
|
||||
video = video.spoiler();
|
||||
}
|
||||
InputMedia::Video(video)
|
||||
}
|
||||
|
||||
pub(super) fn animation_media(file: InputFile, caption: Option<&str>, spoiler: bool) -> InputMedia {
|
||||
let mut animation = InputMediaAnimation::new(file).parse_mode(ParseMode::Html);
|
||||
if let Some(caption) = caption {
|
||||
animation = animation.caption(caption);
|
||||
}
|
||||
if spoiler {
|
||||
animation = animation.spoiler();
|
||||
}
|
||||
InputMedia::Animation(animation)
|
||||
}
|
||||
|
||||
/// Builds a media group from payloads; only the first item of the batch gets
|
||||
@@ -104,25 +106,7 @@ pub(super) fn build_media_group(
|
||||
.enumerate()
|
||||
.map(|(i, item)| {
|
||||
let item_caption = if i == 0 { caption } else { None };
|
||||
Ok(match item {
|
||||
MediaItemPayload::Photo { has_spoiler, .. } => {
|
||||
photo_media(item.input_file()?, item_caption, *has_spoiler)
|
||||
}
|
||||
MediaItemPayload::Video {
|
||||
has_spoiler,
|
||||
thumbnail,
|
||||
..
|
||||
} => {
|
||||
let mut video = video_media(item.input_file()?, item_caption, *has_spoiler);
|
||||
if let (Some(thumb), InputMedia::Video(v)) = (thumbnail, &mut video) {
|
||||
*v = v.clone().thumbnail(input_file_for(thumb)?);
|
||||
}
|
||||
video
|
||||
}
|
||||
MediaItemPayload::Animation { has_spoiler, .. } => {
|
||||
animation_media(item.input_file()?, item_caption, *has_spoiler)
|
||||
}
|
||||
})
|
||||
media_from(item, item.input_file()?, item_caption)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
+869
-337
File diff suppressed because it is too large
Load Diff
@@ -7,21 +7,28 @@ use super::{SendError, Task, forward_messages, send_animation, send_media_sequen
|
||||
use crate::ctx::AppContext;
|
||||
use crate::db::{now_f64, unix_now};
|
||||
use crate::handlers::log_key;
|
||||
use crate::link_cache::{CachedMedia, CachedMediaKind, LinkCache};
|
||||
use crate::link_cache::{CachedMedia, CachedMediaKind};
|
||||
use crate::media_sender::MediaSender;
|
||||
use crate::queue::{PersistentTaskQueue, QueueError};
|
||||
use crate::state::EditMessage;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
use teloxide::types::{ChatId, InlineKeyboardButton, InlineKeyboardMarkup, Message, MessageId};
|
||||
use teloxide::types::{
|
||||
ChatId, InlineKeyboardButton, InlineKeyboardButtonKind, InlineKeyboardMarkup, Message,
|
||||
MessageId,
|
||||
};
|
||||
|
||||
/// Persists a successful send under the post's cache key. Only runs for a
|
||||
/// fresh (non-resumed) task that carried raw cache data with no file ids yet.
|
||||
/// Persists a successful send under the post's cache key. Skips a send that was
|
||||
/// served from the cache — its entry already holds the file ids the next repeat
|
||||
/// wants — *unless* the entry was degraded (no file ids left, see
|
||||
/// `invalidate_cache`): then the ids this send just produced are written back,
|
||||
/// which is what returns a degraded entry to the fast path instead of leaving
|
||||
/// it to re-upload the media on every repeat.
|
||||
pub(super) async fn cache_sent_task(ctx: &AppContext<'_>, task: &Task, media: Vec<CachedMedia>) {
|
||||
let Some(cache_data) = task.cache_data() else {
|
||||
return;
|
||||
};
|
||||
if !cache_data.media.is_empty() || media.is_empty() {
|
||||
if cache_data.media.iter().any(|m| !m.file_id.is_empty()) || media.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut post = cache_data.clone();
|
||||
@@ -33,7 +40,12 @@ pub(super) async fn cache_sent_task(ctx: &AppContext<'_>, task: &Task, media: Ve
|
||||
}
|
||||
|
||||
/// Persists a lone animation send under the post's cache key.
|
||||
pub(super) async fn cache_animation_send(ctx: &AppContext<'_>, task: &Task, message: &Message) {
|
||||
pub(super) async fn cache_animation_send(
|
||||
ctx: &AppContext<'_>,
|
||||
task: &Task,
|
||||
message: &Message,
|
||||
source_url: &str,
|
||||
) {
|
||||
if let Some(file_id) = message.animation().map(|a| a.file.id.to_string()) {
|
||||
cache_sent_task(
|
||||
ctx,
|
||||
@@ -41,6 +53,7 @@ pub(super) async fn cache_animation_send(ctx: &AppContext<'_>, task: &Task, mess
|
||||
vec![CachedMedia {
|
||||
kind: CachedMediaKind::Animation,
|
||||
file_id,
|
||||
url: super::replayable_cache_url(source_url),
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
@@ -57,75 +70,160 @@ pub(crate) enum Settled {
|
||||
/// Every path that ends a task's life — sent, permanently failed, or
|
||||
/// dead-lettered after the last retry — funnels through here, so the cleanup a
|
||||
/// settled task owes cannot be forgotten by a new path: release the keep-alive
|
||||
/// temp media (retryable tasks keep it, they will be resent) and drop the
|
||||
/// link-cache entry that a failed send's stale file ids would keep poisoning.
|
||||
/// temp media (retryable tasks keep it, they will be resent) and deal with the
|
||||
/// link-cache entry a failed send's stale file ids would keep poisoning
|
||||
/// (degraded to its source URLs, dropped once those fail too).
|
||||
pub(crate) async fn settle_task(ctx: &AppContext<'_>, task: &Task, outcome: Settled) {
|
||||
if matches!(outcome, Settled::Failed) {
|
||||
invalidate_cache(ctx.link_cache, task).await;
|
||||
invalidate_cache(ctx, task).await;
|
||||
}
|
||||
release_keep_alive(task);
|
||||
}
|
||||
|
||||
/// A cached Telegram file id failed permanently (stale/expired); drop the
|
||||
/// cache entry so the next request re-fetches instead of repeating it.
|
||||
async fn invalidate_cache(cache: &LinkCache, task: &Task) {
|
||||
if task.is_cached_send()
|
||||
&& let Some(url) = task.source_url()
|
||||
&& let Some(key) = x_media::site::cache_key(url)
|
||||
{
|
||||
log::debug!("removing stale link cache entry for [key={}]", log_key(url));
|
||||
cache.remove(&key).await;
|
||||
/// A cached Telegram file id failed permanently (stale/expired). The media
|
||||
/// itself is usually fine, so the entry is *degraded* rather than dropped: its
|
||||
/// file ids go away and the source URLs stay, and the next request re-sends the
|
||||
/// post from those — no source request, no ugoira encode, no HLS remux — with
|
||||
/// the media fetched by Telegram (or by the upload fallback). An entry that is
|
||||
/// already degraded, or whose older rows carry no URLs, is removed instead: its
|
||||
/// URLs did not work either, and the next request should fetch the post again
|
||||
/// and report what the source says.
|
||||
async fn invalidate_cache(ctx: &AppContext<'_>, task: &Task) {
|
||||
if !task.is_cached_send() {
|
||||
return;
|
||||
}
|
||||
let Some(url) = task.source_url() else {
|
||||
return;
|
||||
};
|
||||
let Some(key) = x_media::site::cache_key(url) else {
|
||||
return;
|
||||
};
|
||||
let Some(mut entry) = ctx.link_cache.get(&key, ctx.config.link_cache_ttl).await else {
|
||||
return;
|
||||
};
|
||||
let degradable = entry.media.iter().all(|m| !m.url.is_empty())
|
||||
&& entry.media.iter().any(|m| !m.file_id.is_empty());
|
||||
if !degradable {
|
||||
log::debug!("removing stale link cache entry for [key={}]", log_key(url));
|
||||
ctx.link_cache.remove(&key).await;
|
||||
return;
|
||||
}
|
||||
log::debug!(
|
||||
"degrading stale link cache entry to its source URLs for [key={}]",
|
||||
log_key(url)
|
||||
);
|
||||
for media in &mut entry.media {
|
||||
media.file_id.clear();
|
||||
}
|
||||
ctx.link_cache.put(&key, &entry).await;
|
||||
}
|
||||
|
||||
/// Locally produced media files (ugoira MP4, bsky remux MP4) whose temp dirs
|
||||
/// must stay alive while their task may be retried by the queue. The fetch
|
||||
/// pipeline hands ownership here via
|
||||
/// [`x_media::site::Fetched::take_keep_alive`] before that
|
||||
/// [`x_media::site::Fetched`] is dropped; a queued retry runs after that drop,
|
||||
/// so without this the local file would be gone by the time the retry sends
|
||||
/// it. Entries are removed when the task settles (see [`release_keep_alive`]).
|
||||
pub(crate) static KEEP_ALIVE: LazyLock<parking_lot::Mutex<Vec<tempfile::TempDir>>> =
|
||||
/// pipeline hands a reference here via [`x_media::site::Fetched::keep_alive`]
|
||||
/// before that [`x_media::site::Fetched`] is dropped; a queued retry runs after
|
||||
/// that drop, so without this the local file would be gone by the time the
|
||||
/// retry sends it. `Arc` because one fetch can serve several tasks (a
|
||||
/// concurrent duplicate of the same link shares it): each holder keeps the
|
||||
/// directory alive until its own task settles. Its entry is removed when that
|
||||
/// task settles (see [`release_keep_alive`]).
|
||||
pub(crate) static KEEP_ALIVE: LazyLock<parking_lot::Mutex<Vec<std::sync::Arc<tempfile::TempDir>>>> =
|
||||
LazyLock::new(|| parking_lot::Mutex::new(Vec::new()));
|
||||
|
||||
/// Drops the keep-alive temp dirs holding media referenced by `task` (matched
|
||||
/// by path prefix). Called once a task settles — sent or permanently failed —
|
||||
/// so retry-only temp files do not leak; retryable tasks keep them alive.
|
||||
/// Drops the keep-alive reference this task's pipeline pushed (one entry,
|
||||
/// matched by path prefix). Called once a task settles — sent or permanently
|
||||
/// failed — so retry-only temp files do not leak; retryable tasks keep theirs.
|
||||
/// Exactly one entry goes per call: a shared fetch pushes one per pipeline, so
|
||||
/// clearing every holder would delete the directory out from under a
|
||||
/// concurrent duplicate's queued retry.
|
||||
pub(crate) fn release_keep_alive(task: &Task) {
|
||||
let paths = task.local_media_paths();
|
||||
if paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut alive = KEEP_ALIVE.lock();
|
||||
alive.retain(|dir| {
|
||||
let dir_path = dir.path();
|
||||
!paths.iter().any(|p| p.starts_with(dir_path))
|
||||
});
|
||||
if let Some(index) = alive
|
||||
.iter()
|
||||
.position(|dir| paths.iter().any(|p| p.starts_with(dir.path())))
|
||||
{
|
||||
alive.remove(index);
|
||||
}
|
||||
}
|
||||
|
||||
/// One button per template name (column layout), then the confirm button.
|
||||
/// Sorted by name: the templates live in a `HashMap`, so an unsorted walk
|
||||
/// would reshuffle the buttons between prompts.
|
||||
pub(super) fn build_edit_markup(templates: &HashMap<String, String>) -> InlineKeyboardMarkup {
|
||||
let mut names: Vec<&String> = templates.keys().collect();
|
||||
names.sort();
|
||||
let mut rows = Vec::with_capacity(names.len() + 1);
|
||||
for name in names {
|
||||
rows.push(vec![InlineKeyboardButton::callback(
|
||||
name.clone(),
|
||||
format!("template|{name}"),
|
||||
)]);
|
||||
/// The edit-before-forward prompt's text. It names both controls and the TTL,
|
||||
/// because the buttons alone left users waiting for a forward that never came
|
||||
/// (nothing is forwarded until Confirm).
|
||||
pub(super) fn edit_prompt_text(ttl: std::time::Duration) -> String {
|
||||
format!(
|
||||
"Reply to edit the caption, or tap a template, then ↩️ Confirm to forward. \
|
||||
Expires in {}. Nothing is forwarded until you confirm.",
|
||||
coarsest_unit(ttl)
|
||||
)
|
||||
}
|
||||
|
||||
/// Text the prompt is rewritten to once its record expires. The sweep edits
|
||||
/// the prompt in place (see `main`): announcing the expiry with a new message
|
||||
/// would wake the chat up to a full TTL later about a prompt nobody is
|
||||
/// waiting on.
|
||||
pub(crate) const EDIT_PROMPT_EXPIRED_TEXT: &str = "⌛ Expired — nothing was forwarded.";
|
||||
|
||||
/// `24h` / `90m` / `45s`: the coarsest whole unit, so the prompt stays short.
|
||||
fn coarsest_unit(ttl: std::time::Duration) -> String {
|
||||
let secs = ttl.as_secs();
|
||||
if secs >= 3600 {
|
||||
format!("{}h", secs / 3600)
|
||||
} else if secs >= 60 {
|
||||
format!("{}m", secs / 60)
|
||||
} else {
|
||||
format!("{secs}s")
|
||||
}
|
||||
rows.push(vec![InlineKeyboardButton::callback(
|
||||
"↩️ Confirm",
|
||||
"forward",
|
||||
)]);
|
||||
}
|
||||
|
||||
/// Templates per keyboard row. Telegram rejects a keyboard with more than 100
|
||||
/// buttons *outright*, which would silently drop the whole prompt, so the
|
||||
/// names are folded and capped rather than listed one per row.
|
||||
pub(super) const TEMPLATE_BUTTONS_PER_ROW: usize = 3;
|
||||
/// Hard cap on template buttons; the prompt text names the ones not shown.
|
||||
pub(super) const MAX_TEMPLATE_BUTTONS: usize = 60;
|
||||
const MAX_CALLBACK_DATA_BYTES: usize = 64;
|
||||
const TEMPLATE_CALLBACK_PREFIX: &str = "template|";
|
||||
|
||||
/// Template buttons ([`TEMPLATE_BUTTONS_PER_ROW`] per row, at most
|
||||
/// [`MAX_TEMPLATE_BUTTONS`]), then the confirm/skip pair. Sorted by name: the
|
||||
/// templates live in a `HashMap`, so an unsorted walk would reshuffle the
|
||||
/// buttons between prompts. A name that cannot fit Telegram's callback-data
|
||||
/// limit is omitted; legacy/imported state cannot poison the whole prompt.
|
||||
pub(super) fn build_edit_markup(templates: &HashMap<String, String>) -> InlineKeyboardMarkup {
|
||||
let mut names: Vec<&String> = templates
|
||||
.keys()
|
||||
.filter(|name| TEMPLATE_CALLBACK_PREFIX.len() + name.len() <= MAX_CALLBACK_DATA_BYTES)
|
||||
.collect();
|
||||
names.sort();
|
||||
let shown = names.len().min(MAX_TEMPLATE_BUTTONS);
|
||||
let mut rows = Vec::with_capacity(shown / TEMPLATE_BUTTONS_PER_ROW + 2);
|
||||
for chunk in names[..shown].chunks(TEMPLATE_BUTTONS_PER_ROW) {
|
||||
rows.push(
|
||||
chunk
|
||||
.iter()
|
||||
.map(|name| {
|
||||
InlineKeyboardButton::callback(
|
||||
name.as_str(),
|
||||
format!("{TEMPLATE_CALLBACK_PREFIX}{name}"),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
rows.push(vec![
|
||||
InlineKeyboardButton::callback("↩️ Confirm", "forward"),
|
||||
InlineKeyboardButton::callback("🛑 Skip", "skip"),
|
||||
]);
|
||||
InlineKeyboardMarkup::new(rows)
|
||||
}
|
||||
|
||||
/// Notifies a chat about a dead-lettered task (skips when `notify_chat_id` is
|
||||
/// absent).
|
||||
pub(super) async fn notify_failure(
|
||||
pub(crate) async fn notify_failure(
|
||||
sender: &dyn MediaSender,
|
||||
chat_id: Option<i64>,
|
||||
message_id: Option<i64>,
|
||||
@@ -185,12 +283,29 @@ pub(crate) async fn post_send_actions(ctx: &AppContext<'_>, task: &Task, message
|
||||
};
|
||||
|
||||
if edit_before_forward {
|
||||
let keyboard = build_edit_markup(&ctx.chat_store.get(chat_id).await.template);
|
||||
let templates = ctx.chat_store.get(chat_id).await.template;
|
||||
let keyboard = build_edit_markup(&templates);
|
||||
let mut text = edit_prompt_text(ctx.config.edit_message_ttl);
|
||||
let shown = keyboard
|
||||
.inline_keyboard
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|button| {
|
||||
matches!(&button.kind, InlineKeyboardButtonKind::CallbackData(data) if data.starts_with(TEMPLATE_CALLBACK_PREFIX))
|
||||
})
|
||||
.count();
|
||||
let hidden = templates.len().saturating_sub(shown);
|
||||
if hidden > 0 {
|
||||
// The keyboard is capped; say so instead of silently hiding them.
|
||||
text.push_str(&format!(
|
||||
"\n({hidden} more templates not shown — /remove_template to prune.)"
|
||||
));
|
||||
}
|
||||
let prompt = ctx
|
||||
.sender
|
||||
.send_message(
|
||||
ChatId(chat_id),
|
||||
"Reply to edit message.".to_string(),
|
||||
text,
|
||||
Some(MessageId(reply_to as i32)),
|
||||
Some(keyboard),
|
||||
)
|
||||
@@ -198,11 +313,13 @@ pub(crate) async fn post_send_actions(ctx: &AppContext<'_>, task: &Task, message
|
||||
match prompt {
|
||||
Ok(prompt_id) => {
|
||||
log::info!(
|
||||
"edit-before-forward prompt {prompt_id} opened for {} message(s)",
|
||||
message_ids.len()
|
||||
"edit-before-forward prompt {prompt_id} opened for {} message(s) [key={}] chat={chat_id}",
|
||||
message_ids.len(),
|
||||
log_key(&source_url)
|
||||
);
|
||||
let source_url = source_url.clone();
|
||||
ctx.chat_store
|
||||
let saved = match ctx
|
||||
.chat_store
|
||||
.update(chat_id, move |data| {
|
||||
data.edit_message.insert(
|
||||
prompt_id,
|
||||
@@ -215,22 +332,55 @@ pub(crate) async fn post_send_actions(ctx: &AppContext<'_>, task: &Task, message
|
||||
},
|
||||
);
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok((_, true)) => true,
|
||||
Ok((_, false)) | Err(()) => false,
|
||||
};
|
||||
if !saved {
|
||||
log::error!("edit prompt {prompt_id} could not be persisted; removing it");
|
||||
let _ = ctx
|
||||
.sender
|
||||
.delete_message(ChatId(chat_id), MessageId(prompt_id as i32))
|
||||
.await;
|
||||
notify_failure(
|
||||
ctx.sender,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
"Could not save the edit-before-forward prompt — nothing was forwarded.",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("failed to send edit prompt: {e}");
|
||||
// Nothing is forwarded until the prompt is confirmed, so a
|
||||
// prompt that never arrived means this post is never forwarded.
|
||||
// Tell the chat instead of letting it wait for a prompt that
|
||||
// will not come.
|
||||
notify_failure(
|
||||
ctx.sender,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
"Could not open the edit-before-forward prompt — nothing was forwarded.",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(e) => log::error!("failed to send edit prompt: {e}"),
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(channel_id) = forward_channel_id {
|
||||
log::info!(
|
||||
"forwarding {} message(s) to channel {channel_id}",
|
||||
message_ids.len()
|
||||
"forwarding {} message(s) to channel {channel_id} from chat {chat_id} [key={}]",
|
||||
message_ids.len(),
|
||||
log_key(&source_url)
|
||||
);
|
||||
let forward_task = Task::ForwardMessages {
|
||||
from_chat_id: chat_id,
|
||||
to_chat_id: channel_id,
|
||||
message_ids,
|
||||
forward_offset: 0,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
};
|
||||
@@ -240,14 +390,24 @@ pub(crate) async fn post_send_actions(ctx: &AppContext<'_>, task: &Task, message
|
||||
delay_seconds,
|
||||
task,
|
||||
}) => {
|
||||
enqueue_retry(ctx.task_queue, *task, delay_seconds).await;
|
||||
// The forward is already committed from the user's side; if it
|
||||
// cannot be queued, say so rather than going quiet.
|
||||
if !enqueue_retry(ctx.task_queue, &task, delay_seconds).await {
|
||||
notify_failure(
|
||||
ctx.sender,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
&failure_text(task.source_url(), "retry could not be queued"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(SendError::Permanent { message, .. }) => {
|
||||
notify_failure(
|
||||
ctx.sender,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
&format!("Task failed after retries: {message}"),
|
||||
&failure_text(None, &message),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -255,16 +415,24 @@ pub(crate) async fn post_send_actions(ctx: &AppContext<'_>, task: &Task, message
|
||||
}
|
||||
}
|
||||
|
||||
/// Enqueues a task for a later attempt (retry / forward resume). When the
|
||||
/// enqueue itself fails the task can never be sent again, so its keep-alive
|
||||
/// temp media is released instead of leaking until process exit.
|
||||
pub(crate) async fn enqueue_retry(queue: &PersistentTaskQueue, task: Task, delay_seconds: f64) {
|
||||
let payload = serde_json::to_value(&task).expect("task serializes");
|
||||
/// Enqueues a task for a later attempt (retry / forward resume). Returns
|
||||
/// whether the retry is actually persisted: when the enqueue itself fails the
|
||||
/// task can never run again, so its keep-alive temp media is released instead
|
||||
/// of leaking until process exit — and the caller must not tell the user a
|
||||
/// retry is coming (nothing would ever deliver it).
|
||||
pub(crate) async fn enqueue_retry(
|
||||
queue: &PersistentTaskQueue,
|
||||
task: &Task,
|
||||
delay_seconds: f64,
|
||||
) -> bool {
|
||||
let payload = serde_json::to_value(task).expect("task serializes");
|
||||
let run_after = now_f64() + delay_seconds;
|
||||
if let Err(e) = queue.enqueue(payload, run_after).await {
|
||||
log::error!("failed to enqueue retry: {e}");
|
||||
release_keep_alive(&task);
|
||||
release_keep_alive(task);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Queue entry point: parses the stored task and dispatches.
|
||||
@@ -295,7 +463,10 @@ pub(crate) async fn handle_task(
|
||||
});
|
||||
}
|
||||
Err(SendError::Permanent { message, task }) => {
|
||||
settle_task(ctx, &task, Settled::Failed).await;
|
||||
// The queue dead-letters this payload into
|
||||
// `dead_letter_notify`, which settles the task — settling
|
||||
// here as well would release a shared keep-alive
|
||||
// directory twice.
|
||||
return Err(QueueError::Permanent {
|
||||
message,
|
||||
payload: serde_json::to_value(task).expect("task serializes"),
|
||||
@@ -323,7 +494,8 @@ pub(crate) async fn handle_task(
|
||||
payload: serde_json::to_value(task).expect("task serializes"),
|
||||
}),
|
||||
Err(SendError::Permanent { message, task }) => {
|
||||
settle_task(ctx, &task, Settled::Failed).await;
|
||||
// Settled by `dead_letter_notify`, which the queue invokes for
|
||||
// this payload.
|
||||
Err(QueueError::Permanent {
|
||||
message,
|
||||
payload: serde_json::to_value(task).expect("task serializes"),
|
||||
@@ -341,6 +513,36 @@ async fn send_media_or_animation(ctx: &AppContext<'_>, task: &Task) -> Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// User-facing text for a task that will never run again: which link died and
|
||||
/// why. The raw error alone left the user guessing which post it was about.
|
||||
pub(super) fn failure_text(source_url: Option<&str>, message: &str) -> String {
|
||||
match source_url.map(log_key) {
|
||||
Some(key) => format!("Send failed permanently for {key}: {message}"),
|
||||
// `ForwardMessages` carries no source URL (and neither does an
|
||||
// unparsable payload): that failure is about the channel copy, not
|
||||
// about a post.
|
||||
None => format!("Forward failed permanently: {message}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The post a stored payload is about, without parsing it into a [`Task`]:
|
||||
/// used when the payload no longer deserializes (written by an older version,
|
||||
/// or corrupted) but its identity fields are still readable.
|
||||
fn payload_source_url(payload: &serde_json::Value) -> Option<&str> {
|
||||
payload.get("source_url").and_then(|v| v.as_str())
|
||||
}
|
||||
|
||||
/// Whether a stored payload was a *cached* send (see `Task::is_cached_send`),
|
||||
/// read straight off the JSON — the unparsable case still has to know whether
|
||||
/// a link-cache entry may be holding the media that failed.
|
||||
fn payload_is_cached_send(payload: &serde_json::Value) -> bool {
|
||||
payload
|
||||
.get("cache_data")
|
||||
.and_then(|data| data.get("media"))
|
||||
.and_then(|media| media.as_array())
|
||||
.is_some_and(|media| !media.is_empty())
|
||||
}
|
||||
|
||||
/// Dead-letter callback wired to the queue in main: settles the task and
|
||||
/// notifies its chat.
|
||||
pub(crate) async fn dead_letter_notify(
|
||||
@@ -351,8 +553,21 @@ pub(crate) async fn dead_letter_notify(
|
||||
// A dead-lettered task never runs again, and the queue dead-letters retry
|
||||
// exhaustion itself (the handler is not called again), so this is the only
|
||||
// place that sees the final payload.
|
||||
if let Ok(task) = serde_json::from_value::<Task>(payload.clone()) {
|
||||
settle_task(ctx, &task, Settled::Failed).await;
|
||||
let task = serde_json::from_value::<Task>(payload.clone()).ok();
|
||||
if let Some(task) = &task {
|
||||
settle_task(ctx, task, Settled::Failed).await;
|
||||
} else {
|
||||
// A payload that no longer parses (an older version's row shape, a
|
||||
// corrupted one) still says which post it was about: drop the stale
|
||||
// cache entry the same way, instead of leaving a bad file id to be
|
||||
// re-sent forever — and name the post in the notification rather than
|
||||
// reporting a *forward* failure for a send task.
|
||||
if payload_is_cached_send(&payload)
|
||||
&& let Some(key) = payload_source_url(&payload).and_then(x_media::site::cache_key)
|
||||
{
|
||||
log::debug!("removing stale link cache entry for [key={key}]");
|
||||
ctx.link_cache.remove(&key).await;
|
||||
}
|
||||
}
|
||||
let notify_chat_id = payload.get("notify_chat_id").and_then(|v| v.as_i64());
|
||||
let notify_message_id = payload.get("notify_message_id").and_then(|v| v.as_i64());
|
||||
@@ -360,7 +575,12 @@ pub(crate) async fn dead_letter_notify(
|
||||
ctx.sender,
|
||||
notify_chat_id,
|
||||
notify_message_id,
|
||||
&format!("Task failed after retries: {message}"),
|
||||
&failure_text(
|
||||
task.as_ref()
|
||||
.and_then(|task| task.source_url())
|
||||
.or_else(|| payload_source_url(&payload)),
|
||||
&message,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
@@ -2,15 +2,49 @@
|
||||
//! itself (hotlink protection), the bot downloads the file, shrinks photos
|
||||
//! that exceed Telegram's limits and uploads the batch via multipart.
|
||||
|
||||
use super::input_media::{animation_media, input_file_for, item_url, photo_media, video_media};
|
||||
use super::{MediaItemPayload, SendError, Task, classify_to_send_error, retry_delay_seconds};
|
||||
use super::input_media::{input_file_for, item_url, media_from};
|
||||
use super::{
|
||||
MediaItemPayload, MediaRef, SendError, Task, classify_to_send_error, retry_delay_seconds,
|
||||
};
|
||||
use crate::media_sender::MediaSender;
|
||||
use crate::photo::{self, MAX_UPLOAD_BYTES, PhotoPrep};
|
||||
use crate::photo::{self, PhotoPrep};
|
||||
use std::sync::LazyLock;
|
||||
use teloxide::prelude::*;
|
||||
use teloxide::types::{ChatId, InputFile, InputMedia, MessageId};
|
||||
use tempfile::NamedTempFile;
|
||||
use x_media::site::FetchError;
|
||||
|
||||
/// How many fallback items may be downloaded and processed at once, across the
|
||||
/// whole process. A per-batch bound is not a memory bound: `URL_WORKERS` (8)
|
||||
/// and the queue's workers (4) can each be inside a batch, so a per-batch three
|
||||
/// allowed two dozen downloads in flight, each buffering a whole photo
|
||||
/// (up to [`photo::MAX_PHOTO_DOWNLOAD_BYTES`]) before it is processed. This is
|
||||
/// the only admission control on the media path; the send itself is paced by
|
||||
/// the rate limiter.
|
||||
const PREP_CONCURRENCY: usize = 6;
|
||||
static PREP_SLOTS: LazyLock<tokio::sync::Semaphore> =
|
||||
LazyLock::new(|| tokio::sync::Semaphore::new(PREP_CONCURRENCY));
|
||||
|
||||
/// Telegram's multipart upload limit for everything that is not a photo:
|
||||
/// its own docs on `sendVideo`/`sendAnimation`/`sendDocument` say 50 MB
|
||||
/// (`RequestEntityTooLarge` is "larger than 50 MB"), while photos are the
|
||||
/// 10 MiB [`photo::MAX_UPLOAD_BYTES`] case. Using the photo cap here refused
|
||||
/// to even download a 10–50 MB video that Telegram itself would have
|
||||
/// accepted, and a video has no smaller variant to fall back to — so the
|
||||
/// post was lost.
|
||||
pub(super) const MAX_MEDIA_UPLOAD_BYTES: u64 = 50 * 1024 * 1024;
|
||||
|
||||
/// Whole-transfer budget for one fallback download. The prep slot (and the
|
||||
/// non-photo memory reservation) is held while this runs, and the idle window
|
||||
/// alone lets a server drip one byte every 29 s forever — so this path caps
|
||||
/// its own transfers well below the in-fetch default: 50 MiB in 300 s needs
|
||||
/// about 1.4 Mbit/s, and a much slower link is better served by the retry
|
||||
/// path toward the item's smaller fallback URL than by pinning a slot for
|
||||
/// ten minutes.
|
||||
/// ponytail: if slow-link reports show up, move the download out of the prep
|
||||
/// slot (slot = decode/upload only) instead of raising this again.
|
||||
const FALLBACK_DOWNLOAD_TOTAL: std::time::Duration = std::time::Duration::from_secs(300);
|
||||
|
||||
/// Infers a file extension from magic bytes so Telegram detects the mime type
|
||||
/// on multipart uploads.
|
||||
pub(super) fn sniff_ext(bytes: &[u8]) -> &'static str {
|
||||
@@ -55,74 +89,109 @@ pub(super) enum FallbackError {
|
||||
/// errors are not.
|
||||
async fn download_to_temp(
|
||||
item: &MediaItemPayload,
|
||||
media_url: &str,
|
||||
) -> Result<(NamedTempFile, bytes::Bytes), FallbackError> {
|
||||
let media_url = match item {
|
||||
MediaItemPayload::Photo { media, .. }
|
||||
| MediaItemPayload::Video { media, .. }
|
||||
| MediaItemPayload::Animation { media, .. } => media,
|
||||
};
|
||||
// The caller narrows the media to a source URL before calling (its entry
|
||||
// guard rejects a file id), so there is nothing to match on here.
|
||||
// Photos are downloaded even over the upload cap so `prepare_photo` can
|
||||
// downscale / transcode them (cap = decode budget); videos/animations
|
||||
// abort as soon as the upload cap is crossed mid-stream.
|
||||
let limit = if matches!(item, MediaItemPayload::Photo { .. }) {
|
||||
photo::MAX_DECODE_BYTES
|
||||
// downscale / transcode them, up to their own download cap; videos and
|
||||
// animations are refused as soon as the declared size crosses their own
|
||||
// (larger) upload cap. The limit is that cap, not `cap + 1`: a file of
|
||||
// exactly the cap is admitted (`len > max_bytes` is false), and one byte
|
||||
// over is not — the same boundary the size probe this replaced drew.
|
||||
let is_photo = matches!(item, MediaItemPayload::Photo { .. });
|
||||
let limit = if is_photo {
|
||||
photo::MAX_PHOTO_DOWNLOAD_BYTES
|
||||
} else {
|
||||
MAX_UPLOAD_BYTES + 1
|
||||
MAX_MEDIA_UPLOAD_BYTES
|
||||
};
|
||||
let bytes = match x_media::site::download_media_limited(media_url, limit).await {
|
||||
// A non-photo body is buffered whole and charges the process-wide budget
|
||||
// for as long as this function holds it (one 64 MiB unit covers the cap):
|
||||
// `PREP_SLOTS` bounds how many are in flight, this bounds what they add
|
||||
// up to. Photos charge their own download cap for the same window — their
|
||||
// real cost (header probe + decode buffer) is charged again by the
|
||||
// prepare step right after, where both are actually held together.
|
||||
let _budget = Some(
|
||||
photo::reserve_memory(if is_photo {
|
||||
photo::MAX_PHOTO_DOWNLOAD_BYTES
|
||||
} else {
|
||||
MAX_MEDIA_UPLOAD_BYTES
|
||||
})
|
||||
.await,
|
||||
);
|
||||
let bytes = match x_media::site::download_media_limited(
|
||||
media_url,
|
||||
limit,
|
||||
FALLBACK_DOWNLOAD_TOTAL,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(bytes) => bytes,
|
||||
Err(FetchError::Http(_)) => {
|
||||
return Err(FallbackError::Retryable {
|
||||
delay_seconds: retry_delay_seconds(0),
|
||||
});
|
||||
}
|
||||
Err(FetchError::TooLarge) => {
|
||||
return Err(FallbackError::MediaTooLarge);
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(FallbackError::Permanent {
|
||||
message: format!("download failed: {e}"),
|
||||
});
|
||||
}
|
||||
Err(e) => return Err(classify_download_error(e)),
|
||||
};
|
||||
let ext = sniff_ext(&bytes);
|
||||
let mut file = tempfile::Builder::new()
|
||||
.prefix(x_media::TEMP_FILE_PREFIX)
|
||||
.suffix(&format!(".{ext}"))
|
||||
.tempfile()
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("temp file failed: {e}"),
|
||||
})?;
|
||||
use std::io::Write;
|
||||
file.as_file_mut()
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("temp file write failed: {e}"),
|
||||
})?;
|
||||
// The write runs on a blocking thread: up to 50 MiB of sync disk I/O on
|
||||
// an executor thread would stall whatever else that worker runs (six prep
|
||||
// tasks could stall six threads at once on a slow volume). A write
|
||||
// failure is resource exhaustion far more often than a broken temp
|
||||
// dir (ENOSPC / EDQUOT), and that clears on its own — worth an attempt
|
||||
// instead of dropping the post on the first try. Creating the file (above)
|
||||
// stays permanent: a temp dir that cannot be created at all is a
|
||||
// deployment fault that should fail loudly and immediately. `Retryable`
|
||||
// carries no message, so the cause is logged here.
|
||||
let (written, file, bytes) = tokio::task::spawn_blocking(move || {
|
||||
use std::io::Write;
|
||||
let written = file.as_file_mut().write_all(&bytes);
|
||||
(written, file, bytes)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("upload write worker panicked: {e}"),
|
||||
})?;
|
||||
written.map_err(|e| {
|
||||
log::error!("temp file write failed: {e}");
|
||||
FallbackError::Retryable {
|
||||
delay_seconds: retry_delay_seconds(0),
|
||||
}
|
||||
})?;
|
||||
Ok((file, bytes))
|
||||
}
|
||||
|
||||
/// Which failure class a media download belongs to. Transport errors and
|
||||
/// server-side hiccups (429/5xx, see `download_media_limited`) are worth
|
||||
/// another attempt; a 4xx means the media itself is gone or refused, and a
|
||||
/// retry could only ask the same URL again.
|
||||
fn classify_download_error(err: FetchError) -> FallbackError {
|
||||
match err {
|
||||
FetchError::RateLimited {
|
||||
retry_after_secs, ..
|
||||
} => FallbackError::Retryable {
|
||||
delay_seconds: retry_after_secs as f64,
|
||||
},
|
||||
FetchError::Http(_) | FetchError::Transient(_) => FallbackError::Retryable {
|
||||
delay_seconds: retry_delay_seconds(0),
|
||||
},
|
||||
FetchError::TooLarge => FallbackError::MediaTooLarge,
|
||||
e => FallbackError::Permanent {
|
||||
message: format!("download failed: {e}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the media group item from an uploaded file.
|
||||
fn media_from_file(
|
||||
item: &MediaItemPayload,
|
||||
path: std::path::PathBuf,
|
||||
caption: Option<&str>,
|
||||
thumbnail: Option<&str>,
|
||||
) -> Result<InputMedia, String> {
|
||||
let mut media = match item {
|
||||
MediaItemPayload::Photo { has_spoiler, .. } => {
|
||||
photo_media(InputFile::file(path), caption, *has_spoiler)
|
||||
}
|
||||
MediaItemPayload::Video { has_spoiler, .. } => {
|
||||
video_media(InputFile::file(path), caption, *has_spoiler)
|
||||
}
|
||||
MediaItemPayload::Animation { has_spoiler, .. } => {
|
||||
animation_media(InputFile::file(path), caption, *has_spoiler)
|
||||
}
|
||||
};
|
||||
if let (Some(thumb), InputMedia::Video(v)) = (thumbnail, &mut media) {
|
||||
*v = v.clone().thumbnail(input_file_for(thumb)?);
|
||||
}
|
||||
Ok(media)
|
||||
media_from(item, InputFile::file(path), caption)
|
||||
}
|
||||
|
||||
/// Builds the media group item from a (smaller) URL.
|
||||
@@ -130,23 +199,8 @@ fn media_from_url(
|
||||
item: &MediaItemPayload,
|
||||
url: &str,
|
||||
caption: Option<&str>,
|
||||
thumbnail: Option<&str>,
|
||||
) -> Result<InputMedia, String> {
|
||||
let mut media = match item {
|
||||
MediaItemPayload::Photo { has_spoiler, .. } => {
|
||||
photo_media(input_file_for(url)?, caption, *has_spoiler)
|
||||
}
|
||||
MediaItemPayload::Video { has_spoiler, .. } => {
|
||||
video_media(input_file_for(url)?, caption, *has_spoiler)
|
||||
}
|
||||
MediaItemPayload::Animation { has_spoiler, .. } => {
|
||||
animation_media(input_file_for(url)?, caption, *has_spoiler)
|
||||
}
|
||||
};
|
||||
if let (Some(thumb), InputMedia::Video(v)) = (thumbnail, &mut media) {
|
||||
*v = v.clone().thumbnail(input_file_for(thumb)?);
|
||||
}
|
||||
Ok(media)
|
||||
media_from(item, input_file_for(url)?, caption)
|
||||
}
|
||||
|
||||
/// One item prepared for the upload fallback: the ready-to-send media plus
|
||||
@@ -166,40 +220,34 @@ pub(super) async fn prepare_upload_item(
|
||||
index: usize,
|
||||
caption: Option<&str>,
|
||||
) -> Result<PreparedItem, FallbackError> {
|
||||
// A file id is already Telegram's copy of an uploaded file: there is no
|
||||
// URL to re-fetch, and without this guard `item_url` presents the id as
|
||||
// a *path*, which fails at upload time with a confusing open error
|
||||
// instead of a classification. Re-upload cannot apply to it.
|
||||
if matches!(item.media_ref(), MediaRef::FileId(_)) {
|
||||
return Err(FallbackError::Permanent {
|
||||
message: "file id reached the upload fallback".into(),
|
||||
});
|
||||
}
|
||||
let media_url = item_url(&item);
|
||||
// Locally produced files (ugoira / bsky remux MP4): nothing to download
|
||||
// or shrink — upload the file directly. The send is a multipart upload,
|
||||
// so the only remaining failure is an upload-cap error, which is
|
||||
// permanent (a video cannot be re-encoded here).
|
||||
let media_url = item_url(&item);
|
||||
if !media_url.starts_with("http://") && !media_url.starts_with("https://") {
|
||||
let media = media_from_file(
|
||||
&item,
|
||||
std::path::PathBuf::from(media_url),
|
||||
caption,
|
||||
item.thumbnail_url(),
|
||||
)
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
return Ok(PreparedItem {
|
||||
index,
|
||||
media,
|
||||
keep_alive: None,
|
||||
});
|
||||
}
|
||||
// Size check before downloading/uploading: over the cap, use the
|
||||
// smaller URL instead of the file. Photos are exempt — they are
|
||||
// downloaded and processed (downscale / PNG→JPEG) before uploading.
|
||||
let too_large = match x_media::site::media_size(media_url).await {
|
||||
Ok(Some(size)) => size > MAX_UPLOAD_BYTES,
|
||||
_ => false,
|
||||
};
|
||||
let too_large = too_large && !matches!(item, MediaItemPayload::Photo { .. });
|
||||
if too_large {
|
||||
let url = item
|
||||
.fallback_url()
|
||||
.ok_or_else(|| FallbackError::Permanent {
|
||||
message: "media too large".into(),
|
||||
})?;
|
||||
let media = media_from_url(&item, url, caption, item.thumbnail_url())
|
||||
let path = std::path::Path::new(media_url);
|
||||
let size = tokio::fs::metadata(path)
|
||||
.await
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("local media unavailable: {e}"),
|
||||
})?
|
||||
.len();
|
||||
if size > MAX_MEDIA_UPLOAD_BYTES {
|
||||
return Err(FallbackError::Permanent {
|
||||
message: "local media exceeds Telegram upload limit".into(),
|
||||
});
|
||||
}
|
||||
let media = media_from_file(&item, path.to_path_buf(), caption)
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
return Ok(PreparedItem {
|
||||
index,
|
||||
@@ -207,7 +255,14 @@ pub(super) async fn prepare_upload_item(
|
||||
keep_alive: None,
|
||||
});
|
||||
}
|
||||
match download_to_temp(&item).await {
|
||||
// Whether a file is over the cap is settled by the download itself:
|
||||
// `download_media_limited` reads the declared Content-Length before any
|
||||
// body byte and aborts with `FetchError::TooLarge`, which arrives here as
|
||||
// `FallbackError::MediaTooLarge` — turned into the item's smaller URL by
|
||||
// the match below. A separate size probe used to issue a second GET of the
|
||||
// same URL for an answer this path already has (and issued it for photos,
|
||||
// whose answer was discarded one line later).
|
||||
match download_to_temp(&item, media_url).await {
|
||||
Ok((file, bytes)) => {
|
||||
if matches!(item, MediaItemPayload::Photo { .. }) {
|
||||
// Telegram rejects photos wider+taller than 10000 px combined
|
||||
@@ -215,16 +270,33 @@ pub(super) async fn prepare_upload_item(
|
||||
// before uploading; photos that cannot be brought within the
|
||||
// limits degrade to the smaller URL. CPU-heavy work runs off
|
||||
// the async executor thread.
|
||||
let prep = tokio::task::spawn_blocking(move || photo::prepare_photo(file, &bytes))
|
||||
.await
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("photo worker panicked: {e}"),
|
||||
})?
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
//
|
||||
// Keep the permit inside the blocking closure. If the async
|
||||
// future is cancelled while `spawn_blocking` is still
|
||||
// decoding, dropping the permit here would undercount the
|
||||
// process memory bound until that closure finishes.
|
||||
let (bytes, budget_bytes) = tokio::task::spawn_blocking(move || {
|
||||
let budget_bytes = photo::prepare_budget_bytes(&bytes);
|
||||
(bytes, budget_bytes)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("photo worker panicked: {e}"),
|
||||
})?;
|
||||
let budget = photo::reserve_memory(budget_bytes).await;
|
||||
let prep = tokio::task::spawn_blocking(move || {
|
||||
let _budget = budget;
|
||||
photo::prepare_photo(file, &bytes)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| FallbackError::Permanent {
|
||||
message: format!("photo worker panicked: {e}"),
|
||||
})?
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
match prep {
|
||||
PhotoPrep::Upload(upload) => {
|
||||
let path = upload.path().to_path_buf();
|
||||
let media = media_from_file(&item, path, caption, item.thumbnail_url())
|
||||
let media = media_from_file(&item, path, caption)
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
Ok(PreparedItem {
|
||||
index,
|
||||
@@ -237,7 +309,7 @@ pub(super) async fn prepare_upload_item(
|
||||
message: "photo dimensions exceed Telegram limits and no smaller variant is available"
|
||||
.into(),
|
||||
})?;
|
||||
let media = media_from_url(&item, url, caption, item.thumbnail_url())
|
||||
let media = media_from_url(&item, url, caption)
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
Ok(PreparedItem {
|
||||
index,
|
||||
@@ -248,7 +320,7 @@ pub(super) async fn prepare_upload_item(
|
||||
}
|
||||
} else {
|
||||
let path = file.path().to_path_buf();
|
||||
let media = media_from_file(&item, path, caption, item.thumbnail_url())
|
||||
let media = media_from_file(&item, path, caption)
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
Ok(PreparedItem {
|
||||
index,
|
||||
@@ -263,7 +335,7 @@ pub(super) async fn prepare_upload_item(
|
||||
.ok_or_else(|| FallbackError::Permanent {
|
||||
message: "media too large".into(),
|
||||
})?;
|
||||
let media = media_from_url(&item, url, caption, item.thumbnail_url())
|
||||
let media = media_from_url(&item, url, caption)
|
||||
.map_err(|message| FallbackError::Permanent { message })?;
|
||||
Ok(PreparedItem {
|
||||
index,
|
||||
@@ -277,10 +349,12 @@ pub(super) async fn prepare_upload_item(
|
||||
|
||||
/// Download-and-reupload fallback for one media batch. Files over the upload
|
||||
/// cap are not downloaded/uploaded; the item falls back to its smaller URL
|
||||
/// (which Telegram fetches itself). Items are prepared concurrently (bounded)
|
||||
/// because the downloads are network-bound; the batch is then uploaded in its
|
||||
/// original order. Returns the fallback-error without the task attached;
|
||||
/// callers wrap it with the updated task state.
|
||||
/// (which Telegram fetches itself). Items are prepared concurrently because the
|
||||
/// downloads are network-bound, under one process-wide bound ([`PREP_SLOTS`] —
|
||||
/// the URL and queue workers can each be inside a batch, so a per-batch bound
|
||||
/// would multiply); the batch is then uploaded in its original order. Returns
|
||||
/// the fallback-error without the task attached; callers wrap it with the
|
||||
/// updated task state.
|
||||
pub(super) async fn send_batch_via_upload(
|
||||
sender: &dyn MediaSender,
|
||||
chat_id: i64,
|
||||
@@ -289,7 +363,6 @@ pub(super) async fn send_batch_via_upload(
|
||||
caption: Option<&str>,
|
||||
task: Task,
|
||||
) -> Result<Vec<Message>, SendError> {
|
||||
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(3));
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for (i, item) in batch.iter().enumerate() {
|
||||
let item_caption = if i == 0 {
|
||||
@@ -298,9 +371,8 @@ pub(super) async fn send_batch_via_upload(
|
||||
None
|
||||
};
|
||||
let item = item.clone();
|
||||
let sem = std::sync::Arc::clone(&sem);
|
||||
set.spawn(async move {
|
||||
let _permit = sem.acquire().await.expect("upload semaphore closed");
|
||||
let _permit = PREP_SLOTS.acquire().await.expect("upload semaphore closed");
|
||||
prepare_upload_item(item, i, item_caption.as_deref()).await
|
||||
});
|
||||
}
|
||||
@@ -343,3 +415,75 @@ pub(super) async fn send_batch_via_upload(
|
||||
Err(e) => Err(classify_to_send_error(&e, task, "upload failed")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod download_class_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn download_errors_split_by_whether_a_retry_can_help() {
|
||||
// Transport failure and a server-side hiccup: try again.
|
||||
assert!(matches!(
|
||||
classify_download_error(FetchError::Transient("media status 503".into())),
|
||||
FallbackError::Retryable { .. }
|
||||
));
|
||||
// The media is gone / the host refuses us: a retry repeats the 4xx.
|
||||
assert!(matches!(
|
||||
classify_download_error(FetchError::NotFound),
|
||||
FallbackError::Permanent { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
classify_download_error(FetchError::Blocked),
|
||||
FallbackError::Permanent { .. }
|
||||
));
|
||||
// Over the cap: degrade to the smaller URL, never retry.
|
||||
assert!(matches!(
|
||||
classify_download_error(FetchError::TooLarge),
|
||||
FallbackError::MediaTooLarge
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limited_media_keeps_the_server_delay() {
|
||||
match classify_download_error(FetchError::RateLimited {
|
||||
site: "media",
|
||||
retry_after_secs: 60,
|
||||
}) {
|
||||
FallbackError::Retryable { delay_seconds } => assert_eq!(delay_seconds, 60.0),
|
||||
_ => panic!("expected retryable rate limit"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_file_id_item_is_refused_before_any_download() {
|
||||
let item = MediaItemPayload::Photo {
|
||||
media: MediaRef::FileId("AgACAgIAAx".into()),
|
||||
has_spoiler: false,
|
||||
fallback_url: None,
|
||||
};
|
||||
match prepare_upload_item(item, 0, None).await {
|
||||
Err(FallbackError::Permanent { .. }) => {}
|
||||
Err(_) => panic!("expected a permanent classification, got a different error"),
|
||||
Ok(_) => panic!("a file id must be refused, not prepared"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_local_media_is_refused_before_upload() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("video.mp4");
|
||||
let handle = std::fs::File::create(&file).unwrap();
|
||||
handle.set_len(MAX_MEDIA_UPLOAD_BYTES + 1).unwrap();
|
||||
drop(handle);
|
||||
let item = MediaItemPayload::Video {
|
||||
media: MediaRef::Source(file.to_string_lossy().into_owned()),
|
||||
has_spoiler: false,
|
||||
thumbnail: None,
|
||||
fallback_url: None,
|
||||
};
|
||||
assert!(matches!(
|
||||
prepare_upload_item(item, 0, None).await,
|
||||
Err(FallbackError::Permanent { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+326
-54
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::db::unix_now;
|
||||
use parking_lot::Mutex;
|
||||
use rusqlite::OptionalExtension;
|
||||
use rusqlite::params;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -17,11 +18,19 @@ pub struct ChatData {
|
||||
pub edit_message: HashMap<i64, EditMessage>,
|
||||
/// name -> HTML template containing "[]"
|
||||
pub template: HashMap<String, String>,
|
||||
/// site name (twitter/bsky/misskey/pixiv) -> user-supplied caption format
|
||||
/// with {url} {author} {author_url} {title} {tags} placeholders.
|
||||
/// site name (twitter/bsky/misskey/pixiv/bilibili) -> user-supplied caption format
|
||||
/// with {url} {author} {author_url} {title} {content} {tags} placeholders.
|
||||
pub message_format: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl ChatData {
|
||||
/// The chat's caption format for `site`, empty when it has none — the
|
||||
/// built-in caption then applies (`caption_from_fields`).
|
||||
pub fn format_for(&self, site: &str) -> String {
|
||||
self.message_format.get(site).cloned().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
||||
pub struct EditMessage {
|
||||
pub url: String,
|
||||
@@ -53,53 +62,78 @@ impl ChatStore {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get(&self, chat_id: i64) -> ChatData {
|
||||
/// Loads persisted state, distinguishing a missing row and a failed read
|
||||
/// from valid default settings. Only the ordinary read-only `get` path is
|
||||
/// allowed to degrade to defaults; mutations must not write those defaults
|
||||
/// back over a real row.
|
||||
async fn load(&self, chat_id: i64) -> Result<ChatData, ()> {
|
||||
if let Some(data) = self.cache.lock().get(&chat_id) {
|
||||
return data.clone();
|
||||
return Ok(data.clone());
|
||||
}
|
||||
let chat_key = chat_id.to_string();
|
||||
let payload = self
|
||||
.pool
|
||||
.with_conn(move |conn| {
|
||||
// Concurrent handler tasks (batch-forwards) may write chat_state
|
||||
// while this read runs; the shared busy timeout handles the
|
||||
// write-lock collision instead of failing the query.
|
||||
let mut stmt = conn.prepare("SELECT payload FROM chat_state WHERE chat_id = ?1")?;
|
||||
let mut rows = stmt.query(params![chat_key])?;
|
||||
match rows.next()? {
|
||||
Some(row) => Ok(Some(row.get::<_, String>(0)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
// Concurrent handler tasks (batch-forwards) may write
|
||||
// chat_state while this read runs; the shared busy timeout
|
||||
// handles the write-lock collision instead of failing the
|
||||
// query.
|
||||
conn.query_row(
|
||||
"SELECT payload FROM chat_state WHERE chat_id = ?1",
|
||||
params![chat_key],
|
||||
|row| row.get::<_, String>(0),
|
||||
)
|
||||
.optional()
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
log::error!("chat_state read failed: {e}");
|
||||
None
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let data: ChatData = serde_json::from_str(&payload).unwrap_or_default();
|
||||
self.cache.lock().insert(chat_id, data.clone());
|
||||
data
|
||||
.map_err(|e| {
|
||||
log::warn!("chat_state read failed: {e}");
|
||||
})?;
|
||||
let payload = payload.unwrap_or_default();
|
||||
let data = if payload.is_empty() {
|
||||
ChatData::default()
|
||||
} else {
|
||||
serde_json::from_str(&payload).map_err(|e| {
|
||||
log::warn!("chat_state payload is invalid: {e}");
|
||||
})?
|
||||
};
|
||||
// Only fill a miss: an unconditional insert would let this (possibly
|
||||
// stale) snapshot overwrite what a concurrent set just wrote.
|
||||
self.cache
|
||||
.lock()
|
||||
.entry(chat_id)
|
||||
.or_insert_with(|| data.clone());
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Write-through: update the cache and the DB.
|
||||
pub async fn set(&self, chat_id: i64, data: &ChatData) {
|
||||
/// Read-only access may degrade to defaults for display and control flow.
|
||||
/// Mutating callers use [`Self::update`], which refuses a failed load.
|
||||
pub async fn get(&self, chat_id: i64) -> ChatData {
|
||||
self.load(chat_id).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Write-through: update the cache and the DB. Returns whether the DB
|
||||
/// write landed: the cache is updated either way, so `false` means the
|
||||
/// change lives only until the next restart and the caller has to say so
|
||||
/// instead of reporting a save that did not happen.
|
||||
pub async fn set(&self, chat_id: i64, data: &ChatData) -> bool {
|
||||
self.cache.lock().insert(chat_id, data.clone());
|
||||
let payload = serde_json::to_string(data).expect("chat state serializes");
|
||||
let chat_id = chat_id.to_string();
|
||||
let result = self
|
||||
.pool
|
||||
.with_conn(move |conn| {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO chat_state (chat_id, payload) VALUES (?1, ?2)",
|
||||
params![chat_id, payload],
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
if let Err(e) = result {
|
||||
log::error!("chat_state write failed: {e}");
|
||||
}
|
||||
self.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"chat_state write failed",
|
||||
false,
|
||||
move |conn| {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO chat_state (chat_id, payload) VALUES (?1, ?2)",
|
||||
params![chat_id, payload],
|
||||
)?;
|
||||
Ok(true)
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The per-chat async lock serializing get→mutate→set cycles.
|
||||
@@ -115,14 +149,19 @@ impl ChatStore {
|
||||
/// (the batch-forward design spawns several per chat) each snapshot the
|
||||
/// same `ChatData` and last-writer-wins would silently drop mutations,
|
||||
/// e.g. a second `edit_message` record. The per-chat lock makes the
|
||||
/// cycle atomic. Returns the closure's result.
|
||||
pub async fn update<R>(&self, chat_id: i64, f: impl FnOnce(&mut ChatData) -> R) -> R {
|
||||
/// cycle atomic. Returns the closure's result plus whether the DB write
|
||||
/// landed (see [`Self::set`]); callers that do not care ignore the flag.
|
||||
pub async fn update<R>(
|
||||
&self,
|
||||
chat_id: i64,
|
||||
f: impl FnOnce(&mut ChatData) -> R,
|
||||
) -> Result<(R, bool), ()> {
|
||||
let lock = self.lock_for(chat_id);
|
||||
let _guard = lock.lock().await;
|
||||
let mut data = self.get(chat_id).await;
|
||||
let mut data = self.load(chat_id).await?;
|
||||
let r = f(&mut data);
|
||||
self.set(chat_id, &data).await;
|
||||
r
|
||||
let saved = self.set(chat_id, &data).await;
|
||||
Ok((r, saved))
|
||||
}
|
||||
|
||||
/// Removes edit-before-forward records whose `created_at + ttl` is in the
|
||||
@@ -131,22 +170,70 @@ impl ChatStore {
|
||||
pub async fn prune_expired(&self, ttl: Duration) -> Vec<(i64, i64)> {
|
||||
let now = unix_now();
|
||||
let ttl_secs = ttl.as_secs() as i64;
|
||||
// Chats that may have an expired record, from a cache snapshot; the
|
||||
// pruning itself re-reads and writes under the per-chat lock below
|
||||
// (see the eviction note). Takes no lock of its own, so a chat
|
||||
// appearing later is simply picked up by the next sweep.
|
||||
let candidates: Vec<i64> = {
|
||||
// Chats worth looking at, from a cache snapshot: the ones with an
|
||||
// expired record, plus the ones holding no record at all. The latter
|
||||
// used to be left alone for the process lifetime — every chat that ever
|
||||
// sent a message or ran a command stayed in the cache and in the
|
||||
// per-chat lock map — even though a chat with no live prompt is exactly
|
||||
// what the eviction below is for. The pruning itself re-reads and
|
||||
// writes under the per-chat lock below; taking no lock here means a
|
||||
// chat appearing later is simply picked up by the next sweep.
|
||||
let mut candidates: Vec<i64> = {
|
||||
let cache = self.cache.lock();
|
||||
cache
|
||||
.iter()
|
||||
.filter(|(_, data)| {
|
||||
data.edit_message
|
||||
.values()
|
||||
.any(|entry| entry.created_at + ttl_secs <= now)
|
||||
data.edit_message.is_empty()
|
||||
|| data
|
||||
.edit_message
|
||||
.values()
|
||||
.any(|entry| entry.created_at + ttl_secs <= now)
|
||||
})
|
||||
.map(|(chat_id, _)| *chat_id)
|
||||
.collect()
|
||||
};
|
||||
let persisted = self
|
||||
.pool
|
||||
.with_conn_or(
|
||||
log::Level::Warn,
|
||||
"expired prompt scan failed",
|
||||
Vec::<i64>::new(),
|
||||
move |conn| {
|
||||
let mut stmt = conn.prepare("SELECT chat_id, payload FROM chat_state")?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
let id: String = row.get(0)?;
|
||||
let id: i64 = id.parse().map_err(|e| {
|
||||
rusqlite::Error::FromSqlConversionFailure(
|
||||
0,
|
||||
rusqlite::types::Type::Text,
|
||||
Box::new(e),
|
||||
)
|
||||
})?;
|
||||
let payload: String = row.get(1)?;
|
||||
let data: ChatData = serde_json::from_str(&payload).map_err(|e| {
|
||||
rusqlite::Error::FromSqlConversionFailure(
|
||||
0,
|
||||
rusqlite::types::Type::Text,
|
||||
Box::new(e),
|
||||
)
|
||||
})?;
|
||||
Ok((id, data))
|
||||
})?;
|
||||
Ok(rows
|
||||
.filter_map(Result::ok)
|
||||
.filter(|(_, data)| {
|
||||
data.edit_message
|
||||
.values()
|
||||
.any(|entry| entry.created_at + ttl_secs <= now)
|
||||
})
|
||||
.map(|(id, _)| id)
|
||||
.collect())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
candidates.extend(persisted);
|
||||
candidates.sort_unstable();
|
||||
candidates.dedup();
|
||||
let mut removed = Vec::new();
|
||||
let mut evicted_chats = Vec::new();
|
||||
for chat_id in candidates {
|
||||
@@ -173,12 +260,20 @@ impl ChatStore {
|
||||
}
|
||||
if !evicted_chats.is_empty() {
|
||||
let mut cache = self.cache.lock();
|
||||
let mut locks = self.locks.lock();
|
||||
for chat_id in &evicted_chats {
|
||||
cache.remove(chat_id);
|
||||
locks.remove(chat_id);
|
||||
}
|
||||
}
|
||||
// Per-chat locks go only while uncontended (the same rule as
|
||||
// rate_limit's prune): pulling a lock out from under an in-flight
|
||||
// update — between its `lock_for` clone and its `lock().await` —
|
||||
// would let a second writer `lock_for` a fresh one and enter the
|
||||
// critical section concurrently. A contended lock stays until a later
|
||||
// sweep, and dropping the uncontended ones also catches chats an
|
||||
// earlier sweep had to skip, so the map stays bounded.
|
||||
self.locks
|
||||
.lock()
|
||||
.retain(|_, lock| Arc::strong_count(lock) > 1);
|
||||
if !removed.is_empty() {
|
||||
log::info!(
|
||||
"pruned {} expired edit-before-forward record(s)",
|
||||
@@ -215,7 +310,8 @@ mod tests {
|
||||
},
|
||||
);
|
||||
})
|
||||
.await;
|
||||
.await
|
||||
.unwrap();
|
||||
}));
|
||||
}
|
||||
for h in handles {
|
||||
@@ -251,7 +347,8 @@ mod tests {
|
||||
data.edit_message.insert(1, edit_entry(7, now - 3600));
|
||||
data.edit_message.insert(2, edit_entry(7, now));
|
||||
})
|
||||
.await;
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let removed = store.prune_expired(Duration::from_secs(60)).await;
|
||||
|
||||
@@ -265,6 +362,85 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persisted_expired_prompts_are_pruned_after_restart() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("cold.db");
|
||||
let pool = crate::db::open_store(path.to_str().unwrap()).unwrap();
|
||||
let raw = rusqlite::Connection::open(&path).unwrap();
|
||||
let data = ChatData {
|
||||
edit_message: [(1, edit_entry(7, unix_now() - 3600))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..ChatData::default()
|
||||
};
|
||||
raw.execute(
|
||||
"INSERT INTO chat_state (chat_id, payload) VALUES ('7', ?1)",
|
||||
rusqlite::params![serde_json::to_string(&data).unwrap()],
|
||||
)
|
||||
.unwrap();
|
||||
let store = ChatStore::new(pool);
|
||||
assert!(store.cache.lock().get(&7).is_none());
|
||||
assert_eq!(
|
||||
store.prune_expired(Duration::from_secs(60)).await,
|
||||
vec![(7, 1)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_idle_chat_is_evicted_and_its_state_reloads() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pool = crate::db::open_store(dir.path().join("e.db").to_str().unwrap()).unwrap();
|
||||
let store = ChatStore::new(pool);
|
||||
// Durable settings and no prompt at all: this chat used to sit in the
|
||||
// cache (and in the per-chat lock map) for the process lifetime,
|
||||
// because the sweep only ever looked at chats with an *expired* record.
|
||||
store
|
||||
.update(9, |data| {
|
||||
data.forward_channel_id = Some(-100);
|
||||
data.message_format.insert("twitter".into(), "{url}".into());
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(store.cache.lock().contains_key(&9));
|
||||
|
||||
let removed = store.prune_expired(Duration::from_secs(60)).await;
|
||||
|
||||
assert!(removed.is_empty(), "nothing had expired");
|
||||
assert!(
|
||||
!store.cache.lock().contains_key(&9),
|
||||
"a chat with no live prompt must leave the cache"
|
||||
);
|
||||
assert!(!store.locks.lock().contains_key(&9), "…and its lock");
|
||||
// The DB kept the row, so the next use reloads everything it held.
|
||||
let data = store.get(9).await;
|
||||
assert_eq!(data.forward_channel_id, Some(-100));
|
||||
assert_eq!(
|
||||
data.message_format.get("twitter").map(String::as_str),
|
||||
Some("{url}")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_live_prompt_keeps_its_chat_cached() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pool = crate::db::open_store(dir.path().join("k.db").to_str().unwrap()).unwrap();
|
||||
let store = ChatStore::new(pool);
|
||||
store
|
||||
.update(10, |data| {
|
||||
data.edit_message.insert(1, edit_entry(10, unix_now()));
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
store.prune_expired(Duration::from_secs(3600)).await;
|
||||
|
||||
assert!(
|
||||
store.cache.lock().contains_key(&10),
|
||||
"a live prompt holds its chat in the cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prune_eviction_keeps_the_persisted_state() {
|
||||
// Every record expires → the chat is evicted from the cache; the
|
||||
@@ -277,7 +453,8 @@ mod tests {
|
||||
data.template.insert("keep".into(), "[]".into());
|
||||
data.edit_message.insert(1, edit_entry(8, 0));
|
||||
})
|
||||
.await;
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let removed = store.prune_expired(Duration::from_secs(60)).await;
|
||||
|
||||
@@ -290,4 +467,99 @@ mod tests {
|
||||
"eviction dropped state the DB never received"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_read_is_not_cached() {
|
||||
// A read that errors (busy, IO, a missing table) answers the default;
|
||||
// caching that answer would make the next get return it blind and the
|
||||
// next update write it back over the chat's real settings.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("f.db");
|
||||
let pool = crate::db::open_store(path.to_str().unwrap()).unwrap();
|
||||
let raw = rusqlite::Connection::open(&path).unwrap();
|
||||
raw.execute_batch("DROP TABLE chat_state").unwrap();
|
||||
let store = ChatStore::new(pool);
|
||||
|
||||
let first = store.get(7).await;
|
||||
assert!(first.forward_channel_id.is_none());
|
||||
assert!(
|
||||
!store.cache.lock().contains_key(&7),
|
||||
"a failed read must not poison the cache"
|
||||
);
|
||||
|
||||
// The next get retries the DB and sees the real row.
|
||||
raw.execute_batch(
|
||||
"CREATE TABLE chat_state (chat_id TEXT PRIMARY KEY, payload TEXT NOT NULL)",
|
||||
)
|
||||
.unwrap();
|
||||
let real = ChatData {
|
||||
forward_channel_id: Some(42),
|
||||
..ChatData::default()
|
||||
};
|
||||
raw.execute(
|
||||
"INSERT INTO chat_state (chat_id, payload) VALUES ('7', ?1)",
|
||||
rusqlite::params![serde_json::to_string(&real).unwrap()],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(store.get(7).await.forward_channel_id, Some(42));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_read_does_not_overwrite_existing_state() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.db");
|
||||
let pool = crate::db::open_store(path.to_str().unwrap()).unwrap();
|
||||
let raw = rusqlite::Connection::open(&path).unwrap();
|
||||
let stored = "{\"forward_channel_id\":";
|
||||
raw.execute(
|
||||
"INSERT INTO chat_state (chat_id, payload) VALUES ('7', ?1)",
|
||||
rusqlite::params![stored],
|
||||
)
|
||||
.unwrap();
|
||||
let store = ChatStore::new(pool);
|
||||
let mut called = false;
|
||||
let result = store
|
||||
.update(7, |data| {
|
||||
called = true;
|
||||
data.message_format.insert("twitter".into(), "{url}".into());
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(result.is_err());
|
||||
assert!(!called, "a failed load must not run a destructive mutation");
|
||||
assert!(!store.cache.lock().contains_key(&7));
|
||||
let payload: String = raw
|
||||
.query_row(
|
||||
"SELECT payload FROM chat_state WHERE chat_id='7'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(payload, stored, "the original row must remain unchanged");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prune_spares_a_lock_someone_still_holds() {
|
||||
// The sweep evicts uncontended locks only: removing one an update
|
||||
// still holds (its `lock_for` clone alive) would let a second writer
|
||||
// create a fresh lock and enter the critical section concurrently.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pool = crate::db::open_store(dir.path().join("l.db").to_str().unwrap()).unwrap();
|
||||
let store = ChatStore::new(pool);
|
||||
store.set(1, &ChatData::default()).await;
|
||||
|
||||
let held = store.lock_for(1); // an update between lock_for and lock().await
|
||||
store.prune_expired(Duration::from_secs(60)).await;
|
||||
assert!(
|
||||
store.locks.lock().contains_key(&1),
|
||||
"a contended lock must survive the sweep"
|
||||
);
|
||||
|
||||
drop(held);
|
||||
store.prune_expired(Duration::from_secs(60)).await;
|
||||
assert!(
|
||||
!store.locks.lock().contains_key(&1),
|
||||
"the next sweep drops it once uncontended"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# Deployment reference for the Docker Hub image. Instance values (token, admins,
|
||||
# site credentials, domain) live in `.env` next to this file — `docker compose`
|
||||
# substitutes every `${VAR}` from it automatically — so this file stays in the
|
||||
# repository unmodified. A variable that is not listed here is not passed into
|
||||
# the container at all.
|
||||
#
|
||||
# JSON-file logs grow without limit by default: a long-running bot (and the
|
||||
# proxy in front of it) will fill the disk. One cap, applied to every service
|
||||
# below via the anchor.
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: '10m'
|
||||
max-file: '3'
|
||||
|
||||
services:
|
||||
nginx-proxy:
|
||||
image: nginxproxy/nginx-proxy:1.11.6-alpine
|
||||
restart: always
|
||||
environment:
|
||||
# Routes requests with an unknown Host (i.e. plain IP access) here; set
|
||||
# DEFAULT_HOST in .env to use it.
|
||||
DEFAULT_HOST: '${DEFAULT_HOST:-}'
|
||||
ports:
|
||||
- '80:80'
|
||||
- '443:443'
|
||||
volumes:
|
||||
- /var/run/docker.sock:/tmp/docker.sock:ro
|
||||
- certs:/etc/nginx/certs:ro
|
||||
- html:/usr/share/nginx/html:ro
|
||||
networks: [proxy]
|
||||
labels:
|
||||
- 'com.github.nginx-proxy.nginx'
|
||||
container_name: nginx-proxy
|
||||
logging: *default-logging
|
||||
|
||||
acme-companion:
|
||||
image: nginxproxy/acme-companion:2.8.2
|
||||
restart: always
|
||||
environment:
|
||||
DEFAULT_EMAIL: '${DEFAULT_EMAIL:-}'
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- certs:/etc/nginx/certs:rw
|
||||
- html:/usr/share/nginx/html:rw
|
||||
- acme:/etc/acme.sh
|
||||
networks: [proxy]
|
||||
container_name: acme-companion
|
||||
depends_on:
|
||||
- nginx-proxy
|
||||
logging: *default-logging
|
||||
|
||||
tgxmb:
|
||||
image: yoursfunny/telegram-twitter-media-bot:latest
|
||||
restart: always
|
||||
environment:
|
||||
# From .env (the instance's own values; see the env table in README.md).
|
||||
TELOXIDE_TOKEN: '${TELOXIDE_TOKEN:-}'
|
||||
BOT_ADMIN: '${BOT_ADMIN:-}'
|
||||
PIXIV_REFRESH_TOKEN: '${PIXIV_REFRESH_TOKEN:-}'
|
||||
TWITTER_AUTH_TOKEN: '${TWITTER_AUTH_TOKEN:-}'
|
||||
BILIBILI_COOKIE: '${BILIBILI_COOKIE:-}'
|
||||
VIRTUAL_HOST: '${VIRTUAL_HOST:-}'
|
||||
WEBHOOK_URL: '${WEBHOOK_URL:-}'
|
||||
WEBHOOK_SECRET_TOKEN: '${WEBHOOK_SECRET_TOKEN:-}'
|
||||
# Defaults, listed so they are discoverable; override in .env when needed.
|
||||
LOCAL_USER_ID: '${LOCAL_USER_ID:-9001}'
|
||||
RUST_LOG: '${RUST_LOG:-info}'
|
||||
EDIT_MESSAGE_TTL_SECONDS: '${EDIT_MESSAGE_TTL_SECONDS:-86400}'
|
||||
LINK_CACHE_TTL_SECONDS: '${LINK_CACHE_TTL_SECONDS:-604800}'
|
||||
CAPTION_QUOTE_TEXT_CHARS: '${CAPTION_QUOTE_TEXT_CHARS:-200}'
|
||||
VIRTUAL_PORT: '${VIRTUAL_PORT:-8443}'
|
||||
WEBHOOK: '${WEBHOOK:-true}'
|
||||
WEBHOOK_LISTEN: '${WEBHOOK_LISTEN:-0.0.0.0}'
|
||||
WEBHOOK_PORT: '${WEBHOOK_PORT:-8443}'
|
||||
# For a certificate on a bare IP: uncomment and set ACME_HOST in .env.
|
||||
# ACME_HOST: '${ACME_HOST:-}'
|
||||
#
|
||||
# Not listed on purpose: TELOXIDE_PROXY. Docker Desktop reaches a host
|
||||
# proxy through host.docker.internal (a loopback address inside the
|
||||
# container is the container itself), and teloxide panics on an *empty*
|
||||
# value, so add the line deliberately when this deployment needs one:
|
||||
# TELOXIDE_PROXY: '${TELOXIDE_PROXY}'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
networks: [proxy]
|
||||
depends_on:
|
||||
- nginx-proxy
|
||||
container_name: tgxmb
|
||||
logging: *default-logging
|
||||
# Probes the listener only when WEBHOOK=true (compose interpolates the
|
||||
# value from .env); a polling deployment has no listener and must not be
|
||||
# reported unhealthy. nginx-proxy shows 502s while webhook mode is down,
|
||||
# so surface that to the orchestrator.
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "test '${WEBHOOK:-true}' != true || bash -c 'exec 3<>/dev/tcp/127.0.0.1/${WEBHOOK_PORT:-8443}'"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
volumes:
|
||||
certs:
|
||||
html:
|
||||
acme:
|
||||
|
||||
networks:
|
||||
proxy:
|
||||
name: proxy
|
||||
@@ -1,74 +0,0 @@
|
||||
services:
|
||||
nginx-proxy:
|
||||
image: nginxproxy/nginx-proxy:1.11.6-alpine
|
||||
restart: always
|
||||
ports:
|
||||
- '80:80'
|
||||
- '443:443'
|
||||
volumes:
|
||||
- /var/run/docker.sock:/tmp/docker.sock:ro
|
||||
- certs:/etc/nginx/certs:ro
|
||||
- html:/usr/share/nginx/html:ro
|
||||
networks: [proxy]
|
||||
labels:
|
||||
- 'com.github.nginx-proxy.nginx'
|
||||
container_name: nginx-proxy
|
||||
|
||||
acme-companion:
|
||||
image: nginxproxy/acme-companion
|
||||
restart: always
|
||||
environment:
|
||||
DEFAULT_EMAIL: ''
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- certs:/etc/nginx/certs:rw
|
||||
- html:/usr/share/nginx/html:rw
|
||||
- acme:/etc/acme.sh
|
||||
networks: [proxy]
|
||||
container_name: acme-companion
|
||||
depends_on:
|
||||
- nginx-proxy
|
||||
|
||||
tgxmb:
|
||||
image: yoursfunny/telegram-twitter-media-bot:latest
|
||||
restart: always
|
||||
environment:
|
||||
LOCAL_USER_ID: '1000'
|
||||
TELOXIDE_TOKEN: ''
|
||||
BOT_ADMIN: ''
|
||||
PIXIV_REFRESH_TOKEN: ''
|
||||
TWITTER_AUTH_TOKEN: ''
|
||||
EDIT_MESSAGE_TTL_SECONDS: '86400'
|
||||
LINK_CACHE_TTL_SECONDS: '604800'
|
||||
RUST_LOG: 'info'
|
||||
VIRTUAL_HOST: '<YOUR_DOMAIN>'
|
||||
VIRTUAL_PORT: '8443'
|
||||
# ACME_HOST: 'your.domain.com'
|
||||
WEBHOOK: 'true'
|
||||
WEBHOOK_LISTEN: '0.0.0.0'
|
||||
WEBHOOK_PORT: '8443'
|
||||
WEBHOOK_URL: 'https://<YOUR_DOMAIN>/'
|
||||
WEBHOOK_SECRET_TOKEN: ''
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
networks: [proxy]
|
||||
depends_on:
|
||||
- nginx-proxy
|
||||
container_name: tgxmb
|
||||
# Webhook mode only: the bot listens on WEBHOOK_PORT; nginx-proxy shows
|
||||
# 502s while this is down, so surface it to the orchestrator.
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8443'"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
volumes:
|
||||
certs:
|
||||
html:
|
||||
acme:
|
||||
|
||||
networks:
|
||||
proxy:
|
||||
name: proxy
|
||||
+20
-4
@@ -5,6 +5,22 @@ if [ "$(id -u)" -eq '0' ]
|
||||
then
|
||||
USER_ID=${LOCAL_USER_ID:-9001}
|
||||
|
||||
# A non-numeric id breaks useradd/usermod in confusing ways, and uid 0
|
||||
# would sail straight through the privilege drop below (`setpriv
|
||||
# --reuid=0` keeps the bot root while looking configured) — refuse both
|
||||
# up front.
|
||||
case $USER_ID in
|
||||
''|*[!0-9]*)
|
||||
echo "docker-entrypoint: LOCAL_USER_ID must be a numeric uid, got '$USER_ID'" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
if [ "$USER_ID" -eq 0 ]
|
||||
then
|
||||
echo "docker-entrypoint: LOCAL_USER_ID=0 would keep the bot root; refusing" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# `docker compose restart` / `docker restart` reuse the same container, so
|
||||
# the overlay fs keeps the user created on first boot. A second `useradd`
|
||||
# then fails with exit code 9, which would trip `set -e` and kill the
|
||||
@@ -12,18 +28,18 @@ then
|
||||
# otherwise so LOCAL_USER_ID changes still apply.
|
||||
if ! id user > /dev/null 2>&1
|
||||
then
|
||||
useradd --shell /bin/bash -u ${USER_ID} -o -c "" -m user > /dev/null 2>&1 || true
|
||||
useradd --shell /bin/bash -u "${USER_ID}" -o -c "" -m user > /dev/null 2>&1 || true
|
||||
else
|
||||
usermod -u ${USER_ID} -o user > /dev/null 2>&1 || true
|
||||
usermod -u "${USER_ID}" -o user > /dev/null 2>&1 || true
|
||||
fi
|
||||
# Bind-mounted volumes may not support chown; a failure here must not kill
|
||||
# the container either.
|
||||
chown -R `id -u user`:`id -u user` /app > /dev/null 2>&1 || true
|
||||
chown -R "$(id -u user):$(id -g user)" /app > /dev/null 2>&1 || true
|
||||
|
||||
export HOME=/home/user
|
||||
# setpriv (util-linux, present in bookworm-slim) replaces gosu: drop to the
|
||||
# target user and exec, keeping the process as PID 1.
|
||||
exec setpriv --reuid=`id -u user` --regid=`id -g user` --init-groups "$@"
|
||||
exec setpriv --reuid="$(id -u user)" --regid="$(id -g user)" --init-groups "$@"
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
# Bilibili 动态支持:研究与实现记录
|
||||
|
||||
状态:已实现(`crates/x-media/src/site/bilibili/`)。本文记录上游调研、实测数据与最终设计;
|
||||
长期契约以 `AGENTS.md` 为准。
|
||||
|
||||
范围:**只发动态里的图片与动图**。动态内嵌视频不发流,降级为封面图;`b23.tv` 短链不匹配;
|
||||
视频页 / 番剧 / 直播间 / 专栏 / 音频均不支持。
|
||||
|
||||
---
|
||||
|
||||
## 1. 上游实现研究
|
||||
|
||||
### 1.1 nazurin(`nazurin/sites/bilibili/`,4 个文件 ~6 KB)
|
||||
|
||||
- 入口正则:`t\.bilibili\.com/(\d+)`、`t\.bilibili\.com/h5/dynamic/detail/(\d+)`、`bilibili\.com/opus/(\d+)`。
|
||||
- 请求:`GET https://api.bilibili.com/x/polymer/web-dynamic/v1/detail?id={id}`,仅加 `Referer: https://t.bilibili.com/{id}`。
|
||||
**无 cookie、无 WBI 签名、无 `build` 参数**。
|
||||
- 错误:`code == 4101147` → not found;`code != 0` 或缺 `data` → 报错。
|
||||
- 媒体:只取 `item.modules.module_dynamic.major.draw.items[].src`;缩略图 `src + "@518w.jpg"`;
|
||||
`size` 字段单位是 **KB**。`major` 为空或 `draw.items` 为空 → "No image found"。
|
||||
**忽略视频、转发(forward)与纯文字动态**。
|
||||
- caption:`"#" + module_author.name` + `module_dynamic.desc.text`,链接写死 `https://www.bilibili.com/opus/{id}`。
|
||||
|
||||
### 1.2 telegram-bili-feed-helper(`biliparser/provider/bilibili/`,9 个文件 ~57 KB)
|
||||
|
||||
- 9 个策略类(Video/Opus/Live/Audio/Read + Feed 基类 + Credential + api 工具):门禁正则
|
||||
`bilibili\.com|b23\.tv|BV\w{10}|av\d+`,再分流,兜底 `client.head(url)` 跟随重定向后按子串分流。
|
||||
- 动态:`GET /x/polymer/web-dynamic/desktop/v1/detail?id={id}&build=11605`(**单条,无分页**);
|
||||
客户端带桌面 UA、随机 `buvid3={uuid}infoc`;登录态用 `bilibili-api-python` 的 `Credential`
|
||||
(Redis 持久化 `SESSDATA/bili_jct/buvid3/buvid4/ac_time_value/DedeUserID`,扫码登录)。
|
||||
- **同样没有 WBI 签名 / appkey 签名**:playurl 用的是非 WBI 的 `/x/player/playurl`。
|
||||
- 媒体:`major.type` 分派 —— DRAW 取全部 `items[].src`;ARCHIVE/PGC/ARTICLE/MUSIC/COMMON/LIVE
|
||||
只取一张 `cover`;FORWARD 取原动态作者/正文并递归进 `orig` 找媒体。
|
||||
- 视频:仅独立 video 策略解析(`qn` 720P→480P→360P 试 durl,再退 DASH + ffmpeg 合并);
|
||||
**动态内嵌视频只发封面**。
|
||||
- 错误:要求 `status==200 && code==0`;风控 `-352`/`-412` 无特殊处理。
|
||||
|
||||
### 1.3 取舍
|
||||
|
||||
| 维度 | nazurin | bff | 本仓库 |
|
||||
|---|---|---|---|
|
||||
| 接口 | `v1/detail?id=` | `desktop/v1/detail?id=&build=` | `v1/detail?id=`(实测可用) |
|
||||
| 认证 | 无 | buvid3 + SESSDATA | 默认匿名;可选 `BILIBILI_COOKIE` |
|
||||
| WBI | 无 | 无 | 不实现(无需求) |
|
||||
| 图片 | `major.draw.items` | 同 + forward 递归 | 同,加 `orig` 递归、`http→https`、`.gif → Animated` |
|
||||
| 视频 | 完全忽略 | 动态内嵌视频发封面 | 发封面(不发流) |
|
||||
| 短链 | 不匹配 | 跟随重定向 | 不匹配(多数短链是视频,会让"静默忽略"变成失败提示) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 实测验证(2026-09-17,真实请求)
|
||||
|
||||
| 验证项 | 结果 |
|
||||
|---|---|
|
||||
| `v1/detail?id=`(无 cookie、UA `Mozilla/5.0`、带 Referer) | `200 {"code":0}` ✅ |
|
||||
| 同上,不带 cookie 也不带 Referer | `200 {"code":0}` ✅(无强制鉴权) |
|
||||
| bff 的 `bilibili_pc/…Electron/22.3.27` UA | `code:-352` ❌ → **不要抄它的 UA** |
|
||||
| `desktop/v1/detail?build=11605` | `code:-352` ❌ |
|
||||
| `feed/space?host_mid=`(用户时间线) | 首次成功、随后 `-352`,也见过 HTTP 412 → **不碰** |
|
||||
| 不存在 / 已删除的动态 | `code:500` "Cannot read property 'only_fans' of undefined"(nazurin 的 4101147 已失效) |
|
||||
| 非数字 id | `code:-400` param parsing failed |
|
||||
| 图片 `i0.hdslb.com/bfs/new_dyn/*.jpg` | `HEAD 200 image/jpeg`,带/不带 Referer 均可;`+@518w.jpg` → 25–42 KB ✅ |
|
||||
| `t.bilibili.com/h5/dynamic/detail/<id>` | `200` ✅ |
|
||||
| `m.bilibili.com/dynamic/<id>` | `302 → t.bilibili.com/<id>` ✅ |
|
||||
| `www.bilibili.com/opus/<id>` | `200`,转发动态 `302 → t.bilibili.com/<id>` ✅ |
|
||||
| `b23.tv/BV1JTtt6JEZu` | `302 → www.bilibili.com/video/BV…`(视频) |
|
||||
| `b23.tv/<无效码>` | **HTTP 200** + `{"code":-404}` ⚠️ 短链判定不能只看状态码 |
|
||||
| `playurl`(仅调研用,未采用) | `fnval=1` 匿名给 durl:720P=9.18 MiB / 360P=2.97 MiB;`fnval=4048` 匿名 DASH 上限仅 480P |
|
||||
| `dyn_archive` 字段 | 有 `aid/bvid/cover/title/duration_text`,**没有 `cid`**(所以发流要再来一次 `view` 请求) |
|
||||
| **风控阶梯(同一 IP 连续请求后实测)** | ① 无 cookie → `-352`;② 仅 `buvid3` → 仍 `-352`;③ `buvid3`+`buvid4`(取自匿名 `/x/frontend/finger/spi`)→ **`code:0` 恢复**;④ 继续高频请求后 → 连同 buvid 一起 `-352`(此时只有登录 cookie 或换 IP) |
|
||||
| **正文位置(24 条真实动态逐条审计)** | 有正文的动态都在 `module_dynamic.desc.text`(图文/转发/纯文字,含 34–193 字样本);**AV(视频投稿)动态 `desc` 恒为 `null`**,内容在 `major.archive.title` / `.desc` 卡片里 → 已做 title 回退 |
|
||||
| **`features=itemOpusStyle` 的效果** | 同一端点带此参数后,图文帖改为 `major.opus` 形态:`pics[]`(图,key 是 `url`)、`summary.text`(正文,未截断,实测 307 字整段)、`title`(可选标题);不带参数则是 legacy `major.draw` + `desc`,而 **opus 图文帖的 `desc` 为 `null`、正文与标题完全丢失**(`opus/1248857553488576532`:legacy `desc:null`,带参数 `summary.text="[doge_金箍]黑白搭配"`)。AV / 转发帖不受该参数影响 → 适配器改为请求时带参数,并保留 legacy 形态兜底 |
|
||||
| feed 与 detail 的差异 | `feed/space` 的 item 会把 `desc.text` 挖空,**只有 detail 有正文** → 排查时不要用 feed 数据判断正文缺失 |
|
||||
| 不存在的 19 位 id | `4101105 请求数据发生错误`(提示可重试,但只出现在不可能存在的 id 上)→ 仍归入永久错误,见 `code_error` 注释 |
|
||||
|
||||
测试样本(live 测试用):
|
||||
|
||||
| 样本 | id | 期望 |
|
||||
|---|---|---|
|
||||
| 图片动态(2 图 + 话题) | `1245284537985925159` | 2 个 `Illustration`,`{tags}` = `ALin出道20周年快乐` |
|
||||
| 转发动态 | `1248982077447077907` | 媒体来自 `orig`(1 图),正文可含 `//@` |
|
||||
| 视频动态 | `1248717597691609105` | 封面 1 张 `Illustration` |
|
||||
| 纯文字动态 | `1246767523595026450` | `media` 为空 |
|
||||
|
||||
关键字段路径:
|
||||
|
||||
```
|
||||
data.item.id_str
|
||||
data.item.modules.module_author.{name,mid}
|
||||
data.item.modules.module_dynamic.desc.text
|
||||
data.item.modules.module_dynamic.topic.{id,name} # 单话题,{tags} 来源
|
||||
data.item.modules.module_dynamic.major.{draw.items[].src, archive.cover}
|
||||
data.item.orig # 转发时存在,结构与 item 相同
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 实现
|
||||
|
||||
```
|
||||
crates/x-media/src/site/bilibili/mod.rs # re-export
|
||||
crates/x-media/src/site/bilibili/interface.rs # PATTERN / cache_key / enabled / is_retryable /
|
||||
# media_headers / BilibiliSite / fetch / code_error /
|
||||
# From<Item> for Fetched / caption / 12 单测 + 2 live
|
||||
crates/x-media/src/site/bilibili/model.rs # 纯 Deserialize DTO(全 Option)
|
||||
```
|
||||
|
||||
- **正则**(同时用于分发、抽 id、缓存键,一个正则三用):
|
||||
`^(?:https?://)?(?:www|t|m)\.bilibili\.com/(?:opus/|dynamic/|h5/dynamic/detail/)?(\d+)`
|
||||
- **缓存键**:`bilibili:<动态 id>`;`source_url` 统一 `https://www.bilibili.com/opus/{id}`。
|
||||
- **请求**:`GET /x/polymer/web-dynamic/v1/detail?id=` + `Referer: https://www.bilibili.com/`;
|
||||
`Cookie` 头按优先级取:`BILIBILI_COOKIE` → 缓存的设备 cookie(`GET /x/frontend/finger/spi` 取 `buvid3`/`buvid4`,
|
||||
进程内缓存一次;取不到就不带 cookie,仅 debug 日志)→ 无。指纹接口本身失败**不**让抓取失败。
|
||||
走共享 `CLIENT`(UA `Mozilla/5.0`,30s 超时,`TELOXIDE_PROXY` 透传)。
|
||||
- **错误映射**:`0` → 成功;`-352/-412` 与 HTTP 412 → `Transient`(可重试,队列退避;首次记一条 warn 提示
|
||||
`BILIBILI_COOKIE`);`500`/`4101147` → `NotFound`(永久);其他 code → `Site`(永久)。
|
||||
- **媒体**:
|
||||
- `major.opus.pics[]`(带 `features=itemOpusStyle` 时的图文帖形态,字段名是 `url`)→ 每张一张图;
|
||||
其次 `major.draw.items[]`(legacy,字段名 `src`)→ 同样逐张;`http://` / `//` → `https://`,非 https 开头直接丢弃。
|
||||
`.gif` → `Media::Animated`(`thumbnail_url` 留空,Telegram 自己取首帧——`@518w.jpg` 只对 jpg/webp 实测过),
|
||||
其余 → `Media::Illustration`(`thumbnail_url = url + "@518w.jpg"`,兼作超大时的降级 URL)。
|
||||
- `major.archive.cover` → 1 张 `Illustration`(视频不发流)。
|
||||
- 转发且自身无媒体 → 递归取 `orig` 的媒体;正文拼 `//@{原作者}:\n{原文}`。
|
||||
- 其他 major(PGC/ARTICLE/MUSIC/LIVE/COMMON)不建模 → 无媒体,走既有 "No media found"。
|
||||
- **正文 / title**(按信息量从多到少回退):`major.opus.title` + `major.opus.summary.text`
|
||||
→ `module_dynamic.desc.text` → `major.archive.title`。三者分别对应:图文文档(标题+正文)、
|
||||
legacy/转发帖正文、视频投稿卡片标题。开头结尾空白做 trim;整体再由既有 `truncate_caption` 截断。
|
||||
- **caption**(与 misskey 同形):`{opus 链接}\n<a href="space.bilibili.com/{mid}">{name}</a>: {正文}`;
|
||||
`RenderData` 的 `{tags}` 来自话题名;正文由既有 `truncate_caption` 截断。
|
||||
- **注册表**:`SITES` 末尾追加 → `/set_format` 白名单、链接缓存、启动校验、日志前缀全部自动生效。
|
||||
- **bot 侧仅文案**:`handlers/commands.rs` 三处站点清单字符串 + `state.rs`/`handlers/mod.rs` 注释。
|
||||
|
||||
### 与原计划的偏差(及原因)
|
||||
|
||||
| 原计划 | 实际 | 原因 |
|
||||
|---|---|---|
|
||||
| `x/web-interface/view` + `playurl` 发视频 | 不做 | 需求收窄为图片/动图;视频只发封面 |
|
||||
| `site/mod.rs` 加 `MAX_MEDIA_UPLOAD_BYTES` 常量 | 不加 | 没有视频尺寸决策就不需要该常量,避免跨 crate 耦合 |
|
||||
| `b23.tv` 短链(跟随重定向) | 不匹配 | 多数短链指向视频,匹配后会把"静默忽略"变成用户的 "Failed to fetch media" |
|
||||
| `validate()` 校验 cookie | 不做 | 匿名可用,cookie 失效不致命;校验要额外请求一个端点,收益低 |
|
||||
| `media_headers` 给 hdslb 加 Referer | 返回 `None` | 实测图片与 durl 均无需 Referer(注释里记了这条验证) |
|
||||
| 计划阶段认为设备 cookie 是 YAGNI,不实现 | **实现**(`buvid3`+`buvid4`) | 计划之后做了对照实验:同一 IP 上"无 cookie → -352、只有 buvid3 → -352、buvid3+buvid4 → code:0",说明这是对本适配器主要失败模式的直接修复,而不是冗余保险 |
|
||||
| 只用不带参数的 `v1/detail` | 加 `features=itemOpusStyle` | 用户实测反馈"有内容的动态没有 title":不带参数时 opus 图文帖返回 legacy 形态,`desc` 为 `null`,正文与标题整个丢失。带参数后同一 ID 返回 `major.opus.summary.text` / `title` / `pics`。AV / 转发帖不受影响,legacy 形态仍保留为兜底 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 测试与验证
|
||||
|
||||
- 单元(13):正则匹配/拒绝/忽略短链、缓存键归一、图片映射(https 归一 + 缩略图 + `.gif → Animated`)、
|
||||
封面、转发取 `orig` 媒体与正文拼接、纯文字无媒体、caption 转义、业务 code 分类(可重试性)、URL 归一、
|
||||
设备 cookie 拼装。
|
||||
- live(3,`#[ignore = "live network: …"]`):设备 cookie 可取、图片动态 2 图、纯文字动态无媒体。
|
||||
CI 的 `live` job 已覆盖。动态接口被风控时这两条 live 测试打印 `skipping:` 并提前返回(与 pixiv 的
|
||||
token 门控同款约定),设备 cookie 那条仍会真实执行。
|
||||
- 实测命令:
|
||||
`cargo run -p x-media --example fetch -- https://www.bilibili.com/opus/1245284537985925159`
|
||||
(输出 2 张 `https://i0.hdslb.com/…jpg` + `@518w.jpg` 缩略图 + 话题 tags)。
|
||||
- 全套:`cargo fmt --check`、`cargo clippy --workspace --all-targets -- -D warnings`、`cargo test --workspace` 全绿。
|
||||
|
||||
## 5. 已知限制
|
||||
|
||||
- 风控按 IP/请求量漂移,阶梯见 §2 最后一行:轻度靠设备 cookie 自愈,重度需 `BILIBILI_COOKIE` 或换 IP。
|
||||
被拦时按**可重试**失败处理(队列退避)+ 一条 warn,不会静默丢帖。
|
||||
- 接口 schema 会漂移(`module_dynamic.major` 实测可为 `null` 而正文留在 `desc`);DTO 全 `Option`,
|
||||
未知形态降级为"无媒体",不 panic。
|
||||
- 动态内嵌视频只发封面图(与 bff 同策略),不下载流。
|
||||
- 纯文字动态复用既有 "No media found" 回复。
|
||||
- `b23.tv` 短链不被匹配(见上表)。
|
||||
Reference in New Issue
Block a user