Commit 00214e85 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add bulk Telegram chat scanning: approve a chat, tag+save every song in it

New foundation for scanning a whole chat instead of one song at a time:
ApprovedChat (opt a chat in) and ChatScanJob (a background job that
lists a chat's music, then downloads+identifies+tags+saves each song
via the same pipeline /music/tag already uses per song). Mirrors
RemixJob's proven pattern - a status column + BackgroundTasks, no new
task-queue infrastructure - rather than inventing a new one.

Deliberately on-demand (user approves a chat, then triggers one scan)
rather than automatic background polling, which needs a materially
different architecture (persistent per-user Telegram connections or a
scheduler) not worth building until on-demand proves out the feature.

Guardrails baked in from the start rather than bolted on later: a
50-message cap per scan, a 5-scans/day per-user cap, no two concurrent
scans of the same chat, and a 1.5s pause between songs so a scan reads
like a real user, not a script hammering Telegram/AcoustID/Gemini.
Per-song outcomes (saved/skipped_duplicate/failed) are tracked
individually in results_json, not just one pass/fail for the whole job.

_identify_tag_and_store's request param is now optional so the
background job can call it without a live HTTP request in scope - same
reasoning as RemixJob storing a bare filename instead of a full URL.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 98dbaf27
Pipeline #1112 passed with stage
in 3 minutes and 13 seconds
"""add approved_chats and chat_scan_jobs tables
Revision ID: f3514f910205
Revises: 9f6585c71f80
Create Date: 2026-08-19 13:24:50.698201
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'f3514f910205'
down_revision: Union[str, Sequence[str], None] = '9f6585c71f80'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('approved_chats',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('chat_id', sa.Integer(), nullable=False),
sa.Column('chat_title', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id', 'chat_id', name='uq_approved_chat_user_chat')
)
op.create_index(op.f('ix_approved_chats_id'), 'approved_chats', ['id'], unique=False)
op.create_index(op.f('ix_approved_chats_user_id'), 'approved_chats', ['user_id'], unique=False)
op.create_table('chat_scan_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('chat_id', sa.Integer(), nullable=False),
sa.Column('chat_title', sa.String(), nullable=True),
sa.Column('status', sa.String(), nullable=True),
sa.Column('songs_found', sa.Integer(), nullable=True),
sa.Column('songs_processed', sa.Integer(), nullable=True),
sa.Column('songs_saved', sa.Integer(), nullable=True),
sa.Column('songs_skipped', sa.Integer(), nullable=True),
sa.Column('songs_failed', sa.Integer(), nullable=True),
sa.Column('results_json', sa.String(), nullable=True),
sa.Column('error', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_chat_scan_jobs_id'), 'chat_scan_jobs', ['id'], unique=False)
op.create_index(op.f('ix_chat_scan_jobs_user_id'), 'chat_scan_jobs', ['user_id'], unique=False)
# Note: autogenerate also detected a pre-existing, unrelated drift here - remix_jobs.user_id
# has no FK constraint in the actual DB (added by an earlier migration without one, likely
# a SQLite ALTER TABLE limitation) even though the RemixJob model declares one. Deliberately
# left alone - out of scope for this migration, unrelated to approved_chats/chat_scan_jobs.
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_chat_scan_jobs_user_id'), table_name='chat_scan_jobs')
op.drop_index(op.f('ix_chat_scan_jobs_id'), table_name='chat_scan_jobs')
op.drop_table('chat_scan_jobs')
op.drop_index(op.f('ix_approved_chats_user_id'), table_name='approved_chats')
op.drop_index(op.f('ix_approved_chats_id'), table_name='approved_chats')
op.drop_table('approved_chats')
# ### end Alembic commands ###
......@@ -10,7 +10,7 @@ from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, channels, discovery, library, music, remix, social, soundmarks
from src.api.routers import auth, channels, discovery, library, music, remix, social, soundmarks, telegram_scan
from src.core.config import CORS_ORIGINS, DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal
from src.services.storage import DOWNLOADS_DIR
......@@ -92,6 +92,7 @@ app.include_router(social.router)
app.include_router(remix.router)
app.include_router(channels.router)
app.include_router(soundmarks.router)
app.include_router(telegram_scan.router)
@app.get("/", include_in_schema=False)
......
......@@ -50,12 +50,18 @@ async def _identify_tag_and_store(
db: Session,
current_user: User,
raw_file_path: str,
request: Request,
request: Request = None,
language_preference: str = "native",
) -> dict:
"""Shared by /music/upload and /music/tag: identify -> lyrics -> genre -> tag -> durable
storage -> LibrarySong row. This is what makes /library non-empty - nothing wrote to it
before this existed."""
"""Shared by /music/upload, /music/tag, and the bulk chat-scan background job: identify ->
lyrics -> genre -> tag -> durable storage -> LibrarySong row. This is what makes /library
non-empty - nothing wrote to it before this existed.
request is optional because the background scan job (telegram_scan.py) has no live
request to build an absolute download_url from - same reasoning as RemixJob storing a bare
result_filename and letting GET /remix/{job_id} build the URL later from *its own* request.
When request is None, download_url comes back None too; callers that need it always pass
one (both /music/tag and /music/upload do)."""
try:
fingerprint = await compute_fingerprint(raw_file_path)
......@@ -69,11 +75,13 @@ async def _identify_tag_and_store(
# Same user, same recording (by content fingerprint, not just title/artist text) -
# they already have this tagged and stored. Hand back the existing entry instead of
# re-running identification, re-tagging, and writing a second copy of the file.
download_url = str(request.base_url).rstrip('/') + urllib.parse.quote(
storage.url_path_for(existing_song.file_path)
download_url = (
str(request.base_url).rstrip('/') + urllib.parse.quote(storage.url_path_for(existing_song.file_path))
if request else None
)
return {
"status": "success",
"deduped": True, # already had this exact recording - filtered out by response_model on the HTTP endpoints, read directly by the chat-scan background job
"download_url": download_url,
"metadata": {
"library_song_id": existing_song.id,
......@@ -165,10 +173,11 @@ async def _identify_tag_and_store(
db.commit()
db.refresh(library_song)
download_url = str(request.base_url).rstrip('/') + urllib.parse.quote(url_path)
download_url = str(request.base_url).rstrip('/') + urllib.parse.quote(url_path) if request else None
return {
"status": "success",
"deduped": False,
"download_url": download_url,
"metadata": {
"library_song_id": library_song.id,
......
import asyncio
import json
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
import src.telegram_worker.telegram_sync as telegram_sync
from src.api.routers.music import _identify_tag_and_store
from src.core.config import logger
from src.core.database import ApprovedChat, ChatScanJob, SessionLocal, User, get_db
from src.core.security import get_current_user
from src.services import storage
from src.services.audio_processing import AudioDecodeError
router = APIRouter(prefix="/telegram", tags=["Telegram Bulk Scan"])
# Same ceiling get_chat_music already defaults to for a single on-demand listing - a scan job
# uses it explicitly so the limit is visible here rather than only living inside telegram_sync.
MAX_MESSAGES_PER_SCAN = 50
# Backstop against one user (accidentally or not) spinning up scan after scan - each job can
# already cost dozens of paid/rate-limited identify calls on its own.
MAX_SCAN_JOBS_PER_DAY = 5
JOB_WINDOW = timedelta(hours=24)
# Sequential, not parallel, with a pause between songs - hammering Telegram's download API and
# the identify pipeline back-to-back across dozens of messages reads as abuse, not a real user.
SCAN_DELAY_SECONDS = 1.5
def _utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class ApproveChatReq(BaseModel):
chat_title: str | None = None
@router.post("/chats/{chat_id}/approve")
async def approve_chat(
chat_id: int,
req: ApproveChatReq = ApproveChatReq(),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Opts a chat into bulk scanning - distinct from just being able to browse it (GET
/auth/telegram/chats/{id}/music), which needs no approval. Idempotent: approving an
already-approved chat just returns the existing row instead of erroring."""
existing = (
db.query(ApprovedChat)
.filter(ApprovedChat.user_id == current_user.id, ApprovedChat.chat_id == chat_id)
.first()
)
if existing:
return {"status": "success", "chat_id": chat_id, "already_approved": True}
db.add(ApprovedChat(user_id=current_user.id, chat_id=chat_id, chat_title=req.chat_title))
db.commit()
return {"status": "success", "chat_id": chat_id, "already_approved": False}
@router.delete("/chats/{chat_id}/approve")
async def revoke_chat(
chat_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
approved = (
db.query(ApprovedChat)
.filter(ApprovedChat.user_id == current_user.id, ApprovedChat.chat_id == chat_id)
.first()
)
if not approved:
raise HTTPException(status_code=404, detail="This chat isn't approved for scanning")
db.delete(approved)
db.commit()
return {"status": "success"}
@router.get("/chats/approved")
async def list_approved_chats(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
approved = db.query(ApprovedChat).filter(ApprovedChat.user_id == current_user.id).all()
return {
"status": "success",
"chats": [{"chat_id": a.chat_id, "chat_title": a.chat_title, "approved_at": a.created_at} for a in approved],
}
async def _run_chat_scan(job_id: int, user_id: int, chat_id: int, session_string: str, language_preference: str):
"""The background job body - runs after the kickoff response has already been sent, so it
opens its own DB session rather than reusing the (by-then-closed) request-scoped one. Same
pattern as remix_engine.render_remix_sync: a status column plus progress fields the polling
endpoint reads, no task queue involved."""
db = SessionLocal()
try:
job = db.query(ChatScanJob).filter(ChatScanJob.id == job_id).first()
if not job:
return
job.status = "scanning"
db.commit()
try:
music = await telegram_sync.get_chat_music(session_string, chat_id, limit=MAX_MESSAGES_PER_SCAN)
except Exception as e:
logger.error(f"Chat scan job {job_id}: could not list chat music: {e}")
job.status = "error"
job.error = f"Could not list music in this chat: {e}"
db.commit()
return
job.songs_found = len(music)
db.commit()
user = db.query(User).filter(User.id == user_id).first()
results = []
for m in music:
title, artist = m.get("title"), m.get("artist")
outcome, detail = "failed", None
raw_path = None
try:
dest = storage.new_temp_path(f"scan_{chat_id}_{m['message_id']}")
raw_path = await telegram_sync.download_chat_audio(session_string, chat_id, m["message_id"], dest)
result = await _identify_tag_and_store(db, user, raw_path, None, language_preference)
outcome = "skipped_duplicate" if result.get("deduped") else "saved"
title = result["metadata"]["title"]
artist = result["metadata"]["artist"]
except AudioDecodeError:
detail = "Couldn't process this audio file - it may be corrupted or in an unsupported format."
except Exception as e:
logger.error(f"Chat scan job {job_id}: failed on message {m.get('message_id')}: {e}")
detail = str(e)[:200]
if outcome == "saved":
job.songs_saved += 1
elif outcome == "skipped_duplicate":
job.songs_skipped += 1
else:
job.songs_failed += 1
job.songs_processed += 1
results.append({
"message_id": m.get("message_id"),
"title": title,
"artist": artist,
"outcome": outcome,
"detail": detail,
})
job.results_json = json.dumps(results)
db.commit()
await asyncio.sleep(SCAN_DELAY_SECONDS)
job.status = "done"
db.commit()
except Exception as e:
logger.exception(f"Chat scan job {job_id}: unexpected failure")
job = db.query(ChatScanJob).filter(ChatScanJob.id == job_id).first()
if job:
job.status = "error"
job.error = str(e)[:500]
db.commit()
finally:
db.close()
@router.post("/chats/{chat_id}/scan")
async def scan_chat(
chat_id: int,
background_tasks: BackgroundTasks,
language_preference: str = "native",
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
"""Kicks off a background job that tags and saves every song found in one approved chat.
Deliberately on-demand (user asks, once) rather than automatic background polling - see
the chat-scan design notes for why that's a materially bigger, separate piece of work."""
if not current_user.telegram_session_string:
raise HTTPException(status_code=400, detail="No linked Telegram session")
approved = (
db.query(ApprovedChat)
.filter(ApprovedChat.user_id == current_user.id, ApprovedChat.chat_id == chat_id)
.first()
)
if not approved:
raise HTTPException(status_code=403, detail="This chat hasn't been approved for scanning yet")
already_running = (
db.query(ChatScanJob)
.filter(
ChatScanJob.user_id == current_user.id,
ChatScanJob.chat_id == chat_id,
ChatScanJob.status.in_(["queued", "scanning"]),
)
.first()
)
if already_running:
raise HTTPException(status_code=409, detail="A scan of this chat is already in progress")
recent_count = (
db.query(ChatScanJob)
.filter(ChatScanJob.user_id == current_user.id, ChatScanJob.created_at >= _utcnow() - JOB_WINDOW)
.count()
)
if recent_count >= MAX_SCAN_JOBS_PER_DAY:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"Limit of {MAX_SCAN_JOBS_PER_DAY} chat scans per day reached - try again later",
)
job = ChatScanJob(user_id=current_user.id, chat_id=chat_id, chat_title=approved.chat_title, status="queued")
db.add(job)
db.commit()
db.refresh(job)
background_tasks.add_task(
_run_chat_scan, job.id, current_user.id, chat_id, current_user.telegram_session_string, language_preference
)
return {"job_id": job.id, "status": job.status, "status_url": f"/telegram/scan/{job.id}"}
@router.get("/scan/{job_id}")
async def get_scan_status(
job_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
job = db.query(ChatScanJob).filter(ChatScanJob.id == job_id, ChatScanJob.user_id == current_user.id).first()
if not job:
raise HTTPException(status_code=404, detail="Scan job not found")
return {
"job_id": job.id,
"chat_id": job.chat_id,
"chat_title": job.chat_title,
"status": job.status,
"songs_found": job.songs_found,
"songs_processed": job.songs_processed,
"songs_saved": job.songs_saved,
"songs_skipped": job.songs_skipped,
"songs_failed": job.songs_failed,
"results": json.loads(job.results_json) if job.results_json else [],
"error": job.error,
}
......@@ -293,6 +293,44 @@ class RemixJob(Base):
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class ApprovedChat(Base):
"""A Telegram chat a user has explicitly opted into bulk scanning for - distinct from
just being able to browse a chat's music one song at a time (GET
/auth/telegram/chats/{id}/music), which needs no approval. chat_title is cached at
approval time purely for display - it's not re-synced, so a chat rename won't retroactively
update it here."""
__tablename__ = "approved_chats"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
chat_id = Column(Integer, nullable=False)
chat_title = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
__table_args__ = (UniqueConstraint("user_id", "chat_id", name="uq_approved_chat_user_chat"),)
class ChatScanJob(Base):
"""Bulk-tags every song found in one approved chat, in the background - mirrors RemixJob's
shape (status column + counters, polled via GET /telegram/scan/{job_id}) since that pattern
already solves "slow multi-step pipeline with live status" without needing a real task
queue. Each item's outcome (saved/skipped/failed and why) goes in results_json rather than
a separate table - same reasoning as RemixJob.plan_json, upgradeable later if it ever needs
to be queried independently instead of just displayed."""
__tablename__ = "chat_scan_jobs"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
chat_id = Column(Integer, nullable=False)
chat_title = Column(String, nullable=True)
status = Column(String, default="queued") # queued, scanning, done, error
songs_found = Column(Integer, default=0)
songs_processed = Column(Integer, default=0)
songs_saved = Column(Integer, default=0)
songs_skipped = Column(Integer, default=0) # already in the user's library (fingerprint match)
songs_failed = Column(Integer, default=0)
results_json = Column(String, nullable=True) # list of {message_id, title, artist, outcome, detail}
error = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
# --- Channels: the creator hub. Users host a channel and publish Vibe Sets (curated song
# collections), Audio Stories (ephemeral short clips), and showcase specific remixes
# (existing Posts) - the one pillar from the original vision doc with nothing built at all
......
import src.api.routers.telegram_scan as telegram_scan_router
from src.core.database import ApprovedChat, ChatScanJob
from src.services.audio_processing import AudioDecodeError
FAKE_MUSIC = [
{"message_id": 1, "title": "Song One", "artist": "Artist One", "duration": 180, "file_name": "one.mp3"},
{"message_id": 2, "title": "Song Two", "artist": "Artist Two", "duration": 200, "file_name": "two.mp3"},
{"message_id": 3, "title": "Song Three", "artist": "Artist Three", "duration": 150, "file_name": "three.mp3"},
]
def _no_delay(monkeypatch):
# SCAN_DELAY_SECONDS paces real Telegram/identify calls between songs - irrelevant (and
# slow) in tests where those calls are mocked out entirely.
monkeypatch.setattr(telegram_scan_router, "SCAN_DELAY_SECONDS", 0)
# --- Approve / revoke / list ---
def test_approve_chat_requires_auth(client):
response = client.post("/telegram/chats/123/approve")
assert response.status_code == 401
def test_approve_chat(client, db_session, auth_as):
headers, user = auth_as()
response = client.post("/telegram/chats/123/approve", json={"chat_title": "Music Chat"}, headers=headers)
assert response.status_code == 200
assert response.json()["already_approved"] is False
row = db_session.query(ApprovedChat).filter(ApprovedChat.user_id == user.id, ApprovedChat.chat_id == 123).first()
assert row is not None
assert row.chat_title == "Music Chat"
def test_approve_chat_is_idempotent(client, auth_as):
headers, _ = auth_as()
client.post("/telegram/chats/123/approve", json={"chat_title": "Music Chat"}, headers=headers)
response = client.post("/telegram/chats/123/approve", json={"chat_title": "Music Chat"}, headers=headers)
assert response.status_code == 200
assert response.json()["already_approved"] is True
def test_revoke_chat_that_was_never_approved(client, auth_as):
headers, _ = auth_as()
response = client.delete("/telegram/chats/999/approve", headers=headers)
assert response.status_code == 404
def test_revoke_chat(client, db_session, auth_as):
headers, user = auth_as()
client.post("/telegram/chats/123/approve", headers=headers)
response = client.delete("/telegram/chats/123/approve", headers=headers)
assert response.status_code == 200
assert db_session.query(ApprovedChat).filter(ApprovedChat.user_id == user.id).count() == 0
def test_list_approved_chats_is_scoped_to_the_caller(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
client.post("/telegram/chats/111/approve", json={"chat_title": "A's chat"}, headers=headers_a)
client.post("/telegram/chats/222/approve", json={"chat_title": "B's chat"}, headers=headers_b)
response = client.get("/telegram/chats/approved", headers=headers_a)
chats = response.json()["chats"]
assert len(chats) == 1
assert chats[0]["chat_id"] == 111
assert chats[0]["chat_title"] == "A's chat"
# --- Scan kickoff: auth, approval gate, caps ---
def test_scan_requires_auth(client):
response = client.post("/telegram/chats/123/scan")
assert response.status_code == 401
def test_scan_requires_linked_telegram_session(client, auth_as):
headers, _ = auth_as(telegram_session_string=None)
response = client.post("/telegram/chats/123/scan", headers=headers)
assert response.status_code == 400
def test_scan_requires_the_chat_to_be_approved_first(client, auth_as):
headers, _ = auth_as()
response = client.post("/telegram/chats/123/scan", headers=headers)
assert response.status_code == 403
def test_scan_rejects_a_second_concurrent_scan_of_the_same_chat(client, auth_as, monkeypatch):
headers, _ = auth_as()
client.post("/telegram/chats/123/approve", headers=headers)
# Freeze the first job in "scanning" instead of letting it run to completion, so a second
# kickoff request has something in-progress to collide with.
monkeypatch.setattr(telegram_scan_router, "_run_chat_scan", lambda *a, **kw: None)
first = client.post("/telegram/chats/123/scan", headers=headers)
assert first.status_code == 200
job_id = first.json()["job_id"]
from src.core.database import SessionLocal
db = SessionLocal()
job = db.query(ChatScanJob).filter(ChatScanJob.id == job_id).first()
job.status = "scanning"
db.commit()
db.close()
second = client.post("/telegram/chats/123/scan", headers=headers)
assert second.status_code == 409
def test_scan_enforces_the_daily_job_cap(client, db_session, auth_as, monkeypatch):
headers, user = auth_as()
client.post("/telegram/chats/123/approve", headers=headers)
monkeypatch.setattr(telegram_scan_router, "MAX_SCAN_JOBS_PER_DAY", 2)
monkeypatch.setattr(telegram_scan_router, "_run_chat_scan", lambda *a, **kw: None)
# Two different chats so the concurrent-scan-of-the-same-chat guard doesn't interfere -
# this test is specifically about the per-user daily total, not per-chat.
client.post("/telegram/chats/123/approve", headers=headers)
client.post("/telegram/chats/456/approve", headers=headers)
r1 = client.post("/telegram/chats/123/scan", headers=headers)
r2 = client.post("/telegram/chats/456/scan", headers=headers)
assert r1.status_code == 200 and r2.status_code == 200
client.post("/telegram/chats/789/approve", headers=headers)
r3 = client.post("/telegram/chats/789/scan", headers=headers)
assert r3.status_code == 429
# --- Scan status polling ---
def test_scan_status_requires_auth(client):
response = client.get("/telegram/scan/1")
assert response.status_code == 401
def test_scan_status_not_found(client, auth_as):
headers, _ = auth_as()
response = client.get("/telegram/scan/999999", headers=headers)
assert response.status_code == 404
def test_scan_status_is_scoped_to_the_caller(client, auth_as, monkeypatch):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
monkeypatch.setattr(telegram_scan_router, "_run_chat_scan", lambda *a, **kw: None)
client.post("/telegram/chats/123/approve", headers=headers_a)
job_id = client.post("/telegram/chats/123/scan", headers=headers_a).json()["job_id"]
response = client.get(f"/telegram/scan/{job_id}", headers=headers_b)
assert response.status_code == 404
# --- The actual scan job: per-item outcomes ---
def test_chat_scan_saves_skips_and_fails_songs_individually(client, db_session, auth_as, mocker, monkeypatch):
_no_delay(monkeypatch)
headers, user = auth_as()
client.post("/telegram/chats/123/approve", json={"chat_title": "Music Chat"}, headers=headers)
mocker.patch("src.api.routers.telegram_scan.telegram_sync.get_chat_music", return_value=FAKE_MUSIC)
mocker.patch(
"src.api.routers.telegram_scan.telegram_sync.download_chat_audio",
return_value="/tmp/downloaded.mp3",
)
mocker.patch(
"src.api.routers.telegram_scan._identify_tag_and_store",
side_effect=[
{"status": "success", "deduped": False, "download_url": None, "metadata": {"title": "Song One", "artist": "Artist One"}},
{"status": "success", "deduped": True, "download_url": None, "metadata": {"title": "Song Two", "artist": "Artist Two"}},
AudioDecodeError("corrupt"),
],
)
response = client.post("/telegram/chats/123/scan", headers=headers)
job_id = response.json()["job_id"]
status_response = client.get(f"/telegram/scan/{job_id}", headers=headers)
body = status_response.json()
assert body["status"] == "done"
assert body["songs_found"] == 3
assert body["songs_processed"] == 3
assert body["songs_saved"] == 1
assert body["songs_skipped"] == 1
assert body["songs_failed"] == 1
outcomes = {r["message_id"]: r["outcome"] for r in body["results"]}
assert outcomes == {1: "saved", 2: "skipped_duplicate", 3: "failed"}
def test_chat_scan_records_an_error_status_if_listing_the_chat_fails(client, auth_as, mocker, monkeypatch):
_no_delay(monkeypatch)
headers, _ = auth_as()
client.post("/telegram/chats/123/approve", headers=headers)
mocker.patch(
"src.api.routers.telegram_scan.telegram_sync.get_chat_music",
side_effect=Exception("Telegram flood wait"),
)
job_id = client.post("/telegram/chats/123/scan", headers=headers).json()["job_id"]
body = client.get(f"/telegram/scan/{job_id}", headers=headers).json()
assert body["status"] == "error"
assert "Telegram flood wait" in body["error"]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment