Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
598fe1b825 | ||
|
|
db5774bc98
|
||
|
|
f307010c1c
|
||
|
|
309cf83cb7
|
||
|
|
d0e70f2a59
|
||
|
|
1407f0ef61
|
||
|
|
aaa877f272
|
||
|
|
4c222b1fe1
|
||
|
|
db15605518
|
||
|
|
8091671363
|
||
|
|
c88a54b376
|
||
|
|
25d694ee22
|
||
|
|
04e7b181af
|
||
|
|
89a0f8f7d8
|
||
|
|
2a6f0a1027
|
||
|
|
40083c9812 | ||
|
|
44ea47985b | ||
|
|
e086a377e0 | ||
|
|
46187ade32 | ||
|
|
d3ea8b30fc | ||
|
|
e7cb14a888 | ||
|
|
878c3eb9a1 | ||
|
|
ceaa53757e | ||
|
|
9e8718556a |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
name: Announce Release to Discord
|
||||
|
||||
# Releases published by hand in the Gitea UI. A release that release.yml makes
|
||||
# with the job token fires no `release` event, so that workflow announces its own.
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Existing release tag to re-announce"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
# The reusable reads the release through the Gitea API with the job token.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
announce:
|
||||
# Pinned to a commit of poli0981/.github, with `ops_ref` at the same SHA so the
|
||||
# notifier script matches the workflow. Renovate does not bump this pin (the
|
||||
# comment holds no version it reads): move both by hand when the ops repo is
|
||||
# tagged (runbook §3.2 item 3).
|
||||
uses: poli0981/.github/.gitea/workflows/announce-release.yml@8e6582af9a5846b4d8995b26b1421488d29d761b # ops main 2026-11-23 (untagged, after v2026.11.1)
|
||||
with:
|
||||
tag_override: ${{ inputs.tag || '' }}
|
||||
ops_ref: 8e6582af9a5846b4d8995b26b1421488d29d761b
|
||||
secrets:
|
||||
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
|
||||
DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }}
|
||||
DISCORD_PING_ROLE_ID: ${{ secrets.DISCORD_PING_ROLE_ID }}
|
||||
@@ -0,0 +1,252 @@
|
||||
# CI — lint, tests with coverage, workflow security audit, Qodana.
|
||||
# The `ci` gate job is the required status check on `main`; add new jobs to its
|
||||
# `needs` list, not to the branch protection rule.
|
||||
#
|
||||
# Gitea has no CodeQL and no code-scanning UI (runbook §1), so workflow security is
|
||||
# covered by zizmor + actionlint, Python security by ruff's `S` (bandit) rules, and
|
||||
# bugs and code smells by Qodana's PyCharm inspections. SonarQube Cloud was dropped
|
||||
# with the move to Gitea (ops decision D1). Secrets, SAST and dependency checks
|
||||
# from the ops repo run in security.yml.
|
||||
name: ci
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.15"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
# Hash-locked (requirements-dev.in, compiled), wheels only: a new release of
|
||||
# any package, indirect ones included, can't reach the job, and no build
|
||||
# script runs. A block scalar, because the `: ` in `:all: -r` would end a
|
||||
# plain one.
|
||||
- name: Install dev tools
|
||||
run: |
|
||||
python -m pip install --require-hashes --only-binary :all: -r requirements-dev.txt
|
||||
|
||||
- name: Ruff check
|
||||
run: ruff check .
|
||||
|
||||
- name: Ruff format
|
||||
run: ruff format --check .
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.15"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
# Hash-locked, wheels only (see `lint`).
|
||||
- name: Install dev tools
|
||||
run: |
|
||||
python -m pip install --require-hashes --only-binary :all: -r requirements-dev.txt
|
||||
|
||||
# Coverage settings (what is measured, branches, the floor) are in pyproject.toml.
|
||||
- name: Pytest with coverage
|
||||
run: pytest --cov --cov-report=term-missing
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
# Both tools without Docker: zizmor from the hash-locked dev tools, actionlint
|
||||
# and shellcheck as release binaries at pinned versions, SHA-256 verified (the
|
||||
# ops repo's ops-lint.yml pins). Renovate does not update the binaries: bump
|
||||
# version and checksum together, by hand.
|
||||
env:
|
||||
ACTIONLINT_VERSION: 1.7.12
|
||||
ACTIONLINT_SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 # actionlint_1.7.12_linux_amd64.tar.gz (release checksums file)
|
||||
SHELLCHECK_VERSION: v0.11.0
|
||||
SHELLCHECK_SHA256: 8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198 # shellcheck-v0.11.0.linux.x86_64.tar.xz
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.15"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
# Hash-locked, wheels only (see `lint`).
|
||||
- name: Install dev tools
|
||||
run: |
|
||||
python -m pip install --require-hashes --only-binary :all: -r requirements-dev.txt
|
||||
|
||||
# The files by name: zizmor only looks for .github/workflows by itself.
|
||||
# Offline: its online audits ask GitHub's API about the actions, with a token
|
||||
# this runner does not have. No SARIF upload either: Gitea has no
|
||||
# code-scanning UI, and zizmor's exit code fails the step on any finding.
|
||||
- name: zizmor (workflow security audit)
|
||||
run: zizmor --offline --config .github/zizmor.yml .gitea/workflows/*.yml
|
||||
|
||||
- name: Install actionlint ${{ env.ACTIONLINT_VERSION }} + shellcheck ${{ env.SHELLCHECK_VERSION }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tmp="${RUNNER_TEMP:-/tmp}"
|
||||
bin="$tmp/lint-bin"
|
||||
mkdir -p "$bin"
|
||||
curl -fsSL --retry 3 -o "$tmp/actionlint.tar.gz" "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz"
|
||||
echo "${ACTIONLINT_SHA256} $tmp/actionlint.tar.gz" | sha256sum -c -
|
||||
tar -xzf "$tmp/actionlint.tar.gz" -C "$bin" actionlint
|
||||
curl -fsSL --retry 3 -o "$tmp/shellcheck.tar.xz" "https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION}/shellcheck-${SHELLCHECK_VERSION}.linux.x86_64.tar.xz"
|
||||
echo "${SHELLCHECK_SHA256} $tmp/shellcheck.tar.xz" | sha256sum -c -
|
||||
tar -xJf "$tmp/shellcheck.tar.xz" -C "$bin" --strip-components=1 "shellcheck-${SHELLCHECK_VERSION}/shellcheck"
|
||||
echo "$bin" >> "$GITHUB_PATH"
|
||||
|
||||
# .github/actionlint.yaml ignores only the Gitea features actionlint does not
|
||||
# know; everything else stays an error.
|
||||
- name: actionlint (workflow syntax and expressions)
|
||||
run: |
|
||||
actionlint -version
|
||||
actionlint -color -config-file .github/actionlint.yaml -shellcheck "$(command -v shellcheck)" .gitea/workflows/*.yml
|
||||
|
||||
qodana:
|
||||
# Qodana Cloud, the Ultimate Python linter (settings: qodana.yaml) in native
|
||||
# mode with the job's Python 3.15. Any problem fails the job (failThreshold).
|
||||
#
|
||||
# The Qodana CLI, not JetBrains/qodana-action, which needs GitHub's APIs (runbook
|
||||
# §3.2 item 6). A local job rather than a call to the ops repo's
|
||||
# reusable-qodana.yml: qodana-python must analyse against the bot's Python 3.15
|
||||
# (QODANA_PYTHON_PATH), so setup-python runs before the scan (runbook §3.5
|
||||
# item 5). Gitea has no code-scanning UI: the findings live in Qodana Cloud and
|
||||
# in the `qodana-report` artifact (SARIF + HTML report).
|
||||
#
|
||||
# The CLI is downloaded at the ops repo's pinned version and SHA-256 verified.
|
||||
# Renovate does not update it (it is not an action): bump the version and the
|
||||
# checksum together, by hand; JetBrains publishes both in qodana-action's
|
||||
# common/cli.json.
|
||||
#
|
||||
# A job of its own with no pip install, so QODANA_TOKEN never shares a job with
|
||||
# pip packages. Gitea gives every same-repo pull request the repository's
|
||||
# secrets, Renovate's included, and a Renovate pull request carries the very
|
||||
# update under review: runs by renovate-bot skip the scan with a notice and
|
||||
# still pass, as Dependabot's did on GitHub. The push to main scans the update.
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
QODANA_CLI_VERSION: 2026.3.1
|
||||
QODANA_CLI_SHA256: dae6d31f481ed15c6c016fd746e907978f0c1437010326fa04a92f13c7c52338 # qodana_linux_x86_64.tar.gz
|
||||
steps:
|
||||
- name: Check for QODANA_TOKEN
|
||||
id: token
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
run: |
|
||||
if [ "$ACTOR" = renovate-bot ] || [ "$AUTHOR" = renovate-bot ]; then
|
||||
echo "::notice::Renovate run: Qodana analysis skipped; the push to main analyses the update."
|
||||
elif [ -n "$QODANA_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "::notice::No QODANA_TOKEN in this run: Qodana analysis skipped."
|
||||
fi
|
||||
|
||||
# On Gitea a pull request's ref is its head (refs/pull/N/head, no merge
|
||||
# preview), so the report names a commit of the branch. Full history for
|
||||
# Qodana Cloud's VCS data.
|
||||
- name: Checkout
|
||||
if: steps.token.outputs.present == 'true'
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
if: steps.token.outputs.present == 'true'
|
||||
id: python
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.15"
|
||||
|
||||
- name: Install the Qodana CLI ${{ env.QODANA_CLI_VERSION }}
|
||||
if: steps.token.outputs.present == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tmp="${RUNNER_TEMP:-/tmp}"
|
||||
tgz="$tmp/qodana.tar.gz"
|
||||
curl -fsSL --retry 3 -o "$tgz" "https://github.com/JetBrains/qodana-cli/releases/download/v${QODANA_CLI_VERSION}/qodana_linux_x86_64.tar.gz"
|
||||
echo "${QODANA_CLI_SHA256} $tgz" | sha256sum -c -
|
||||
mkdir -p "$tmp/qodana-cli"
|
||||
tar -xzf "$tgz" -C "$tmp/qodana-cli" qodana
|
||||
echo "$tmp/qodana-cli" >> "$GITHUB_PATH"
|
||||
|
||||
# The whole project every time (the action's `pr-mode: false`): it is small.
|
||||
- name: Qodana scan
|
||||
if: steps.token.outputs.present == 'true'
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
QODANA_ENDPOINT: https://qodana.cloud
|
||||
# The interpreter Qodana analyses against (the bot's Python).
|
||||
QODANA_PYTHON_PATH: ${{ steps.python.outputs.python-path }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tmp="${RUNNER_TEMP:-/tmp}"
|
||||
qodana --version
|
||||
qodana scan --within-docker false --results-dir "$tmp/qodana/results" --cache-dir "$tmp/qodana/cache"
|
||||
|
||||
# !cancelled(), not the implicit success(): a scan that FINDS something fails,
|
||||
# and those are exactly the findings the report must keep.
|
||||
- name: Keep the report
|
||||
if: ${{ !cancelled() && steps.token.outputs.present == 'true' }}
|
||||
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: qodana-report
|
||||
path: ${{ runner.temp }}/qodana/results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
ci:
|
||||
# Gate job: the single required status check. `if: always()` so it reports even
|
||||
# when a dependency fails, and the step below turns that into a red check.
|
||||
needs: [lint, test, security, qodana]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: All jobs succeeded?
|
||||
env:
|
||||
RESULTS: ${{ toJSON(needs) }}
|
||||
run: |
|
||||
echo "$RESULTS"
|
||||
if echo "$RESULTS" | grep -Eq '"result": "(failure|cancelled|skipped)"'; then
|
||||
echo "::error::A required job did not succeed."
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,24 @@
|
||||
name: Notify CI Failures
|
||||
|
||||
# Gitea matches `workflows` as a glob against each workflow's `name:`, so "*"
|
||||
# watches every workflow here. The reusable posts only failures on `main`, and
|
||||
# skips its own notifiers, releases and Renovate.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["*"]
|
||||
types: [completed]
|
||||
|
||||
# Matches the reusable's needs: `actions: read` to read the workflow_run details.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
# Pinned like announce-release.yml: `ops_ref` is the same SHA as `uses:`.
|
||||
uses: poli0981/.github/.gitea/workflows/notify-ci-failure.yml@8e6582af9a5846b4d8995b26b1421488d29d761b # ops main 2026-11-23 (untagged, after v2026.11.1)
|
||||
with:
|
||||
default_branch: main
|
||||
ops_ref: 8e6582af9a5846b4d8995b26b1421488d29d761b
|
||||
secrets:
|
||||
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
|
||||
@@ -2,13 +2,16 @@ name: YouTube Auto-Post
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# 3 times/day (06:30, 14:30, 22:30 UTC). GitHub routinely starts scheduled runs
|
||||
# 1-2 hours late; the script's lookback window (LOOKBACK_HOURS) absorbs that.
|
||||
- cron: "30 6,14,22 * * *"
|
||||
# Once a day at 14:47 UTC (21:47 Vietnam), this repo's slot in the ops registry.
|
||||
# The runner is the maintainer's PC: scheduled jobs live inside 13:00-16:00 UTC,
|
||||
# and while the PC is off a run waits, starts when it comes back, and is
|
||||
# cancelled after 24 h unpicked (runbook §1, §3.2 item 9). The lookback window
|
||||
# (LOOKBACK_HOURS) covers a late start and one missed day.
|
||||
- cron: "47 14 * * *"
|
||||
workflow_dispatch: # Manual trigger for testing
|
||||
|
||||
# `main` is ruleset-protected and GITHUB_TOKEN cannot bypass it, so the posted-ID
|
||||
# state lives on the orphan `state` branch. Nothing here ever pushes to `main`.
|
||||
# `main` is protected and the job token cannot push to it, so the posted-ID state
|
||||
# lives on the orphan `state` branch. Nothing here ever pushes to `main`.
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
@@ -37,14 +40,14 @@ jobs:
|
||||
persist-credentials: true
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.14"
|
||||
python-version: "3.15"
|
||||
|
||||
- name: Run notification script
|
||||
env:
|
||||
STATE_FILE: state/last_video.txt
|
||||
LOOKBACK_HOURS: "48"
|
||||
LOOKBACK_HOURS: "72"
|
||||
# Required
|
||||
YOUTUBE_CHANNEL_ID: ${{ secrets.YOUTUBE_CHANNEL_ID }}
|
||||
# Telegram
|
||||
@@ -58,14 +61,6 @@ jobs:
|
||||
# Mastodon (optional)
|
||||
MASTODON_INSTANCE_URL: ${{ secrets.MASTODON_INSTANCE_URL }}
|
||||
MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }}
|
||||
# X / Twitter (optional)
|
||||
X_API_KEY: ${{ secrets.X_API_KEY }}
|
||||
X_API_SECRET: ${{ secrets.X_API_SECRET }}
|
||||
X_ACCESS_TOKEN: ${{ secrets.X_ACCESS_TOKEN }}
|
||||
X_ACCESS_SECRET: ${{ secrets.X_ACCESS_SECRET }}
|
||||
# Facebook Page (optional)
|
||||
FACEBOOK_PAGE_ID: ${{ secrets.FACEBOOK_PAGE_ID }}
|
||||
FACEBOOK_PAGE_TOKEN: ${{ secrets.FACEBOOK_PAGE_TOKEN }}
|
||||
run: python scripts/notify.py
|
||||
|
||||
# Runs even when the script exits 1 (a platform failed) so partial progress is
|
||||
@@ -75,8 +70,9 @@ jobs:
|
||||
working-directory: state
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
# Gitea's own Actions user, as the job token is.
|
||||
git config user.name "gitea-actions"
|
||||
git config user.email "teabot@gitea.io"
|
||||
git add last_video.txt
|
||||
if git diff --cached --quiet; then
|
||||
echo "No state changes."
|
||||
@@ -0,0 +1,75 @@
|
||||
# Tag `vX.Y.Z` → Gitea release whose notes are that version's entry in
|
||||
# `changelog/<major>.x.md` → Discord announcement.
|
||||
#
|
||||
# The announce job calls the ops reusable directly: a release created with the job
|
||||
# token fires no `release: published` to other workflows (Gitea skips its Actions
|
||||
# user, as GitHub skipped GITHUB_TOKEN), so announce-release.yml never fires for
|
||||
# releases made here. It still covers releases published by hand in the UI.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write # VERIFY which of contents / releases Gitea enforces
|
||||
releases: write # for creating a release (runbook §3.2 item 5)
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.15"
|
||||
|
||||
- name: Extract release notes from changelog
|
||||
env:
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: python scripts/release_notes.py "$TAG" > release-notes.md
|
||||
|
||||
# A tag with a suffix (v2.0.0-beta.1) is a pre-release.
|
||||
- name: Release kind
|
||||
id: kind
|
||||
env:
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
case "$TAG" in
|
||||
*-*) echo "prerelease=true" >> "$GITHUB_OUTPUT" ;;
|
||||
*) echo "prerelease=false" >> "$GITHUB_OUTPUT" ;;
|
||||
esac
|
||||
|
||||
# Notes only, no files: Gitea releases carry notes and links (runbook §1).
|
||||
# The action uses the job token by default.
|
||||
- name: Create the Gitea release
|
||||
uses: https://gitea.com/actions/gitea-release-action@5a83c90484ef4355121df5eb60558c8ce66e81ac # v1.3.7
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: ${{ github.ref_name }}
|
||||
body_path: release-notes.md
|
||||
prerelease: ${{ steps.kind.outputs.prerelease }}
|
||||
|
||||
announce:
|
||||
needs: release
|
||||
# Pinned like announce-release.yml: `ops_ref` is the same SHA as `uses:`.
|
||||
uses: poli0981/.github/.gitea/workflows/announce-release.yml@8e6582af9a5846b4d8995b26b1421488d29d761b # ops main 2026-11-23 (untagged, after v2026.11.1)
|
||||
with:
|
||||
tag_override: ${{ github.ref_name }}
|
||||
ops_ref: 8e6582af9a5846b4d8995b26b1421488d29d761b
|
||||
secrets:
|
||||
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
|
||||
DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }}
|
||||
DISCORD_PING_ROLE_ID: ${{ secrets.DISCORD_PING_ROLE_ID }}
|
||||
@@ -0,0 +1,34 @@
|
||||
# Security checks from the ops repo (runbook §3.5 item 2, §4.3):
|
||||
#
|
||||
# secrets → gitleaks over the whole git history; fails on a finding
|
||||
# sast → Opengrep: the workflow, Dockerfile and shell rules always, plus the
|
||||
# Python rules (`python: true`); report only, SARIF as an artifact
|
||||
# (Gitea has no code-scanning UI)
|
||||
# deps → osv-scanner over the lockfiles (requirements-dev.txt); fails on a
|
||||
# known vulnerability
|
||||
#
|
||||
# Next to ci.yml's own checks (ruff's `S` rules, zizmor, actionlint, Qodana), this
|
||||
# stands in for the CodeQL that Gitea does not have. Not part of the required `ci`
|
||||
# check. No secrets: nothing here needs a token.
|
||||
name: Security
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
schedule:
|
||||
- cron: "47 15 * * 4" # weekly, Thursday 15:47 UTC = 22:47 Vietnam (ops registry slot)
|
||||
workflow_dispatch:
|
||||
|
||||
# Explicit, and granted on the job.
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
permissions:
|
||||
contents: read
|
||||
# Pinned like the notifier callers. Renovate does not bump this pin: move it by
|
||||
# hand when the ops repo is tagged (runbook §3.2 item 3).
|
||||
uses: poli0981/.github/.gitea/workflows/security.yml@8e6582af9a5846b4d8995b26b1421488d29d761b # ops main 2026-11-23 (untagged, after v2026.11.1)
|
||||
with:
|
||||
python: true
|
||||
@@ -0,0 +1,12 @@
|
||||
# actionlint settings, read by the `security` job in .gitea/workflows/ci.yml and by a
|
||||
# local run from the repo root:
|
||||
# actionlint -config-file .github/actionlint.yaml .gitea/workflows/*.yml
|
||||
# Only Gitea features that actionlint does not know are ignored here (as in the ops
|
||||
# repo's own .github/actionlint.yaml); everything else stays an error.
|
||||
paths:
|
||||
.gitea/workflows/*.yml:
|
||||
ignore:
|
||||
# Gitea's own token scope for releases (runbook §3.2 item 5)
|
||||
- 'unknown permission scope "releases"'
|
||||
# Gitea resolves full-URL actions; bare owner/repo goes to github.com (runbook §1)
|
||||
- 'specifying action "https://gitea\.com/[^"]+" in invalid format'
|
||||
@@ -1,35 +0,0 @@
|
||||
# Actions are SHA-pinned with a `# vX.Y.Z` comment; Dependabot is the only thing
|
||||
# that notices when a pin goes stale. `pip` covers requirements-dev.txt only — the
|
||||
# scripts themselves are stdlib-only.
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 5
|
||||
cooldown:
|
||||
default-days: 7 # let a release age a week before we take it (zizmor dependabot-cooldown)
|
||||
groups:
|
||||
actions:
|
||||
patterns: ["*"]
|
||||
commit-message:
|
||||
prefix: ci
|
||||
labels: [dependencies]
|
||||
|
||||
- package-ecosystem: pip
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 5
|
||||
cooldown:
|
||||
default-days: 7
|
||||
groups:
|
||||
dev:
|
||||
patterns: ["*"]
|
||||
commit-message:
|
||||
prefix: chore
|
||||
labels: [dependencies]
|
||||
@@ -1,23 +0,0 @@
|
||||
name: Announce Release to Discord
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Existing release tag to re-announce"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
# Reusable announce-release.yml only needs `contents: read` to fetch
|
||||
# release metadata via the gh CLI.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
announce:
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
with:
|
||||
tag_override: ${{ inputs.tag || '' }}
|
||||
secrets: inherit
|
||||
@@ -1,104 +0,0 @@
|
||||
# CI — lint, tests, workflow security audit. The `ci` gate job is the required
|
||||
# status check on `main`; add new jobs to its `needs` list, not to the ruleset.
|
||||
#
|
||||
# CodeQL is not available on a personal private repository, so workflow security is
|
||||
# covered by zizmor + actionlint and Python security by ruff's `S` (bandit) rules.
|
||||
name: ci
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.14"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dev tools
|
||||
run: python -m pip install -r requirements-dev.txt
|
||||
|
||||
- name: Ruff check
|
||||
run: ruff check .
|
||||
|
||||
- name: Ruff format
|
||||
run: ruff format --check .
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.14"
|
||||
cache: pip
|
||||
cache-dependency-path: requirements-dev.txt
|
||||
|
||||
- name: Install dev tools
|
||||
run: python -m pip install -r requirements-dev.txt
|
||||
|
||||
- name: Pytest
|
||||
run: pytest
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# SARIF upload needs Advanced Security, which this repo cannot have; with it
|
||||
# off, zizmor's own exit code fails the step on any finding.
|
||||
- name: zizmor (workflow security audit)
|
||||
uses: zizmorcore/zizmor-action@70fb788f84895a7701f5643d103d587e460b5c99 # v0.6.3
|
||||
with:
|
||||
advanced-security: false
|
||||
version: "1.30.0"
|
||||
|
||||
- name: actionlint (workflow syntax and expressions)
|
||||
run: docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.12 -color
|
||||
|
||||
ci:
|
||||
# Gate job: the single required status check. `if: always()` so it reports even
|
||||
# when a dependency fails, and the step below turns that into a red check.
|
||||
needs: [lint, test, security]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: All jobs succeeded?
|
||||
env:
|
||||
RESULTS: ${{ toJSON(needs) }}
|
||||
run: |
|
||||
echo "$RESULTS"
|
||||
if echo "$RESULTS" | grep -Eq '"result": "(failure|cancelled|skipped)"'; then
|
||||
echo "::error::A required job did not succeed."
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,17 +0,0 @@
|
||||
name: Notify CI Failures
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["*"]
|
||||
types: [completed]
|
||||
|
||||
# REQUIRED: declare permissions matching the reusable workflow's needs.
|
||||
# Reusable needs `actions: read` to inspect workflow_run details.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
|
||||
secrets: inherit
|
||||
@@ -1,58 +0,0 @@
|
||||
# Tag `vX.Y.Z` → GitHub Release whose notes are that version's entry in
|
||||
# `changelog/<major>.x.md` → Discord announcement.
|
||||
#
|
||||
# The announce job calls the ops reusable directly: a release created with
|
||||
# GITHUB_TOKEN does not emit `release: published` to other workflows, so
|
||||
# announce-release.yml would never fire for releases made here. It still covers
|
||||
# releases published by hand in the UI.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write # create the release
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.14"
|
||||
|
||||
- name: Extract release notes from changelog
|
||||
env:
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: python scripts/release_notes.py "$TAG" > release-notes.md
|
||||
|
||||
- name: Create GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
args=()
|
||||
case "$TAG" in *-*) args+=(--prerelease) ;; esac
|
||||
gh release create "$TAG" --verify-tag --title "$TAG" --notes-file release-notes.md "${args[@]}"
|
||||
|
||||
announce:
|
||||
needs: release
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
with:
|
||||
tag_override: ${{ github.ref_name }}
|
||||
secrets: inherit
|
||||
+6
-12
@@ -1,4 +1,6 @@
|
||||
# zizmor configuration — https://docs.zizmor.sh/configuration/
|
||||
# Read by the `security` job in .gitea/workflows/ci.yml (`--config`), which audits
|
||||
# .gitea/workflows offline.
|
||||
#
|
||||
# Every ignore below names the workflow it applies to and why the finding is
|
||||
# accepted. Anything not listed here must be fixed, not ignored.
|
||||
@@ -6,21 +8,13 @@ rules:
|
||||
unpinned-uses:
|
||||
config:
|
||||
policies:
|
||||
# Our own reusable workflows in poli0981/.github deliberately track @main.
|
||||
"poli0981/*": ref-pin
|
||||
# Every action and every call into poli0981/.github is pinned to a full
|
||||
# commit SHA, the ops repo included (runbook §3.2 item 3, rule 6).
|
||||
"*": hash-pin
|
||||
|
||||
secrets-inherit:
|
||||
# Thin callers into poli0981/.github reusables; the secret names are owned by
|
||||
# the reusable side, so `secrets: inherit` is the contract.
|
||||
ignore:
|
||||
- announce-release.yml
|
||||
- notify-ci-failure.yml
|
||||
- release.yml
|
||||
|
||||
dangerous-triggers:
|
||||
# `workflow_run` with no checkout and no use of PR-controlled input; it only
|
||||
# forwards run metadata to a Discord webhook.
|
||||
# `workflow_run` with no checkout of the triggering code and no use of
|
||||
# PR-controlled input; it only forwards run metadata to a Discord webhook.
|
||||
ignore:
|
||||
- notify-ci-failure.yml
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# gitleaks findings accepted on purpose (read by the ops repo's security.yml, which
|
||||
# runs `gitleaks git` from the repo root). Each line is a finding's fingerprint
|
||||
# (commit:file:rule:line), with the reason above it. Anything else gets fixed.
|
||||
|
||||
# SETUP_NEW_PLATFORMS.md, the Mastodon curl example: `Authorization: Bearer
|
||||
# YOUR_TOKEN` is a placeholder for the reader's own token, not a credential.
|
||||
779499c1bffca6e13b36d076e0df24160214ad43:SETUP_NEW_PLATFORMS.md:curl-auth-header:25
|
||||
@@ -1,9 +1,37 @@
|
||||
# 🤖 YouTube Auto-Post
|
||||
|
||||
Tự động đăng thông báo video mới của kênh YouTube lên **Telegram, Bluesky, Discord, Mastodon,
|
||||
X/Twitter, Facebook Page** bằng GitHub Actions. Script chỉ dùng thư viện chuẩn Python, không cài gì
|
||||
[](#9-trạng-thái-dự-án)
|
||||
[](https://git.poli0981.dev/poli0981/youtube-auto-post/actions?workflow=ci.yml)
|
||||
[](https://qodana.cloud/projects/oDgKr)
|
||||
[](#6-phát-triển)
|
||||
[](#6-phát-triển)
|
||||
[](https://github.com/astral-sh/ruff)
|
||||
[](https://zizmor.sh/)
|
||||
[](renovate.json)
|
||||
|
||||
Tự động đăng thông báo video mới của kênh YouTube lên **Telegram, Bluesky, Discord, Mastodon**
|
||||
bằng Gitea Actions. Script chỉ dùng thư viện chuẩn Python, không cài gì
|
||||
thêm.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Chế độ bảo trì** từ 1.4.2: không thêm tính năng mới, trừ vài trường hợp ở
|
||||
> [mục 9](#9-trạng-thái-dự-án) (cập nhật phụ thuộc, vá bảo mật, lên bản Python mới).
|
||||
|
||||
## Repo ở đâu
|
||||
|
||||
- **Mã nguồn (bản gốc):** [`git.poli0981.dev/poli0981/youtube-auto-post`](https://git.poli0981.dev/poli0981/youtube-auto-post), clone
|
||||
`https://git.poli0981.dev/poli0981/youtube-auto-post.git`.
|
||||
- **Issue và merge request:** mirror
|
||||
[`gitlab.com/poli0981/youtube-auto-post`](https://gitlab.com/poli0981/youtube-auto-post/-/issues).
|
||||
Gitea không mở đăng ký nên người ngoài không mở issue hay PR ở đó được; mirror trên GitLab không
|
||||
chạy CI, CI chạy trên Gitea.
|
||||
- **Gửi patch và câu hỏi:** `code@poli0981.dev`.
|
||||
- **Bảo mật:** `security@poli0981.dev`, xem [SECURITY.md](SECURITY.md). Đừng mở issue công khai cho
|
||||
lỗ hổng.
|
||||
|
||||
Repo chuyển khỏi GitHub vào tháng 11/2026; link `github.com/poli0981/youtube-auto-post` không còn
|
||||
dẫn tới đâu.
|
||||
|
||||
---
|
||||
|
||||
## Mục lục
|
||||
@@ -16,22 +44,26 @@ thêm.
|
||||
6. [Phát triển](#6-phát-triển)
|
||||
7. [Release](#7-release)
|
||||
8. [Bảo vệ nhánh](#8-bảo-vệ-nhánh)
|
||||
9. [Trạng thái dự án](#9-trạng-thái-dự-án)
|
||||
|
||||
---
|
||||
|
||||
## 1. Cách hoạt động
|
||||
|
||||
Workflow [`notify.yml`](.github/workflows/notify.yml) chạy 3 lần/ngày (06:30, 14:30, 22:30 UTC)
|
||||
hoặc khi bấm **Run workflow**. GitHub thường khởi động lịch trễ 1–2 giờ; script không phụ thuộc
|
||||
vào giờ chạy chính xác.
|
||||
Workflow [`notify.yml`](.gitea/workflows/notify.yml) chạy mỗi ngày một lần lúc **14:47 UTC**
|
||||
(21:47 giờ Việt Nam) hoặc khi bấm **Run workflow**. Runner là máy PC của maintainer, nên lịch của mọi
|
||||
repo chỉ nằm trong khung 13:00–16:00 UTC. Máy tắt thì lần chạy chờ tới khi máy bật lại, quá 24 giờ
|
||||
chưa chạy thì bị huỷ: một video có thể chờ tới một ngày mới được đăng. Script không phụ thuộc vào giờ
|
||||
chạy chính xác.
|
||||
|
||||
1. Đọc RSS của kênh, giữ các video có `published` trong `LOOKBACK_HOURS` gần nhất (mặc định 48h).
|
||||
1. Đọc RSS của kênh, giữ các video có `published` trong `LOOKBACK_HOURS` gần nhất (mặc định 72h,
|
||||
đủ cho một lần chạy trễ cộng một ngày bị lỡ).
|
||||
2. Bỏ các ID đã có trong state (`last_video.txt` trên nhánh `state`).
|
||||
3. Với mỗi video còn lại, kiểm tra trang watch: **Premiere chưa lên sóng thì bỏ qua**, lần chạy sau
|
||||
thử lại. RSS liệt kê Premiere từ lúc upload, nên không có bước này bot sẽ đăng sớm.
|
||||
4. Đăng lên từng platform có secret; platform thiếu secret thì skip.
|
||||
5. Lưu ID vào nhánh `state` khi ít nhất một platform đăng được. Nếu một platform **đã cấu hình** mà
|
||||
lỗi, job kết thúc đỏ và [`notify-ci-failure.yml`](.github/workflows/notify-ci-failure.yml) báo
|
||||
lỗi, job kết thúc đỏ và [`notify-ci-failure.yml`](.gitea/workflows/notify-ci-failure.yml) báo
|
||||
lên Discord.
|
||||
|
||||
Nội dung bài đăng:
|
||||
@@ -44,23 +76,25 @@ Nội dung bài đăng:
|
||||
▶️ https://www.youtube.com/watch?v=...
|
||||
```
|
||||
|
||||
Mastodon và X thêm dòng hashtag (`HASHTAGS`). Bluesky đính link card kèm thumbnail. Tiêu đề quá dài
|
||||
được cắt cho Bluesky (300) và X (280).
|
||||
Mastodon thêm dòng hashtag (`HASHTAGS`). Bluesky đính link card kèm thumbnail, tiêu đề quá dài
|
||||
được cắt về 300 ký tự.
|
||||
|
||||
---
|
||||
|
||||
## 2. Cấu trúc repo
|
||||
|
||||
```
|
||||
.github/
|
||||
.gitea/
|
||||
workflows/
|
||||
notify.yml # Đăng bài theo lịch, ghi state lên nhánh `state`
|
||||
ci.yml # ruff, pytest, zizmor, actionlint — gate `ci` là required check
|
||||
release.yml # tag v* → GitHub Release từ changelog → Discord
|
||||
ci.yml # ruff, pytest + coverage, zizmor, actionlint, Qodana — gate `ci` là required check
|
||||
security.yml # Caller vào security.yml của poli0981/.github: gitleaks, Opengrep, osv-scanner
|
||||
release.yml # tag v* → Gitea release từ changelog → Discord
|
||||
announce-release.yml # Caller vào reusable của poli0981/.github (release tạo tay)
|
||||
notify-ci-failure.yml # Caller vào reusable của poli0981/.github
|
||||
dependabot.yml
|
||||
zizmor.yml
|
||||
.github/
|
||||
actionlint.yaml # actionlint: chỉ bỏ qua tính năng riêng của Gitea
|
||||
zizmor.yml # zizmor: các finding được chấp nhận, kèm lý do
|
||||
scripts/
|
||||
notify.py # Điều phối: RSS → lọc → kiểm tra public → đăng → state → exit code
|
||||
youtube.py # Parse RSS, cửa sổ thời gian, kiểm tra Premiere
|
||||
@@ -72,13 +106,18 @@ scripts/
|
||||
platforms/ # Mỗi module: post(video) -> PostStatus
|
||||
tests/ # pytest, không gọi mạng
|
||||
changelog/ # Chi tiết từng phiên bản (CHANGELOG.md ở root chỉ trỏ tới đây)
|
||||
requirements-dev.in # Công cụ dev; requirements-dev.txt là bản khoá theo hash của nó
|
||||
renovate.json # Renovate, dùng preset chung poli0981/renovate-config
|
||||
.gitleaksignore # gitleaks (security.yml): các finding được chấp nhận, kèm lý do
|
||||
qodana.yaml # Qodana, đọc bởi job `qodana` của ci.yml
|
||||
SECURITY.md # Cách báo lỗ hổng bảo mật
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Secrets và biến
|
||||
|
||||
Repo → Settings → Secrets and variables → Actions → **New repository secret**.
|
||||
Trên Gitea: repo → **Settings → Actions → Secrets → Add secret**.
|
||||
|
||||
| Secret | Platform | Bắt buộc | Ghi chú |
|
||||
|-------------------------|-----------|----------|-------------------------------------------------|
|
||||
@@ -90,21 +129,26 @@ Repo → Settings → Secrets and variables → Actions → **New repository sec
|
||||
| `DISCORD_WEBHOOK_URL` | Discord | Tuỳ chọn | `https://discord.com/api/webhooks/ID/TOKEN` |
|
||||
| `MASTODON_INSTANCE_URL` | Mastodon | Tuỳ chọn | Không có `/` cuối |
|
||||
| `MASTODON_ACCESS_TOKEN` | Mastodon | Tuỳ chọn | Scope `write:statuses` |
|
||||
| `X_API_KEY` | X/Twitter | Tuỳ chọn | ⚠️ Hiện **chưa có** trong repo → X luôn skip |
|
||||
| `X_API_SECRET` | X/Twitter | Tuỳ chọn | |
|
||||
| `X_ACCESS_TOKEN` | X/Twitter | Tuỳ chọn | Generate sau khi set Read and Write |
|
||||
| `X_ACCESS_SECRET` | X/Twitter | Tuỳ chọn | |
|
||||
| `FACEBOOK_PAGE_ID` | Facebook | Tuỳ chọn | |
|
||||
| `FACEBOOK_PAGE_TOKEN` | Facebook | Tuỳ chọn | Page token never-expiring |
|
||||
|
||||
Cách lấy token Mastodon, X, Facebook: [SETUP_NEW_PLATFORMS.md](SETUP_NEW_PLATFORMS.md).
|
||||
Cách lấy token Mastodon và Discord: [SETUP_NEW_PLATFORMS.md](SETUP_NEW_PLATFORMS.md).
|
||||
|
||||
Secret cho CI và thông báo, không phải cho bot. Secret dùng chung cho nhiều repo nên đặt ở mức user
|
||||
(Gitea → Settings của tài khoản → Actions → Secrets), repo nào cũng đọc được:
|
||||
|
||||
| Secret | Dùng ở | Bắt buộc | Ghi chú |
|
||||
|----------------------------|---------------------------------------|----------|--------------------------------------------|
|
||||
| `QODANA_TOKEN` | Job `qodana` của `ci.yml` | ✅ | Project token của Qodana Cloud (mục 6) |
|
||||
| `DISCORD_CI_WEBHOOK` | `notify-ci-failure.yml` | ✅ | Kênh Discord nhận báo workflow lỗi |
|
||||
| `DISCORD_RELEASES_WEBHOOK` | `release.yml`, `announce-release.yml` | Tuỳ chọn | Cần ít nhất một trong hai webhook release |
|
||||
| `DISCORD_REPO_WEBHOOK` | `release.yml`, `announce-release.yml` | Tuỳ chọn | |
|
||||
| `DISCORD_PING_ROLE_ID` | `release.yml`, `announce-release.yml` | Tuỳ chọn | Role được ping khi có bản chính thức |
|
||||
|
||||
Biến đặt trực tiếp trong `notify.yml` (không phải secret):
|
||||
|
||||
| Biến | Mặc định | Ý nghĩa |
|
||||
|------------------|-----------------------------------|-------------------------------------------------|
|
||||
| `LOOKBACK_HOURS` | `48` | Chỉ xét video published trong khoảng này |
|
||||
| `HASHTAGS` | `#gaming #gameplay #nocommentary` | Dòng hashtag cho Mastodon và X; để rỗng để tắt |
|
||||
| `LOOKBACK_HOURS` | `72` | Chỉ xét video published trong khoảng này |
|
||||
| `HASHTAGS` | `#gaming #gameplay #nocommentary` | Dòng hashtag cho Mastodon; để rỗng để tắt |
|
||||
|
||||
---
|
||||
|
||||
@@ -129,7 +173,8 @@ cho webhook.
|
||||
|
||||
## 5. Nhánh `state`
|
||||
|
||||
`main` được bảo vệ (mục 8) và `GITHUB_TOKEN` không bypass được, nên bot không thể commit lên `main`.
|
||||
`main` được bảo vệ (mục 8) và job token của Gitea Actions không push được lên đó, nên bot không thể
|
||||
commit lên `main`.
|
||||
Danh sách ID đã đăng nằm trên nhánh orphan **`state`**, chỉ có một file `last_video.txt` (tối đa 100
|
||||
ID, cũ nhất ở trên). Workflow checkout nhánh này vào thư mục `state/` và push lại sau khi chạy.
|
||||
|
||||
@@ -140,7 +185,7 @@ git fetch origin state && git show origin/state:last_video.txt
|
||||
```
|
||||
|
||||
Muốn bot đăng lại một video (hoặc bỏ qua một video): sửa file trên nhánh `state` và push — nhánh
|
||||
này không bị ruleset chặn.
|
||||
này không được bảo vệ (job token phải push được lên nó).
|
||||
|
||||
Chạy local thì đặt `STATE_FILE` (mặc định `state/last_video.txt`, thư mục `state/` đã gitignore).
|
||||
|
||||
@@ -148,14 +193,48 @@ Chạy local thì đặt `STATE_FILE` (mặc định `state/last_video.txt`, th
|
||||
|
||||
## 6. Phát triển
|
||||
|
||||
Cần **Python 3.15**, cùng bản với CI, bot và release. Code dùng cú pháp chỉ có từ 3.14
|
||||
(`except A, B:` không ngoặc), nên Python 3.13 trở xuống không chạy được.
|
||||
|
||||
```bash
|
||||
python -m pip install -r requirements-dev.txt
|
||||
python -m pip install --require-hashes --only-binary :all: -r requirements-dev.txt
|
||||
ruff check . && ruff format --check .
|
||||
pytest
|
||||
pytest --cov --cov-report=term-missing
|
||||
```
|
||||
|
||||
CI chạy đúng ba lệnh trên cộng zizmor và actionlint cho workflow. Test không gọi mạng; các hàm
|
||||
`build_text`, `select_recent`, `is_public_html` là chỗ để thêm test khi đổi hành vi.
|
||||
CI chạy đúng ba lệnh trên, cộng zizmor và actionlint cho workflow và Qodana (dưới đây). Kiểm workflow
|
||||
ở máy như CI (actionlint 1.7.12 tải từ trang release của nó):
|
||||
|
||||
```bash
|
||||
zizmor --offline --config .github/zizmor.yml .gitea/workflows/*.yml
|
||||
actionlint -config-file .github/actionlint.yaml .gitea/workflows/*.yml
|
||||
```
|
||||
|
||||
Coverage đo `scripts/` theo cả dòng lẫn nhánh; dưới 95 % thì `pytest --cov` báo lỗi. Test không gọi
|
||||
mạng: mọi request đi qua `http_client`, test thay hàm của nó bằng hàm giả. Các hàm `build_text`,
|
||||
`select_recent`, `is_public_html` là chỗ để thêm test khi đổi hành vi.
|
||||
|
||||
**Công cụ dev** (ruff, zizmor, pytest, pytest-cov) khoá theo hash: sửa `requirements-dev.in`, rồi
|
||||
biên dịch lại `requirements-dev.txt` bằng pip-tools chạy trên **Python 3.14** (Renovate chạy lại
|
||||
lệnh ở header của file khoá, trên bản Python ghi ở đó):
|
||||
|
||||
```bash
|
||||
pip-compile --generate-hashes --allow-unsafe --strip-extras --output-file=requirements-dev.txt requirements-dev.in
|
||||
```
|
||||
|
||||
**Qodana** (JetBrains): job `qodana` chạy linter Ultimate `qodana-python` (bộ inspection của PyCharm
|
||||
Professional, profile `qodana.recommended`) trên mỗi PR và mỗi lần push lên `main`, cấu hình ở
|
||||
[`qodana.yaml`](qodana.yaml). Job tải Qodana CLI ở bản cố định, kiểm SHA-256, rồi chạy linter native
|
||||
trên runner với Python 3.15 của job, không qua Docker. Có problem nào là job đỏ (`failThreshold: 0`),
|
||||
kéo check `ci` đỏ theo. Kết quả nằm trên [Qodana Cloud](https://qodana.cloud/projects/oDgKr) và trong
|
||||
artifact `qodana-report` của lần chạy (Gitea không có giao diện code scanning). Cần secret
|
||||
`QODANA_TOKEN` (project token của Qodana Cloud, cũng là licence Ultimate). Gitea đưa secret cho mọi PR
|
||||
mở từ chính repo, kể cả PR của Renovate, nên lần chạy của `renovate-bot` bỏ qua bước quét mà vẫn
|
||||
xanh; lần push lên `main` sau khi merge mới quét bản cập nhật đó.
|
||||
|
||||
**`security.yml`** gọi workflow bảo mật chung của repo ops: gitleaks quét toàn bộ lịch sử git,
|
||||
Opengrep với bộ rule cho workflow, shell và Python (chỉ báo cáo), osv-scanner quét file khoá. Chạy
|
||||
khi push lên `main`, trên mỗi PR và mỗi thứ Năm lúc 15:47 UTC. Không nằm trong check `ci`.
|
||||
|
||||
Chạy thử script local (cần secret trong env):
|
||||
|
||||
@@ -171,11 +250,11 @@ STATE_FILE=/tmp/state.txt YOUTUBE_CHANNEL_ID=UC... TELEGRAM_BOT_TOKEN=... TELEGR
|
||||
2. Sau khi merge, tag đã ký trên `main` và push:
|
||||
|
||||
```bash
|
||||
git tag -s v1.2.0 -m v1.2.0 && git push origin v1.2.0
|
||||
git tag -s v1.5.0 -m v1.5.0 && git push origin v1.5.0
|
||||
```
|
||||
|
||||
3. [`release.yml`](.github/workflows/release.yml) tạo GitHub Release với nội dung entry đó rồi gọi
|
||||
workflow thông báo Discord.
|
||||
3. [`release.yml`](.gitea/workflows/release.yml) tạo Gitea release (chỉ có ghi chú, không đính file)
|
||||
với nội dung entry đó rồi gọi workflow thông báo Discord.
|
||||
|
||||
Quy ước changelog: [changelog/README.md](changelog/README.md).
|
||||
|
||||
@@ -183,8 +262,34 @@ Quy ước changelog: [changelog/README.md](changelog/README.md).
|
||||
|
||||
## 8. Bảo vệ nhánh
|
||||
|
||||
Ruleset `main` (không có bypass, kể cả admin): chỉ merge qua PR bằng **squash**, commit phải ký,
|
||||
lịch sử tuyến tính, check `ci` phải xanh trên bản mới nhất của `main`, không force-push, không xoá.
|
||||
Ruleset `release-tags` bảo vệ tag `v*` khỏi xoá/ghi đè. Dependabot mở PR gộp mỗi thứ Hai.
|
||||
Branch protection của Gitea trên `main`: không push thẳng, chỉ merge qua PR bằng **squash**, check
|
||||
`ci` phải xanh, không force-push, không xoá. Commit trong PR vẫn ký GPG. Tag `v*` được bảo vệ khỏi
|
||||
xoá/ghi đè (Settings → Tags), vì một tag phải đúng ngay lần đầu.
|
||||
|
||||
Repo private cá nhân không có CodeQL; thay bằng ruff rule `S`, zizmor và actionlint trong CI.
|
||||
**Renovate** (tự host, chạy mỗi ngày lúc 13:31 UTC từ repo `poli0981/renovate-config`) thay
|
||||
Dependabot: mở PR gộp các bản cập nhật non-major cho action và công cụ dev; bản PyPI mới chờ 3 ngày
|
||||
mới được đề xuất; lỗ hổng đã biết thì có PR riêng mang nhãn `security`. Danh sách nằm ở issue
|
||||
**Dependency Dashboard** của repo. PR của Renovate tụt sau `main` thì tick ô rebase/retry trong mô tả
|
||||
PR, lần chạy sau của Renovate sẽ rebase.
|
||||
|
||||
Gitea không có CodeQL; thay bằng ruff rule `S`, zizmor, actionlint và Qodana trong CI, cùng gitleaks,
|
||||
Opengrep và osv-scanner trong `security.yml` (mục 6).
|
||||
|
||||
---
|
||||
|
||||
## 9. Trạng thái dự án
|
||||
|
||||
**Bảo trì** từ 1.4.2 (2026-11-16). Bot đã làm đủ việc của nó, nên **không thêm tính năng mới**. Repo
|
||||
chỉ thay đổi trong ba trường hợp:
|
||||
|
||||
1. **Cập nhật phụ thuộc định kỳ.** Renovate mở PR gộp cho các action và công cụ dev (mục 8); CI
|
||||
xanh thì merge.
|
||||
2. **Bảo mật, và tính năng thật sự cần thiết.** Phụ thuộc dính CVE mức **High** trở lên, hoặc thứ
|
||||
bot chạy trên đó có lỗ hổng nghiêm trọng (như Node.js, runtime của các action), được sửa ngay,
|
||||
không chờ lịch Renovate. Tính năng mới chỉ thêm khi được đánh giá là thật sự cần thiết.
|
||||
3. **Bản ngôn ngữ mới.** Lên bản Python kế tiếp, như 3.14 → 3.15 ở 1.4.0.
|
||||
|
||||
Đề xuất tính năng (issue hay merge request trên mirror GitLab) ngoài ba trường hợp trên sẽ không
|
||||
được nhận. Thay đổi nào cũng vẫn
|
||||
đi qua PR và CI (mục 6–8), và có entry trong [changelog](changelog/1.x.md) nếu người dùng bot nhận
|
||||
thấy.
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported versions
|
||||
|
||||
Only `main` is supported. The bot runs from `main` on a schedule, so a fix is live from the first
|
||||
run after it merges.
|
||||
|
||||
The project is in maintenance mode ([README §9](README.md#9-trạng-thái-dự-án)), and security is the
|
||||
part of it that does not wait: a vulnerability rated **High** or above in a dependency, or a serious
|
||||
one in what the bot runs on (Python, the CI actions and their Node.js runtime), is fixed as soon as a
|
||||
fixed version exists.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
**Report by e-mail to security@poli0981.dev, and do not open a public issue for a security problem,
|
||||
on the GitLab mirror or anywhere else.** E-mail is the only private channel: the repository moved
|
||||
from GitHub in November 2026, and GitHub's private vulnerability reporting went with it. A report
|
||||
that arrives as a public GitLab issue is made confidential there and continued by e-mail.
|
||||
|
||||
This is a solo, unpaid project: there is no bounty and no formal response time, but genuine reports
|
||||
are answered and credited unless you prefer otherwise.
|
||||
|
||||
## Scope
|
||||
|
||||
In scope: the scripts in `scripts/` (for example anything that leaks a platform token, or makes the
|
||||
bot post something other than the channel's own videos), and the workflows in `.gitea/workflows/`
|
||||
(anything that lets untrusted input run code or reach a secret).
|
||||
|
||||
Out of scope: the platforms the bot posts to (Telegram, Bluesky, Discord, Mastodon) and YouTube
|
||||
itself, and anything that needs the maintainer's machine or accounts to be compromised first.
|
||||
|
||||
---
|
||||
|
||||
**Tiếng Việt:** báo lỗ hổng bảo mật qua e-mail tới `security@poli0981.dev`. Đừng mở issue công khai
|
||||
cho lỗ hổng, kể cả trên mirror GitLab.
|
||||
+19
-118
@@ -1,4 +1,7 @@
|
||||
# 🆕 Hướng Dẫn Thiết Lập Platform Mới
|
||||
# 🆕 Hướng Dẫn Thiết Lập Platform Tuỳ Chọn
|
||||
|
||||
Telegram và Bluesky (bắt buộc) xem [README.md](README.md#4-lấy-token-telegram-bluesky). Dưới đây là
|
||||
platform tuỳ chọn; thiếu secret thì bot tự bỏ qua platform đó.
|
||||
|
||||
---
|
||||
|
||||
@@ -31,128 +34,26 @@ Dùng `visibility=direct` để test mà không public.
|
||||
|
||||
---
|
||||
|
||||
## X / Twitter
|
||||
## Discord
|
||||
|
||||
### Tạo App & Lấy Keys
|
||||
1. Discord → Server Settings → Integrations → Webhooks → **New Webhook**
|
||||
2. Chọn kênh, copy **Webhook URL** → secret `DISCORD_WEBHOOK_URL`
|
||||
|
||||
1. Vào [developer.x.com](https://developer.x.com) → Developer Portal
|
||||
2. Tạo Project + App (Free tier cho phép 1 app)
|
||||
3. **User authentication settings**:
|
||||
- App permissions: **Read and Write** ← quan trọng!
|
||||
- Type of App: Web App
|
||||
- Callback URL: `https://example.com` (placeholder, không dùng)
|
||||
4. Vào **Keys and Tokens** tab:
|
||||
- **API Key and Secret** → copy cả 2
|
||||
- **Access Token and Secret** → Generate → copy cả 2
|
||||
- ⚠️ Access Token phải được generate **sau** khi set Read and Write
|
||||
|
||||
### Secrets cần thêm
|
||||
|
||||
| Secret | Giá trị |
|
||||
|-------------------|------------------------------|
|
||||
| `X_API_KEY` | API Key (Consumer Key) — ⚠️ hiện chưa có trong repo secrets, X luôn skip cho tới khi thêm |
|
||||
| `X_API_SECRET` | API Secret (Consumer Secret) |
|
||||
| `X_ACCESS_TOKEN` | Access Token |
|
||||
| `X_ACCESS_SECRET` | Access Token Secret |
|
||||
|
||||
### Lưu ý
|
||||
|
||||
- Free tier: **1 tweet / 15 phút** — workflow chỉ chạy 3 lần/ngày và nghỉ 1–5 giây giữa các video, nên bình thường không chạm giới hạn; nếu một ngày có nhiều video, bài sau có thể bị 429 và sẽ được thử lại ở lần chạy sau
|
||||
- Nếu gặp 403: kiểm tra App permissions phải là **Read and Write**, sau đó **regenerate** Access Token
|
||||
- API Key ≠ Bearer Token — script dùng OAuth 1.0a (4 keys), không dùng Bearer Token
|
||||
|
||||
---
|
||||
|
||||
## Facebook Page
|
||||
|
||||
### Lấy Page Access Token (Never-Expiring)
|
||||
|
||||
Quy trình hơi dài nhưng chỉ cần làm 1 lần:
|
||||
|
||||
#### Bước 1: Tạo Facebook App
|
||||
|
||||
1. Vào [developers.facebook.com](https://developers.facebook.com)
|
||||
2. **My Apps → Create App** → chọn "Business" type
|
||||
3. Thêm product: **Facebook Login for Business**
|
||||
|
||||
#### Bước 2: Lấy Short-Lived User Token
|
||||
|
||||
1. Vào [Graph API Explorer](https://developers.facebook.com/tools/explorer/)
|
||||
2. Chọn app vừa tạo
|
||||
3. Permissions cần thêm:
|
||||
- `pages_manage_posts`
|
||||
- `pages_read_engagement`
|
||||
4. **Generate Access Token** → đăng nhập + cấp quyền
|
||||
5. Copy token này (short-lived, 1-2 giờ)
|
||||
|
||||
#### Bước 3: Đổi sang Long-Lived User Token
|
||||
|
||||
```bash
|
||||
curl "https://graph.facebook.com/v21.0/oauth/access_token?\
|
||||
grant_type=fb_exchange_token&\
|
||||
client_id=YOUR_APP_ID&\
|
||||
client_secret=YOUR_APP_SECRET&\
|
||||
fb_exchange_token=SHORT_LIVED_TOKEN"
|
||||
```
|
||||
|
||||
Copy `access_token` trả về (long-lived, 60 ngày).
|
||||
|
||||
#### Bước 4: Lấy Never-Expiring Page Token
|
||||
|
||||
```bash
|
||||
curl "https://graph.facebook.com/v21.0/me/accounts?\
|
||||
access_token=LONG_LIVED_USER_TOKEN"
|
||||
```
|
||||
|
||||
Tìm Page trong kết quả → copy `access_token` của Page đó.
|
||||
Token này **không hết hạn** nếu User Token là long-lived.
|
||||
|
||||
#### Bước 5: Xác nhận token không hết hạn
|
||||
|
||||
```bash
|
||||
curl "https://graph.facebook.com/v21.0/debug_token?\
|
||||
input_token=PAGE_TOKEN&\
|
||||
access_token=PAGE_TOKEN"
|
||||
```
|
||||
|
||||
Kiểm tra `"expires_at": 0` hoặc `"data_access_expires_at"` rất xa → OK.
|
||||
|
||||
### Secrets cần thêm
|
||||
|
||||
| Secret | Giá trị |
|
||||
|-----------------------|----------------------------------------------------------|
|
||||
| `FACEBOOK_PAGE_ID` | Page ID (tìm trong Page Settings → About hoặc trong URL) |
|
||||
| `FACEBOOK_PAGE_TOKEN` | Never-expiring Page Access Token từ bước 4 |
|
||||
|
||||
### Test nhanh
|
||||
|
||||
```bash
|
||||
curl -X POST "https://graph.facebook.com/v21.0/PAGE_ID/feed" \
|
||||
-d "message=Test post from API" \
|
||||
-d "access_token=PAGE_TOKEN"
|
||||
```
|
||||
Không cần code cũng được: [MonitoRSS](https://monitorss.xyz) đọc thẳng RSS của kênh.
|
||||
|
||||
---
|
||||
|
||||
## Tổng Hợp Secrets
|
||||
|
||||
| Secret | Platform | Bắt buộc |
|
||||
|-------------------------|-----------|----------|
|
||||
| `YOUTUBE_CHANNEL_ID` | YouTube | ✅ |
|
||||
| `TELEGRAM_BOT_TOKEN` | Telegram | ✅ |
|
||||
| `TELEGRAM_CHAT_ID` | Telegram | ✅ |
|
||||
| `BLUESKY_HANDLE` | Bluesky | ✅ |
|
||||
| `BLUESKY_APP_PASSWORD` | Bluesky | ✅ |
|
||||
| `DISCORD_WEBHOOK_URL` | Discord | Tuỳ chọn |
|
||||
| `MASTODON_INSTANCE_URL` | Mastodon | Tuỳ chọn |
|
||||
| `MASTODON_ACCESS_TOKEN` | Mastodon | Tuỳ chọn |
|
||||
| `X_API_KEY` | X/Twitter | Tuỳ chọn |
|
||||
| `X_API_SECRET` | X/Twitter | Tuỳ chọn |
|
||||
| `X_ACCESS_TOKEN` | X/Twitter | Tuỳ chọn |
|
||||
| `X_ACCESS_SECRET` | X/Twitter | Tuỳ chọn |
|
||||
| `FACEBOOK_PAGE_ID` | Facebook | Tuỳ chọn |
|
||||
| `FACEBOOK_PAGE_TOKEN` | Facebook | Tuỳ chọn |
|
||||
Thêm trên Gitea: repo → **Settings → Actions → Secrets → Add secret**.
|
||||
|
||||
Mỗi platform tự skip nếu không có secret tương ứng — không cần cấu hình tất cả cùng lúc. Thêm dần khi sẵn sàng.
|
||||
|
||||
Hướng dẫn Telegram và Bluesky nằm trong [README.md](README.md#4-lấy-token-telegram-bluesky).
|
||||
| Secret | Platform | Bắt buộc |
|
||||
|-------------------------|----------|----------|
|
||||
| `YOUTUBE_CHANNEL_ID` | YouTube | ✅ |
|
||||
| `TELEGRAM_BOT_TOKEN` | Telegram | ✅ |
|
||||
| `TELEGRAM_CHAT_ID` | Telegram | ✅ |
|
||||
| `BLUESKY_HANDLE` | Bluesky | ✅ |
|
||||
| `BLUESKY_APP_PASSWORD` | Bluesky | ✅ |
|
||||
| `DISCORD_WEBHOOK_URL` | Discord | Tuỳ chọn |
|
||||
| `MASTODON_INSTANCE_URL` | Mastodon | Tuỳ chọn |
|
||||
| `MASTODON_ACCESS_TOKEN` | Mastodon | Tuỳ chọn |
|
||||
@@ -2,6 +2,90 @@
|
||||
|
||||
Mới nhất ở trên. Quy ước ở [`README.md`](README.md).
|
||||
|
||||
## 1.5.0 — 2026-11-23
|
||||
|
||||
Repo chuyển từ GitHub sang Gitea, và bot đăng bài mỗi ngày một lần. Nội dung bài đăng và secret của
|
||||
bot không đổi.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Mỗi ngày một lần**, lúc 14:47 UTC (21:47 giờ Việt Nam), thay cho ba lần (06:30, 14:30, 22:30
|
||||
UTC). Workflow chạy trên Gitea Actions với runner là máy của maintainer: máy tắt thì lần chạy chờ
|
||||
tới khi máy bật lại, quá 24 giờ thì bị huỷ, nên một video có thể chờ tới một ngày mới được đăng.
|
||||
- `LOOKBACK_HOURS` mặc định là **72** (trước là 48), đủ cho một lần chạy trễ cộng một ngày bị lỡ.
|
||||
- Mã nguồn ở [git.poli0981.dev/poli0981/youtube-auto-post](https://git.poli0981.dev/poli0981/youtube-auto-post);
|
||||
issue và merge request qua mirror [GitLab](https://gitlab.com/poli0981/youtube-auto-post); lỗ hổng
|
||||
bảo mật báo qua e-mail `security@poli0981.dev` ([SECURITY.md](https://git.poli0981.dev/poli0981/youtube-auto-post/src/branch/main/SECURITY.md)). User-Agent của bot
|
||||
trỏ về địa chỉ Gitea.
|
||||
- Secret đặt trong Gitea (repo → Settings → Actions → Secrets), cùng tên như trước. Release là Gitea
|
||||
release, nội dung vẫn lấy từ entry changelog.
|
||||
- CI: workflow mới `security.yml` (gitleaks, Opengrep, osv-scanner) từ repo ops, Renovate thay
|
||||
Dependabot, Qodana chạy bằng CLI và lưu báo cáo thành artifact.
|
||||
|
||||
### Removed
|
||||
|
||||
- **SonarQube Cloud**: job `sonar` và `sonar-project.properties`. Secret `SONAR_TOKEN` không còn được
|
||||
đọc. Qodana vẫn nằm trong check `ci`.
|
||||
|
||||
## 1.4.2 — 2026-11-16
|
||||
|
||||
Dự án chuyển sang chế độ bảo trì, và Qodana vào CI. Bài đăng, lịch chạy và secret của bot không đổi.
|
||||
[PR #14](https://github.com/poli0981/youtube-auto-post/pull/14)
|
||||
|
||||
### Changed
|
||||
|
||||
- **Chế độ bảo trì**: không thêm tính năng mới. Repo chỉ còn thay đổi khi cập nhật phụ thuộc định
|
||||
kỳ, khi một phụ thuộc dính CVE từ mức High trở lên hoặc nền chạy bot (như Node.js của các action)
|
||||
có lỗ hổng nghiêm trọng, khi một tính năng được đánh giá là thật sự cần thiết, hoặc khi lên bản
|
||||
Python mới. Chi tiết ở mục 9 của README.
|
||||
- **Qodana** (JetBrains, bản Ultimate cho Python) phân tích trong CI cạnh SonarQube Cloud: job
|
||||
`qodana` của `ci.yml`, cấu hình ở `qodana.yaml`. Có problem nào thì check `ci` đỏ và PR không merge
|
||||
được. CI cần secret `QODANA_TOKEN`; PR của Dependabot bỏ qua bước này.
|
||||
|
||||
## 1.4.1 — 2026-10-25
|
||||
|
||||
SonarQube Cloud chạy trong CI, có coverage. Bài đăng, lịch chạy và secret của bot không đổi.
|
||||
[PR #7](https://github.com/poli0981/youtube-auto-post/pull/7)
|
||||
|
||||
### Changed
|
||||
|
||||
- **SonarQube Cloud phân tích trong CI** (job `sonar` của `ci.yml`, cấu hình ở
|
||||
`sonar-project.properties`) thay cho Automatic Analysis, kèm coverage của pytest. Quality gate nằm
|
||||
trong check `ci`: gate fail thì PR không merge được. CI cần secret `SONAR_TOKEN`; PR của Dependabot
|
||||
bỏ qua bước phân tích.
|
||||
- Công cụ dev khoá theo hash (`requirements-dev.in` → `requirements-dev.txt`) và CI chỉ cài wheel, nên
|
||||
bản mới của một gói, kể cả gói gián tiếp, không tự lọt vào CI. zizmor lên 1.31.1.
|
||||
- `release_notes.py` chỉ nhận tag dạng `vX.Y.Z` hoặc `vX.Y.Z-…` và không còn tham số thư mục.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Phản hồi lỗi HTTP (4xx/5xx) được đóng sau khi đọc, không còn để mở tới khi bị dọn.
|
||||
|
||||
## 1.4.0 — 2026-10-22
|
||||
|
||||
Chuyển lên Python 3.15. Bài đăng, lịch chạy và secret không đổi.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Python 3.15** cho bot, CI và release (trước là 3.14). Chạy script hoặc test ở máy cần Python
|
||||
3.15; code dùng cú pháp `except A, B:` của 3.14+, nên 3.13 trở xuống không chạy được.
|
||||
- Trên Windows, script in tiếng Việt ra pipe hoặc file không còn lỗi `UnicodeEncodeError`: Python
|
||||
3.15 mặc định bật UTF-8 mode (PEP 686).
|
||||
- Công cụ dev: ruff 0.17.1, kiểm theo cú pháp Python 3.15. Test coi mọi warning là lỗi, nên một API
|
||||
Python sắp gỡ làm CI đỏ trước khi kịp làm hỏng bot.
|
||||
|
||||
## 1.3.0 — 2026-09-02
|
||||
|
||||
### Removed
|
||||
|
||||
- **X/Twitter và Facebook Page** không còn trong quy trình: module, biến môi trường, dòng secret
|
||||
trong `notify.yml`, phần cắt 280 ký tự và hướng dẫn lấy token đều gỡ. Bot đăng lên Telegram,
|
||||
Bluesky, Discord và Mastodon. Các secret `X_*` còn trong repo không được đọc nữa, xoá tuỳ ý.
|
||||
|
||||
### Changed
|
||||
|
||||
- `HASHTAGS` giờ chỉ áp dụng cho Mastodon.
|
||||
|
||||
## 1.2.0 — 2026-09-02
|
||||
|
||||
Sửa ba lỗi khiến bài đăng sai hoặc thiếu, và dựng hạ tầng CI, bảo vệ nhánh, release.
|
||||
|
||||
+2
-2
@@ -23,7 +23,7 @@ Một câu tóm tắt bản này (tuỳ chọn).
|
||||
```
|
||||
|
||||
Heading phải đúng dạng `## x.y.z — YYYY-MM-DD` (gạch ngang dài `—`): `release.yml` dùng
|
||||
`scripts/release_notes.py` cắt đúng phần dưới heading đó làm nội dung GitHub Release khi push tag
|
||||
`scripts/release_notes.py` cắt đúng phần dưới heading đó làm nội dung Gitea release khi push tag
|
||||
`vX.Y.Z`. Sai định dạng thì release không tạo được.
|
||||
|
||||
Chỉ ghi những gì **người dùng** của bot nhận thấy: bài đăng khác đi, video bị bỏ qua hay đăng
|
||||
@@ -46,4 +46,4 @@ vào bảng trên trong cùng commit.
|
||||
|
||||
1. Mở PR thêm entry `## x.y.z — YYYY-MM-DD` vào đầu file dòng major (cùng PR với code hoặc PR riêng).
|
||||
2. Merge, rồi tag đã ký trên `main`: `git tag -s vX.Y.Z -m vX.Y.Z && git push origin vX.Y.Z`.
|
||||
3. `release.yml` tạo GitHub Release với nội dung entry đó và gọi workflow thông báo Discord.
|
||||
3. `release.yml` tạo Gitea release với nội dung entry đó và gọi workflow thông báo Discord.
|
||||
+14
-1
@@ -1,5 +1,5 @@
|
||||
[tool.ruff]
|
||||
target-version = "py312"
|
||||
target-version = "py315"
|
||||
line-length = 100
|
||||
extend-exclude = ["state"]
|
||||
|
||||
@@ -25,3 +25,16 @@ known-first-party = [
|
||||
pythonpath = ["scripts"]
|
||||
testpaths = ["tests"]
|
||||
addopts = "-q"
|
||||
# A deprecated stdlib call fails CI here, not in production on the next Python.
|
||||
filterwarnings = ["error"]
|
||||
|
||||
# `pytest --cov` (CI's test job) measures scripts/ and fails under the floor below.
|
||||
[tool.coverage.run]
|
||||
source = ["scripts"]
|
||||
relative_files = true
|
||||
branch = true
|
||||
|
||||
[tool.coverage.report]
|
||||
exclude_also = ['if __name__ == "__main__":']
|
||||
# A floor against slow decline, not the target.
|
||||
fail_under = 95
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
# Qodana Cloud (JetBrains), CI-based: the `qodana` job in .gitea/workflows/ci.yml
|
||||
# runs the Qodana CLI with this file on every PR and every push to main. Reference:
|
||||
# https://www.jetbrains.com/help/qodana/qodana-yaml.html
|
||||
version: "1.0"
|
||||
|
||||
# Qodana for Python, the Ultimate linter (PyCharm Professional's inspections; a
|
||||
# Qodana Cloud project token, secret QODANA_TOKEN, is the licence). Native mode:
|
||||
# it runs on the job's runner with the job's Python 3.15 (QODANA_PYTHON_PATH),
|
||||
# the interpreter the bot runs on, not whatever the Docker image ships.
|
||||
linter: qodana-python
|
||||
withinDocker: "false"
|
||||
|
||||
profile:
|
||||
name: qodana.recommended
|
||||
|
||||
# Any problem fails the job, and with it the required `ci` check.
|
||||
failThreshold: 0
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["local>poli0981/renovate-config"],
|
||||
"pip-compile": {
|
||||
"description": "requirements-dev.txt is the hash-locked compile of requirements-dev.in: Renovate updates the .in pin and re-runs pip-compile with the command and the Python version in the lock's header.",
|
||||
"managerFilePatterns": ["/(^|/)requirements-dev\\.txt$/"]
|
||||
},
|
||||
"pip_requirements": {
|
||||
"description": "Off: its default pattern also matches requirements-dev.txt, and editing the lock by hand would break its hashes. pip-compile above owns both files.",
|
||||
"enabled": false
|
||||
},
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "Every update here is a dev tool or a CI pin, never the bot's runtime (stdlib only): a chore, as Dependabot's were.",
|
||||
"matchPackageNames": ["*"],
|
||||
"semanticCommitType": "chore"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Development-only: lint and test tools. The scripts themselves are stdlib-only.
|
||||
# requirements-dev.txt is the hash-locked compile of this file. After an edit,
|
||||
# regenerate it with pip-tools on Python 3.14 (Renovate re-runs the command in the
|
||||
# lock's header on the Python version named there):
|
||||
# pip-compile --generate-hashes --allow-unsafe --strip-extras --output-file=requirements-dev.txt requirements-dev.in
|
||||
ruff==0.17.4
|
||||
# Workflow security audit (the `security` job in ci.yml). A wheel per platform
|
||||
# from PyPI, so the job needs no Docker.
|
||||
zizmor==1.32.0
|
||||
pytest==9.2.0
|
||||
# `pytest --cov`: the coverage floor in pyproject.toml.
|
||||
pytest-cov==7.1.0
|
||||
coverage==7.17.2
|
||||
# pytest needs it on Windows only; listed so a lock compiled on Linux (Renovate)
|
||||
# still installs there.
|
||||
colorama
|
||||
+197
-3
@@ -1,3 +1,197 @@
|
||||
# Development-only. The scripts themselves are stdlib-only.
|
||||
ruff==0.16.5
|
||||
pytest==9.1.1
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.14
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile --allow-unsafe --generate-hashes --output-file=requirements-dev.txt --strip-extras requirements-dev.in
|
||||
#
|
||||
colorama==0.4.6 \
|
||||
--hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
|
||||
--hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
|
||||
# via
|
||||
# -r requirements-dev.in
|
||||
# pytest
|
||||
coverage==7.17.2 \
|
||||
--hash=sha256:01303d9e68b6e6bdc5459b54e3bd0e3539c94c25b50ac7362b7cbcacbc815fbc \
|
||||
--hash=sha256:0439f77deb5c023003533ae8909a9aa1e174c847d655327035b1e542c7c8a54e \
|
||||
--hash=sha256:0712a43e39410aa567f2e85846490f8dd6c839820e7edef2142767c5c03162ba \
|
||||
--hash=sha256:075566a44289afb634ceaafa7d8d377bb2667a5b4a90fbee2609efdcd015c66e \
|
||||
--hash=sha256:091eba4248d31b03828fc657c96d14adfaa8754f5aec7b73298b82894858db06 \
|
||||
--hash=sha256:0a623de5c57c5c3f3aed830c73a3a5aad91dbf76d53bc30ec161be758c8ca408 \
|
||||
--hash=sha256:0d8a5dc709da9b90ad5cc859a9b88c9b801e65ca2fbf7cbdbed5b9cbf457fcc9 \
|
||||
--hash=sha256:0fc17882975fe485cfc95fb2f20eed937e05e0c0d8ffa5048857cda3aa838e8a \
|
||||
--hash=sha256:1682d98ded28524bc6853cc4e7c65175b3e917f38b2e2ddebb28cafd8ab4de74 \
|
||||
--hash=sha256:189cdffb3ebc53d6133de67952dac7cc88d1fcaff5480623fb00ef0bf1cef918 \
|
||||
--hash=sha256:1947bd9d82e405c892c50b0d8dc0c1dea5df2a962129ca238c500a6bcf887509 \
|
||||
--hash=sha256:19d508b0611486f8e23e28abcba77795ee865ff0e0cd936349ba692c8d0d8ca4 \
|
||||
--hash=sha256:1c3146ef9d14c011517422489784a7ac344477e9cdacb05d9529e912721cd5d8 \
|
||||
--hash=sha256:1da1999e3c371edd669b48a1029c86dc0474cdc6ff152d58cb3f15cb3337af72 \
|
||||
--hash=sha256:205f9e329d9d5e47c320f8712326a01620689edae50531cc8934511e2c5e8f7e \
|
||||
--hash=sha256:20faaaf3a49601afbcd6d46c17a594b0ae62631498def44e5eed94789962ea18 \
|
||||
--hash=sha256:248873a144c067f981742ff4bbfb48b57e281a8cb7a3821d4e293bdb50b47970 \
|
||||
--hash=sha256:249c4b4eaac9ced6fb85e465027ca26348111c2760108fffc356a16be4f54cd9 \
|
||||
--hash=sha256:27fc4384a1154f7df30d304ccddc05ef457368c065670ecbd392606279b3329a \
|
||||
--hash=sha256:289a24443352713745f79c1b6aae4e99ced2f5ff3e86bb630c33c631d50f217c \
|
||||
--hash=sha256:298849ca0e385767096995cb57f72059b469f43f9927b8393f29d134f7bb1062 \
|
||||
--hash=sha256:2a6281011cf85699763bf88ab55e0774f6696f87b390f39152b14ecefadccb59 \
|
||||
--hash=sha256:2ad189c65706306644399e48530ad1aea1dfb311bd21d988df1ace422d09f3f8 \
|
||||
--hash=sha256:2b7fe217808239437b8509b869fde2e0cac48776a68c626bd6b15411b087e3de \
|
||||
--hash=sha256:2c42c222939b8699e7bc0e453149627f211ebbbb2f74c1a04331b0cd9834e2c8 \
|
||||
--hash=sha256:2cd1a7472a972fed01c89589b1560846e32e942f8329a515c4059d4521c6579a \
|
||||
--hash=sha256:34e5c7a2da36804c6e6f10b368eae01ad56f5a4ac5ecce7297300a3d46fdef2a \
|
||||
--hash=sha256:36248fb6c03341501169539bcab35eb3a59159100be1246fad3c14cb73c17685 \
|
||||
--hash=sha256:36314997533266bde3d07765289674304d61bfe49165bb1b4fa9be12cb4ba0d1 \
|
||||
--hash=sha256:3bd065e75c077d6de8cd3fe68699a8b47be3ec595af6b66e3629926839094609 \
|
||||
--hash=sha256:3d3d9d79a2b6cdcdde5a1ab1ae89953faea5cb28c0eea17a413ad997bb3cc8a1 \
|
||||
--hash=sha256:3dfefb1ec16ca1a01e5da40ba162e268ced8bd3624b9eba4e9384ebfa14af7ec \
|
||||
--hash=sha256:3f219efbc3ec71c377e278dee201633e1d4ad0d2d9bdaddfd9489b2869d584c4 \
|
||||
--hash=sha256:42133a2647982db7968db138c0f4a57f5836101d8d504600a87ef8ebfa22a4cf \
|
||||
--hash=sha256:4274acd35aae5bbbd0908792260819b9720b171ccc099a8168f7c20ef5d6ab3a \
|
||||
--hash=sha256:460ba2139866e758c3a8e9d9422fdc889942bcbc5ccaf710dc4fbd8707d14aa8 \
|
||||
--hash=sha256:485b2ed9e13b7e9209276843d7147e2f1cd1c816582655650a64c8f922093c58 \
|
||||
--hash=sha256:51c6a60e63ea993113ea5cd24a401cc2faddc54aa7acfddaffa5d3b8c0161b9d \
|
||||
--hash=sha256:545ca42488c7f0e62324fb2621aa05737db843b75e84e65a271bbf976f496f66 \
|
||||
--hash=sha256:555257578e20a46020c27b2af4ef99059cd906aa9b8e163baf9da9a5afb65a64 \
|
||||
--hash=sha256:565f1f1a9632d82678525d668a10fe070a285603a9d3581505b0e1a66624ad50 \
|
||||
--hash=sha256:5b71aeaa4440cbece5498acda30838685793d3bb960aff87ec97fbb546715a5f \
|
||||
--hash=sha256:603140eeae3f9adc562f91b1b98d4d1fc491bd1f66c5082482c568d0b7891bb1 \
|
||||
--hash=sha256:635337a96895f2ffcfe2aa7554468a988f468fb67a8007c1a65e95148c1855a9 \
|
||||
--hash=sha256:674bcd023a3743666d4d7a15238e57a00c968553780a36c80d3779fc410b912c \
|
||||
--hash=sha256:686b6f8f9e57afc3a44096b17ee8de7e11e0a12f2da819e25047af1eb3b0fc6f \
|
||||
--hash=sha256:698ca1575135215be25ac9c5d14f0b5455135d29602b7ee81e511d64a0435c85 \
|
||||
--hash=sha256:6bdf3821fd0740b5369b9ab58b4e9d0d68a2c5c75a7ee0cd3beb624f9f15e4fa \
|
||||
--hash=sha256:6fd6f218e39a621a30dbaf9543831fa10fe713afc8a44b52fc42cfe277412609 \
|
||||
--hash=sha256:70daa8e4b49541b51c0baeba0d802b0d14d3214daeebc071b3db0b0c7dc84646 \
|
||||
--hash=sha256:74d91af590514dda16165d5d7cfa94183150c6a6a80a99f61068369ae3959455 \
|
||||
--hash=sha256:7565c17092f2f4021abbe3f5007300c224f362364a388f5ddad9216dab44b611 \
|
||||
--hash=sha256:7804a6022fcd5e1d4de4dc676e985d6aea0119249e88c041e943f3cd07953527 \
|
||||
--hash=sha256:79cd2d9742419b6d1aaeb1f3fb77a8e6a01c09ebe5bd1b27011752410a5e3781 \
|
||||
--hash=sha256:7a3984fb8c2407721f9bc05573fc9a770752efc756d55068ccbde1fe53e42233 \
|
||||
--hash=sha256:7c123b6bbc183a14372036769f033098026aa75fc8fba37d028b0b772356e90b \
|
||||
--hash=sha256:7c17f716c837db550a202e7732cdfaa726b8515cba88be42193616913970d223 \
|
||||
--hash=sha256:7ce0acb27a823e8e5169282f538f0e182854cc8b472b88d45456f09b6fe364fd \
|
||||
--hash=sha256:81a432793440edef268dbadd493393bd6f70fa4b87f76c58114f7f77f1ccfaea \
|
||||
--hash=sha256:85bccf6fe19ea3747147387971465f6a06197d6b9f6b644a97ba90ca5b09c5cd \
|
||||
--hash=sha256:87b30f3daa0bedda6b770b303410a6def007844772aaa143dc52675b3d95cd8a \
|
||||
--hash=sha256:882cade9b6dc43b2bc819bb444c0a13e4ed1f669a50e0de74adeec54fce486f3 \
|
||||
--hash=sha256:88d4dc83b6ad09a2134cad9d8ec780b274b17ac7dfba8c2c6e92e3bc468fe85d \
|
||||
--hash=sha256:8d3626b9816f7eadd0993c3703a1d8ed124b579cebe5201b446f1c0d551fa245 \
|
||||
--hash=sha256:8dc07ed34bcb206f69d5b54fd3874f7bf39ac941c9f7aec2b53b29874fcfd77a \
|
||||
--hash=sha256:8dc17707fd463b4dfab53792e41d50a23316ac6b98539007aa2388a1d44a8535 \
|
||||
--hash=sha256:8de787f533b13aeeea5d7139610eadb56f249cc739840b973603d1d18d0fb023 \
|
||||
--hash=sha256:8eab0a5cff8dbc563d1416a6e079ba3c146712e47167c022a5df5ea01bd76df9 \
|
||||
--hash=sha256:90c6c5f93606b8803bd7f8a0b2ae05df7e35da4504a1c53cfe9294a1731e1f49 \
|
||||
--hash=sha256:95bd8dc5b356f78f10a967ec50f8902d56f24c623753ac9fce0aba9d6213d5c5 \
|
||||
--hash=sha256:960e199965e506d78f62252355397a05c8cee8072ad2d82d932745517d566539 \
|
||||
--hash=sha256:99b64a12fe6017c254a8027790e0eaa22eaeec201e7dfda5eaac176a6984ef27 \
|
||||
--hash=sha256:a3f49ac9c9e5fd4b450677eb44f4b14ea9ab71950b2896888c9f6a22d5cd1773 \
|
||||
--hash=sha256:a472e23a7514478e1c8124ea056424d681e3173975650b0a06b6181658f1009a \
|
||||
--hash=sha256:a5565a9dd715a5a94ffcf9a0ad4b6b1501b5441fd67d660e78742adff5d37a0a \
|
||||
--hash=sha256:a5909dd087006c70c128297312ba67d877123e871100645d9bd73ae021a4d01d \
|
||||
--hash=sha256:a65faa1ee98e090a5fd7c116f6d3ab5c6a85fcc46849b8494835608715836399 \
|
||||
--hash=sha256:a838a10afb5b60a6cc6315348b176badaf2409d821208a3e3cda1dc608129e23 \
|
||||
--hash=sha256:afd81658f17b1a50bbc1d247a61fa435be0be471246136eb946f9cbfc437a4fa \
|
||||
--hash=sha256:b0209fff1ca92f1e2e344d54b5b3def74efbdb46ba807cd81976a5e9e569cac3 \
|
||||
--hash=sha256:b08ee3ef53e80e5a50c68b3d9764363e373acba540e1b58daee0a9a7f23fdfb2 \
|
||||
--hash=sha256:b94c509e26603ba7f8cb1bf8bb63967c7be533493be5668d8442cd06ec853d76 \
|
||||
--hash=sha256:ba45dc072bfbf1798e68ec81379b73473fc912174bff9f91924d77711a1d2b30 \
|
||||
--hash=sha256:bac3c79c31f45274117ed64c65efeaed85665668aeba7d809c7c38801ada6ed4 \
|
||||
--hash=sha256:bb74283661a239fdaf738ac0b07db4ed9b476c7532d3e713abf0f6a072781e60 \
|
||||
--hash=sha256:be0fec33b69c40f845c76f67fb4495b62a84da8c31a579dc6e18c5a63fa6a1f3 \
|
||||
--hash=sha256:be699e76b57fede8920a0f568eff23b270d9004414b7cf6744bdda851638be6e \
|
||||
--hash=sha256:c10f2a2748dd084e44811bb9b26979763af9003115d9bf93c1da69011944719f \
|
||||
--hash=sha256:c5a98aff9eb681312ed403ecb7beb5f15fd25d6e0acc2554b9ca4b4d6f0b6705 \
|
||||
--hash=sha256:c68f64d96857749a215657c172f7144ed026063489686b901774f271997923c2 \
|
||||
--hash=sha256:c9639c2ea019c948b52067a0f74485039eb84b7a2de828ba6d178e663fb2b8bd \
|
||||
--hash=sha256:cbf751ae86ef0d80e719915c087b05776c8d9300141f6c3e56f536d78a62c301 \
|
||||
--hash=sha256:cfe64d2501806a04507217852a3132a9a9076321435500bf3b11943a5c872732 \
|
||||
--hash=sha256:d0332e2b27fc5cc761d6b8a33118b958e6a46be7f00fd30e03a5cf103350c0b3 \
|
||||
--hash=sha256:d05a1bef52f4d7f1b484a1cf46a8929e50963f910e51396373f06cd3b6248f38 \
|
||||
--hash=sha256:d14872ccef35972c4ac290f2432f43d0a7bb230cae2b5ed26871ab86221e8b5f \
|
||||
--hash=sha256:d2742952851c7f88b1484385f68c42c6388153520efb40ff09fc852c3783aa5c \
|
||||
--hash=sha256:d4004fce7b3a8ae5ef2af835670763f12723e9b9d74837697607b89a17f77312 \
|
||||
--hash=sha256:d5024913651813801fd43b65b6409b0d50f8bae95316c8f1512dfbd8ca96cb1f \
|
||||
--hash=sha256:d7a363c0788435ff5324d9582d37c63f215c75f974d755cfd6cfc9fbe0e64b04 \
|
||||
--hash=sha256:d88fcc24470d73ed4360e910f8549718b913ba56fb8775d9ef929a647835dfea \
|
||||
--hash=sha256:da4b0aef427eb96e422b444e5c2c3d38768fedb9141346294c38717a8b15b416 \
|
||||
--hash=sha256:df0a34d445eea64f3766e9ca2ff57bcde600a89c7c0330434a7a37e8d6e2549f \
|
||||
--hash=sha256:e09c37817768bb71fe3e70b6ce5e6ac1a0cd7398536c2f30a4460218c7b66e93 \
|
||||
--hash=sha256:e269dddf5ebac20dfcc5a2a459528a9d221ab828cb31dfdf19c7cfacdbcee673 \
|
||||
--hash=sha256:e2fd4e664a34854cae8db58ca6132fb7b5a7efc67b14233e797194bd0d63b6b0 \
|
||||
--hash=sha256:e674027ceb6bfd959f1bb035000fd20fa8b717dc6765adaaf8bca347822c8c7d \
|
||||
--hash=sha256:e6bf531deaebf8f69ba6015bba3fb817cab6694dfb69ac2a708889dc59a3926e \
|
||||
--hash=sha256:e6c89d63d43738712ce1febddb7758ffeb56de08f1b2be68aeb9a9c7fee712c7 \
|
||||
--hash=sha256:e72cf9556f799c3fce7597c1bd7dbfc9104befbd08088deb3b9ae9fd98117c02 \
|
||||
--hash=sha256:e86a66f96d80c770daeed78394c1d4f6e8d03e5a3e08c5dab5275d56414f296a \
|
||||
--hash=sha256:e8da5e158d13556457f69245deacf6d8401a2c9c31afaddd18bea691e849b5fd \
|
||||
--hash=sha256:eca90e028932de597e2c50f454ad8cc631281e14d20b9f801a649ab555deb580 \
|
||||
--hash=sha256:ee083412170118074bcc74361fcbc7104eb6d0b7c9c75eb3b84a4c324410c531 \
|
||||
--hash=sha256:ef07aae0a666ef5edcab5bc1bb590468c6f4120a8cdad50a010d042a59ab6e77 \
|
||||
--hash=sha256:f25209696631752468a25e5954fe119503468b3b29b6fa2c621ae766153c6f50 \
|
||||
--hash=sha256:f5a875e92f10c6463027d8151459f2d92b4c13527402ed1301eaddabd79d8cf5 \
|
||||
--hash=sha256:f94d465ee00ebe694ca866d66bbe45fa04618b1afcb377de934694f624fa7cf6 \
|
||||
--hash=sha256:ffbaadf8612781358b3f949ad68dce26c5a35beaafcc48125fc231dbcce7d362
|
||||
# via
|
||||
# -r requirements-dev.in
|
||||
# pytest-cov
|
||||
iniconfig==2.3.1 \
|
||||
--hash=sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960 \
|
||||
--hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7
|
||||
# via pytest
|
||||
packaging==26.3 \
|
||||
--hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
|
||||
--hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
|
||||
# via pytest
|
||||
pluggy==1.7.0 \
|
||||
--hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \
|
||||
--hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8
|
||||
# via
|
||||
# pytest
|
||||
# pytest-cov
|
||||
pygments==2.21.0 \
|
||||
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
|
||||
--hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
|
||||
# via pytest
|
||||
pytest==9.2.0 \
|
||||
--hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 \
|
||||
--hash=sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b
|
||||
# via
|
||||
# -r requirements-dev.in
|
||||
# pytest-cov
|
||||
pytest-cov==7.1.0 \
|
||||
--hash=sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2 \
|
||||
--hash=sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678
|
||||
# via -r requirements-dev.in
|
||||
ruff==0.17.4 \
|
||||
--hash=sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8 \
|
||||
--hash=sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7 \
|
||||
--hash=sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131 \
|
||||
--hash=sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90 \
|
||||
--hash=sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89 \
|
||||
--hash=sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690 \
|
||||
--hash=sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf \
|
||||
--hash=sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1 \
|
||||
--hash=sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524 \
|
||||
--hash=sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496 \
|
||||
--hash=sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c \
|
||||
--hash=sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6 \
|
||||
--hash=sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185 \
|
||||
--hash=sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0 \
|
||||
--hash=sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a \
|
||||
--hash=sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5 \
|
||||
--hash=sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d \
|
||||
--hash=sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e
|
||||
# via -r requirements-dev.in
|
||||
zizmor==1.32.0 \
|
||||
--hash=sha256:0a999c98015becd9f69919ce01febadfb1c2be9b8ec2ce9ef7eb13ff23ba8eba \
|
||||
--hash=sha256:0cdd38fca6eb34ceb567548548d706332e3535ea66894b9168c048e03207b68c \
|
||||
--hash=sha256:3f404b26791ed06a5ea9eaa0bfd5b973fc5228bac7db8b3c5ec7f0c7ad2ed16d \
|
||||
--hash=sha256:84a6acb975accc13408786a2bd274b572537ca19c933ebbc13e78f3988562071 \
|
||||
--hash=sha256:913fd3943bc1358aa6e23b33fe01cc98bf67af23985258b8fbf24eaa2f8728ea \
|
||||
--hash=sha256:9cd1dd7734042f40ca0faa2a31fb4e9033dede620d996af2f903744b8f04fca9 \
|
||||
--hash=sha256:aa4b4e216321dd5cf202cd79fc83296468f0eed79d850cd65ac8187a6bbc5496 \
|
||||
--hash=sha256:bddcdb0e37d1aa53c9f831c55627a5829d0d552cb0afb4b80fbe16a3a3140366 \
|
||||
--hash=sha256:d34dcfa702875202b4163d90ebb9cc5222f3d1a7d4b72bf796d87b5a15b24194 \
|
||||
--hash=sha256:dd818f99d833b86cd432d5412d620d936b5df074b33404fff8b67acff55d3259 \
|
||||
--hash=sha256:eaedf57859f026a0a7da2a6b574517b1fe01e256c6875b3319a06ee1cee026a7 \
|
||||
--hash=sha256:f0b664d394576e08605fe8094e8e992056d74b808f30c0c9ca9ed227001dcf67
|
||||
# via -r requirements-dev.in
|
||||
+5
-14
@@ -14,13 +14,14 @@ YOUTUBE_WATCH_URL = "https://www.youtube.com/watch?v={video_id}"
|
||||
|
||||
# Only videos published within this window are considered. The state file dedups
|
||||
# anything already posted, so the window only needs to outlast the gap between two
|
||||
# successful runs (scheduled runs are routinely delayed by GitHub for 1-2 hours).
|
||||
LOOKBACK_HOURS = int(os.environ.get("LOOKBACK_HOURS", "48"))
|
||||
# successful runs: one scheduled run a day, which waits while the runner (the
|
||||
# maintainer's PC) is off, so a late start plus one missed day.
|
||||
LOOKBACK_HOURS = int(os.environ.get("LOOKBACK_HOURS", "72"))
|
||||
|
||||
# Hashtags appended on Mastodon and X. Empty string disables them.
|
||||
# Hashtags appended on Mastodon. Empty string disables them.
|
||||
HASHTAGS = os.environ.get("HASHTAGS", "#gaming #gameplay #nocommentary").strip()
|
||||
|
||||
USER_AGENT = "YouTubeAutoPost/1.2 (+https://github.com/poli0981/youtube-auto-post)"
|
||||
USER_AGENT = "YouTubeAutoPost/1.2 (+https://git.poli0981.dev/poli0981/youtube-auto-post)"
|
||||
HTTP_TIMEOUT = 30
|
||||
|
||||
# Telegram
|
||||
@@ -38,16 +39,6 @@ DISCORD_WEBHOOK_URL = os.environ.get("DISCORD_WEBHOOK_URL", "").strip()
|
||||
MASTODON_INSTANCE_URL = os.environ.get("MASTODON_INSTANCE_URL", "").strip().rstrip("/")
|
||||
MASTODON_ACCESS_TOKEN = os.environ.get("MASTODON_ACCESS_TOKEN", "")
|
||||
|
||||
# X / Twitter
|
||||
X_API_KEY = os.environ.get("X_API_KEY", "")
|
||||
X_API_SECRET = os.environ.get("X_API_SECRET", "")
|
||||
X_ACCESS_TOKEN = os.environ.get("X_ACCESS_TOKEN", "")
|
||||
X_ACCESS_SECRET = os.environ.get("X_ACCESS_SECRET", "")
|
||||
|
||||
# Facebook
|
||||
FACEBOOK_PAGE_ID = os.environ.get("FACEBOOK_PAGE_ID", "")
|
||||
FACEBOOK_PAGE_TOKEN = os.environ.get("FACEBOOK_PAGE_TOKEN", "")
|
||||
|
||||
# State file (one posted video ID per line). In CI this points into the checkout of
|
||||
# the orphan `state` branch; locally it defaults to an untracked `state/` directory.
|
||||
STATE_FILE = Path(os.environ.get("STATE_FILE") or _REPO_ROOT / "state" / "last_video.txt")
|
||||
|
||||
@@ -45,7 +45,11 @@ def _request(
|
||||
with urlopen(req, timeout=timeout) as resp: # noqa: S310
|
||||
return resp.read(), {k.lower(): v for k, v in resp.headers.items()}
|
||||
except HTTPError as e:
|
||||
raise HttpError(e.code, e.read().decode("utf-8", errors="replace"), url) from e
|
||||
try:
|
||||
body = e.read().decode("utf-8", errors="replace")
|
||||
finally:
|
||||
e.close() # the error is also the response; leaving it open leaks it
|
||||
raise HttpError(e.code, body, url) from e
|
||||
except OSError as e: # URLError, timeouts, connection resets
|
||||
raise HttpError(0, str(e), url) from e
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@ built here once and each platform decorates it.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
|
||||
HEADER = "🎬 New Video / Video Mới"
|
||||
@@ -16,10 +14,6 @@ PLAY = "▶️"
|
||||
ELLIPSIS = "…"
|
||||
|
||||
BLUESKY_MAX_GRAPHEMES = 300
|
||||
X_MAX_WEIGHTED = 280
|
||||
X_URL_WEIGHT = 23
|
||||
|
||||
_URL_RE = re.compile(r"https?://\S+")
|
||||
|
||||
|
||||
def build_message(
|
||||
@@ -39,26 +33,6 @@ def truncate(text: str, max_len: int, suffix: str = ELLIPSIS) -> str:
|
||||
return text[: max_len - len(suffix)].rstrip() + suffix
|
||||
|
||||
|
||||
def _weigh(text: str) -> int:
|
||||
"""twitter-text v3 weights: Latin/common ranges count 1, everything else 2."""
|
||||
total = 0
|
||||
for ch in text:
|
||||
cp = ord(ch)
|
||||
light = cp <= 4351 or 8192 <= cp <= 8205 or 8208 <= cp <= 8223 or 8242 <= cp <= 8247
|
||||
total += 1 if light else 2
|
||||
return total
|
||||
|
||||
|
||||
def x_weighted_length(text: str) -> int:
|
||||
"""Length as X counts it: NFC-normalised, URLs are a flat 23."""
|
||||
text = unicodedata.normalize("NFC", text)
|
||||
total, last = 0, 0
|
||||
for m in _URL_RE.finditer(text):
|
||||
total += _weigh(text[last : m.start()]) + X_URL_WEIGHT
|
||||
last = m.end()
|
||||
return total + _weigh(text[last:])
|
||||
|
||||
|
||||
def _fit(video: dict, hashtags: str, measure: Callable[[str], int], limit: int) -> str:
|
||||
"""Shrink the title until `measure(text) <= limit`. Everything else is kept."""
|
||||
text = build_message(video, hashtags=hashtags)
|
||||
@@ -77,8 +51,3 @@ def _fit(video: dict, hashtags: str, measure: Callable[[str], int], limit: int)
|
||||
def fit_bluesky(video: dict, hashtags: str = "") -> str:
|
||||
"""Bluesky allows 300 graphemes; code points are a safe upper bound."""
|
||||
return _fit(video, hashtags, len, BLUESKY_MAX_GRAPHEMES)
|
||||
|
||||
|
||||
def fit_x(video: dict, hashtags: str = "") -> str:
|
||||
"""X allows 280 weighted characters."""
|
||||
return _fit(video, hashtags, x_weighted_length, X_MAX_WEIGHTED)
|
||||
@@ -6,8 +6,6 @@ Polls the YouTube RSS feed for recently published videos and posts to:
|
||||
- Bluesky (AT Protocol)
|
||||
- Discord (Webhook, optional)
|
||||
- Mastodon (REST API, optional)
|
||||
- X / Twitter (OAuth 1.0a, optional)
|
||||
- Facebook Page (Graph API, optional)
|
||||
|
||||
Exit code is 1 when any configured platform failed, so the CI-failure notifier fires.
|
||||
"""
|
||||
|
||||
@@ -4,7 +4,7 @@ Platform registry. Each module exposes a post(video) -> PostStatus function.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from platforms import bluesky, discord, facebook, mastodon, telegram, x_twitter
|
||||
from platforms import bluesky, discord, mastodon, telegram
|
||||
from platforms.base import PostStatus
|
||||
|
||||
PLATFORMS = [
|
||||
@@ -12,8 +12,6 @@ PLATFORMS = [
|
||||
("bluesky", bluesky.post),
|
||||
("discord", discord.post),
|
||||
("mastodon", mastodon.post),
|
||||
("x_twitter", x_twitter.post),
|
||||
("facebook", facebook.post),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"""Facebook Page Graph API integration (optional)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from config import FACEBOOK_PAGE_ID, FACEBOOK_PAGE_TOKEN
|
||||
from http_client import HttpError, post_form
|
||||
from message import build_message
|
||||
from platforms.base import PostStatus
|
||||
|
||||
GRAPH_API = "https://graph.facebook.com/v21.0"
|
||||
|
||||
|
||||
def post(video: dict) -> PostStatus:
|
||||
"""Post to Facebook Page via Graph API."""
|
||||
if not FACEBOOK_PAGE_ID or not FACEBOOK_PAGE_TOKEN:
|
||||
print("[SKIP] Facebook: missing page ID or access token.")
|
||||
return PostStatus.SKIPPED
|
||||
|
||||
try:
|
||||
result = post_form(
|
||||
f"{GRAPH_API}/{FACEBOOK_PAGE_ID}/feed",
|
||||
{
|
||||
"message": build_message(video),
|
||||
"link": video["url"],
|
||||
"access_token": FACEBOOK_PAGE_TOKEN,
|
||||
},
|
||||
)
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Facebook: {e}")
|
||||
if "OAuthException" in e.body or '"code":190' in e.body.replace(" ", ""):
|
||||
print(
|
||||
"[HINT] Token expired. Facebook Page tokens need to be refreshed.\n"
|
||||
" → Use a long-lived token (60 days) or a never-expiring page token.\n"
|
||||
" → Guide: Graph API Explorer → Get Page Access Token → Extend."
|
||||
)
|
||||
elif e.status == 403:
|
||||
print("[HINT] 403 — app may lack pages_manage_posts permission.")
|
||||
return PostStatus.FAILED
|
||||
|
||||
if not result.get("id"):
|
||||
print(f"[ERROR] Facebook: unexpected response — {result}")
|
||||
return PostStatus.FAILED
|
||||
print(f"[OK] Facebook: posted successfully (id: {result['id']}).")
|
||||
return PostStatus.OK
|
||||
@@ -1,82 +0,0 @@
|
||||
"""X / Twitter API v2 integration with OAuth 1.0a (optional)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from config import HASHTAGS, X_ACCESS_SECRET, X_ACCESS_TOKEN, X_API_KEY, X_API_SECRET
|
||||
from http_client import HttpError, post_json
|
||||
from message import fit_x
|
||||
from platforms.base import PostStatus
|
||||
|
||||
TWEETS_URL = "https://api.x.com/2/tweets"
|
||||
|
||||
|
||||
def _create_oauth_header(method: str, url: str, params: dict) -> str:
|
||||
"""Create OAuth 1.0a Authorization header for X/Twitter API v2."""
|
||||
oauth_params = {
|
||||
"oauth_consumer_key": X_API_KEY,
|
||||
"oauth_nonce": uuid.uuid4().hex,
|
||||
"oauth_signature_method": "HMAC-SHA1",
|
||||
"oauth_timestamp": str(int(time.time())),
|
||||
"oauth_token": X_ACCESS_TOKEN,
|
||||
"oauth_version": "1.0",
|
||||
}
|
||||
|
||||
all_params = {**oauth_params, **params}
|
||||
sorted_params = urlencode(sorted(all_params.items()))
|
||||
|
||||
base_string = f"{method}&{quote(url, safe='')}&{quote(sorted_params, safe='')}"
|
||||
signing_key = f"{quote(X_API_SECRET, safe='')}&{quote(X_ACCESS_SECRET, safe='')}"
|
||||
|
||||
digest = hmac.new(
|
||||
signing_key.encode("utf-8"),
|
||||
base_string.encode("utf-8"),
|
||||
hashlib.sha1, # noqa: S324 — OAuth 1.0a mandates HMAC-SHA1
|
||||
).digest()
|
||||
oauth_params["oauth_signature"] = base64.b64encode(digest).decode("utf-8")
|
||||
|
||||
return "OAuth " + ", ".join(
|
||||
f'{quote(k, safe="")}="{quote(v, safe="")}"' for k, v in sorted(oauth_params.items())
|
||||
)
|
||||
|
||||
|
||||
def post(video: dict) -> PostStatus:
|
||||
"""Post to X/Twitter via API v2 with OAuth 1.0a."""
|
||||
if not all([X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET]):
|
||||
print("[SKIP] X/Twitter: missing API credentials.")
|
||||
return PostStatus.SKIPPED
|
||||
|
||||
text = fit_x(video, HASHTAGS)
|
||||
|
||||
try:
|
||||
result = post_json(
|
||||
TWEETS_URL,
|
||||
{"text": text},
|
||||
headers={"Authorization": _create_oauth_header("POST", TWEETS_URL, {})},
|
||||
)
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] X/Twitter: {e}")
|
||||
if e.status == 401:
|
||||
print("[HINT] 401 — OAuth credentials are invalid or expired.")
|
||||
elif e.status == 403:
|
||||
print(
|
||||
"[HINT] 403 — app may lack write permissions. "
|
||||
"Check: Developer Portal → App → User authentication settings → "
|
||||
"App permissions = Read and Write."
|
||||
)
|
||||
elif e.status == 429:
|
||||
print("[HINT] 429 — rate limited. Free tier: 1 tweet / 15 min.")
|
||||
return PostStatus.FAILED
|
||||
|
||||
tweet_id = result.get("data", {}).get("id", "")
|
||||
if not tweet_id:
|
||||
print(f"[ERROR] X/Twitter: unexpected response — {result}")
|
||||
return PostStatus.FAILED
|
||||
print(f"[OK] X/Twitter: posted successfully (id: {tweet_id}).")
|
||||
return PostStatus.OK
|
||||
+20
-11
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Print the changelog entry for one version, for use as GitHub Release notes.
|
||||
Print the changelog entry for one version, for use as Gitea release notes.
|
||||
|
||||
python scripts/release_notes.py v1.2.0 [changelog_dir]
|
||||
python scripts/release_notes.py v1.2.0
|
||||
|
||||
Entries live in `changelog/<major>.x.md` under `## x.y.z — YYYY-MM-DD` headings.
|
||||
"""
|
||||
@@ -13,6 +13,9 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
HEADING_RE = re.compile(r"^## (?P<version>\S+) — \d{4}-\d{2}-\d{2}\s*$")
|
||||
# A release tag: v1.2.0, or a pre-release such as v2.0.0-beta.1.
|
||||
VERSION_RE = re.compile(r"v?(?P<major>\d+)\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?")
|
||||
CHANGELOG_DIR = Path(__file__).resolve().parent.parent / "changelog"
|
||||
|
||||
|
||||
def normalize_version(version: str) -> str:
|
||||
@@ -20,8 +23,11 @@ def normalize_version(version: str) -> str:
|
||||
|
||||
|
||||
def changelog_file(version: str, changelog_dir: Path) -> Path:
|
||||
major = normalize_version(version).split(".", 1)[0]
|
||||
return changelog_dir / f"{major}.x.md"
|
||||
"""`<major>.x.md` for a release version; the file name is built from the number alone."""
|
||||
m = VERSION_RE.fullmatch(version.strip())
|
||||
if m is None:
|
||||
raise ValueError(f"Not a release version: {version!r}")
|
||||
return changelog_dir / f"{int(m.group('major'))}.x.md"
|
||||
|
||||
|
||||
def extract_section(text: str, version: str) -> str:
|
||||
@@ -41,15 +47,18 @@ def extract_section(text: str, version: str) -> str:
|
||||
return "\n".join(lines[start:]).strip() + "\n"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if len(argv) < 2:
|
||||
print("Usage: release_notes.py <version> [changelog_dir]", file=sys.stderr)
|
||||
def main(argv: list[str], changelog_dir: Path = CHANGELOG_DIR) -> int:
|
||||
if len(argv) != 2:
|
||||
print("Usage: release_notes.py <version>", file=sys.stderr)
|
||||
return 2
|
||||
default_dir = Path(__file__).resolve().parent.parent / "changelog"
|
||||
changelog_dir = Path(argv[2]) if len(argv) > 2 else default_dir
|
||||
path = changelog_file(argv[1], changelog_dir)
|
||||
try:
|
||||
section = extract_section(path.read_text(encoding="utf-8"), argv[1])
|
||||
path = changelog_file(argv[1], changelog_dir)
|
||||
except ValueError as e:
|
||||
print(f"[ERROR] {e}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
section = extract_section(text, argv[1])
|
||||
except (OSError, LookupError) as e:
|
||||
print(f"[ERROR] {e} (looked in {path})", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
+5
-5
@@ -10,8 +10,8 @@ before it is announced.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from xml.etree import ElementTree
|
||||
|
||||
from config import NS, YOUTUBE_RSS_URL, YOUTUBE_WATCH_URL
|
||||
from http_client import HttpError, get_text
|
||||
@@ -34,8 +34,8 @@ _NOT_PUBLIC_PLAYABILITY = {"LIVE_STREAM_OFFLINE"} # upcoming premiere / stream
|
||||
def parse_feed(xml_text: str) -> list[dict]:
|
||||
"""Parse the Atom feed into video dicts. Malformed XML yields an empty list."""
|
||||
try:
|
||||
root = ET.fromstring(xml_text) # noqa: S314 — YouTube's own feed
|
||||
except ET.ParseError as e:
|
||||
root = ElementTree.fromstring(xml_text) # noqa: S314 — YouTube's own feed
|
||||
except ElementTree.ParseError as e:
|
||||
print(f"[ERROR] Could not parse RSS feed: {e}")
|
||||
return []
|
||||
return [_parse_entry(entry) for entry in root.findall("atom:entry", NS)]
|
||||
@@ -46,7 +46,7 @@ def fetch_feed() -> list[dict]:
|
||||
return parse_feed(get_text(YOUTUBE_RSS_URL))
|
||||
|
||||
|
||||
def _parse_entry(entry: ET.Element) -> dict:
|
||||
def _parse_entry(entry: ElementTree.Element) -> dict:
|
||||
video_id = entry.find("yt:videoId", NS)
|
||||
title = entry.find("atom:title", NS)
|
||||
link = entry.find("atom:link", NS)
|
||||
@@ -77,7 +77,7 @@ def parse_timestamp(value: str) -> datetime | None:
|
||||
"""ISO 8601 → aware datetime (UTC assumed when no offset). None if unparsable."""
|
||||
try:
|
||||
dt = datetime.fromisoformat(value.strip())
|
||||
except (ValueError, AttributeError):
|
||||
except ValueError, AttributeError:
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=UTC)
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from http_client import HttpError
|
||||
from platforms import bluesky
|
||||
from platforms.base import PostStatus
|
||||
|
||||
CREATE_SESSION = "com.atproto.server.createSession"
|
||||
UPLOAD_BLOB = "com.atproto.repo.uploadBlob"
|
||||
CREATE_RECORD = "com.atproto.repo.createRecord"
|
||||
THUMBNAIL = "thumbnail"
|
||||
|
||||
SESSION = {"accessJwt": "jwt-for-tests", "did": "did:plc:skullmute"}
|
||||
BLOB = {"$type": "blob", "ref": {"$link": "bafkrei"}, "mimeType": "image/jpeg", "size": 9}
|
||||
NOW = datetime(2026, 8, 31, 10, 0, tzinfo=UTC)
|
||||
|
||||
|
||||
class FakePds:
|
||||
"""Stands in for http_client: records each call and fails the ones named in `fail`."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[str, object, dict | None]] = []
|
||||
self.fail: set[str] = set()
|
||||
self.blob: dict | None = BLOB
|
||||
|
||||
def post_json(self, url, payload, headers=None, timeout=30):
|
||||
name = url.rsplit("/", 1)[-1]
|
||||
self.calls.append((name, payload, headers))
|
||||
if name in self.fail:
|
||||
raise HttpError(400, "bad request", url)
|
||||
return dict(SESSION) if name == CREATE_SESSION else {"uri": "at://post"}
|
||||
|
||||
def get_bytes(self, url, headers=None, timeout=30):
|
||||
self.calls.append((THUMBNAIL, url, headers))
|
||||
if THUMBNAIL in self.fail:
|
||||
raise HttpError(404, "not found", url)
|
||||
return b"jpeg-data", "image/jpeg"
|
||||
|
||||
def post_bytes(self, url, data, content_type, headers=None, timeout=30):
|
||||
name = url.rsplit("/", 1)[-1]
|
||||
self.calls.append((name, (data, content_type), headers))
|
||||
if name in self.fail:
|
||||
raise HttpError(500, "server error", url)
|
||||
return {"blob": self.blob} if self.blob else {}
|
||||
|
||||
def names(self) -> list[str]:
|
||||
return [name for name, _, _ in self.calls]
|
||||
|
||||
def call(self, name: str) -> tuple[object, dict | None]:
|
||||
return next((payload, headers) for n, payload, headers in self.calls if n == name)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_session():
|
||||
bluesky.reset_session()
|
||||
yield
|
||||
bluesky.reset_session()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pds(monkeypatch):
|
||||
fake = FakePds()
|
||||
monkeypatch.setattr(bluesky, "BLUESKY_HANDLE", "skullmute.bsky.social")
|
||||
monkeypatch.setattr(bluesky, "BLUESKY_APP_PASSWORD", "app-pass-for-tests")
|
||||
monkeypatch.setattr(bluesky, "post_json", fake.post_json)
|
||||
monkeypatch.setattr(bluesky, "get_bytes", fake.get_bytes)
|
||||
monkeypatch.setattr(bluesky, "post_bytes", fake.post_bytes)
|
||||
return fake
|
||||
|
||||
|
||||
def test_post_skips_without_credentials(pds, monkeypatch, video):
|
||||
monkeypatch.setattr(bluesky, "BLUESKY_APP_PASSWORD", "")
|
||||
assert bluesky.post(video) is PostStatus.SKIPPED
|
||||
assert pds.calls == []
|
||||
|
||||
|
||||
def test_post_logs_in_uploads_thumbnail_and_creates_record(pds, video):
|
||||
assert bluesky.post(video) is PostStatus.OK
|
||||
assert pds.names() == [CREATE_SESSION, THUMBNAIL, UPLOAD_BLOB, CREATE_RECORD]
|
||||
|
||||
login, _ = pds.call(CREATE_SESSION)
|
||||
assert login["identifier"] == "skullmute.bsky.social"
|
||||
assert login["password"] == bluesky.BLUESKY_APP_PASSWORD
|
||||
|
||||
upload, upload_headers = pds.call(UPLOAD_BLOB)
|
||||
assert upload == (b"jpeg-data", "image/jpeg")
|
||||
assert upload_headers == {"Authorization": "Bearer jwt-for-tests"}
|
||||
|
||||
created, created_headers = pds.call(CREATE_RECORD)
|
||||
assert created["repo"] == SESSION["did"]
|
||||
assert created["collection"] == "app.bsky.feed.post"
|
||||
assert created["record"]["embed"]["external"]["thumb"] == BLOB
|
||||
assert created_headers == {"Authorization": "Bearer jwt-for-tests"}
|
||||
|
||||
|
||||
def test_session_is_created_once_per_process(pds, video):
|
||||
bluesky.post(video)
|
||||
bluesky.post(video)
|
||||
assert pds.names().count(CREATE_SESSION) == 1
|
||||
|
||||
|
||||
def test_login_failure_fails_without_posting(pds, video):
|
||||
pds.fail.add(CREATE_SESSION)
|
||||
assert bluesky.post(video) is PostStatus.FAILED
|
||||
assert pds.names() == [CREATE_SESSION]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failing", [THUMBNAIL, UPLOAD_BLOB])
|
||||
def test_thumbnail_failure_still_posts_without_thumb(pds, video, failing):
|
||||
pds.fail.add(failing)
|
||||
assert bluesky.post(video) is PostStatus.OK
|
||||
created, _ = pds.call(CREATE_RECORD)
|
||||
assert "thumb" not in created["record"]["embed"]["external"]
|
||||
|
||||
|
||||
def test_upload_without_blob_posts_without_thumb(pds, video):
|
||||
pds.blob = None
|
||||
assert bluesky.post(video) is PostStatus.OK
|
||||
created, _ = pds.call(CREATE_RECORD)
|
||||
assert "thumb" not in created["record"]["embed"]["external"]
|
||||
|
||||
|
||||
def test_video_without_thumbnail_skips_the_upload(pds, video):
|
||||
assert bluesky.post({**video, "thumbnail": ""}) is PostStatus.OK
|
||||
assert pds.names() == [CREATE_SESSION, CREATE_RECORD]
|
||||
|
||||
|
||||
def test_create_record_failure_fails(pds, video):
|
||||
pds.fail.add(CREATE_RECORD)
|
||||
assert bluesky.post(video) is PostStatus.FAILED
|
||||
|
||||
|
||||
def test_build_record_link_facet_counts_utf8_bytes(video):
|
||||
record = bluesky.build_record({**video, "title": "Đánh boss 🎮 lần đầu"}, None, NOW)
|
||||
facet = record["facets"][0]
|
||||
start, end = facet["index"]["byteStart"], facet["index"]["byteEnd"]
|
||||
assert record["text"].encode()[start:end] == video["url"].encode()
|
||||
assert facet["features"] == [{"$type": "app.bsky.richtext.facet#link", "uri": video["url"]}]
|
||||
assert record["embed"]["external"] == {
|
||||
"uri": video["url"],
|
||||
"title": "Đánh boss 🎮 lần đầu",
|
||||
"description": video["description"],
|
||||
}
|
||||
assert record["createdAt"] == NOW.isoformat()
|
||||
@@ -0,0 +1,79 @@
|
||||
import pytest
|
||||
|
||||
from http_client import HttpError
|
||||
from message import HEADER
|
||||
from platforms import discord
|
||||
from platforms.base import PostStatus
|
||||
|
||||
WEBHOOK = "https://discord.com/api/webhooks/123/abc"
|
||||
|
||||
|
||||
def test_escape_markdown():
|
||||
assert discord.escape_markdown(r"a*b_c~d`e\f") == r"a\*b\_c\~d\`e\\f"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
WEBHOOK,
|
||||
"https://discordapp.com/api/webhooks/123/abc",
|
||||
"https://discord.com/webhooks/123/abc",
|
||||
"https://discord.com/api/webhooks/123/abc/",
|
||||
],
|
||||
)
|
||||
def test_normalize_webhook_url(url):
|
||||
assert discord.normalize_webhook_url(url) == WEBHOOK
|
||||
|
||||
|
||||
def test_build_text_bolds_header_and_escaped_title(video):
|
||||
text = discord.build_text({**video, "title": "Dark_Souls *2*"})
|
||||
assert text.split("\n\n") == [f"**{HEADER}**", r"**Dark\_Souls \*2\***", f"▶️ {video['url']}"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def webhook(monkeypatch):
|
||||
"""Configure an old-style webhook URL and record what gets posted to it."""
|
||||
sent = []
|
||||
|
||||
def fake_post_json(url, payload, headers=None, timeout=30):
|
||||
sent.append((url, payload))
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(discord, "DISCORD_WEBHOOK_URL", "https://discordapp.com/webhooks/123/abc/")
|
||||
monkeypatch.setattr(discord, "post_json", fake_post_json)
|
||||
return sent
|
||||
|
||||
|
||||
def test_post_skips_without_webhook(monkeypatch, video):
|
||||
monkeypatch.setattr(discord, "DISCORD_WEBHOOK_URL", "")
|
||||
assert discord.post(video) is PostStatus.SKIPPED
|
||||
|
||||
|
||||
def test_post_rejects_urls_that_are_not_webhooks(webhook, monkeypatch, video):
|
||||
monkeypatch.setattr(discord, "DISCORD_WEBHOOK_URL", "https://discord.com/channels/123/456")
|
||||
assert discord.post(video) is PostStatus.FAILED
|
||||
assert webhook == []
|
||||
|
||||
|
||||
def test_post_sends_to_the_normalized_webhook(webhook, video):
|
||||
assert discord.post(video) is PostStatus.OK
|
||||
assert webhook == [
|
||||
(WEBHOOK, {"content": discord.build_text(video), "username": "YouTube Notifications"})
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("status", "hint"),
|
||||
[(403, "403 Forbidden"), (404, "404 Not Found"), (429, "429 Rate Limited"), (500, None)],
|
||||
)
|
||||
def test_post_failures_fail_with_a_hint(monkeypatch, capsys, webhook, video, status, hint):
|
||||
def boom(url, payload, headers=None, timeout=30):
|
||||
raise HttpError(status, "error body", url)
|
||||
|
||||
monkeypatch.setattr(discord, "post_json", boom)
|
||||
assert discord.post(video) is PostStatus.FAILED
|
||||
out = capsys.readouterr().out
|
||||
if hint is None:
|
||||
assert "[HINT]" not in out
|
||||
else:
|
||||
assert f"[HINT] {hint}" in out
|
||||
@@ -0,0 +1,144 @@
|
||||
import io
|
||||
import json
|
||||
from email.message import Message
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
import pytest
|
||||
|
||||
import http_client
|
||||
from config import HTTP_TIMEOUT, USER_AGENT
|
||||
from http_client import HttpError, get_bytes, get_text, post_bytes, post_form, post_json
|
||||
|
||||
URL = "https://api.example.com/v1/endpoint"
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self, body: bytes, headers: dict[str, str]) -> None:
|
||||
self.body = body
|
||||
self.headers = headers
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc_info):
|
||||
return False
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self.body
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(monkeypatch):
|
||||
"""Fake urlopen: set `body`, `headers` or `error`; `request` is what was sent."""
|
||||
state = {"body": b"{}", "headers": {}, "error": None}
|
||||
|
||||
def fake_urlopen(request, timeout):
|
||||
state["request"] = request
|
||||
state["timeout"] = timeout
|
||||
if state["error"] is not None:
|
||||
raise state["error"]
|
||||
return FakeResponse(state["body"], state["headers"])
|
||||
|
||||
monkeypatch.setattr(http_client, "urlopen", fake_urlopen)
|
||||
return state
|
||||
|
||||
|
||||
def test_http_error_message_keeps_status_and_short_body_but_not_url():
|
||||
err = HttpError(404, " " + "x" * 400 + "\n", URL)
|
||||
assert str(err) == "HTTP 404 — " + "x" * 300
|
||||
assert (err.status, err.url) == (404, URL)
|
||||
assert str(HttpError(0, "timed out", URL)) == "connection error — timed out"
|
||||
|
||||
|
||||
def test_refuses_urls_that_are_not_https(server):
|
||||
with pytest.raises(ValueError, match="non-HTTPS"):
|
||||
get_text("www.youtube.com/feeds/videos.xml")
|
||||
assert "request" not in server
|
||||
|
||||
|
||||
def test_get_text_decodes_utf8_and_sends_user_agent(server):
|
||||
server["body"] = "Video Mới ✓".encode() + b"\xff"
|
||||
assert get_text(URL) == "Video Mới ✓\N{REPLACEMENT CHARACTER}"
|
||||
request = server["request"]
|
||||
assert request.get_method() == "GET"
|
||||
assert request.get_header("User-agent") == USER_AGENT
|
||||
assert server["timeout"] == HTTP_TIMEOUT
|
||||
|
||||
|
||||
def test_get_text_adds_headers_and_timeout(server):
|
||||
get_text(URL, headers={"Accept-Language": "en-US"}, timeout=5)
|
||||
assert server["request"].get_header("Accept-language") == "en-US"
|
||||
assert server["timeout"] == 5
|
||||
|
||||
|
||||
def test_get_bytes_returns_content_type_whatever_its_case(server):
|
||||
server["body"], server["headers"] = b"\x89PNG", {"Content-Type": "image/png"}
|
||||
assert get_bytes(URL) == (b"\x89PNG", "image/png")
|
||||
|
||||
|
||||
def test_get_bytes_defaults_content_type(server):
|
||||
assert get_bytes(URL) == (b"{}", "application/octet-stream")
|
||||
|
||||
|
||||
def test_post_json_sends_json_and_parses_reply(server):
|
||||
server["body"] = b'{"ok": true}'
|
||||
payload = {"text": "Video Mới"}
|
||||
assert post_json(URL, payload, headers={"Authorization": "Bearer abc"}) == {"ok": True}
|
||||
request = server["request"]
|
||||
assert request.get_method() == "POST"
|
||||
assert request.data == json.dumps(payload).encode()
|
||||
assert request.get_header("Content-type") == "application/json"
|
||||
assert request.get_header("Authorization") == "Bearer abc"
|
||||
|
||||
|
||||
def test_post_form_urlencodes_fields(server):
|
||||
post_form(URL, {"status": "a b&c", "visibility": "public"})
|
||||
request = server["request"]
|
||||
assert request.data == b"status=a+b%26c&visibility=public"
|
||||
assert request.get_header("Content-type") == "application/x-www-form-urlencoded"
|
||||
|
||||
|
||||
def test_post_bytes_sends_raw_body_with_its_type(server):
|
||||
post_bytes(URL, b"\xff\xd8jpeg", "image/jpeg")
|
||||
request = server["request"]
|
||||
assert request.data == b"\xff\xd8jpeg"
|
||||
assert request.get_header("Content-type") == "image/jpeg"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("body", "expected"),
|
||||
[
|
||||
(b"", {}),
|
||||
(b" \n", {}),
|
||||
(b"not json", {"_raw": "not json"}),
|
||||
(b"[1, 2]", {"_data": [1, 2]}),
|
||||
(b'{"id": "42"}', {"id": "42"}),
|
||||
],
|
||||
)
|
||||
def test_reply_bodies_always_become_dicts(server, body, expected):
|
||||
server["body"] = body
|
||||
assert post_json(URL, {}) == expected
|
||||
|
||||
|
||||
def test_http_status_errors_keep_status_and_body_and_close_the_response(server):
|
||||
body = io.BytesIO(b'{"error": "forbidden"}')
|
||||
server["error"] = HTTPError(URL, 403, "Forbidden", Message(), body)
|
||||
with pytest.raises(HttpError) as info:
|
||||
post_json(URL, {})
|
||||
assert (info.value.status, info.value.body, info.value.url) == (
|
||||
403,
|
||||
'{"error": "forbidden"}',
|
||||
URL,
|
||||
)
|
||||
assert body.closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error", [URLError("timed out"), TimeoutError("timed out"), ConnectionResetError("reset")]
|
||||
)
|
||||
def test_transport_errors_become_status_zero(server, error):
|
||||
server["error"] = error
|
||||
with pytest.raises(HttpError) as info:
|
||||
get_text(URL)
|
||||
assert info.value.status == 0
|
||||
assert str(error) in info.value.body
|
||||
@@ -0,0 +1,60 @@
|
||||
import pytest
|
||||
|
||||
from http_client import HttpError
|
||||
from message import build_message
|
||||
from platforms import mastodon
|
||||
from platforms.base import PostStatus
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def instance(monkeypatch):
|
||||
"""Configure an instance and record what gets posted; set `reply` to change the response."""
|
||||
state = {"sent": [], "reply": {"id": "109"}}
|
||||
|
||||
def fake_post_form(url, fields, headers=None, timeout=30):
|
||||
state["sent"].append((url, fields, headers))
|
||||
return state["reply"]
|
||||
|
||||
monkeypatch.setattr(mastodon, "MASTODON_INSTANCE_URL", "https://mastodon.social")
|
||||
monkeypatch.setattr(mastodon, "MASTODON_ACCESS_TOKEN", "access-for-tests")
|
||||
monkeypatch.setattr(mastodon, "HASHTAGS", "#gaming #gameplay")
|
||||
monkeypatch.setattr(mastodon, "post_form", fake_post_form)
|
||||
return state
|
||||
|
||||
|
||||
def test_post_skips_without_access_token(instance, monkeypatch, video):
|
||||
monkeypatch.setattr(mastodon, "MASTODON_ACCESS_TOKEN", "")
|
||||
assert mastodon.post(video) is PostStatus.SKIPPED
|
||||
assert instance["sent"] == []
|
||||
|
||||
|
||||
def test_post_publishes_a_public_status_with_hashtags(instance, video):
|
||||
assert mastodon.post(video) is PostStatus.OK
|
||||
assert instance["sent"] == [
|
||||
(
|
||||
"https://mastodon.social/api/v1/statuses",
|
||||
{"status": build_message(video, hashtags="#gaming #gameplay"), "visibility": "public"},
|
||||
{"Authorization": "Bearer access-for-tests"},
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_post_without_status_id_fails(instance, video):
|
||||
instance["reply"] = {"error": "unexpected"}
|
||||
assert mastodon.post(video) is PostStatus.FAILED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("status", "hint"), [(401, "401 Unauthorized"), (422, "422 —"), (503, None)]
|
||||
)
|
||||
def test_post_failures_fail_with_a_hint(instance, monkeypatch, capsys, video, status, hint):
|
||||
def boom(url, fields, headers=None, timeout=30):
|
||||
raise HttpError(status, "error body", url)
|
||||
|
||||
monkeypatch.setattr(mastodon, "post_form", boom)
|
||||
assert mastodon.post(video) is PostStatus.FAILED
|
||||
out = capsys.readouterr().out
|
||||
if hint is None:
|
||||
assert "[HINT]" not in out
|
||||
else:
|
||||
assert f"[HINT] {hint}" in out
|
||||
+4
-23
@@ -1,13 +1,4 @@
|
||||
from message import (
|
||||
BLUESKY_MAX_GRAPHEMES,
|
||||
HEADER,
|
||||
X_MAX_WEIGHTED,
|
||||
build_message,
|
||||
fit_bluesky,
|
||||
fit_x,
|
||||
truncate,
|
||||
x_weighted_length,
|
||||
)
|
||||
from message import BLUESKY_MAX_GRAPHEMES, HEADER, build_message, fit_bluesky, truncate
|
||||
|
||||
|
||||
def test_build_message_layout(video):
|
||||
@@ -30,13 +21,6 @@ def test_truncate():
|
||||
assert truncate("abcdefghij", 1) == "a"
|
||||
|
||||
|
||||
def test_x_weighted_length_counts_urls_as_23_and_cjk_as_2():
|
||||
assert x_weighted_length("https://www.youtube.com/watch?v=E0jg71lJE1Q") == 23
|
||||
assert x_weighted_length("ab") == 2
|
||||
assert x_weighted_length("日本") == 4
|
||||
assert x_weighted_length("🎬") == 2
|
||||
|
||||
|
||||
def test_fit_bluesky_keeps_short_titles(video):
|
||||
assert fit_bluesky(video) == build_message(video)
|
||||
|
||||
@@ -49,9 +33,6 @@ def test_fit_bluesky_truncates_long_titles(video):
|
||||
assert "…" in text
|
||||
|
||||
|
||||
def test_fit_x_truncates_by_weighted_length(video):
|
||||
long_video = {**video, "title": "日" * 200}
|
||||
text = fit_x(long_video, "#gaming")
|
||||
assert x_weighted_length(text) <= X_MAX_WEIGHTED
|
||||
assert text.endswith("#gaming")
|
||||
assert video["url"] in text
|
||||
def test_fit_bluesky_drops_the_title_when_even_that_is_not_enough(video):
|
||||
long_url = {**video, "url": video["url"] + "&list=" + "x" * BLUESKY_MAX_GRAPHEMES}
|
||||
assert fit_bluesky(long_url) == build_message(long_url, title="")
|
||||
@@ -58,6 +58,11 @@ def test_is_public_fetches_watch_page(monkeypatch):
|
||||
assert seen["url"] == "https://www.youtube.com/watch?v=abc"
|
||||
|
||||
|
||||
def test_is_public_passes_a_public_watch_page(monkeypatch):
|
||||
monkeypatch.setattr(youtube, "get_text", lambda url, headers=None, timeout=30: PUBLIC)
|
||||
assert is_public("abc", now=NOW) is True
|
||||
|
||||
|
||||
def test_is_public_fails_open_on_network_error(monkeypatch):
|
||||
def boom(url, headers=None, timeout=30):
|
||||
raise HttpError(0, "timed out", url)
|
||||
|
||||
@@ -31,17 +31,46 @@ def test_missing_version_raises():
|
||||
extract_section(CHANGELOG, "9.9.9")
|
||||
|
||||
|
||||
def test_changelog_file_uses_major_line(tmp_path):
|
||||
assert changelog_file("v2.3.4", tmp_path) == tmp_path / "2.x.md"
|
||||
@pytest.mark.parametrize("version", ["v2.3.4", "2.3.4", " v2.0.0-beta.1 "])
|
||||
def test_changelog_file_uses_major_line(tmp_path, version):
|
||||
assert changelog_file(version, tmp_path) == tmp_path / "2.x.md"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", ["v1.2", "latest", "../1.0.0", "v1.0.0/../../x", ""])
|
||||
def test_changelog_file_rejects_anything_but_a_version(tmp_path, version):
|
||||
with pytest.raises(ValueError, match="Not a release version"):
|
||||
changelog_file(version, tmp_path)
|
||||
|
||||
|
||||
def test_main_prints_section(tmp_path, capsys):
|
||||
(tmp_path / "1.x.md").write_text(CHANGELOG, encoding="utf-8")
|
||||
assert main(["release_notes.py", "v1.2.0", str(tmp_path)]) == 0
|
||||
assert main(["release_notes.py", "v1.2.0"], changelog_dir=tmp_path) == 0
|
||||
assert capsys.readouterr().out == "### Fixed\n\n- Telegram titles.\n"
|
||||
|
||||
|
||||
def test_main_reports_missing(tmp_path, capsys):
|
||||
(tmp_path / "1.x.md").write_text(CHANGELOG, encoding="utf-8")
|
||||
assert main(["release_notes.py", "v1.9.0", str(tmp_path)]) == 1
|
||||
assert main(["release_notes.py", "v1.9.0"], changelog_dir=tmp_path) == 1
|
||||
assert "No changelog entry" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_main_reports_a_missing_major_line_file(tmp_path, capsys):
|
||||
assert main(["release_notes.py", "v2.0.0"], changelog_dir=tmp_path) == 1
|
||||
assert "2.x.md" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_main_rejects_a_tag_that_is_not_a_version(capsys):
|
||||
assert main(["release_notes.py", "nightly"]) == 1
|
||||
assert "Not a release version" in capsys.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("argv", [["release_notes.py"], ["release_notes.py", "v1.2.0", "extra"]])
|
||||
def test_main_takes_exactly_one_version(capsys, argv):
|
||||
assert main(argv) == 2
|
||||
assert "Usage" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_main_reads_the_repository_changelog_by_default(capsys):
|
||||
# The real changelog/1.x.md: an entry that release.yml once published.
|
||||
assert main(["release_notes.py", "v1.2.0"]) == 0
|
||||
assert "### Fixed" in capsys.readouterr().out
|
||||
+35
-1
@@ -1,8 +1,9 @@
|
||||
import pytest
|
||||
|
||||
import notify
|
||||
import platforms
|
||||
from http_client import HttpError
|
||||
from platforms import summarize
|
||||
from platforms import post_to_all, summarize
|
||||
from platforms.base import PostStatus
|
||||
|
||||
OK, SKIP, FAIL = PostStatus.OK, PostStatus.SKIPPED, PostStatus.FAILED
|
||||
@@ -15,6 +16,23 @@ def test_summarize():
|
||||
assert summarize({"a": FAIL}) == (False, True)
|
||||
|
||||
|
||||
def test_post_to_all_asks_every_platform_in_order(monkeypatch, video):
|
||||
asked = []
|
||||
|
||||
def platform(name, status):
|
||||
def post(v):
|
||||
asked.append((name, v["video_id"]))
|
||||
return status
|
||||
|
||||
return post
|
||||
|
||||
monkeypatch.setattr(
|
||||
platforms, "PLATFORMS", [("a", platform("a", OK)), ("b", platform("b", FAIL))]
|
||||
)
|
||||
assert post_to_all(video) == {"a": OK, "b": FAIL}
|
||||
assert asked == [("a", video["video_id"]), ("b", video["video_id"])]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(monkeypatch, video):
|
||||
"""Wire notify.main() to fakes; returns a mutable dict describing the scenario."""
|
||||
@@ -65,6 +83,22 @@ def test_already_posted_is_noop(harness, video):
|
||||
assert harness["saved"] == []
|
||||
|
||||
|
||||
def test_nothing_in_the_lookback_window_is_noop(harness, monkeypatch):
|
||||
monkeypatch.setattr(notify, "select_recent", lambda videos, **kw: [])
|
||||
assert notify.main() == 0
|
||||
assert harness["saved"] == []
|
||||
|
||||
|
||||
def test_several_videos_are_paced_and_all_saved(harness, monkeypatch, video):
|
||||
second = {**video, "video_id": "hnxTgODvLiQ", "title": "Part 16"}
|
||||
harness["feed"] = [video, second]
|
||||
pauses = []
|
||||
monkeypatch.setattr(notify.time, "sleep", pauses.append)
|
||||
assert notify.main() == 0
|
||||
assert harness["saved"] == [video["video_id"], second["video_id"]]
|
||||
assert len(pauses) == 1 and 1 <= pauses[0] <= 5
|
||||
|
||||
|
||||
def test_feed_error_exits_one(harness, monkeypatch):
|
||||
def boom():
|
||||
raise HttpError(503, "down", "https://x")
|
||||
|
||||
+34
-1
@@ -1,10 +1,24 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from youtube import parse_feed, parse_timestamp, select_recent
|
||||
import youtube
|
||||
from config import NS
|
||||
from youtube import fetch_feed, parse_feed, parse_timestamp, select_recent
|
||||
|
||||
NOW = datetime(2026, 8, 31, 10, 0, tzinfo=UTC)
|
||||
|
||||
|
||||
def test_fetch_feed_reads_the_channel_rss(monkeypatch, feed_xml):
|
||||
requested = []
|
||||
|
||||
def fake_get_text(url, headers=None, timeout=30):
|
||||
requested.append(url)
|
||||
return feed_xml
|
||||
|
||||
monkeypatch.setattr(youtube, "get_text", fake_get_text)
|
||||
assert len(fetch_feed()) == 4
|
||||
assert requested == [youtube.YOUTUBE_RSS_URL]
|
||||
|
||||
|
||||
def test_parse_feed_reads_entries(feed_xml):
|
||||
videos = parse_feed(feed_xml)
|
||||
assert [v["video_id"] for v in videos] == [
|
||||
@@ -25,12 +39,31 @@ def test_parse_feed_tolerates_malformed_xml():
|
||||
assert parse_feed("<feed><entry></feed>") == []
|
||||
|
||||
|
||||
def test_parse_feed_fills_in_missing_elements():
|
||||
xml = (
|
||||
f'<feed xmlns="{NS["atom"]}" xmlns:media="{NS["media"]}">'
|
||||
"<entry><media:group><media:description/></media:group></entry>"
|
||||
"</feed>"
|
||||
)
|
||||
assert parse_feed(xml) == [
|
||||
{
|
||||
"video_id": "",
|
||||
"title": "Untitled",
|
||||
"url": "",
|
||||
"published": "",
|
||||
"description": "",
|
||||
"thumbnail": "",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_parse_timestamp():
|
||||
assert parse_timestamp("2026-08-31T08:45:06+00:00") == datetime(
|
||||
2026, 8, 31, 8, 45, 6, tzinfo=UTC
|
||||
)
|
||||
assert parse_timestamp("2026-08-31T08:45:06").tzinfo is UTC
|
||||
assert parse_timestamp("nope") is None
|
||||
assert parse_timestamp(None) is None
|
||||
|
||||
|
||||
def test_select_recent_uses_lookback_window_and_sorts_oldest_first(feed_xml):
|
||||
|
||||
Reference in new issue
Block a user