Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d99a41f34a | ||
|
|
b60caa177b | ||
|
|
6a154549b2 | ||
|
|
31836041f0 | ||
|
|
1afc835da4 | ||
|
|
64a6cc594a | ||
|
|
01b6785834 | ||
|
|
702e12aa14 | ||
|
|
01cb1546f5 | ||
|
|
9f08cde34e | ||
|
|
a221e71697 | ||
|
|
28a57ff3e8 | ||
|
|
9fae9b11ac | ||
|
|
b55e9f902d | ||
|
|
3b6aa9f976 | ||
|
|
d98f8710fb | ||
|
|
82d00ce1a7 | ||
|
|
bdebc74e16 | ||
|
|
1374206f52 | ||
|
|
e55919cde1 | ||
|
|
c1f3a5ab3f | ||
|
|
c58e063015 | ||
|
|
c81b84ea6c | ||
|
|
6258d63600 | ||
|
|
c366e1273c | ||
|
|
b334fa30a5 | ||
|
|
deb8584bd9 | ||
|
|
30f35227df | ||
|
|
a879e8ad1c | ||
|
|
f582b0ab45 | ||
|
|
5293669e07 | ||
|
|
12e2c7d12b | ||
|
|
80970848bb | ||
|
|
2242c57b1d | ||
|
|
607a004c89 | ||
|
|
c5134a073b | ||
|
|
2e8434d54a | ||
|
|
d80bca643e | ||
|
|
72ddd03def | ||
|
|
ad9b9bee55 | ||
|
|
985eb9df80 | ||
|
|
91e7905e29 | ||
|
|
665b8d4e3b | ||
|
|
1e19f8c4c7 | ||
|
|
8951c7ba7a | ||
|
|
b14cb22324 | ||
|
|
f3ed4c3da6 | ||
|
|
94ae52e6d7 | ||
|
|
1db7517040 | ||
|
|
dca5a64177 | ||
|
|
57aca0824d | ||
|
|
aaf06bc6d7 | ||
|
|
3c422de915 | ||
|
|
04a2f0d295 | ||
|
|
3bbe2c4d72 | ||
|
|
7642c681c6 | ||
|
|
6c3c8011b8 | ||
|
|
9773f0e507 | ||
|
|
efc1e3ac06 | ||
|
|
8c7edc24d6 | ||
|
|
a338d1ae8a | ||
|
|
c6e98c58e1 | ||
|
|
033a25ca1a | ||
|
|
2a604228bc | ||
|
|
480214c8ee | ||
|
|
1c3d265a9e | ||
|
|
fb90e484de | ||
|
|
0836862b9a | ||
|
|
51aa2fd7e3 | ||
|
|
7883467b85 | ||
|
|
e9a483d099 | ||
|
|
b5978a4e8b | ||
|
|
46ef15e3fa | ||
|
|
cf49fc03cd | ||
|
|
12ec4fd406 | ||
|
|
01606b2bfe | ||
|
|
44c351d337 | ||
|
|
6f91182189 | ||
|
|
cf7366d9a6 | ||
|
|
63b56de9b1 | ||
|
|
23b8f8f195 | ||
|
|
db8f5be43c | ||
|
|
725c16ff1f | ||
|
|
112c76c4ef |
No files matched your search
@@ -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,186 +0,0 @@
|
||||
# CI — lint, tests with coverage, workflow security audit, SonarQube Cloud. 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, Python security by ruff's `S` (bandit) rules, and
|
||||
# bugs, code smells, security hotspots and coverage by SonarQube Cloud.
|
||||
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.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@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.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 --cov-report=xml
|
||||
|
||||
# The report the `sonar` job hands to SonarQube Cloud.
|
||||
- name: Upload coverage report
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: coverage
|
||||
path: coverage.xml
|
||||
retention-days: 1
|
||||
if-no-files-found: error
|
||||
|
||||
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@85b2b9fb8e3325e7a23d7d0a9d7ba5ae0f999e3e # v0.7.1
|
||||
with:
|
||||
advanced-security: false
|
||||
# The action runs only the zizmor releases it was built with, so a newer
|
||||
# `version` here may need a newer action first.
|
||||
version: "1.31.1"
|
||||
|
||||
- name: actionlint (workflow syntax and expressions)
|
||||
run: docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.12 -color
|
||||
|
||||
sonar:
|
||||
# SonarQube Cloud, CI-based analysis (settings: sonar-project.properties) with
|
||||
# the coverage report from `test`. The scan waits for the quality gate and fails
|
||||
# when the gate fails. Automatic Analysis is off in the project's settings, so
|
||||
# this is the only analysis.
|
||||
#
|
||||
# A job of its own so SONAR_TOKEN never shares a job with pip packages: it only
|
||||
# checks out, takes the report and runs the scanner. Dependabot PRs get no
|
||||
# repository secrets, so there everything after the check is skipped with a
|
||||
# notice and the job still passes; `main` is analysed once they merge.
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check for SONAR_TOKEN
|
||||
id: token
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$SONAR_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "::notice::No SONAR_TOKEN in this run (Dependabot PR): SonarQube Cloud analysis skipped."
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.token.outputs.present == 'true'
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
# Full history: blame data, and the new-code diff of a PR.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download coverage report
|
||||
if: steps.token.outputs.present == 'true'
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: coverage
|
||||
|
||||
# The newest changelog entry is the analysis version, so on `main` "new code"
|
||||
# (New Code definition: previous version) starts over at each release.
|
||||
- name: Read the version
|
||||
if: steps.token.outputs.present == 'true'
|
||||
id: version
|
||||
run: |
|
||||
file=$(printf '%s\n' changelog/[0-9]*.x.md | sort -V | tail -n 1)
|
||||
version=$(grep -m 1 -oP '^## \K[0-9]+\.[0-9]+\.[0-9]+(?= — )' "$file" || true)
|
||||
if [ -z "$version" ]; then
|
||||
echo "::error::No '## x.y.z — YYYY-MM-DD' heading in $file"
|
||||
exit 1
|
||||
fi
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: SonarQube Cloud scan
|
||||
if: steps.token.outputs.present == 'true'
|
||||
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
with:
|
||||
args: -Dsonar.projectVersion=${{ steps.version.outputs.version }}
|
||||
|
||||
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, sonar]
|
||||
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,78 +0,0 @@
|
||||
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 * * *"
|
||||
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`.
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: youtube-auto-post
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: write # push to the `state` branch
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout state branch
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: state
|
||||
path: state
|
||||
# This checkout keeps its token on purpose: the last step pushes with it.
|
||||
persist-credentials: true
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.15"
|
||||
|
||||
- name: Run notification script
|
||||
env:
|
||||
STATE_FILE: state/last_video.txt
|
||||
LOOKBACK_HOURS: "48"
|
||||
# Required
|
||||
YOUTUBE_CHANNEL_ID: ${{ secrets.YOUTUBE_CHANNEL_ID }}
|
||||
# Telegram
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
# Bluesky
|
||||
BLUESKY_HANDLE: ${{ secrets.BLUESKY_HANDLE }}
|
||||
BLUESKY_APP_PASSWORD: ${{ secrets.BLUESKY_APP_PASSWORD }}
|
||||
# Discord (optional)
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
# Mastodon (optional)
|
||||
MASTODON_INSTANCE_URL: ${{ secrets.MASTODON_INSTANCE_URL }}
|
||||
MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }}
|
||||
run: python scripts/notify.py
|
||||
|
||||
# Runs even when the script exits 1 (a platform failed) so partial progress is
|
||||
# kept; the job still ends red and the CI-failure notifier fires.
|
||||
- name: Commit state
|
||||
if: ${{ !cancelled() }}
|
||||
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"
|
||||
git add last_video.txt
|
||||
if git diff --cached --quiet; then
|
||||
echo "No state changes."
|
||||
exit 0
|
||||
fi
|
||||
git commit -m "chore: update posted video state"
|
||||
git push origin HEAD:state
|
||||
@@ -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.15"
|
||||
|
||||
- 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
|
||||
@@ -1,31 +0,0 @@
|
||||
# zizmor configuration — https://docs.zizmor.sh/configuration/
|
||||
#
|
||||
# Every ignore below names the workflow it applies to and why the finding is
|
||||
# accepted. Anything not listed here must be fixed, not ignored.
|
||||
rules:
|
||||
unpinned-uses:
|
||||
config:
|
||||
policies:
|
||||
# Our own reusable workflows in poli0981/.github deliberately track @main.
|
||||
"poli0981/*": ref-pin
|
||||
"*": 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.
|
||||
ignore:
|
||||
- notify-ci-failure.yml
|
||||
|
||||
artipacked:
|
||||
# The second checkout in notify.yml keeps its token on purpose: it is the
|
||||
# checkout of the `state` branch that the last step pushes to.
|
||||
ignore:
|
||||
- notify.yml
|
||||
-210
@@ -1,210 +0,0 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
#poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
#pdm.lock
|
||||
#pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
#pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
.idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Cursor
|
||||
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
||||
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||
# refer to https://docs.cursor.com/context/ignore-files
|
||||
.cursorignore
|
||||
.cursorindexingignore
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Local checkout of the orphan `state` branch (see README) and local state runs
|
||||
state/
|
||||
@@ -1,9 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
Chi tiết nằm trong [`changelog/`](changelog/), mỗi dòng major một file, bản mới nhất ở trên.
|
||||
|
||||
- **[1.x](changelog/1.x.md)** — từ 1.0.0 đến hiện tại
|
||||
- [Quy ước và luật tách file](changelog/README.md)
|
||||
|
||||
File này chỉ trỏ, không chép lại nội dung. Một changelog duy nhất cứ dài mãi là thứ thư mục kia
|
||||
sinh ra để tránh, và hai chỗ để ghi release note là một chỗ để quên.
|
||||
@@ -1,211 +0,0 @@
|
||||
# 🤖 YouTube Auto-Post
|
||||
|
||||
Tự động đăng thông báo video mới của kênh YouTube lên **Telegram, Bluesky, Discord, Mastodon**
|
||||
bằng GitHub Actions. Script chỉ dùng thư viện chuẩn Python, không cài gì
|
||||
thêm.
|
||||
|
||||
---
|
||||
|
||||
## Mục lục
|
||||
|
||||
1. [Cách hoạt động](#1-cách-hoạt-động)
|
||||
2. [Cấu trúc repo](#2-cấu-trúc-repo)
|
||||
3. [Secrets và biến](#3-secrets-và-biến)
|
||||
4. [Lấy token Telegram, Bluesky](#4-lấy-token-telegram-bluesky)
|
||||
5. [Nhánh `state`](#5-nhánh-state)
|
||||
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)
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
1. Đọc RSS của kênh, giữ các video có `published` trong `LOOKBACK_HOURS` gần nhất (mặc định 48h).
|
||||
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ên Discord.
|
||||
|
||||
Nội dung bài đăng:
|
||||
|
||||
```
|
||||
🎬 New Video / Video Mới
|
||||
|
||||
<tiêu đề>
|
||||
|
||||
▶️ https://www.youtube.com/watch?v=...
|
||||
```
|
||||
|
||||
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/
|
||||
workflows/
|
||||
notify.yml # Đăng bài theo lịch, ghi state lên nhánh `state`
|
||||
ci.yml # ruff, pytest + coverage, zizmor, actionlint, SonarQube Cloud — gate `ci` là required check
|
||||
release.yml # tag v* → GitHub 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
|
||||
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
|
||||
message.py # Dựng nội dung bài đăng, cắt độ dài
|
||||
http_client.py # urllib + một kiểu lỗi chung (HttpError)
|
||||
state.py # Đọc/ghi last_video.txt
|
||||
config.py # Biến môi trường
|
||||
release_notes.py # Trích entry changelog cho release.yml
|
||||
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ó
|
||||
sonar-project.properties # SonarQube Cloud, đọc bởi job `sonar` của ci.yml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Secrets và biến
|
||||
|
||||
Repo → Settings → Secrets and variables → Actions → **New repository secret**.
|
||||
|
||||
| Secret | Platform | Bắt buộc | Ghi chú |
|
||||
|-------------------------|-----------|----------|-------------------------------------------------|
|
||||
| `YOUTUBE_CHANNEL_ID` | YouTube | ✅ | `UC...` |
|
||||
| `TELEGRAM_BOT_TOKEN` | Telegram | ✅ | Từ BotFather |
|
||||
| `TELEGRAM_CHAT_ID` | Telegram | ✅ | `-100...` |
|
||||
| `BLUESKY_HANDLE` | Bluesky | ✅ | `ten.bsky.social` |
|
||||
| `BLUESKY_APP_PASSWORD` | Bluesky | ✅ | App Password, không phải mật khẩu đăng nhập |
|
||||
| `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` |
|
||||
|
||||
Cách lấy token Mastodon và Discord: [SETUP_NEW_PLATFORMS.md](SETUP_NEW_PLATFORMS.md).
|
||||
|
||||
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; để rỗng để tắt |
|
||||
|
||||
---
|
||||
|
||||
## 4. Lấy token Telegram, Bluesky
|
||||
|
||||
**Telegram Bot**
|
||||
|
||||
1. Nhắn `/newbot` cho [@BotFather](https://t.me/BotFather), nhận **Bot Token**.
|
||||
2. Tạo Channel/Group, thêm bot làm admin.
|
||||
3. Gửi một tin bất kỳ vào channel rồi mở `https://api.telegram.org/bot<TOKEN>/getUpdates`, tìm
|
||||
`"chat":{"id": -100xxxxxxxxxx}`.
|
||||
|
||||
**Bluesky App Password**
|
||||
|
||||
1. [bsky.app](https://bsky.app) → Settings → App Passwords → tạo mới.
|
||||
2. Handle dạng `ten.bsky.social`.
|
||||
|
||||
**Discord không cần code**: có thể dùng [MonitoRSS](https://monitorss.xyz) đọc thẳng RSS kênh thay
|
||||
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`.
|
||||
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.
|
||||
|
||||
Xem state hiện tại:
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
Chạy local thì đặt `STATE_FILE` (mặc định `state/last_video.txt`, thư mục `state/` đã gitignore).
|
||||
|
||||
---
|
||||
|
||||
## 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 --require-hashes --only-binary :all: -r requirements-dev.txt
|
||||
ruff check . && ruff format --check .
|
||||
pytest --cov --cov-report=term-missing
|
||||
```
|
||||
|
||||
CI chạy đúng ba lệnh trên, cộng zizmor và actionlint cho workflow và SonarQube Cloud (dưới đây).
|
||||
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** 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** (Dependabot đọc bản Python ở header của file khoá và chỉ
|
||||
hỗ trợ tới 3.14):
|
||||
|
||||
```bash
|
||||
pip-compile --generate-hashes --allow-unsafe --strip-extras requirements-dev.in
|
||||
```
|
||||
|
||||
**SonarQube Cloud** phân tích trong CI, không dùng Automatic Analysis (đã tắt trong cài đặt project;
|
||||
bật lại thì scan trong CI lỗi). Job `sonar` chạy trên mỗi PR và mỗi lần push lên `main`, với
|
||||
[`sonar-project.properties`](sonar-project.properties) và coverage từ job `test`. Quality gate fail
|
||||
thì `sonar` đỏ, kéo check `ci` đỏ theo. Cần secret `SONAR_TOKEN` (Actions secrets). PR của Dependabot
|
||||
không đọc được secret đó nên bỏ qua phân tích mà vẫn xanh; `main` được phân tích sau khi merge.
|
||||
Finding nào chấp nhận thì ghi trong `sonar-project.properties` kèm lý do, như `zizmor.yml`.
|
||||
|
||||
Chạy thử script local (cần secret trong env):
|
||||
|
||||
```bash
|
||||
STATE_FILE=/tmp/state.txt YOUTUBE_CHANNEL_ID=UC... TELEGRAM_BOT_TOKEN=... TELEGRAM_CHAT_ID=... python scripts/notify.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Release
|
||||
|
||||
1. Thêm entry `## x.y.z — YYYY-MM-DD` vào đầu [`changelog/1.x.md`](changelog/1.x.md) qua PR.
|
||||
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
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
PR của Dependabot bị tụt sau `main` (check `ci` phải chạy trên bản mới nhất) thì comment
|
||||
`@dependabot rebase` trong PR. **Đừng bấm Update branch**: GitHub rebase xong để lại commit không ký
|
||||
nên ruleset chặn merge, và khi đã có người push vào PR thì Dependabot thôi cập nhật nó.
|
||||
|
||||
Repo private cá nhân không có CodeQL; thay bằng ruff rule `S`, zizmor, actionlint và SonarQube Cloud
|
||||
trong CI (mục 6).
|
||||
@@ -1,57 +0,0 @@
|
||||
# 🆕 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 đó.
|
||||
|
||||
---
|
||||
|
||||
## Mastodon
|
||||
|
||||
### Lấy Access Token
|
||||
|
||||
1. Đăng nhập Mastodon instance (e.g. `https://mastodon.social`)
|
||||
2. Vào **Preferences → Development → New Application**
|
||||
3. Tên: `YouTubeAutoPost`
|
||||
4. Scopes: chỉ cần ✅ `write:statuses`
|
||||
5. Submit → copy **Access Token**
|
||||
|
||||
### Secrets cần thêm
|
||||
|
||||
| Secret | Giá trị | Ví dụ |
|
||||
|-------------------------|----------------------------------|---------------------------|
|
||||
| `MASTODON_INSTANCE_URL` | URL instance (không có `/` cuối) | `https://mastodon.social` |
|
||||
| `MASTODON_ACCESS_TOKEN` | Token từ bước trên | `abc123...` |
|
||||
|
||||
### Test nhanh
|
||||
|
||||
```bash
|
||||
curl -X POST "https://mastodon.social/api/v1/statuses" \
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \
|
||||
-d "status=Test post from API&visibility=direct"
|
||||
```
|
||||
|
||||
Dùng `visibility=direct` để test mà không public.
|
||||
|
||||
---
|
||||
|
||||
## Discord
|
||||
|
||||
1. Discord → Server Settings → Integrations → Webhooks → **New Webhook**
|
||||
2. Chọn kênh, copy **Webhook URL** → secret `DISCORD_WEBHOOK_URL`
|
||||
|
||||
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 |
|
||||
@@ -1,128 +0,0 @@
|
||||
# 1.x
|
||||
|
||||
Mới nhất ở trên. Quy ước ở [`README.md`](README.md).
|
||||
|
||||
## 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.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Telegram hiển thị `\[2K\] ... \|` với backslash.** Tiêu đề được escape theo MarkdownV2 nhưng
|
||||
gửi với `parse_mode=Markdown` cũ, nên backslash hiện nguyên. Chuyển sang HTML mode; tiêu đề
|
||||
hiện đúng nguyên văn.
|
||||
- **Premiere đã lên lịch bị đăng trước giờ lên sóng.** RSS liệt kê Premiere từ lúc upload với
|
||||
`published` là giờ upload, nên bot đăng "video mới" khi người xem bấm vào chỉ thấy đếm ngược.
|
||||
Nay mỗi video được kiểm tra trên trang watch; chưa public thì để lần chạy sau.
|
||||
- **Video đăng cuối ngày có thể bị bỏ sót vĩnh viễn.** Bộ lọc "published hôm nay (UTC)" cộng với
|
||||
lịch chạy bị GitHub trễ qua nửa đêm UTC làm video đăng sau lần chạy cuối trong ngày không bao
|
||||
giờ được xét. Thay bằng cửa sổ `LOOKBACK_HOURS` (mặc định 48h); state vẫn chặn đăng trùng.
|
||||
- **Lỗi platform không bao giờ được báo.** Skip (thiếu secret) và lỗi thật đều là "false" và job
|
||||
luôn xanh. Nay phân biệt `OK / skipped / FAILED`; có platform đã cấu hình mà lỗi thì job đỏ và
|
||||
thông báo CI-failure trên Discord bắn.
|
||||
- RSS trả XML hỏng làm script crash; Bluesky đăng nhập lại cho từng video.
|
||||
|
||||
### Added
|
||||
|
||||
- **CI** (`ci.yml`): ruff (kèm rule bảo mật `S`), pytest, zizmor và actionlint cho workflow. Job
|
||||
gate `ci` là required status check của `main`.
|
||||
- **Dependabot** cho GitHub Actions và công cụ dev; action pin theo SHA.
|
||||
- **`release.yml`**: push tag `v*` → GitHub Release với nội dung lấy từ entry changelog tương ứng →
|
||||
thông báo Discord.
|
||||
- Cắt tiêu đề quá dài cho Bluesky (300) và X (280, tính theo trọng số của X).
|
||||
- Biến `HASHTAGS` (Mastodon, X) và `LOOKBACK_HOURS` đặt trong `notify.yml`.
|
||||
- Thư mục `changelog/` này và `CHANGELOG.md` trỏ tới nó.
|
||||
|
||||
### Changed
|
||||
|
||||
- **State chuyển sang nhánh orphan `state`** (file `last_video.txt`). `main` không còn nhận
|
||||
commit "chore: update last video state" và được bảo vệ bằng ruleset: bắt buộc PR, chỉ squash,
|
||||
commit ký, CI xanh, không ai bypass.
|
||||
- Nội dung bài đăng dựng ở một chỗ (`scripts/message.py`); mọi request HTTP đi qua
|
||||
`scripts/http_client.py` với một kiểu lỗi chung.
|
||||
- `actions/checkout` và `actions/setup-python` lên v7. README viết lại theo hiện trạng.
|
||||
|
||||
### Removed
|
||||
|
||||
- `.github/scripts/discord_notify.py` — bản sao không được workflow nào dùng; reusable workflow
|
||||
lấy script từ `poli0981/.github`.
|
||||
- `data/last_video.txt` trên `main` (đã sang nhánh `state`).
|
||||
|
||||
### Cần làm tay
|
||||
|
||||
- Thêm secret `X_API_KEY`: hiện thiếu nên X/Twitter luôn bị skip.
|
||||
|
||||
## 1.1.1 — 2026-05-09
|
||||
|
||||
### Added
|
||||
|
||||
- Thông báo Discord khi publish release và khi CI lỗi, qua reusable workflows của
|
||||
`poli0981/.github`.
|
||||
|
||||
## 1.1.0 — 2026-04-16
|
||||
|
||||
Tách script đơn khối thành module và đăng được nhiều video trong một ngày.
|
||||
[PR #1](https://github.com/poli0981/youtube-auto-post/pull/1)
|
||||
|
||||
### Added
|
||||
|
||||
- Đăng mọi video mới trong ngày, có nghỉ ngẫu nhiên 1–5 giây giữa các video.
|
||||
- State giữ tối đa 100 ID thay vì một ID cuối.
|
||||
|
||||
### Changed
|
||||
|
||||
- Lịch chạy 3 lần/ngày (06:30, 14:30, 22:30 UTC) thay vì mỗi giờ.
|
||||
- Mã tách thành `scripts/youtube.py`, `scripts/state.py`, `scripts/platforms/*`.
|
||||
|
||||
## 1.0.0 — 2026-04-13
|
||||
|
||||
### Added
|
||||
|
||||
- Đăng thông báo video mới lên Telegram, Bluesky và Discord; cùng ngày thêm Mastodon, X/Twitter
|
||||
và Facebook Page. Platform thiếu secret tự bỏ qua.
|
||||
- Chuẩn hoá URL webhook Discord và gợi ý lỗi theo mã HTTP.
|
||||
- State `data/last_video.txt` commit lên `main` sau mỗi lần chạy.
|
||||
@@ -1,49 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
Mỗi **dòng major** một file. `1.x.md` chứa mọi bản 1.y.z; khi lên 2.0.0 thì mở `2.x.md`.
|
||||
|
||||
| File | Phạm vi |
|
||||
|---|---|
|
||||
| [`1.x.md`](1.x.md) | 1.0.0 → hiện tại |
|
||||
|
||||
Bản **pre-release** có file riêng, đặt tên theo dòng nó dẫn tới — `2.0-beta.md` cho `2.0.0-beta.1`
|
||||
trở đi — và không gộp vào `2.x.md` khi dòng đó ổn định.
|
||||
|
||||
## Định dạng một entry
|
||||
|
||||
```
|
||||
## 1.2.0 — 2026-09-02
|
||||
|
||||
Một câu tóm tắt bản này (tuỳ chọn).
|
||||
|
||||
### Fixed
|
||||
### Added
|
||||
### Changed
|
||||
### Removed
|
||||
```
|
||||
|
||||
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
|
||||
`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
|
||||
thừa, secret/biến mới phải thêm. Link PR khi có. Không ghi số commit hay số test — con số về repo
|
||||
viết trong repo lỗi thời ngay lúc commit.
|
||||
|
||||
## Khi file dài, tách theo khoảng minor
|
||||
|
||||
Mục đích của thư mục này là mở một file, thấy ngay phiên bản mình cần mà không cuộn qua những bản
|
||||
không quan tâm. Luật là về **độ dài đọc**, không phải số bản:
|
||||
|
||||
**Tách khi file vượt khoảng 600 dòng**, thành các khoảng minor liền nhau — `1.0-1.4.md`,
|
||||
`1.5-1.9.md` — và để `1.x.md` lại làm stub trỏ tới cả hai để link cũ không hỏng. Thêm file mới
|
||||
vào bảng trên trong cùng commit.
|
||||
|
||||
- **Không đổi tên file đã có.** `1.0-1.4.md` giữ tên đó mãi, kể cả sau lần tách tiếp theo.
|
||||
- **Mới nhất ở trên** trong một file, để phần đầu là phần người ta cần và điểm tách luôn ở cuối.
|
||||
|
||||
## Quy trình phát hành
|
||||
|
||||
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.
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
qt7RVP32AV4
|
||||
uZll6csX9kI
|
||||
DRDhW9LMLMQ
|
||||
4VuhBOTTkrQ
|
||||
8WtLZYAhVg0
|
||||
9SOW4GxxbLM
|
||||
pYQib1AX1ks
|
||||
VB7DjTeqXTI
|
||||
-9rtdC9uSbg
|
||||
uvzecbUqaJw
|
||||
3UlnBbHmJbs
|
||||
ApnNvVldt1s
|
||||
esWbaCgUBPc
|
||||
QE-bTkU_0IE
|
||||
XRU-dsONddE
|
||||
h-rycsixtcA
|
||||
qrxVfwlIKzU
|
||||
B2rKCyxHV8Y
|
||||
rE8BNUIgyjE
|
||||
9mCNQHsSc94
|
||||
m1G-vd3bito
|
||||
ho6J2SuH-7M
|
||||
bVn-d9GhnDY
|
||||
u_bjkT0Hr5U
|
||||
IPeedP8whSI
|
||||
Sm1kpYxnZlA
|
||||
rJh14s1t2u0
|
||||
rjUgg-e2kYA
|
||||
-FFqAobCvWI
|
||||
6koVzftcgzY
|
||||
N7_aqUpek50
|
||||
iXXF5iMJwYA
|
||||
ArLjmBqJLSY
|
||||
giIoDtgGIcg
|
||||
-1pJWrS9qP0
|
||||
uHogFOXPYME
|
||||
IepgEU2rJ2w
|
||||
8cNbRjfm-ag
|
||||
C1bzYM7TnQY
|
||||
1YdBNdsPS4w
|
||||
L3ry1zbvYnA
|
||||
3E5rQ1A_KC8
|
||||
scQrHFvmXyg
|
||||
Rj94dYEPaYU
|
||||
dh3qlRq-Q8E
|
||||
ecB7WwmlZao
|
||||
_YoSCfjkVd4
|
||||
FWf1VQq7Y2E
|
||||
XXb0ZLIGc1k
|
||||
kJSU9kflD6E
|
||||
Ip4BKSfXBAo
|
||||
91z2V3pTA48
|
||||
y6gnQCZtFWI
|
||||
Xll88Fk7_4c
|
||||
VD8Lgura8KQ
|
||||
-5GLcSWxGWs
|
||||
PZWlYWJL9-k
|
||||
oqWSuUzr8sw
|
||||
FoyoXkpCtdU
|
||||
GbZuHF6Ll8w
|
||||
Ru9OvLe6MgQ
|
||||
9n8Dkx_pfFI
|
||||
Eo6y0jpwJWM
|
||||
f3kG_8g3TCg
|
||||
fjNGBL22V4w
|
||||
KRSMLQZkWJ4
|
||||
YeGCvXUlG6E
|
||||
6Lwr4FeNt8A
|
||||
YxK-_auE4LI
|
||||
Vegjg8AObAQ
|
||||
bIthyYDqqUA
|
||||
EZ9HPFNSu80
|
||||
b-sFO9vIdhc
|
||||
JFHD34lBYdU
|
||||
CaviT86imQ0
|
||||
xtNNZmBdwBE
|
||||
8adQpu22_38
|
||||
aWdZq4QQLqc
|
||||
8beMNIp_fBQ
|
||||
a6qoMHtTP8M
|
||||
kA5ZVnb_mTE
|
||||
tPHbXvSxDa8
|
||||
8C-NvlVVxmE
|
||||
yERCN0W3CYA
|
||||
tGqKh5Ojntc
|
||||
ya3QDrO5fDY
|
||||
pvxPJw3A-Zg
|
||||
HLCDQ7QnVak
|
||||
PfCeLnaPD1M
|
||||
pCkG1eVQDJk
|
||||
MaqNXKkTHWA
|
||||
xhOQgyKitiw
|
||||
73AL7Fv9OFg
|
||||
qdWwUtlta1k
|
||||
_ZRNX23D-80
|
||||
znyMQmPtoK4
|
||||
8B8d2ErMZt8
|
||||
Z2fnRXXzqsk
|
||||
EPOAN9NwHaE
|
||||
CXHwqjHO7no
|
||||
@@ -1,42 +0,0 @@
|
||||
[tool.ruff]
|
||||
target-version = "py315"
|
||||
line-length = 100
|
||||
extend-exclude = ["state"]
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "W", "I", "UP", "B", "S"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"tests/*" = ["S101"] # assert is the point of a test
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-first-party = [
|
||||
"config",
|
||||
"http_client",
|
||||
"message",
|
||||
"notify",
|
||||
"platforms",
|
||||
"release_notes",
|
||||
"state",
|
||||
"youtube",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
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 writes coverage.xml for
|
||||
# SonarQube Cloud. Relative paths, so the scanner can match them to its files.
|
||||
[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. SonarQube Cloud's gate ignores
|
||||
# coverage on PRs with fewer than 20 new lines and does not run on Dependabot PRs.
|
||||
fail_under = 95
|
||||
@@ -1,13 +0,0 @@
|
||||
# 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 (Dependabot reads the version from
|
||||
# the lock's header and supports up to 3.14):
|
||||
# pip-compile --generate-hashes --allow-unsafe --strip-extras requirements-dev.in
|
||||
ruff==0.17.1
|
||||
pytest==9.1.1
|
||||
# `pytest --cov`: coverage.xml for SonarQube Cloud (the `sonar` job in ci.yml).
|
||||
pytest-cov==7.1.0
|
||||
coverage==7.16.2
|
||||
# pytest needs it on Windows only; listed so a lock compiled on Linux (Dependabot)
|
||||
# still installs there.
|
||||
colorama
|
||||
@@ -1,185 +0,0 @@
|
||||
#
|
||||
# This file is autogenerated by pip-compile with Python 3.14
|
||||
# by the following command:
|
||||
#
|
||||
# pip-compile --allow-unsafe --generate-hashes --strip-extras requirements-dev.in
|
||||
#
|
||||
colorama==0.4.6 \
|
||||
--hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
|
||||
--hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
|
||||
# via
|
||||
# -r requirements-dev.in
|
||||
# pytest
|
||||
coverage==7.16.2 \
|
||||
--hash=sha256:00d3eb96e9988c45f50cccd1f1496571ac5c1f91386ac02c4d55516eeda19a24 \
|
||||
--hash=sha256:01c6908bc613b420c26c818fe948e1b97dfd041a53c98b01c63bd8321f5c9aae \
|
||||
--hash=sha256:066429634299e14dd2d511e1e85f8f9cecc500781f6b41907c0dd6f1baea7e63 \
|
||||
--hash=sha256:0993d0e90858c03943d3cb152e068a20dd4707924deec84dd2230261baae3b1b \
|
||||
--hash=sha256:0dcbcfcc059117284c603ff8cb61a65872512882f84a8cf0339241f7f7c2f148 \
|
||||
--hash=sha256:0fd7a86fdda7cb6d616d178654bd0ad6bc0f3f33c2e478aa598500a1a9e34eda \
|
||||
--hash=sha256:11d28e9123a9156cb405d8d27b44256c9a58fb5decc2073a8f17862057e3aa0f \
|
||||
--hash=sha256:11e597173af1dc33d5f8a7332ada544199269a223af1ee1770ddd5e245ad0fe8 \
|
||||
--hash=sha256:126d1af8804d7224421fe991ff65d3ce649081560df7a98b1a5ffff07f9923bd \
|
||||
--hash=sha256:14253fc7bb15749b849795a06f5d3b6d8bc3fb8a4b5ddc341faf7a89dce205fc \
|
||||
--hash=sha256:152877cdc8a07264882cfcd503ba56a3ef6cba56a70e8c70f6eb8ffd7384789a \
|
||||
--hash=sha256:17228fbca0f22976f797be94e975dcd237799c657d49551c7de1e0654d1202e9 \
|
||||
--hash=sha256:191803c4996b499fcd78c2ad5e5f767dcc53cb4dc6de6d6a741b443a1821ef02 \
|
||||
--hash=sha256:1a37c6e478cf687e1aa30a593d19c92c02fad9d122b51ab73f51b8dc7a0c0fc9 \
|
||||
--hash=sha256:1c569a9fd25505f1cd6bea90588818f90373ce90e2632e2cacf19ddbd6e14fdb \
|
||||
--hash=sha256:1d56e4d21c56d2046447733f8b118409597db48c01efe898ee9ac24e858ec2d6 \
|
||||
--hash=sha256:1d5d0e3b660506fb84f995814e3118a21efdc0c8eb80127da1be627d90093c17 \
|
||||
--hash=sha256:1f15254427c9b33eedac4f198eaf9e356eb4f6214551afb43da6194a2c088ad7 \
|
||||
--hash=sha256:218d742afca2b5ad5ca759e93eddedfbcc6eadf8322f080dcefc40b7bd4e2d48 \
|
||||
--hash=sha256:22957cef43ce038641de78ba995de7568d2d6a37c6ddbf7fa0fd7d1ae2344d91 \
|
||||
--hash=sha256:23219888477edd736b6fcaec1272d47d93b926e999641ffea7e53a1738e70b2b \
|
||||
--hash=sha256:251aed777c47c77aba047096d4542889db089227655711dfc2b9c54ef0e15e35 \
|
||||
--hash=sha256:28ff850182a67d117990fa2ce5ea1032836d8c9630dae867e8bdd3bff4533b79 \
|
||||
--hash=sha256:29309ccc86b7f33df7db12813c299f215bbbc470ed6292d0bedd63ffae1ebf64 \
|
||||
--hash=sha256:2aca0bdfa9e91621d5b09d815357bf63def4fc0e9cb66da67bf2cf93f3b1a6f5 \
|
||||
--hash=sha256:30c1b65d529e46569899fadca59e4a87c1faf2886923f1307ba61e654d4f3c20 \
|
||||
--hash=sha256:35f37886699cb9abd29958247d718628d5bc6f39e623dff66a09e546c42a7e03 \
|
||||
--hash=sha256:382d3346d56b0eec1b793d53a4c88799c8053f516aa3a8d7c44315696954bacf \
|
||||
--hash=sha256:396bb16e04ce04efbb3df91456ae4e3da918e69ecdf67fb711b0a0fdf35ccce0 \
|
||||
--hash=sha256:3e7f99698ba3a7d13988bdd984b7ebf13af4dbe2166dc8502eef90d77603b0a4 \
|
||||
--hash=sha256:3e861f1071dcc2fec1e88bef0920f6b1eaa66a143555b4f8ab79ba2b0f30ef55 \
|
||||
--hash=sha256:3f43bac1856ba269b905302778d4df433d6006489a192174ad77ac528e395032 \
|
||||
--hash=sha256:40c0f00899fe6181ae7f434ceb200e51f5ee4b8ed10e3b5f0b605f0cae15da87 \
|
||||
--hash=sha256:414c26dfdb96aac2d570a54e03008f001e32eb2d413705365503648c6bd361d8 \
|
||||
--hash=sha256:4358b9c8c0125b460407f3017c6cce8156e904b32772c5630d27112f52bdbfe5 \
|
||||
--hash=sha256:444889f7f66b74e4455c0a97e0e166dd41177f1dca8c0239a47cff25e05ba7e1 \
|
||||
--hash=sha256:44f21e407b278efdfc1ee5e481e00518bd1d500310a30a5fbf2bcbedfef4aaf0 \
|
||||
--hash=sha256:4cc4f73aa3fabc36e32046d6cd2971405948d8a903636508a3d3b2f9128b3a95 \
|
||||
--hash=sha256:4dbbd1155ca46e6e0b6b89d204428c56ef6a459af21333f365d135a2820e5a09 \
|
||||
--hash=sha256:4ee546b9e4872ffa194bf07ac87bfa1202ebb824d0795dc1ef22f175545ca90a \
|
||||
--hash=sha256:5139009b5efd2194fc168ee9362f0e191ba612ef5d29242f9269c22f9b8f80c7 \
|
||||
--hash=sha256:5375ebd99038021b35e99dc88255022912c06565d316212f4a576e4b08d30f5d \
|
||||
--hash=sha256:5397e21a90dde0e9c6896b77ded8f0be26b66f8b22b33aed41f6043ed95d55e6 \
|
||||
--hash=sha256:57ff3783f99d75a1e81dd56a9737eb5665e6736a5d93258ba596b6dcad8fd05b \
|
||||
--hash=sha256:58d4a54c6ea672afef66d49be922a2c69826c5ae1a42a9cd94f0c9c2bacdf800 \
|
||||
--hash=sha256:59c3926585e1cd1f2190f4b2ac9014de1bbeaf0d5d0587b0dc6b0aa90d17896a \
|
||||
--hash=sha256:5a27b731c171e43dc8b5f32b76a5051dde2ec9b9366c87028f08a7088ebc2c7b \
|
||||
--hash=sha256:5b3146d2317c75f70df2509066d979dadd941f7021cdf9b5db4bcd8568258e25 \
|
||||
--hash=sha256:5dca0bb66b4c3d624ba047887bf70270030c150692d543cb501293dc38a9f4b5 \
|
||||
--hash=sha256:611a44e5229a59d7483ce830160e1a0e85f700562c7a5651c7c63fb8f4eb528c \
|
||||
--hash=sha256:648352b94507179d82637292e7ae8802508d95f78e2f00a705a50b6c48011681 \
|
||||
--hash=sha256:6a75180829efb8ae62b4aded25be6ddca1c888d138d2d82e21d93bfbd88f41cb \
|
||||
--hash=sha256:705e5af11d34647efdc170c7840b6857c81cf74be96419a553f237e68e62cb72 \
|
||||
--hash=sha256:723dcdab91357159b722935b500ee8abc0a66c8c432e1e9fabf4cc7598952de8 \
|
||||
--hash=sha256:724bd0f1e81856b35e59fc98cf7b4e544a3cb662e4e0864dca73d4326ee9d808 \
|
||||
--hash=sha256:732d950e51f3ba4fb6209c73250f3e8924fefca42953ee04a9e65d8c02414d7d \
|
||||
--hash=sha256:736fde09ea39646d11f8e3b76bd3425c075aa4dd45f24891970bb77c14ff20f5 \
|
||||
--hash=sha256:7a076277ca9f5750cc230f0f578ebd2620cec60255b25707361699fef6fb465c \
|
||||
--hash=sha256:7b3bce4a0d05401d70b7d0d5ca783e686bc9d30e81dbd7d980d532609bf809e4 \
|
||||
--hash=sha256:7b451c68218c150f616bc9649783ec8de76a59792c759b43aa0c9c0466a465e4 \
|
||||
--hash=sha256:7d0732c83746bc24123c581a85d9dd96b70ddb538c9076020aa1a041790361e9 \
|
||||
--hash=sha256:7ed238d227e23cc300c3d464babdaf9f6ddc740aa1b15a77ae96136e6a7c4516 \
|
||||
--hash=sha256:80d3f7b48d43ee8fc5e8707a8adb43d743a5a1a85256c25a24f9d6d0e2238fa6 \
|
||||
--hash=sha256:80e9fdb4c3d926b6ba721d4bf7435bdb869c3527ae7803290361d0ab73db13b6 \
|
||||
--hash=sha256:848893e1d361448c113dc2f0913503522a6f7be231d0e38333d2a22d9698a011 \
|
||||
--hash=sha256:893ea9cf86cb8d2546812ac93d973aaf2ee1fb45110a873b014214fd23e3725e \
|
||||
--hash=sha256:8afd9bf35cc6a1f22eb3634808fa8e0b91902459c5721ef2e4461dfe771d7f08 \
|
||||
--hash=sha256:8be099e979fc42559328a21828281b4578304191ae46ed4e80a407048a82eee6 \
|
||||
--hash=sha256:8e209591f7c41ae4a9171335cf6156afda0b21de73b02f73f5aa95b2d5fbb08d \
|
||||
--hash=sha256:8fc15cc8d0d06e873c00ef18e1372d605f9aaf3de27d8c24e50782e75bc8b843 \
|
||||
--hash=sha256:9174f0af24e5eff248b9dbfe76ec5275a3d19d37edbc2810543f12cf97347a34 \
|
||||
--hash=sha256:921415102a90637fcc2e3f169f61dad7699ecf690e8639fc21b813acbedc0967 \
|
||||
--hash=sha256:967d72c835d7a8cf0af99ec813a2d06e3db6df706402f1fe85b31b437645f495 \
|
||||
--hash=sha256:98d9c97f51b334b0adce7b964442a9af33c1a00c6ac856984cc5dc8d18f81c75 \
|
||||
--hash=sha256:99704f73721e23859112072d522076e11c31744fc96b5652e5dd2018aa4359f7 \
|
||||
--hash=sha256:9a75a4704ff640e46170042eec1f984385a121227c505d5a16ad8e495f452541 \
|
||||
--hash=sha256:9acc7f7ec4a1b5f89bd929fde5b8a714f6fafdc6cc18725413d510aa082b47ad \
|
||||
--hash=sha256:9c6afdd69218202bc1758c9a14b86b8cf1084f37ed2ca143e567a103772b16d1 \
|
||||
--hash=sha256:9cdf19874e0d247f32f03609200370343c3c7aa260b191d8c2bb251d36198283 \
|
||||
--hash=sha256:9e1d0ced76318bab499693ff25f64faa343415187cb2e4d7befdfdd391a1cf6a \
|
||||
--hash=sha256:9fd670ac43b709c575aefc25bf52d8a598a3bc5017bddfd0a179152ab06a2deb \
|
||||
--hash=sha256:a0f2285329dac10ab08f79cb11f5692c497018e6c7c511f95e6fd63a70b8f831 \
|
||||
--hash=sha256:a2fac6895eb299a2e52d7bbb8fb3903502b9da8d3f5309ceb16ec40c646b58ee \
|
||||
--hash=sha256:a336eec40e3520d369b8a6cdabb4f596e69a8b42927ca074aa1452fed943238a \
|
||||
--hash=sha256:a4624f80732f6b427ac58f1f59c577a0994a12e8174b5af6a027b4b58795d4c3 \
|
||||
--hash=sha256:a56ac4fa5a75c7e182e8f62600cfb4aff43c5ed7356a034f3557659c3bec1d90 \
|
||||
--hash=sha256:a678c0b6b22086ec2427359d22e37445d4a792f5fdbbc744112c7dade65cad02 \
|
||||
--hash=sha256:a740ea6f083c6db7b926534d159508f80ba275ab35e722522de0d18d0f56e55f \
|
||||
--hash=sha256:a90700f743e29aa3d75a6ff5f01953176a889c00e526194bc4d281731b88d99d \
|
||||
--hash=sha256:a9a638be322a8d76a41cdb17781c7f82aaee6a66493d8ffb7e2c09ee22423d99 \
|
||||
--hash=sha256:a9cd3de0a5bfe7b0e21ee10e1a14e3d61bf52efc88217ab1d95d6ace6970bd46 \
|
||||
--hash=sha256:aa62c85046473959c13ba9edca9dc90a77d5c1095b1ba313556314d77fe5b036 \
|
||||
--hash=sha256:aba5c63b7afdc749cc9eae943d5b868cba2b261a176378fa1c5a30bc8bc89982 \
|
||||
--hash=sha256:ac0f3b379c94acc2f7dce5f5f0b24d44fa1cc6a509717ef83dfee07450c2117c \
|
||||
--hash=sha256:af2a2a8c7c74de0559e0c368d94c8def9e16c58faaee33a0bf081057c4227e3b \
|
||||
--hash=sha256:af98ad5ed9d6daaca956201e00bb429a7eb2b080426686f70a20353e0f9839f5 \
|
||||
--hash=sha256:afdf43b72ef3876c1fe66423b91466e37877c9e81e8cec70542b7e8525b9d1b7 \
|
||||
--hash=sha256:b88841e654f09732804809e435b3e005a929ffd9998b872b7b213957b8759cb8 \
|
||||
--hash=sha256:bb2fc905bbf4e6b7f40806ea79e31515abf6349594cdf0adf27c4215f0463204 \
|
||||
--hash=sha256:bb4ffe96aa663cee727659db5a2afeb38c95f8677b747d447b90d6d4874ea2c5 \
|
||||
--hash=sha256:bc0b0ac781d489304b741269857f1f8338b7a26b1b89c06c0344658001ec0035 \
|
||||
--hash=sha256:bf1bd822ec4e387ed245bed0d71151582cf7be9e5309bc4145eefe36083d5878 \
|
||||
--hash=sha256:c19cd6d025c1673f22afcd22c7df8a662d779e05d8e3fa6820c22afb895b0206 \
|
||||
--hash=sha256:c3305c38a2fa21a4254f2ace7dd9ef5fc569c9a558b66e7017650b3d637fb95e \
|
||||
--hash=sha256:c85d54e7e8a2ca932fe8399301af9b8d5907ea2a455ffaff6e7d1208db83b943 \
|
||||
--hash=sha256:ca64d9f1f384f151b9511bec01126072acd2f313439f8ed015a22d8790aab6fa \
|
||||
--hash=sha256:cce2bc991293f15cc4084ca116827b5900c5f34e1a54dfe83f10ab5c43162eb7 \
|
||||
--hash=sha256:d6276d78f6fca7d0ac066d5da4165c5acd07829e8305c2cb900b738fb3a75a72 \
|
||||
--hash=sha256:d93db87adb6b1c1b408dce4763314b55d76a9f589e96783a84ac9e7689e48bdf \
|
||||
--hash=sha256:db5f8394e17f877a625b257f2ba0ce8e728a499c2c1579ad66220272cd3df510 \
|
||||
--hash=sha256:db76506aa5416081f3e8974ae0f7965c58ada0bb0ef7339ac86099588dbb20d3 \
|
||||
--hash=sha256:dba2edfb054f6d4a08df9d1637c39a5aa3865bca6617c13c86be21e45658a59c \
|
||||
--hash=sha256:dcf4bc2aab4e16b1c4c0c2005918f23a7dd5d7821ddae82caed9e3342dc2fcce \
|
||||
--hash=sha256:e1fa594c887365b69745f25a416806e61085dd07b94c9eae68a6e20730629b23 \
|
||||
--hash=sha256:e6c52d3307824ff93b39efd99e4185d557db40bd841452abfb32e5d9151ca162 \
|
||||
--hash=sha256:eb57acff4a74246ae513c142d4b36e18c389c3aed8661914a53f7cd0071031b2 \
|
||||
--hash=sha256:f80bd9f9633eafc73d0a913ba2645c96ba58bba1befc30590f7c0fbfde59d865 \
|
||||
--hash=sha256:f8475460aa33ee28ac896ab1156d0bb3b6c639f7f8383c2677d3359eb35f8205 \
|
||||
--hash=sha256:fb2bde05838fffae1a1bf75e5d411a6cac3e4e9bb97e6640fed8cd47888b33f0 \
|
||||
--hash=sha256:fb9d92ecfe2d5b494367c67f7446f8b75b68d8d0c8cf3bc3e6997478be25d9e2 \
|
||||
--hash=sha256:fd3d72233eb8b48acc94fa57d44e2d32ce8e7abed02882ccb6d855ccc4ed33ec
|
||||
# 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.1.1 \
|
||||
--hash=sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313 \
|
||||
--hash=sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c
|
||||
# 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.1 \
|
||||
--hash=sha256:056c5d5fa0ac790051ae165d7035c7bf956d02de2db557f2e9b31d877a505fca \
|
||||
--hash=sha256:1796c41eafec66f4635125dd1e074a7aa27b8d20c187d484360acf11d247fc4a \
|
||||
--hash=sha256:1de0030a8aa78c65c5fecb84b2e5c390ac684c0452875a02afc7c083d49a496a \
|
||||
--hash=sha256:29b454f18ca3eeaf37fbf140841dcf27d36109e29dee9aae8acecb68c26c6f74 \
|
||||
--hash=sha256:42400b9a6ff8515ff27796f07f92e0195be011c86e81e381606f58ea5502fef4 \
|
||||
--hash=sha256:4c0d6cb5f8fbac77eec9af49f4fc0eaf856b05545e372b0694d24b4e76b1c640 \
|
||||
--hash=sha256:5bb796c5112e9fb9527f2ef2faa0a130d6312d19de92bcfaddd70dbb2d41020f \
|
||||
--hash=sha256:5df76f16580fab58d0f6c98a3ac254a4abceb7b2489b8b678335869cff77b3d7 \
|
||||
--hash=sha256:684154861a819bf1f433669d2a0ce9c3e54677c65b8ebb866cc2a7ec86345785 \
|
||||
--hash=sha256:78beced4a3c94dfedbee4b999b95b6a27b35820fdc0afbacc6d37a8da26c1cd1 \
|
||||
--hash=sha256:7feefc63921202894f0e158b0e32f45a5950d70a7fb693ccb9264816c25b1c05 \
|
||||
--hash=sha256:80e53b0e5faa3c5667f035daaa032893ae42b7cfe708c886d39ed131e54688ab \
|
||||
--hash=sha256:872e03dd231744d6c5ec5c8af6be52b71323fc6ee096e4c8b34d9f844ee3b978 \
|
||||
--hash=sha256:8eadb09a788010be29c895418bdfa513e4e1c65e64b94e5b19e4cd381f6cc7fb \
|
||||
--hash=sha256:8f9aa5b5bd5fa1937803ea609c8f153b8de39bf3e0e149897ae34b0c5b52f467 \
|
||||
--hash=sha256:a6ef98e51de8ef38082f90653ceeb84944bd7673783eea13e1647c5b9b064189 \
|
||||
--hash=sha256:bd8f5a55b10f371642eacd0e8665a42a8b97da15c9a7187c79e697b77b5e0ce4 \
|
||||
--hash=sha256:ce05e6f3973611d9550a600e04bb531061e368baba31610eb57c1509a8f21a0a
|
||||
# via -r requirements-dev.in
|
||||
@@ -1,53 +0,0 @@
|
||||
"""
|
||||
Configuration constants loaded from environment variables.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
_REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
# YouTube
|
||||
YOUTUBE_CHANNEL_ID = os.environ.get("YOUTUBE_CHANNEL_ID", "").strip()
|
||||
YOUTUBE_RSS_URL = f"https://www.youtube.com/feeds/videos.xml?channel_id={YOUTUBE_CHANNEL_ID}"
|
||||
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"))
|
||||
|
||||
# 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)"
|
||||
HTTP_TIMEOUT = 30
|
||||
|
||||
# Telegram
|
||||
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
||||
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")
|
||||
|
||||
# Bluesky
|
||||
BLUESKY_HANDLE = os.environ.get("BLUESKY_HANDLE", "")
|
||||
BLUESKY_APP_PASSWORD = os.environ.get("BLUESKY_APP_PASSWORD", "")
|
||||
|
||||
# Discord
|
||||
DISCORD_WEBHOOK_URL = os.environ.get("DISCORD_WEBHOOK_URL", "").strip()
|
||||
|
||||
# Mastodon
|
||||
MASTODON_INSTANCE_URL = os.environ.get("MASTODON_INSTANCE_URL", "").strip().rstrip("/")
|
||||
MASTODON_ACCESS_TOKEN = os.environ.get("MASTODON_ACCESS_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")
|
||||
|
||||
# Max IDs to keep in state file
|
||||
MAX_STATE_IDS = 100
|
||||
|
||||
# XML namespaces for YouTube RSS
|
||||
NS = {
|
||||
"atom": "http://www.w3.org/2005/Atom",
|
||||
"yt": "http://www.youtube.com/xml/schemas/2015",
|
||||
"media": "http://search.yahoo.com/mrss/",
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
"""
|
||||
Thin urllib wrapper shared by every platform module.
|
||||
|
||||
One request path, one exception type. Callers catch `HttpError` and decide what the
|
||||
status means for them. The URL is kept on the exception but left out of its message
|
||||
because several endpoints carry credentials in the path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from config import HTTP_TIMEOUT, USER_AGENT
|
||||
|
||||
|
||||
class HttpError(Exception):
|
||||
"""Non-2xx response (`status` > 0) or transport failure (`status` == 0)."""
|
||||
|
||||
def __init__(self, status: int, body: str, url: str) -> None:
|
||||
self.status = status
|
||||
self.body = body
|
||||
self.url = url
|
||||
detail = body.strip()[:300]
|
||||
super().__init__(f"HTTP {status} — {detail}" if status else f"connection error — {detail}")
|
||||
|
||||
|
||||
def _request(
|
||||
url: str,
|
||||
*,
|
||||
data: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
method: str | None = None,
|
||||
timeout: int = HTTP_TIMEOUT,
|
||||
) -> tuple[bytes, dict[str, str]]:
|
||||
"""Perform a request. Returns (body, lower-cased response headers)."""
|
||||
if not url.startswith("https://"):
|
||||
raise ValueError("Refusing non-HTTPS URL")
|
||||
req = Request( # noqa: S310 — scheme checked above
|
||||
url, data=data, headers={"User-Agent": USER_AGENT, **(headers or {})}, method=method
|
||||
)
|
||||
try:
|
||||
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:
|
||||
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
|
||||
|
||||
|
||||
def _as_dict(body: bytes) -> dict:
|
||||
"""Parse a JSON body. Empty bodies (e.g. Discord 204) become {}."""
|
||||
if not body.strip():
|
||||
return {}
|
||||
try:
|
||||
parsed = json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
return {"_raw": body.decode("utf-8", errors="replace")}
|
||||
return parsed if isinstance(parsed, dict) else {"_data": parsed}
|
||||
|
||||
|
||||
def get_text(url: str, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT) -> str:
|
||||
body, _ = _request(url, headers=headers, timeout=timeout)
|
||||
return body.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def get_bytes(
|
||||
url: str, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT
|
||||
) -> tuple[bytes, str]:
|
||||
"""Returns (body, content-type)."""
|
||||
body, resp_headers = _request(url, headers=headers, timeout=timeout)
|
||||
return body, resp_headers.get("content-type", "application/octet-stream")
|
||||
|
||||
|
||||
def post_json(
|
||||
url: str, payload: dict, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT
|
||||
) -> dict:
|
||||
body, _ = _request(
|
||||
url,
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json", **(headers or {})},
|
||||
method="POST",
|
||||
timeout=timeout,
|
||||
)
|
||||
return _as_dict(body)
|
||||
|
||||
|
||||
def post_form(
|
||||
url: str, fields: dict, headers: dict[str, str] | None = None, timeout: int = HTTP_TIMEOUT
|
||||
) -> dict:
|
||||
body, _ = _request(
|
||||
url,
|
||||
data=urlencode(fields).encode("utf-8"),
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded", **(headers or {})},
|
||||
method="POST",
|
||||
timeout=timeout,
|
||||
)
|
||||
return _as_dict(body)
|
||||
|
||||
|
||||
def post_bytes(
|
||||
url: str,
|
||||
data: bytes,
|
||||
content_type: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
timeout: int = HTTP_TIMEOUT,
|
||||
) -> dict:
|
||||
body, _ = _request(
|
||||
url,
|
||||
data=data,
|
||||
headers={"Content-Type": content_type, **(headers or {})},
|
||||
method="POST",
|
||||
timeout=timeout,
|
||||
)
|
||||
return _as_dict(body)
|
||||
@@ -1,53 +0,0 @@
|
||||
"""
|
||||
Notification text shared by every platform.
|
||||
|
||||
Platforms differ only in markup (bold, hashtags) and length limits, so the body is
|
||||
built here once and each platform decorates it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
HEADER = "🎬 New Video / Video Mới"
|
||||
PLAY = "▶️"
|
||||
ELLIPSIS = "…"
|
||||
|
||||
BLUESKY_MAX_GRAPHEMES = 300
|
||||
|
||||
|
||||
def build_message(
|
||||
video: dict, *, hashtags: str = "", title: str | None = None, header: str = HEADER
|
||||
) -> str:
|
||||
"""Header, title, play line, optional hashtags — separated by blank lines."""
|
||||
parts = [header, video["title"] if title is None else title, f"{PLAY} {video['url']}", hashtags]
|
||||
return "\n\n".join(p for p in parts if p)
|
||||
|
||||
|
||||
def truncate(text: str, max_len: int, suffix: str = ELLIPSIS) -> str:
|
||||
"""Cut `text` to at most `max_len` code points, ending with `suffix` when cut."""
|
||||
if len(text) <= max_len:
|
||||
return text
|
||||
if max_len <= len(suffix):
|
||||
return text[:max_len]
|
||||
return text[: max_len - len(suffix)].rstrip() + suffix
|
||||
|
||||
|
||||
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)
|
||||
if measure(text) <= limit:
|
||||
return text
|
||||
title = video["title"]
|
||||
budget = len(title)
|
||||
while budget > 0:
|
||||
budget -= 1
|
||||
text = build_message(video, hashtags=hashtags, title=truncate(title, budget))
|
||||
if measure(text) <= limit:
|
||||
return text
|
||||
return build_message(video, hashtags=hashtags, title="")
|
||||
|
||||
|
||||
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)
|
||||
@@ -1,98 +0,0 @@
|
||||
"""
|
||||
YouTube Auto-Post Notification Script
|
||||
|
||||
Polls the YouTube RSS feed for recently published videos and posts to:
|
||||
- Telegram (Bot API)
|
||||
- Bluesky (AT Protocol)
|
||||
- Discord (Webhook, optional)
|
||||
- Mastodon (REST API, optional)
|
||||
|
||||
Exit code is 1 when any configured platform failed, so the CI-failure notifier fires.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from config import LOOKBACK_HOURS, YOUTUBE_CHANNEL_ID
|
||||
from http_client import HttpError
|
||||
from platforms import post_to_all, summarize
|
||||
from state import load_posted_ids, save_posted_ids
|
||||
from youtube import fetch_feed, is_public, select_recent
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not YOUTUBE_CHANNEL_ID:
|
||||
print("[ERROR] YOUTUBE_CHANNEL_ID not set.")
|
||||
return 1
|
||||
|
||||
now = datetime.now(UTC)
|
||||
print(f"[INFO] Checking YouTube RSS for channel: {YOUTUBE_CHANNEL_ID}")
|
||||
|
||||
try:
|
||||
videos = fetch_feed()
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Failed to fetch RSS: {e}")
|
||||
return 1
|
||||
|
||||
recent = select_recent(videos, now=now, lookback_hours=LOOKBACK_HOURS)
|
||||
if not recent:
|
||||
print(f"[INFO] No videos published in the last {LOOKBACK_HOURS}h. Exiting.")
|
||||
return 0
|
||||
|
||||
posted_ids = load_posted_ids()
|
||||
new_videos = [v for v in recent if v["video_id"] not in posted_ids]
|
||||
if not new_videos:
|
||||
print("[INFO] All recent videos already posted. Exiting.")
|
||||
return 0
|
||||
|
||||
print(f"[INFO] Found {len(new_videos)} new video(s) to post.")
|
||||
|
||||
successfully_posted: list[str] = []
|
||||
had_failure = False
|
||||
attempted = 0
|
||||
|
||||
for i, video in enumerate(new_videos):
|
||||
if i > 0:
|
||||
delay = random.uniform(1, 5) # noqa: S311 — pacing only
|
||||
print(f"[INFO] Waiting {delay:.1f}s before next video...")
|
||||
time.sleep(delay)
|
||||
|
||||
print(f"\n[INFO] Video {i + 1}/{len(new_videos)}: {video['title']}")
|
||||
if not is_public(video["video_id"], now=now):
|
||||
print(f"[INFO] Skipping '{video['video_id']}' for now; will retry next run.")
|
||||
continue
|
||||
|
||||
attempted += 1
|
||||
results = post_to_all(video)
|
||||
any_ok, any_failed = summarize(results)
|
||||
for platform, status in results.items():
|
||||
print(f" {platform}: {status.value}")
|
||||
|
||||
if any_ok:
|
||||
successfully_posted.append(video["video_id"])
|
||||
else:
|
||||
print(f"[WARN] No platform posted '{video['video_id']}'. Will retry next run.")
|
||||
if any_failed:
|
||||
had_failure = True
|
||||
|
||||
if successfully_posted:
|
||||
save_posted_ids(successfully_posted)
|
||||
print(f"\n[INFO] State saved: {len(successfully_posted)} new ID(s).")
|
||||
|
||||
print(f"\n[SUMMARY] {len(successfully_posted)}/{len(new_videos)} videos posted.")
|
||||
|
||||
if had_failure:
|
||||
print("[ERROR] At least one configured platform failed.")
|
||||
return 1
|
||||
if attempted and not successfully_posted:
|
||||
print("[ERROR] No platform is configured; nothing was posted.")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,26 +0,0 @@
|
||||
"""
|
||||
Platform registry. Each module exposes a post(video) -> PostStatus function.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from platforms import bluesky, discord, mastodon, telegram
|
||||
from platforms.base import PostStatus
|
||||
|
||||
PLATFORMS = [
|
||||
("telegram", telegram.post),
|
||||
("bluesky", bluesky.post),
|
||||
("discord", discord.post),
|
||||
("mastodon", mastodon.post),
|
||||
]
|
||||
|
||||
|
||||
def post_to_all(video: dict) -> dict[str, PostStatus]:
|
||||
"""Post video to all platforms. Returns {platform_name: status}."""
|
||||
return {name: post_fn(video) for name, post_fn in PLATFORMS}
|
||||
|
||||
|
||||
def summarize(results: dict[str, PostStatus]) -> tuple[bool, bool]:
|
||||
"""Returns (any_ok, any_failed)."""
|
||||
statuses = set(results.values())
|
||||
return PostStatus.OK in statuses, PostStatus.FAILED in statuses
|
||||
@@ -1,9 +0,0 @@
|
||||
"""Shared result type for platform modules."""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class PostStatus(Enum):
|
||||
OK = "OK"
|
||||
SKIPPED = "skipped" # platform not configured
|
||||
FAILED = "FAILED" # configured, but the request failed
|
||||
@@ -1,114 +0,0 @@
|
||||
"""Bluesky AT Protocol integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from config import BLUESKY_APP_PASSWORD, BLUESKY_HANDLE
|
||||
from http_client import HttpError, get_bytes, post_bytes, post_json
|
||||
from message import fit_bluesky
|
||||
from platforms.base import PostStatus
|
||||
|
||||
_PDS = "https://bsky.social/xrpc"
|
||||
_session: dict | None = None
|
||||
|
||||
|
||||
def reset_session() -> None:
|
||||
global _session
|
||||
_session = None
|
||||
|
||||
|
||||
def _get_session() -> dict:
|
||||
"""Authenticate once per process. Raises HttpError on failure."""
|
||||
global _session
|
||||
if _session is None:
|
||||
_session = post_json(
|
||||
f"{_PDS}/com.atproto.server.createSession",
|
||||
{"identifier": BLUESKY_HANDLE, "password": BLUESKY_APP_PASSWORD},
|
||||
)
|
||||
return _session
|
||||
|
||||
|
||||
def _auth(session: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {session['accessJwt']}"}
|
||||
|
||||
|
||||
def _upload_thumbnail(session: dict, image_url: str) -> dict | None:
|
||||
"""Download thumbnail and upload as blob. Best effort."""
|
||||
if not image_url:
|
||||
return None
|
||||
try:
|
||||
image_data, content_type = get_bytes(image_url)
|
||||
except HttpError as e:
|
||||
print(f"[WARN] Bluesky: failed to download thumbnail ({e}).")
|
||||
return None
|
||||
try:
|
||||
result = post_bytes(
|
||||
f"{_PDS}/com.atproto.repo.uploadBlob", image_data, content_type, headers=_auth(session)
|
||||
)
|
||||
except HttpError as e:
|
||||
print(f"[WARN] Bluesky: thumbnail upload failed ({e}).")
|
||||
return None
|
||||
return result.get("blob")
|
||||
|
||||
|
||||
def build_record(video: dict, thumb_blob: dict | None, now: datetime) -> dict:
|
||||
text = fit_bluesky(video)
|
||||
|
||||
# Facet makes the URL clickable; offsets are in UTF-8 bytes.
|
||||
url_start = text.index(video["url"])
|
||||
byte_start = len(text[:url_start].encode("utf-8"))
|
||||
byte_end = byte_start + len(video["url"].encode("utf-8"))
|
||||
|
||||
embed = {
|
||||
"$type": "app.bsky.embed.external",
|
||||
"external": {
|
||||
"uri": video["url"],
|
||||
"title": video["title"],
|
||||
"description": video.get("description", ""),
|
||||
},
|
||||
}
|
||||
if thumb_blob:
|
||||
embed["external"]["thumb"] = thumb_blob
|
||||
|
||||
return {
|
||||
"$type": "app.bsky.feed.post",
|
||||
"text": text,
|
||||
"facets": [
|
||||
{
|
||||
"index": {"byteStart": byte_start, "byteEnd": byte_end},
|
||||
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": video["url"]}],
|
||||
}
|
||||
],
|
||||
"embed": embed,
|
||||
"createdAt": now.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def post(video: dict) -> PostStatus:
|
||||
"""Post to Bluesky with link card and optional thumbnail."""
|
||||
if not BLUESKY_HANDLE or not BLUESKY_APP_PASSWORD:
|
||||
print("[SKIP] Bluesky: missing handle or app password.")
|
||||
return PostStatus.SKIPPED
|
||||
|
||||
try:
|
||||
session = _get_session()
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Bluesky auth: {e}")
|
||||
return PostStatus.FAILED
|
||||
|
||||
thumb_blob = _upload_thumbnail(session, video.get("thumbnail", ""))
|
||||
record = build_record(video, thumb_blob, datetime.now(UTC))
|
||||
|
||||
try:
|
||||
post_json(
|
||||
f"{_PDS}/com.atproto.repo.createRecord",
|
||||
{"repo": session["did"], "collection": "app.bsky.feed.post", "record": record},
|
||||
headers=_auth(session),
|
||||
)
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Bluesky post: {e}")
|
||||
return PostStatus.FAILED
|
||||
|
||||
print("[OK] Bluesky: posted successfully.")
|
||||
return PostStatus.OK
|
||||
@@ -1,68 +0,0 @@
|
||||
"""Discord Webhook integration (optional)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from config import DISCORD_WEBHOOK_URL
|
||||
from http_client import HttpError, post_json
|
||||
from message import HEADER, build_message
|
||||
from platforms.base import PostStatus
|
||||
|
||||
_MARKDOWN_RE = re.compile(r"([\\*_~`])")
|
||||
|
||||
|
||||
def escape_markdown(text: str) -> str:
|
||||
"""Backslash-escape the inline markdown Discord would otherwise render."""
|
||||
return _MARKDOWN_RE.sub(r"\\\1", text)
|
||||
|
||||
|
||||
def normalize_webhook_url(url: str) -> str:
|
||||
"""Normalize Discord webhook URL to the API form."""
|
||||
url = url.replace("https://discordapp.com/", "https://discord.com/")
|
||||
url = url.replace("https://discord.com/webhooks/", "https://discord.com/api/webhooks/")
|
||||
return url.rstrip("/")
|
||||
|
||||
|
||||
def build_text(video: dict) -> str:
|
||||
return build_message(
|
||||
video, header=f"**{HEADER}**", title=f"**{escape_markdown(video['title'])}**"
|
||||
)
|
||||
|
||||
|
||||
def post(video: dict) -> PostStatus:
|
||||
"""Post to Discord via webhook."""
|
||||
if not DISCORD_WEBHOOK_URL:
|
||||
print("[SKIP] Discord: no webhook URL configured.")
|
||||
return PostStatus.SKIPPED
|
||||
|
||||
webhook_url = normalize_webhook_url(DISCORD_WEBHOOK_URL)
|
||||
if "/api/webhooks/" not in webhook_url:
|
||||
print(
|
||||
"[ERROR] Discord: invalid webhook URL format. "
|
||||
"Expected: https://discord.com/api/webhooks/ID/TOKEN"
|
||||
)
|
||||
return PostStatus.FAILED
|
||||
|
||||
payload = {"content": build_text(video), "username": "YouTube Notifications"}
|
||||
|
||||
try:
|
||||
post_json(webhook_url, payload)
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Discord webhook: {e}")
|
||||
if e.status == 403:
|
||||
print(
|
||||
"[HINT] 403 Forbidden — possible causes:\n"
|
||||
" 1. Webhook URL is invalid or token is wrong\n"
|
||||
" 2. Webhook was deleted from Discord\n"
|
||||
" 3. Channel type doesn't support webhooks\n"
|
||||
" 4. Re-create webhook: Server Settings → Integrations → Webhooks"
|
||||
)
|
||||
elif e.status == 404:
|
||||
print("[HINT] 404 Not Found — webhook was deleted. Create a new one.")
|
||||
elif e.status == 429:
|
||||
print("[HINT] 429 Rate Limited — too many requests. Will retry next run.")
|
||||
return PostStatus.FAILED
|
||||
|
||||
print("[OK] Discord: posted successfully.")
|
||||
return PostStatus.OK
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Mastodon REST API integration (optional)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from config import HASHTAGS, MASTODON_ACCESS_TOKEN, MASTODON_INSTANCE_URL
|
||||
from http_client import HttpError, post_form
|
||||
from message import build_message
|
||||
from platforms.base import PostStatus
|
||||
|
||||
|
||||
def post(video: dict) -> PostStatus:
|
||||
"""Post to Mastodon instance via REST API."""
|
||||
if not MASTODON_INSTANCE_URL or not MASTODON_ACCESS_TOKEN:
|
||||
print("[SKIP] Mastodon: missing instance URL or access token.")
|
||||
return PostStatus.SKIPPED
|
||||
|
||||
text = build_message(video, hashtags=HASHTAGS)
|
||||
|
||||
try:
|
||||
result = post_form(
|
||||
f"{MASTODON_INSTANCE_URL}/api/v1/statuses",
|
||||
{"status": text, "visibility": "public"},
|
||||
headers={"Authorization": f"Bearer {MASTODON_ACCESS_TOKEN}"},
|
||||
)
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Mastodon: {e}")
|
||||
if e.status == 401:
|
||||
print("[HINT] 401 Unauthorized — access token is invalid or revoked.")
|
||||
elif e.status == 422:
|
||||
print("[HINT] 422 — status might be too long or contain invalid content.")
|
||||
return PostStatus.FAILED
|
||||
|
||||
if not result.get("id"):
|
||||
print(f"[ERROR] Mastodon: unexpected response — {result}")
|
||||
return PostStatus.FAILED
|
||||
print(f"[OK] Mastodon: posted successfully (id: {result['id']}).")
|
||||
return PostStatus.OK
|
||||
@@ -1,47 +0,0 @@
|
||||
"""Telegram Bot API integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
|
||||
from config import TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
|
||||
from http_client import HttpError, post_json
|
||||
from message import HEADER, build_message
|
||||
from platforms.base import PostStatus
|
||||
|
||||
|
||||
def build_text(video: dict) -> str:
|
||||
"""HTML parse mode: only <, > and & need escaping, so titles render verbatim."""
|
||||
safe_video = {**video, "url": html.escape(video["url"], quote=False)}
|
||||
return build_message(
|
||||
safe_video,
|
||||
header=f"<b>{html.escape(HEADER, quote=False)}</b>",
|
||||
title=f"<b>{html.escape(video['title'], quote=False)}</b>",
|
||||
)
|
||||
|
||||
|
||||
def post(video: dict) -> PostStatus:
|
||||
"""Send notification to Telegram channel/group."""
|
||||
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
|
||||
print("[SKIP] Telegram: missing token or chat ID.")
|
||||
return PostStatus.SKIPPED
|
||||
|
||||
payload = {
|
||||
"chat_id": TELEGRAM_CHAT_ID,
|
||||
"text": build_text(video),
|
||||
"parse_mode": "HTML",
|
||||
"link_preview_options": {"is_disabled": False},
|
||||
}
|
||||
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
||||
|
||||
try:
|
||||
result = post_json(url, payload)
|
||||
except HttpError as e:
|
||||
print(f"[ERROR] Telegram: {e}")
|
||||
return PostStatus.FAILED
|
||||
|
||||
if not result.get("ok"):
|
||||
print(f"[ERROR] Telegram: unexpected response — {result}")
|
||||
return PostStatus.FAILED
|
||||
print("[OK] Telegram: posted successfully.")
|
||||
return PostStatus.OK
|
||||
@@ -1,70 +0,0 @@
|
||||
"""
|
||||
Print the changelog entry for one version, for use as GitHub Release notes.
|
||||
|
||||
python scripts/release_notes.py v1.2.0
|
||||
|
||||
Entries live in `changelog/<major>.x.md` under `## x.y.z — YYYY-MM-DD` headings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
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:
|
||||
return version.strip().removeprefix("v")
|
||||
|
||||
|
||||
def changelog_file(version: str, changelog_dir: Path) -> Path:
|
||||
"""`<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:
|
||||
"""Body of the `## <version> — <date>` entry, without the heading."""
|
||||
wanted = normalize_version(version)
|
||||
lines = text.splitlines()
|
||||
start: int | None = None
|
||||
for i, line in enumerate(lines):
|
||||
if start is None:
|
||||
m = HEADING_RE.match(line)
|
||||
if m and m.group("version") == wanted:
|
||||
start = i + 1
|
||||
elif line.startswith("## "):
|
||||
return "\n".join(lines[start:i]).strip() + "\n"
|
||||
if start is None:
|
||||
raise LookupError(f"No changelog entry for {wanted}")
|
||||
return "\n".join(lines[start:]).strip() + "\n"
|
||||
|
||||
|
||||
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
|
||||
try:
|
||||
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
|
||||
sys.stdout.write(section)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -1,35 +0,0 @@
|
||||
"""
|
||||
State management for tracking posted video IDs.
|
||||
|
||||
State file: one video ID per line, oldest first, capped at MAX_STATE_IDS.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from config import MAX_STATE_IDS, STATE_FILE
|
||||
|
||||
|
||||
def _read_ids(path: Path) -> list[str]:
|
||||
if not path.exists():
|
||||
return []
|
||||
return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
|
||||
|
||||
def load_posted_ids(path: Path = STATE_FILE) -> set[str]:
|
||||
"""Read all posted video IDs from the state file."""
|
||||
return set(_read_ids(path))
|
||||
|
||||
|
||||
def save_posted_ids(new_ids: list[str], path: Path = STATE_FILE) -> None:
|
||||
"""Append new IDs, keeping order and at most MAX_STATE_IDS entries."""
|
||||
combined = _read_ids(path)
|
||||
seen = set(combined)
|
||||
for vid in new_ids:
|
||||
if vid not in seen:
|
||||
combined.append(vid)
|
||||
seen.add(vid)
|
||||
combined = combined[-MAX_STATE_IDS:]
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("\n".join(combined) + "\n", encoding="utf-8")
|
||||
@@ -1,129 +0,0 @@
|
||||
"""
|
||||
YouTube RSS feed fetching, filtering and visibility checks.
|
||||
|
||||
The feed lists the channel's 15 most recent uploads, including scheduled Premieres
|
||||
that are not public yet (their `published` value is the upload time until they go
|
||||
live). So besides a time window, each candidate is checked against its watch page
|
||||
before it is announced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from config import NS, YOUTUBE_RSS_URL, YOUTUBE_WATCH_URL
|
||||
from http_client import HttpError, get_text
|
||||
|
||||
# YouTube serves the full player metadata only to browser-like user agents.
|
||||
_WATCH_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) YouTubeAutoPost/1.2",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
}
|
||||
|
||||
# Allow a little clock skew between YouTube and the runner.
|
||||
FUTURE_GRACE = timedelta(minutes=5)
|
||||
|
||||
_UPCOMING_FLAG = '"isUpcoming":true'
|
||||
_START_DATE_RE = re.compile(r'itemprop="startDate"\s+content="([^"]+)"')
|
||||
_PLAYABILITY_RE = re.compile(r'"playabilityStatus":\{"status":"([A-Z_]+)"')
|
||||
_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:
|
||||
print(f"[ERROR] Could not parse RSS feed: {e}")
|
||||
return []
|
||||
return [_parse_entry(entry) for entry in root.findall("atom:entry", NS)]
|
||||
|
||||
|
||||
def fetch_feed() -> list[dict]:
|
||||
"""Fetch and parse the channel feed. Raises HttpError on transport failure."""
|
||||
return parse_feed(get_text(YOUTUBE_RSS_URL))
|
||||
|
||||
|
||||
def _parse_entry(entry: ET.Element) -> dict:
|
||||
video_id = entry.find("yt:videoId", NS)
|
||||
title = entry.find("atom:title", NS)
|
||||
link = entry.find("atom:link", NS)
|
||||
published = entry.find("atom:published", NS)
|
||||
media_group = entry.find("media:group", NS)
|
||||
|
||||
description = ""
|
||||
thumbnail = ""
|
||||
if media_group is not None:
|
||||
desc_el = media_group.find("media:description", NS)
|
||||
if desc_el is not None and desc_el.text:
|
||||
description = desc_el.text[:200]
|
||||
thumb_el = media_group.find("media:thumbnail", NS)
|
||||
if thumb_el is not None:
|
||||
thumbnail = thumb_el.get("url", "")
|
||||
|
||||
return {
|
||||
"video_id": (video_id.text or "") if video_id is not None else "",
|
||||
"title": (title.text or "Untitled") if title is not None else "Untitled",
|
||||
"url": link.get("href", "") if link is not None else "",
|
||||
"published": (published.text or "") if published is not None else "",
|
||||
"description": description,
|
||||
"thumbnail": thumbnail,
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
return None
|
||||
return dt if dt.tzinfo else dt.replace(tzinfo=UTC)
|
||||
|
||||
|
||||
def select_recent(videos: list[dict], *, now: datetime, lookback_hours: int) -> list[dict]:
|
||||
"""Videos published within the lookback window, oldest first."""
|
||||
lower = now - timedelta(hours=lookback_hours)
|
||||
upper = now + FUTURE_GRACE
|
||||
dated: list[tuple[datetime, dict]] = []
|
||||
for video in videos:
|
||||
published = parse_timestamp(video.get("published", ""))
|
||||
if published is None:
|
||||
print(f"[WARN] Bad date for {video.get('video_id')}: {video.get('published')!r}")
|
||||
continue
|
||||
if lower <= published <= upper:
|
||||
dated.append((published, video))
|
||||
dated.sort(key=lambda pair: pair[0])
|
||||
return [video for _, video in dated]
|
||||
|
||||
|
||||
def is_public_html(html: str, *, now: datetime) -> tuple[bool, str]:
|
||||
"""Inspect a watch page. Returns (public, reason-if-not)."""
|
||||
if _UPCOMING_FLAG in html:
|
||||
return False, "flagged as upcoming"
|
||||
m = _START_DATE_RE.search(html)
|
||||
if m:
|
||||
start = parse_timestamp(m.group(1))
|
||||
if start is not None and start > now:
|
||||
return False, f"premieres at {start.isoformat()}"
|
||||
m = _PLAYABILITY_RE.search(html)
|
||||
if m is None:
|
||||
print("[WARN] Watch page has no playability marker; assuming public.")
|
||||
elif m.group(1) in _NOT_PUBLIC_PLAYABILITY:
|
||||
return False, f"playability {m.group(1)}"
|
||||
return True, ""
|
||||
|
||||
|
||||
def is_public(video_id: str, *, now: datetime) -> bool:
|
||||
"""True when the video can be watched now. Fails open on network errors."""
|
||||
url = YOUTUBE_WATCH_URL.format(video_id=video_id)
|
||||
try:
|
||||
html = get_text(url, headers=_WATCH_HEADERS)
|
||||
except HttpError as e:
|
||||
print(f"[WARN] Could not check visibility of {video_id} ({e}); assuming public.")
|
||||
return True
|
||||
public, reason = is_public_html(html, now=now)
|
||||
if not public:
|
||||
print(f"[INFO] Video {video_id} is not public yet ({reason}).")
|
||||
return public
|
||||
@@ -1,37 +0,0 @@
|
||||
# SonarQube Cloud, CI-based analysis: the `sonar` job in .github/workflows/ci.yml
|
||||
# reads this file on every PR and every push to main
|
||||
# (https://sonarcloud.io/project/overview?id=poli0981_youtube-auto-post).
|
||||
# Automatic Analysis is switched off on sonarcloud.io: the two can't run together.
|
||||
sonar.organization=poli0981
|
||||
sonar.projectKey=poli0981_youtube-auto-post
|
||||
sonar.projectName=youtube-auto-post
|
||||
sonar.sourceEncoding=UTF-8
|
||||
|
||||
# The bot runs on Python 3.15 (every workflow's setup-python), but SonarQube
|
||||
# Cloud's Python analyzer stops at 3.14: given 3.15 it warns "No explicit support
|
||||
# for version 3.15" and falls back to 3.14. Raise this once it supports 3.15.
|
||||
# Leaving it unset is worse: Sonar then also reads the code as Python 2, where
|
||||
# `except A, B:` (PEP 758, Python 3.14+) means something else.
|
||||
sonar.python.version=3.14
|
||||
|
||||
# The whole repository, as Automatic Analysis read it, with the tests as tests.
|
||||
sonar.sources=.
|
||||
sonar.exclusions=tests/**
|
||||
sonar.tests=tests
|
||||
|
||||
# Written by the `test` job (`pytest --cov --cov-report=xml`; settings in
|
||||
# [tool.coverage.*] of pyproject.toml, with relative paths the scanner resolves).
|
||||
sonar.python.coverage.reportPaths=coverage.xml
|
||||
|
||||
# The scan waits for the quality gate and fails the job when the gate fails, so
|
||||
# the required `ci` check goes red with it.
|
||||
sonar.qualitygate.wait=true
|
||||
|
||||
# Accepted findings. Each names its rule and file and says why; anything not
|
||||
# listed here gets fixed, not ignored (the same rule as .github/zizmor.yml).
|
||||
sonar.issue.ignore.multicriteria=xmlns
|
||||
# python:S5332 (clear-text HTTP) on the RSS feed's XML namespace names in NS.
|
||||
# They are identifiers that must equal the feed's xmlns attributes, never
|
||||
# fetched: an "https://" spelling would match no element.
|
||||
sonar.issue.ignore.multicriteria.xmlns.ruleKey=python:S5332
|
||||
sonar.issue.ignore.multicriteria.xmlns.resourceKey=scripts/config.py
|
||||
@@ -1,22 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def video() -> dict:
|
||||
return {
|
||||
"video_id": "E0jg71lJE1Q",
|
||||
"title": "[2K] Dark Souls Remastered | Asylum Demon Boss Fight | Gameplay No Commentary",
|
||||
"url": "https://www.youtube.com/watch?v=E0jg71lJE1Q",
|
||||
"published": "2026-08-30T17:00:31+00:00",
|
||||
"description": "First boss.",
|
||||
"thumbnail": "https://i4.ytimg.com/vi/E0jg71lJE1Q/hqdefault.jpg",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def feed_xml() -> str:
|
||||
return (FIXTURES / "feed.xml").read_text(encoding="utf-8")
|
||||
Vendored
-40
@@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns:yt="http://www.youtube.com/xml/schemas/2015" xmlns:media="http://search.yahoo.com/mrss/" xmlns="http://www.w3.org/2005/Atom">
|
||||
<title>SkullMute</title>
|
||||
<entry>
|
||||
<id>yt:video:hnxTgODvLiQ</id>
|
||||
<yt:videoId>hnxTgODvLiQ</yt:videoId>
|
||||
<title>[2K] Be Missed And Remembered | Part 16 | Gameplay No Commentary</title>
|
||||
<link rel="alternate" href="https://www.youtube.com/watch?v=hnxTgODvLiQ"/>
|
||||
<published>2026-08-31T08:45:06+00:00</published>
|
||||
<media:group>
|
||||
<media:title>[2K] Be Missed And Remembered | Part 16 | Gameplay No Commentary</media:title>
|
||||
<media:thumbnail url="https://i2.ytimg.com/vi/hnxTgODvLiQ/hqdefault.jpg" width="480" height="360"/>
|
||||
<media:description>Part 16 & more.</media:description>
|
||||
</media:group>
|
||||
</entry>
|
||||
<entry>
|
||||
<id>yt:video:E0jg71lJE1Q</id>
|
||||
<yt:videoId>E0jg71lJE1Q</yt:videoId>
|
||||
<title>[2K] Dark Souls Remastered | Asylum Demon Boss Fight | Gameplay No Commentary</title>
|
||||
<link rel="alternate" href="https://www.youtube.com/watch?v=E0jg71lJE1Q"/>
|
||||
<published>2026-08-30T17:00:31+00:00</published>
|
||||
<media:group>
|
||||
<media:thumbnail url="https://i4.ytimg.com/vi/E0jg71lJE1Q/hqdefault.jpg" width="480" height="360"/>
|
||||
</media:group>
|
||||
</entry>
|
||||
<entry>
|
||||
<id>yt:video:Op9T4uhBwm0</id>
|
||||
<yt:videoId>Op9T4uhBwm0</yt:videoId>
|
||||
<title>[2K] Soup's Tail | Demo | Gameplay No Commentary</title>
|
||||
<link rel="alternate" href="https://www.youtube.com/watch?v=Op9T4uhBwm0"/>
|
||||
<published>2026-08-11T06:00:06+00:00</published>
|
||||
</entry>
|
||||
<entry>
|
||||
<id>yt:video:badDate0000</id>
|
||||
<yt:videoId>badDate0000</yt:videoId>
|
||||
<title>Broken date</title>
|
||||
<link rel="alternate" href="https://www.youtube.com/watch?v=badDate0000"/>
|
||||
<published>not-a-date</published>
|
||||
</entry>
|
||||
</feed>
|
||||
@@ -1,145 +0,0 @@
|
||||
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()
|
||||
@@ -1,79 +0,0 @@
|
||||
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
|
||||
@@ -1,144 +0,0 @@
|
||||
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
|
||||
@@ -1,60 +0,0 @@
|
||||
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
|
||||
@@ -1,38 +0,0 @@
|
||||
from message import BLUESKY_MAX_GRAPHEMES, HEADER, build_message, fit_bluesky, truncate
|
||||
|
||||
|
||||
def test_build_message_layout(video):
|
||||
text = build_message(video, hashtags="#a #b")
|
||||
assert text.split("\n\n") == [HEADER, video["title"], f"▶️ {video['url']}", "#a #b"]
|
||||
|
||||
|
||||
def test_build_message_without_hashtags_has_no_trailing_block(video):
|
||||
assert build_message(video).endswith(video["url"])
|
||||
|
||||
|
||||
def test_build_message_overrides(video):
|
||||
text = build_message(video, title="<b>T</b>", header="H")
|
||||
assert text.startswith("H\n\n<b>T</b>\n\n")
|
||||
|
||||
|
||||
def test_truncate():
|
||||
assert truncate("short", 10) == "short"
|
||||
assert truncate("abcdefghij", 5) == "abcd…"
|
||||
assert truncate("abcdefghij", 1) == "a"
|
||||
|
||||
|
||||
def test_fit_bluesky_keeps_short_titles(video):
|
||||
assert fit_bluesky(video) == build_message(video)
|
||||
|
||||
|
||||
def test_fit_bluesky_truncates_long_titles(video):
|
||||
long_video = {**video, "title": "x" * 400}
|
||||
text = fit_bluesky(long_video)
|
||||
assert len(text) <= BLUESKY_MAX_GRAPHEMES
|
||||
assert video["url"] in text
|
||||
assert "…" 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="")
|
||||
@@ -1,71 +0,0 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import youtube
|
||||
from http_client import HttpError
|
||||
from youtube import is_public, is_public_html
|
||||
|
||||
NOW = datetime(2026, 8, 30, 18, 7, tzinfo=UTC)
|
||||
PUBLIC = (
|
||||
'<meta itemprop="isLiveBroadcast" content="True"><meta itemprop="startDate" '
|
||||
'content="2026-08-30T17:00:31+00:00">...{"playabilityStatus":{"status":"OK","playableInEmbed":true}'
|
||||
)
|
||||
UPCOMING_FLAG = '{"playabilityStatus":{"status":"OK"},"videoDetails":{"isUpcoming":true}}'
|
||||
UPCOMING_DATE = (
|
||||
'<meta itemprop="startDate" content="2026-08-31T01:00:06+00:00">'
|
||||
'{"playabilityStatus":{"status":"OK"}}'
|
||||
)
|
||||
OFFLINE = '{"playabilityStatus":{"status":"LIVE_STREAM_OFFLINE","reason":"Premieres in 2 hours"}}'
|
||||
AGE_GATED = (
|
||||
'{"playabilityStatus":{"status":"LOGIN_REQUIRED","reason":"Sign in to confirm your age"}}'
|
||||
)
|
||||
|
||||
|
||||
def test_public_video_passes():
|
||||
assert is_public_html(PUBLIC, now=NOW) == (True, "")
|
||||
|
||||
|
||||
def test_upcoming_flag_blocks():
|
||||
public, reason = is_public_html(UPCOMING_FLAG, now=NOW)
|
||||
assert not public and "upcoming" in reason
|
||||
|
||||
|
||||
def test_future_start_date_blocks():
|
||||
public, reason = is_public_html(UPCOMING_DATE, now=NOW)
|
||||
assert not public and "2026-08-31T01:00:06" in reason
|
||||
|
||||
|
||||
def test_offline_stream_blocks():
|
||||
assert is_public_html(OFFLINE, now=NOW)[0] is False
|
||||
|
||||
|
||||
def test_other_playability_statuses_do_not_block_forever():
|
||||
assert is_public_html(AGE_GATED, now=NOW)[0] is True
|
||||
|
||||
|
||||
def test_no_markers_assumes_public():
|
||||
assert is_public_html("<html>consent wall</html>", now=NOW)[0] is True
|
||||
|
||||
|
||||
def test_is_public_fetches_watch_page(monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def fake_get_text(url, headers=None, timeout=30):
|
||||
seen["url"] = url
|
||||
return OFFLINE
|
||||
|
||||
monkeypatch.setattr(youtube, "get_text", fake_get_text)
|
||||
assert is_public("abc", now=NOW) is False
|
||||
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)
|
||||
|
||||
monkeypatch.setattr(youtube, "get_text", boom)
|
||||
assert is_public("abc", now=NOW) is True
|
||||
@@ -1,76 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from release_notes import changelog_file, extract_section, main
|
||||
|
||||
CHANGELOG = """# 1.x
|
||||
|
||||
Intro paragraph.
|
||||
|
||||
## 1.2.0 — 2026-09-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- Telegram titles.
|
||||
|
||||
## 1.1.0 — 2026-04-16
|
||||
|
||||
- Refactor.
|
||||
"""
|
||||
|
||||
|
||||
def test_extract_middle_section():
|
||||
assert extract_section(CHANGELOG, "v1.2.0") == "### Fixed\n\n- Telegram titles.\n"
|
||||
|
||||
|
||||
def test_extract_last_section():
|
||||
assert extract_section(CHANGELOG, "1.1.0") == "- Refactor.\n"
|
||||
|
||||
|
||||
def test_missing_version_raises():
|
||||
with pytest.raises(LookupError):
|
||||
extract_section(CHANGELOG, "9.9.9")
|
||||
|
||||
|
||||
@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"], 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"], 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
|
||||
@@ -1,112 +0,0 @@
|
||||
import pytest
|
||||
|
||||
import notify
|
||||
import platforms
|
||||
from http_client import HttpError
|
||||
from platforms import post_to_all, summarize
|
||||
from platforms.base import PostStatus
|
||||
|
||||
OK, SKIP, FAIL = PostStatus.OK, PostStatus.SKIPPED, PostStatus.FAILED
|
||||
|
||||
|
||||
def test_summarize():
|
||||
assert summarize({"a": OK, "b": SKIP}) == (True, False)
|
||||
assert summarize({"a": OK, "b": FAIL}) == (True, True)
|
||||
assert summarize({"a": SKIP, "b": SKIP}) == (False, False)
|
||||
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."""
|
||||
state = {
|
||||
"feed": [video],
|
||||
"posted": set(),
|
||||
"public": {video["video_id"]: True},
|
||||
"results": {"telegram": OK, "bluesky": SKIP},
|
||||
"saved": [],
|
||||
}
|
||||
monkeypatch.setattr(notify, "YOUTUBE_CHANNEL_ID", "UC123")
|
||||
monkeypatch.setattr(notify, "fetch_feed", lambda: state["feed"])
|
||||
monkeypatch.setattr(notify, "select_recent", lambda videos, **kw: videos)
|
||||
monkeypatch.setattr(notify, "load_posted_ids", lambda: state["posted"])
|
||||
monkeypatch.setattr(notify, "save_posted_ids", lambda ids: state["saved"].extend(ids))
|
||||
monkeypatch.setattr(notify, "is_public", lambda vid, now: state["public"].get(vid, True))
|
||||
monkeypatch.setattr(notify, "post_to_all", lambda v: dict(state["results"]))
|
||||
monkeypatch.setattr(notify.time, "sleep", lambda s: None)
|
||||
return state
|
||||
|
||||
|
||||
def test_success_saves_state_and_exits_zero(harness, video):
|
||||
assert notify.main() == 0
|
||||
assert harness["saved"] == [video["video_id"]]
|
||||
|
||||
|
||||
def test_platform_failure_exits_one_but_still_saves(harness, video):
|
||||
harness["results"] = {"telegram": OK, "mastodon": FAIL}
|
||||
assert notify.main() == 1
|
||||
assert harness["saved"] == [video["video_id"]]
|
||||
|
||||
|
||||
def test_all_platforms_skipped_exits_one_without_saving(harness):
|
||||
harness["results"] = {"telegram": SKIP, "bluesky": SKIP}
|
||||
assert notify.main() == 1
|
||||
assert harness["saved"] == []
|
||||
|
||||
|
||||
def test_premiere_not_public_is_skipped_and_not_saved(harness, video):
|
||||
harness["public"][video["video_id"]] = False
|
||||
assert notify.main() == 0
|
||||
assert harness["saved"] == []
|
||||
|
||||
|
||||
def test_already_posted_is_noop(harness, video):
|
||||
harness["posted"] = {video["video_id"]}
|
||||
assert notify.main() == 0
|
||||
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")
|
||||
|
||||
monkeypatch.setattr(notify, "fetch_feed", boom)
|
||||
assert notify.main() == 1
|
||||
|
||||
|
||||
def test_missing_channel_id_exits_one(harness, monkeypatch):
|
||||
monkeypatch.setattr(notify, "YOUTUBE_CHANNEL_ID", "")
|
||||
assert notify.main() == 1
|
||||
@@ -1,27 +0,0 @@
|
||||
from config import MAX_STATE_IDS
|
||||
from state import load_posted_ids, save_posted_ids
|
||||
|
||||
|
||||
def test_load_missing_file_is_empty(tmp_path):
|
||||
assert load_posted_ids(tmp_path / "nope.txt") == set()
|
||||
|
||||
|
||||
def test_load_ignores_blank_lines_and_whitespace(tmp_path):
|
||||
path = tmp_path / "s.txt"
|
||||
path.write_text("a\n\n b \n", encoding="utf-8")
|
||||
assert load_posted_ids(path) == {"a", "b"}
|
||||
|
||||
|
||||
def test_save_appends_in_order_and_dedups(tmp_path):
|
||||
path = tmp_path / "nested" / "s.txt"
|
||||
save_posted_ids(["a", "b"], path)
|
||||
save_posted_ids(["b", "c", "c"], path)
|
||||
assert path.read_text(encoding="utf-8") == "a\nb\nc\n"
|
||||
|
||||
|
||||
def test_save_caps_to_max_ids(tmp_path):
|
||||
path = tmp_path / "s.txt"
|
||||
save_posted_ids([f"v{i}" for i in range(MAX_STATE_IDS + 10)], path)
|
||||
ids = path.read_text(encoding="utf-8").split()
|
||||
assert len(ids) == MAX_STATE_IDS
|
||||
assert ids[-1] == f"v{MAX_STATE_IDS + 9}"
|
||||
@@ -1,59 +0,0 @@
|
||||
import pytest
|
||||
|
||||
from http_client import HttpError
|
||||
from platforms import telegram
|
||||
from platforms.base import PostStatus
|
||||
|
||||
|
||||
def test_build_text_keeps_brackets_and_pipes_verbatim(video):
|
||||
text = telegram.build_text(video)
|
||||
assert (
|
||||
"<b>[2K] Dark Souls Remastered | Asylum Demon Boss Fight | Gameplay No Commentary</b>"
|
||||
in text
|
||||
)
|
||||
assert "\\" not in text
|
||||
|
||||
|
||||
def test_build_text_escapes_html_specials(video):
|
||||
text = telegram.build_text({**video, "title": "Tom & Jerry <3"})
|
||||
assert "<b>Tom & Jerry <3</b>" in text
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def configured(monkeypatch):
|
||||
monkeypatch.setattr(telegram, "TELEGRAM_BOT_TOKEN", "123:abc")
|
||||
monkeypatch.setattr(telegram, "TELEGRAM_CHAT_ID", "-100")
|
||||
|
||||
|
||||
def test_post_skips_without_credentials(monkeypatch, video):
|
||||
monkeypatch.setattr(telegram, "TELEGRAM_BOT_TOKEN", "")
|
||||
assert telegram.post(video) is PostStatus.SKIPPED
|
||||
|
||||
|
||||
def test_post_sends_html_payload(monkeypatch, configured, video):
|
||||
calls = []
|
||||
|
||||
def fake_post_json(url, payload, headers=None, timeout=30):
|
||||
calls.append((url, payload))
|
||||
return {"ok": True}
|
||||
|
||||
monkeypatch.setattr(telegram, "post_json", fake_post_json)
|
||||
assert telegram.post(video) is PostStatus.OK
|
||||
url, payload = calls[0]
|
||||
assert url == "https://api.telegram.org/bot123:abc/sendMessage"
|
||||
assert payload["parse_mode"] == "HTML"
|
||||
assert payload["link_preview_options"] == {"is_disabled": False}
|
||||
assert "disable_web_page_preview" not in payload
|
||||
|
||||
|
||||
def test_post_fails_on_http_error(monkeypatch, configured, video):
|
||||
def boom(url, payload, headers=None, timeout=30):
|
||||
raise HttpError(400, '{"ok":false}', url)
|
||||
|
||||
monkeypatch.setattr(telegram, "post_json", boom)
|
||||
assert telegram.post(video) is PostStatus.FAILED
|
||||
|
||||
|
||||
def test_post_fails_on_not_ok_body(monkeypatch, configured, video):
|
||||
monkeypatch.setattr(telegram, "post_json", lambda *a, **k: {"ok": False})
|
||||
assert telegram.post(video) is PostStatus.FAILED
|
||||
@@ -1,84 +0,0 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
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] == [
|
||||
"hnxTgODvLiQ",
|
||||
"E0jg71lJE1Q",
|
||||
"Op9T4uhBwm0",
|
||||
"badDate0000",
|
||||
]
|
||||
first = videos[0]
|
||||
assert first["title"].startswith("[2K] Be Missed")
|
||||
assert first["url"] == "https://www.youtube.com/watch?v=hnxTgODvLiQ"
|
||||
assert first["description"] == "Part 16 & more."
|
||||
assert first["thumbnail"].endswith("hqdefault.jpg")
|
||||
assert videos[2]["description"] == "" and videos[2]["thumbnail"] == ""
|
||||
|
||||
|
||||
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):
|
||||
videos = parse_feed(feed_xml)
|
||||
recent = select_recent(videos, now=NOW, lookback_hours=48)
|
||||
assert [v["video_id"] for v in recent] == ["E0jg71lJE1Q", "hnxTgODvLiQ"]
|
||||
|
||||
|
||||
def test_select_recent_keeps_videos_published_after_a_delayed_run(feed_xml):
|
||||
# 22:30 cron actually ran at 00:21 the next day; a "today only" filter lost this video.
|
||||
videos = parse_feed(feed_xml)
|
||||
recent = select_recent(videos, now=datetime(2026, 8, 31, 0, 21, tzinfo=UTC), lookback_hours=48)
|
||||
assert "E0jg71lJE1Q" in [v["video_id"] for v in recent]
|
||||
|
||||
|
||||
def test_select_recent_drops_far_future_timestamps(video):
|
||||
future = {**video, "published": "2026-09-01T00:00:00+00:00"}
|
||||
assert select_recent([future], now=NOW, lookback_hours=48) == []
|
||||
Reference in new issue
Block a user