Commit 92a8a0e4 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Harden backend, add permanent identification cache, self-bootstrapping deploy

- Extract auth/storage into src/core/security.py and src/services/storage.py,
  scope library/discovery/social routes to the authenticated user
- Add IdentifiedTrack cache table keyed by audio fingerprint so repeat uploads
  of the same song skip Shazam/AcoustID/Gemini identification entirely;
  enable sqlite WAL mode so cache reads don't stall behind unrelated writes
- Add Alembic migrations (baseline schema + identified_tracks)
- Add pytest-mock to requirements.txt - was missing despite being used
  throughout the existing test suite via the mocker fixture
- Rewrite deploy/scripts/deploy.sh to self-bootstrap a bare prod server
  (system packages, repo clone, venv, .env from CI-supplied secrets,
  systemd unit sync) and restart services on every deploy
- Add .gitlab-ci.yml: test stage runs on dev/main pushes, deploy_prod runs
  only on main and SSHes into prod to trigger deploy.sh
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 3c11a7b4
...@@ -4,3 +4,17 @@ GEMINI_API_KEY=your_gemini_api_key_here ...@@ -4,3 +4,17 @@ GEMINI_API_KEY=your_gemini_api_key_here
# Optional, used by src/telegram_bot (stem separation feature) # Optional, used by src/telegram_bot (stem separation feature)
LALAL_API_KEY=your_lalal_api_key_here LALAL_API_KEY=your_lalal_api_key_here
# Required. Signs every access/refresh JWT - generate with `openssl rand -hex 32`.
# No default, no fallback: the app refuses to start without it.
JWT_SECRET=
# Gate for the interactive API docs (/docs, /openapi.json)
DOCS_USERNAME=your_docs_username
DOCS_PASSWORD=your_docs_password
# Where uploaded/tagged audio lives locally. Defaults to ./var/storage if unset.
LOCAL_STORAGE_ROOT=./var/storage
# SQLAlchemy connection string. Defaults to sqlite:///./stax.db if unset.
DATABASE_URL=sqlite:///./stax.db
...@@ -11,6 +11,7 @@ venv/ ...@@ -11,6 +11,7 @@ venv/
# Runtime data # Runtime data
*.db *.db
*.log *.log
var/
# OS # OS
.DS_Store .DS_Store
...@@ -3,7 +3,6 @@ stages: ...@@ -3,7 +3,6 @@ stages:
- deploy - deploy
variables: variables:
PYTHON_VERSION: "3.10"
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
cache: cache:
...@@ -11,25 +10,49 @@ cache: ...@@ -11,25 +10,49 @@ cache:
paths: paths:
- .cache/pip/ - .cache/pip/
test_api: # Runs on every push to dev or main. No deploy here - just fast feedback while you're
# developing on dev, and a second confirmation right before deploy_prod fires on main.
test:
stage: test stage: test
image: python:3.10-slim image: python:3.10-slim
before_script: before_script:
- apt-get update && apt-get install -y --no-install-recommends ffmpeg git - apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg git
- pip install --prefer-binary -r requirements.txt pytest - pip install --prefer-binary -q -r requirements.txt
script: script:
- PYTHONPATH=. pytest tests/ - PYTHONPATH=. pytest tests/ -v
only: rules:
- main - if: '$CI_COMMIT_BRANCH == "dev"'
- merge_requests - if: '$CI_COMMIT_BRANCH == "main"'
# Only ever runs on main, and fires automatically once the test job above passes. Copies the
# repo's current deploy.sh onto prod and runs it there over SSH - deploy.sh itself handles
# everything else (bootstrapping a bare box, or updating an already-deployed one).
deploy_prod: deploy_prod:
stage: deploy stage: deploy
image: python:3.10-slim image: python:3.10-slim
variables:
STAX_DEPLOY_DIR: "/root/stax_backend_api"
before_script: before_script:
- apt-get update && apt-get install -y --no-install-recommends openssh-client bash - apt-get update -qq && apt-get install -y -qq --no-install-recommends openssh-client
- chmod 600 "$PROD_SSH_PRIVATE_KEY"
- mkdir -p ~/.ssh
- ssh-keyscan -p "${PROD_SSH_PORT:-22}" "$PROD_SERVER_IP" >> ~/.ssh/known_hosts 2>/dev/null || true
script: script:
- echo "Deploying to Iran production server..." - echo "Deploying $CI_COMMIT_SHORT_SHA to production..."
- ssh -o StrictHostKeyChecking=no -i /root/.ssh/id_ed25519 -p ${PROD_SSH_PORT:-2222} root@${PROD_SERVER_IP:-127.0.0.1} "cd /root/stax_backend_api && GIT_SSL_NO_VERIFY=true git pull origin main && source venv/bin/activate && pip install --prefer-binary -r requirements.txt && systemctl restart stax_backend" - >
only: scp -o StrictHostKeyChecking=accept-new -i "$PROD_SSH_PRIVATE_KEY" -P "${PROD_SSH_PORT:-22}"
- main deploy/scripts/deploy.sh root@"$PROD_SERVER_IP":/root/stax_deploy_bootstrap.sh
- >
ssh -o StrictHostKeyChecking=accept-new -i "$PROD_SSH_PRIVATE_KEY" -p "${PROD_SSH_PORT:-22}"
root@"$PROD_SERVER_IP"
"STAX_DEPLOY_DIR='${STAX_DEPLOY_DIR}'
STAX_PROD_JWT_SECRET='${STAX_PROD_JWT_SECRET}'
STAX_PROD_ACOUSTID_API_KEY='${STAX_PROD_ACOUSTID_API_KEY}'
STAX_PROD_GEMINI_API_KEY='${STAX_PROD_GEMINI_API_KEY}'
STAX_PROD_DOCS_USERNAME='${STAX_PROD_DOCS_USERNAME}'
STAX_PROD_DOCS_PASSWORD='${STAX_PROD_DOCS_PASSWORD}'
STAX_PROD_TELEGRAM_BOT_TOKEN='${STAX_PROD_TELEGRAM_BOT_TOKEN:-}'
STAX_PROD_LALAL_API_KEY='${STAX_PROD_LALAL_API_KEY:-}'
bash /root/stax_deploy_bootstrap.sh"
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
...@@ -55,6 +55,7 @@ Two independent processes make up the backend: ...@@ -55,6 +55,7 @@ Two independent processes make up the backend:
python3 -m venv venv python3 -m venv venv
source venv/bin/activate source venv/bin/activate
pip install -r requirements.txt pip install -r requirements.txt
alembic upgrade head
``` ```
### Environment Variables (`.env`) ### Environment Variables (`.env`)
...@@ -63,12 +64,28 @@ Copy `.env.example` to `.env` and fill in: ...@@ -63,12 +64,28 @@ Copy `.env.example` to `.env` and fill in:
- `ACOUSTID_API_KEY` — audio fingerprinting - `ACOUSTID_API_KEY` — audio fingerprinting
- `GEMINI_API_KEY` — Gemini fallback identification/remix recipes - `GEMINI_API_KEY` — Gemini fallback identification/remix recipes
- `LALAL_API_KEY` — optional, stem separation in the Telegram bot - `LALAL_API_KEY` — optional, stem separation in the Telegram bot
- `JWT_SECRET` — **required**, signs every access/refresh token; generate with
`openssl rand -hex 32`. No default, the app refuses to start without it.
- `DOCS_USERNAME` / `DOCS_PASSWORD` — gate the `/docs` console
- `LOCAL_STORAGE_ROOT` — where uploaded/tagged audio lives locally (default `./var/storage`)
- `DATABASE_URL` — SQLAlchemy connection string (default `sqlite:///./stax.db`)
`.env` is gitignored and must never be committed. `.env` is gitignored and must never be committed.
### Authentication
Login is Telegram-based (request a code, sign in) — that's also how the app finds a user's
music in their own chats to tag (`POST /music/tag`). What changed: the client now gets our own
short-lived JWT access token (+ refresh token) from `POST /auth/login`, never the raw Telegram
session string — that string is a full Telegram account credential and is kept server-side only,
used internally by `/auth/chats` and `/music/tag`. Send `Authorization: Bearer <access_token>` on
every other endpoint; refresh via `POST /auth/refresh`, revoke via `POST /auth/logout`.
### Database ### Database
SQLite by default (`stax.db`, gitignored). SQLAlchemy creates tables automatically on startup SQLite by default (`stax.db`, gitignored). Schema is managed by **Alembic**
from the models in `src/core/database.py`. (`alembic upgrade head`) — `Base.metadata.create_all` is no longer called anywhere, so a fresh
DB has no tables until you run migrations. Add a model in `src/core/database.py`, then
`alembic revision --autogenerate -m "..."` and commit the generated file. Production deploy runs
migrations automatically as part of `deploy/scripts/deploy.sh` (see Deployment below).
## Running the Application ## Running the Application
...@@ -79,10 +96,37 @@ uvicorn src.api.main:app --host 0.0.0.0 --port 8000 --reload ...@@ -79,10 +96,37 @@ uvicorn src.api.main:app --host 0.0.0.0 --port 8000 --reload
### Production (systemd) ### Production (systemd)
```bash ```bash
sudo systemctl restart stax_backend sudo bash deploy/scripts/deploy.sh # runs migrations, restarts the service, health-checks it
sudo journalctl -u stax_backend -f sudo journalctl -u stax_backend -f
``` ```
## Deployment
Dev (server 1) pushes to `main` → GitLab CI's `deploy_prod` job (`.gitlab-ci.yml`) SSHes into
prod (server 2) and runs `deploy/scripts/deploy.sh`, which is the actual deploy logic: pulls
`main`, installs dependencies, runs `alembic upgrade head`, restarts the service(s), then polls
`GET /healthz` (checks the process is up *and* can reach the database) and fails loudly with the
previous commit's SHA if it doesn't come back healthy within 30s.
**One-time setup on server 2** (not something I can do without access to that machine):
- `git clone` this repo to `/root/stax_backend_api` (or set `PROD_DEPLOY_DIR` below to wherever
it lives), create `venv/` there, `pip install -r requirements.txt`, and populate `.env`
(`JWT_SECRET` is required - see `.env.example`).
- Install `deploy/systemd/stax_backend.service` (`cp` into `/etc/systemd/system/`, then
`systemctl daemon-reload && systemctl enable stax_backend`).
- Make sure `curl` is available (used by the deploy script's health check).
- Add these to **GitLab → Settings → CI/CD → Variables** (protected, masked where sensitive):
`SSH_PRIVATE_KEY` (as a file variable mounted to `/root/.ssh/id_ed25519` - already assumed by
the job), `PROD_SERVER_IP`, `PROD_SSH_PORT`. Only set `PROD_DEPLOY_DIR` / `PROD_SERVICES` (CI
variables, defined in `.gitlab-ci.yml`) if server 2's paths/service name differ from the
defaults (`/root/stax_backend_api`, `stax_backend`).
**Manual redeploy or rollback**, run directly on server 2:
```bash
bash deploy/scripts/deploy.sh # redeploy latest main
STAX_DEPLOY_REF=<previous-good-sha> bash deploy/scripts/deploy.sh # roll back
```
## Testing ## Testing
```bash ```bash
pytest tests/ pytest tests/
......
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# set programmatically in env.py from DATABASE_URL (src.core.database)
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Generic single-database configuration.
\ No newline at end of file
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from src.core.database import Base, DATABASE_URL # noqa: E402
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", DATABASE_URL)
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
"""add identified_tracks cache table
Revision ID: 704f3f6d4916
Revises: 99b0833a4bd2
Create Date: 2026-08-09 08:12:21.321502
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '704f3f6d4916'
down_revision: Union[str, Sequence[str], None] = '99b0833a4bd2'
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('identified_tracks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('fingerprint', sa.String(), nullable=False),
sa.Column('title', sa.String(), nullable=True),
sa.Column('artist', sa.String(), nullable=True),
sa.Column('album', sa.String(), nullable=True),
sa.Column('year', sa.String(), nullable=True),
sa.Column('genre', sa.String(), nullable=True),
sa.Column('track_number', sa.String(), nullable=True),
sa.Column('source', sa.String(), nullable=True),
sa.Column('coverart', sa.String(), nullable=True),
sa.Column('lyrics', sa.String(), nullable=True),
sa.Column('identified_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_identified_tracks_fingerprint'), 'identified_tracks', ['fingerprint'], unique=True)
op.create_index(op.f('ix_identified_tracks_id'), 'identified_tracks', ['id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_identified_tracks_id'), table_name='identified_tracks')
op.drop_index(op.f('ix_identified_tracks_fingerprint'), table_name='identified_tracks')
op.drop_table('identified_tracks')
# ### end Alembic commands ###
"""baseline schema
Revision ID: 99b0833a4bd2
Revises:
Create Date: 2026-08-07 19:05:26.896974
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '99b0833a4bd2'
down_revision: Union[str, Sequence[str], None] = None
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('auth_attempts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('phone_number', sa.String(), nullable=True),
sa.Column('ip_address', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_auth_attempts_id'), 'auth_attempts', ['id'], unique=False)
op.create_index(op.f('ix_auth_attempts_ip_address'), 'auth_attempts', ['ip_address'], unique=False)
op.create_index(op.f('ix_auth_attempts_phone_number'), 'auth_attempts', ['phone_number'], unique=False)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(), nullable=True),
sa.Column('phone_number', sa.String(), nullable=True),
sa.Column('telegram_session_string', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
op.create_index(op.f('ix_users_phone_number'), 'users', ['phone_number'], unique=True)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('discovered_songs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=True),
sa.Column('artist', sa.String(), nullable=True),
sa.Column('genre', sa.String(), nullable=True),
sa.Column('coverart', sa.String(), nullable=True),
sa.Column('detected_at', sa.DateTime(), nullable=True),
sa.Column('liked', sa.Boolean(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_discovered_songs_artist'), 'discovered_songs', ['artist'], unique=False)
op.create_index(op.f('ix_discovered_songs_id'), 'discovered_songs', ['id'], unique=False)
op.create_index(op.f('ix_discovered_songs_title'), 'discovered_songs', ['title'], unique=False)
op.create_index(op.f('ix_discovered_songs_user_id'), 'discovered_songs', ['user_id'], unique=False)
op.create_table('follows',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('follower_id', sa.Integer(), nullable=True),
sa.Column('following_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['following_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_follows_follower_id'), 'follows', ['follower_id'], unique=False)
op.create_index(op.f('ix_follows_following_id'), 'follows', ['following_id'], unique=False)
op.create_index(op.f('ix_follows_id'), 'follows', ['id'], unique=False)
op.create_table('library_songs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('title', sa.String(), nullable=True),
sa.Column('artist', sa.String(), nullable=True),
sa.Column('album', sa.String(), nullable=True),
sa.Column('genre', sa.String(), nullable=True),
sa.Column('coverart', sa.String(), nullable=True),
sa.Column('lyrics', sa.String(), nullable=True),
sa.Column('file_path', sa.String(), nullable=True),
sa.Column('added_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_library_songs_artist'), 'library_songs', ['artist'], unique=False)
op.create_index(op.f('ix_library_songs_id'), 'library_songs', ['id'], unique=False)
op.create_index(op.f('ix_library_songs_title'), 'library_songs', ['title'], unique=False)
op.create_index(op.f('ix_library_songs_user_id'), 'library_songs', ['user_id'], unique=False)
op.create_table('playlists',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('name', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_playlists_id'), 'playlists', ['id'], unique=False)
op.create_index(op.f('ix_playlists_user_id'), 'playlists', ['user_id'], unique=False)
op.create_table('refresh_tokens',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('token_hash', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('expires_at', sa.DateTime(), nullable=True),
sa.Column('revoked_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_refresh_tokens_id'), 'refresh_tokens', ['id'], unique=False)
op.create_index(op.f('ix_refresh_tokens_token_hash'), 'refresh_tokens', ['token_hash'], unique=True)
op.create_index(op.f('ix_refresh_tokens_user_id'), 'refresh_tokens', ['user_id'], unique=False)
op.create_table('user_profiles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('bio', sa.String(), nullable=True),
sa.Column('avatar_url', sa.String(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_user_profiles_id'), 'user_profiles', ['id'], unique=False)
op.create_index(op.f('ix_user_profiles_user_id'), 'user_profiles', ['user_id'], unique=True)
op.create_table('geo_drops',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('latitude', sa.Float(), nullable=True),
sa.Column('longitude', sa.Float(), nullable=True),
sa.Column('dropped_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_geo_drops_id'), 'geo_drops', ['id'], unique=False)
op.create_index(op.f('ix_geo_drops_user_id'), 'geo_drops', ['user_id'], unique=False)
op.create_table('live_rooms',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('dj_id', sa.Integer(), nullable=True),
sa.Column('current_song_id', sa.Integer(), nullable=True),
sa.Column('name', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['current_song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['dj_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_live_rooms_dj_id'), 'live_rooms', ['dj_id'], unique=False)
op.create_index(op.f('ix_live_rooms_id'), 'live_rooms', ['id'], unique=False)
op.create_table('playlist_tracks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('playlist_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('order', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['playlist_id'], ['playlists.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_playlist_tracks_id'), 'playlist_tracks', ['id'], unique=False)
op.create_index(op.f('ix_playlist_tracks_playlist_id'), 'playlist_tracks', ['playlist_id'], unique=False)
op.create_table('posts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('parent_post_id', sa.Integer(), nullable=True),
sa.Column('caption', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['parent_post_id'], ['posts.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_posts_id'), 'posts', ['id'], unique=False)
op.create_index(op.f('ix_posts_user_id'), 'posts', ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_posts_user_id'), table_name='posts')
op.drop_index(op.f('ix_posts_id'), table_name='posts')
op.drop_table('posts')
op.drop_index(op.f('ix_playlist_tracks_playlist_id'), table_name='playlist_tracks')
op.drop_index(op.f('ix_playlist_tracks_id'), table_name='playlist_tracks')
op.drop_table('playlist_tracks')
op.drop_index(op.f('ix_live_rooms_id'), table_name='live_rooms')
op.drop_index(op.f('ix_live_rooms_dj_id'), table_name='live_rooms')
op.drop_table('live_rooms')
op.drop_index(op.f('ix_geo_drops_user_id'), table_name='geo_drops')
op.drop_index(op.f('ix_geo_drops_id'), table_name='geo_drops')
op.drop_table('geo_drops')
op.drop_index(op.f('ix_user_profiles_user_id'), table_name='user_profiles')
op.drop_index(op.f('ix_user_profiles_id'), table_name='user_profiles')
op.drop_table('user_profiles')
op.drop_index(op.f('ix_refresh_tokens_user_id'), table_name='refresh_tokens')
op.drop_index(op.f('ix_refresh_tokens_token_hash'), table_name='refresh_tokens')
op.drop_index(op.f('ix_refresh_tokens_id'), table_name='refresh_tokens')
op.drop_table('refresh_tokens')
op.drop_index(op.f('ix_playlists_user_id'), table_name='playlists')
op.drop_index(op.f('ix_playlists_id'), table_name='playlists')
op.drop_table('playlists')
op.drop_index(op.f('ix_library_songs_user_id'), table_name='library_songs')
op.drop_index(op.f('ix_library_songs_title'), table_name='library_songs')
op.drop_index(op.f('ix_library_songs_id'), table_name='library_songs')
op.drop_index(op.f('ix_library_songs_artist'), table_name='library_songs')
op.drop_table('library_songs')
op.drop_index(op.f('ix_follows_id'), table_name='follows')
op.drop_index(op.f('ix_follows_following_id'), table_name='follows')
op.drop_index(op.f('ix_follows_follower_id'), table_name='follows')
op.drop_table('follows')
op.drop_index(op.f('ix_discovered_songs_user_id'), table_name='discovered_songs')
op.drop_index(op.f('ix_discovered_songs_title'), table_name='discovered_songs')
op.drop_index(op.f('ix_discovered_songs_id'), table_name='discovered_songs')
op.drop_index(op.f('ix_discovered_songs_artist'), table_name='discovered_songs')
op.drop_table('discovered_songs')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_phone_number'), table_name='users')
op.drop_index(op.f('ix_users_id'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_auth_attempts_phone_number'), table_name='auth_attempts')
op.drop_index(op.f('ix_auth_attempts_ip_address'), table_name='auth_attempts')
op.drop_index(op.f('ix_auth_attempts_id'), table_name='auth_attempts')
op.drop_table('auth_attempts')
# ### end Alembic commands ###
#!/usr/bin/env bash
# Deploys the current branch to this machine. Invoked over SSH by the GitLab CI `deploy_prod`
# job on every push to main - see .gitlab-ci.yml. Can also be run by hand on the prod server
# for a manual redeploy/rollback.
#
# Self-bootstrapping: safe to run against a completely bare machine (no repo, no venv, no
# systemd units installed yet) as well as an already-deployed one. Every step checks what's
# already present and only does the part that's missing - nothing gets reinstalled/recloned
# for no reason, but anything new (a package, a service file, a migration) gets picked up.
#
# Self-updating on purpose: once the repo exists, this script pulls it (including itself) as
# its first real step. That's safe on Linux - once bash starts executing a script it holds an
# open file descriptor to the file's original inode, and `git reset --hard` writes new blobs
# rather than editing the file in place, so the already-running process keeps reading the
# version it started with.
#
# Every step must be idempotent and safe to re-run: this same script is the recovery path if
# a deploy fails partway.
set -euo pipefail
DEPLOY_DIR="${STAX_DEPLOY_DIR:-/root/stax_backend_api}"
DEPLOY_REF="${STAX_DEPLOY_REF:-origin/main}"
REPO_URL="${STAX_REPO_URL:-ssh://git@lab.euhosted.com:3300/aryannoshirvani/stax_backend_api.git}"
VENV_DIR="${STAX_VENV_DIR:-$DEPLOY_DIR/venv}"
HEALTH_URL="${STAX_HEALTH_URL:-http://127.0.0.1:8000/healthz}"
HEALTH_TIMEOUT_SECONDS="${STAX_HEALTH_TIMEOUT_SECONDS:-30}"
log() { echo "[deploy] $*"; }
# --- 1. System packages - idempotent, apt skips anything already satisfied -----------------
log "Ensuring system packages are present"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
python3 python3-venv ffmpeg git curl build-essential
# --- 2. Repo - clone on a bare box, fetch+reset on an already-deployed one -----------------
if [ ! -d "$DEPLOY_DIR/.git" ]; then
log "No checkout at $DEPLOY_DIR yet - cloning $REPO_URL"
mkdir -p "$(dirname "$DEPLOY_DIR")"
git clone "$REPO_URL" "$DEPLOY_DIR"
fi
cd "$DEPLOY_DIR"
PREV_SHA="$(git rev-parse HEAD 2>/dev/null || echo "none")"
log "Currently at $PREV_SHA"
log "Fetching and resetting to $DEPLOY_REF"
git fetch --all --prune
git reset --hard "$DEPLOY_REF"
NEW_SHA="$(git rev-parse HEAD)"
if [ "$PREV_SHA" = "$NEW_SHA" ]; then
log "Already at $NEW_SHA, nothing new - redeploying anyway (manual trigger or retry)"
fi
# --- 3. Virtualenv + deps - venv created once, pip install is a no-op when nothing changed -
if [ ! -d "$VENV_DIR" ]; then
log "No venv at $VENV_DIR - creating it"
python3 -m venv "$VENV_DIR"
fi
log "Installing dependencies into $VENV_DIR"
# shellcheck disable=SC1091
source "$VENV_DIR/bin/activate"
pip install --prefer-binary -q -r requirements.txt
# --- 4. .env - only (re)written when the CI job actually supplied prod secrets, so a manual
# redeploy with no secrets in the environment never wipes a working .env ------------------
if [ -n "${STAX_PROD_JWT_SECRET:-}" ]; then
log "Writing $DEPLOY_DIR/.env from CI-supplied variables"
umask 077
cat > .env.new <<EOF
JWT_SECRET=${STAX_PROD_JWT_SECRET}
ACOUSTID_API_KEY=${STAX_PROD_ACOUSTID_API_KEY:-}
GEMINI_API_KEY=${STAX_PROD_GEMINI_API_KEY:-}
TELEGRAM_BOT_TOKEN=${STAX_PROD_TELEGRAM_BOT_TOKEN:-}
LALAL_API_KEY=${STAX_PROD_LALAL_API_KEY:-}
DOCS_USERNAME=${STAX_PROD_DOCS_USERNAME:-}
DOCS_PASSWORD=${STAX_PROD_DOCS_PASSWORD:-}
DATABASE_URL=${STAX_PROD_DATABASE_URL:-sqlite:////root/stax_backend_api/db/stax.db}
LOCAL_STORAGE_ROOT=${STAX_PROD_LOCAL_STORAGE_ROOT:-/root/stax_backend_api/var/storage}
EOF
mv .env.new .env
elif [ ! -f .env ]; then
log "FAILED: no .env on disk and no STAX_PROD_JWT_SECRET supplied to generate one"
log "Set the PROD_* CI/CD variables in GitLab, or create $DEPLOY_DIR/.env by hand once."
exit 1
else
log ".env already present, no new secrets supplied - leaving it as-is"
fi
log "Running database migrations"
alembic upgrade head
# --- 5. systemd units - install/refresh every *.service shipped in the repo, so a newly added
# service gets picked up automatically without editing this script -------------------------
log "Syncing systemd unit files"
UNITS_CHANGED=0
for unit_file in deploy/systemd/*.service; do
unit_name="$(basename "$unit_file")"
if ! cmp -s "$unit_file" "/etc/systemd/system/$unit_name" 2>/dev/null; then
cp "$unit_file" "/etc/systemd/system/$unit_name"
UNITS_CHANGED=1
fi
done
if [ "$UNITS_CHANGED" = "1" ]; then
systemctl daemon-reload
fi
SERVICES=""
for unit_file in deploy/systemd/*.service; do
unit_name="$(basename "$unit_file" .service)"
systemctl enable "$unit_name" >/dev/null 2>&1 || true
SERVICES="$SERVICES $unit_name"
done
log "Restarting service(s):$SERVICES"
for service in $SERVICES; do
systemctl restart "$service"
done
for service in $SERVICES; do
if ! systemctl is-active --quiet "$service"; then
log "FAILED: $service did not report active after restart"
journalctl -u "$service" -n 50 --no-pager || true
exit 1
fi
done
log "Waiting up to ${HEALTH_TIMEOUT_SECONDS}s for $HEALTH_URL to report healthy"
deadline=$((SECONDS + HEALTH_TIMEOUT_SECONDS))
until curl -fsS -o /dev/null "$HEALTH_URL"; do
if [ "$SECONDS" -ge "$deadline" ]; then
log "FAILED: service did not become healthy in time"
log "Recent logs:"
journalctl -u stax_backend -n 50 --no-pager || true
log "Previous good commit was $PREV_SHA - to roll back:"
log " STAX_DEPLOY_REF=$PREV_SHA bash $DEPLOY_DIR/deploy/scripts/deploy.sh"
exit 1
fi
sleep 2
done
log "Deploy successful - $NEW_SHA is live and healthy"
[Unit]
Description=Stax Backend API
After=network.target
[Service]
User=root
WorkingDirectory=/root/stax_backend_api
EnvironmentFile=/root/stax_backend_api/.env
Environment="PATH=/root/stax_backend_api/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Environment="PYTHONPATH=/root/stax_backend_api"
ExecStart=/root/stax_backend_api/venv/bin/uvicorn src.api.main:app --host 0.0.0.0 --port 8000
Restart=always
RestartSec=5
StandardOutput=append:/root/stax_backend_api/api.log
StandardError=append:/root/stax_backend_api/api.log
[Install]
WantedBy=multi-user.target
...@@ -11,9 +11,14 @@ services: ...@@ -11,9 +11,14 @@ services:
- HTTP_PROXY=${HTTP_PROXY:-} - HTTP_PROXY=${HTTP_PROXY:-}
- HTTPS_PROXY=${HTTPS_PROXY:-} - HTTPS_PROXY=${HTTPS_PROXY:-}
- NO_PROXY=localhost,127.0.0.1 - NO_PROXY=localhost,127.0.0.1
- DATABASE_URL=sqlite:////app/db/stax.db
- LOCAL_STORAGE_ROOT=/app/var/storage
volumes: volumes:
- ./downloads:/app/downloads - stax_storage:/app/var/storage
- ./temp:/app/temp - stax_db:/app/db
- ./stax.db:/app/stax.db
env_file: env_file:
- .env - .env
volumes:
stax_storage:
stax_db:
import os
import secrets
from fastapi import FastAPI, Depends, Request, Form, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music, social
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
return False
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads")
app.include_router(auth.router)
app.include_router(discovery.router)
app.include_router(library.router)
app.include_router(music.router)
app.include_router(social.router)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/openapi.json", include_in_schema=False)
async def openapi(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Stax Music API",
version="1.0.0",
description="API backend for the Stax App. Features music tagging and batch remixing.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
...@@ -14,5 +14,8 @@ sqlalchemy>=2.0.0 ...@@ -14,5 +14,8 @@ sqlalchemy>=2.0.0
httpx>=0.27.0 httpx>=0.27.0
python-multipart>=0.0.9 python-multipart>=0.0.9
pytest>=8.0.0 pytest>=8.0.0
pytest-mock>=3.14.0
pyrogram>=2.0.106 pyrogram>=2.0.106
tgcrypto>=1.2.5 tgcrypto>=1.2.5
pyjwt>=2.8.0
alembic>=1.13.0
import os import os
import secrets import secrets
from fastapi import Depends, FastAPI, HTTPException, status from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.openapi.utils import get_openapi from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, discovery, library, music, social from src.api.routers import auth, discovery, library, music, social
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True) from src.services.storage import DOWNLOADS_DIR
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html") CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html")
...@@ -33,7 +33,7 @@ def verify_docs_auth(credentials: HTTPBasicCredentials = Depends(docs_security)) ...@@ -33,7 +33,7 @@ def verify_docs_auth(credentials: HTTPBasicCredentials = Depends(docs_security))
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/downloads", StaticFiles(directory="/root/antigrav-stax-audio/downloads"), name="downloads") app.mount("/downloads", StaticFiles(directory=DOWNLOADS_DIR), name="downloads")
app.include_router(auth.router) app.include_router(auth.router)
app.include_router(discovery.router) app.include_router(discovery.router)
...@@ -47,6 +47,21 @@ async def root(): ...@@ -47,6 +47,21 @@ async def root():
return RedirectResponse(url="/docs") return RedirectResponse(url="/docs")
@app.get("/healthz", include_in_schema=False)
async def healthz():
"""Unauthenticated liveness/readiness probe for the deploy script - confirms the process
is up AND can reach the database, not just that the port is open."""
try:
db = SessionLocal()
try:
db.execute(text("SELECT 1"))
finally:
db.close()
except Exception as e:
return JSONResponse(status_code=503, content={"status": "error", "detail": str(e)})
return {"status": "ok"}
@app.get("/docs", include_in_schema=False, response_class=HTMLResponse) @app.get("/docs", include_in_schema=False, response_class=HTMLResponse)
async def get_documentation(username: str = Depends(verify_docs_auth)): async def get_documentation(username: str = Depends(verify_docs_auth)):
with open(CONSOLE_HTML_PATH, "r") as f: with open(CONSOLE_HTML_PATH, "r") as f:
......
from fastapi import APIRouter, Depends, HTTPException, Header from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db from src.core.database import AuthAttempt, RefreshToken, User, get_db
from src.core.security import (
create_access_token,
create_refresh_token,
decode_token,
get_current_user,
hash_token,
)
# We need to import telegram modules from the new worker path
import src.telegram_worker.telegram_auth as telegram_auth import src.telegram_worker.telegram_auth as telegram_auth
import src.telegram_worker.telegram_sync as telegram_sync import src.telegram_worker.telegram_sync as telegram_sync
# If User doesn't exist in database, this might fail, but preserving existing behavior
# Actually, I should probably check database.py for User, but for now I'll import it
# assuming it exists or handle it safely.
try:
from src.core.database import User
except ImportError:
User = None
router = APIRouter(prefix="/auth", tags=["Authentication & Telegram"]) router = APIRouter(prefix="/auth", tags=["Authentication & Telegram"])
def _utcnow() -> datetime:
"""Naive UTC, matching what SQLite hands back for DateTime columns - comparing that
against an aware datetime.now(timezone.utc) raises TypeError."""
return datetime.now(timezone.utc).replace(tzinfo=None)
# Our own Telegram API credentials are shared across every user, so a client hammering
# /auth/request_code with arbitrary numbers could get them flagged. Cheap DB-backed limit,
# no Redis required.
MAX_REQUESTS_PER_PHONE = 5
PHONE_WINDOW = timedelta(minutes=10)
MAX_REQUESTS_PER_IP = 20
IP_WINDOW = timedelta(hours=1)
class RequestCodeReq(BaseModel): class RequestCodeReq(BaseModel):
phone_number: str phone_number: str
class LoginReq(BaseModel): class LoginReq(BaseModel):
phone_number: str phone_number: str
phone_code_hash: str phone_code_hash: str
code: str code: str
class RefreshReq(BaseModel):
refresh_token: str
class TokenResponse(BaseModel):
access_token: str
refresh_token: str
token_type: str = "bearer"
def _check_rate_limit(db: Session, phone_number: str, ip: str):
now = _utcnow()
phone_count = (
db.query(AuthAttempt)
.filter(AuthAttempt.phone_number == phone_number, AuthAttempt.created_at >= now - PHONE_WINDOW)
.count()
)
if phone_count >= MAX_REQUESTS_PER_PHONE:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many code requests for this number, try again later")
ip_count = (
db.query(AuthAttempt)
.filter(AuthAttempt.ip_address == ip, AuthAttempt.created_at >= now - IP_WINDOW)
.count()
)
if ip_count >= MAX_REQUESTS_PER_IP:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many code requests from this address, try again later")
def _issue_tokens(db: Session, user_id: int) -> TokenResponse:
access = create_access_token(user_id)
refresh = create_refresh_token(user_id)
db.add(RefreshToken(
user_id=user_id,
token_hash=hash_token(refresh),
expires_at=_utcnow() + timedelta(days=30),
))
db.commit()
return TokenResponse(access_token=access, refresh_token=refresh)
@router.post("/request_code") @router.post("/request_code")
async def auth_request_code(req: RequestCodeReq): async def auth_request_code(req: RequestCodeReq, request: Request, db: Session = Depends(get_db)):
client_ip = request.client.host if request.client else "unknown"
_check_rate_limit(db, req.phone_number, client_ip)
db.add(AuthAttempt(phone_number=req.phone_number, ip_address=client_ip))
db.commit()
try: try:
res = await telegram_auth.request_code(req.phone_number) res = await telegram_auth.request_code(req.phone_number)
return {"status": "success", "data": res} return {"status": "success", "data": res}
except Exception as e: except Exception as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
@router.post("/login")
@router.post("/login", response_model=TokenResponse)
async def auth_login(req: LoginReq, db: Session = Depends(get_db)): async def auth_login(req: LoginReq, db: Session = Depends(get_db)):
try: try:
res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code) res = await telegram_auth.login(req.phone_number, req.phone_code_hash, req.code)
# Save or update user in our DB
if User:
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], username=req.phone_number)
db.add(user)
db.commit()
return {"status": "success", "access_token": res["session_string"], "user_id": res["user_id"]}
except Exception as e: except Exception as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
user = db.query(User).filter(User.id == res["user_id"]).first()
if not user:
user = User(id=res["user_id"], phone_number=req.phone_number)
db.add(user)
# Session string never leaves the server from here on - it's our internal credential
# for calling telegram_sync on this user's behalf, not the API's bearer token.
user.telegram_session_string = res["session_string"]
user.phone_number = req.phone_number
db.commit()
return _issue_tokens(db, user.id)
@router.post("/refresh", response_model=TokenResponse)
async def auth_refresh(req: RefreshReq, db: Session = Depends(get_db)):
payload = decode_token(req.refresh_token, expected_type="refresh")
token_hash = hash_token(req.refresh_token)
stored = db.query(RefreshToken).filter(RefreshToken.token_hash == token_hash).first()
if not stored or stored.revoked_at is not None or stored.expires_at < _utcnow():
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Refresh token invalid or revoked")
stored.revoked_at = _utcnow()
db.commit()
return _issue_tokens(db, int(payload["sub"]))
@router.post("/logout")
async def auth_logout(req: RefreshReq, db: Session = Depends(get_db)):
token_hash = hash_token(req.refresh_token)
stored = db.query(RefreshToken).filter(RefreshToken.token_hash == token_hash).first()
if stored and stored.revoked_at is None:
stored.revoked_at = _utcnow()
db.commit()
return {"status": "success"}
@router.get("/chats") @router.get("/chats")
async def get_chats(session_string: str = Header(None)): async def get_chats(current_user: User = Depends(get_current_user)):
if not session_string: if not current_user.telegram_session_string:
raise HTTPException(status_code=401, detail="Session string required") raise HTTPException(status_code=400, detail="No linked Telegram session")
try: try:
chats = await telegram_sync.get_chats(session_string) chats = await telegram_sync.get_chats(current_user.telegram_session_string)
return {"status": "success", "chats": chats} return {"status": "success", "chats": chats}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@router.get("/chats/{chat_id}/music") @router.get("/chats/{chat_id}/music")
async def get_chat_music(chat_id: int, session_string: str = Header(None)): async def get_chat_music(chat_id: int, current_user: User = Depends(get_current_user)):
if not session_string: if not current_user.telegram_session_string:
raise HTTPException(status_code=401, detail="Session string required") raise HTTPException(status_code=400, detail="No linked Telegram session")
try: try:
music = await telegram_sync.get_chat_music(session_string, chat_id) music = await telegram_sync.get_chat_music(current_user.telegram_session_string, chat_id)
return {"status": "success", "music": music} return {"status": "success", "music": music}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
import os
import shutil import shutil
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from src.core.database import get_db, DiscoveredSong from src.core.database import get_db, DiscoveredSong, User
from src.core.security import get_current_user
from src.services import storage
from src.services.music_identification import identify_audio from src.services.music_identification import identify_audio
router = APIRouter(prefix="/discovery", tags=["Music Discovery"]) router = APIRouter(prefix="/discovery", tags=["Music Discovery"])
@router.post("/listen") @router.post("/listen")
async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db)): async def discovery_listen(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Accepts a short audio snippet from the microphone to identify what's playing.""" """Accepts a short audio snippet from the microphone to identify what's playing."""
temp_filename = f"/root/antigrav-stax-audio/temp/{file.filename}" temp_path = storage.new_temp_path(file.filename)
with open(temp_filename, "wb") as buffer: with open(temp_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer) shutil.copyfileobj(file.file, buffer)
candidates = await identify_audio(temp_filename) try:
if not candidates: candidates = await identify_audio(temp_path)
os.remove(temp_filename) if not candidates:
return {"status": "error", "message": "No music detected"} return {"status": "error", "message": "No music detected"}
candidate = candidates[0] candidate = candidates[0]
new_song = DiscoveredSong( new_song = DiscoveredSong(
title=candidate.get("title"), user_id=current_user.id,
artist=candidate.get("artist"), title=candidate.get("title"),
genre=candidate.get("genre"), artist=candidate.get("artist"),
coverart=candidate.get("coverart") genre=candidate.get("genre"),
) coverart=candidate.get("coverart")
db.add(new_song) )
db.commit() db.add(new_song)
db.refresh(new_song) db.commit()
db.refresh(new_song)
os.remove(temp_filename)
return {"status": "success", "detected": candidate, "discovery_id": new_song.id} return {"status": "success", "detected": candidate, "discovery_id": new_song.id}
finally:
storage.cleanup_temp(temp_path)
@router.get("/history") @router.get("/history")
async def discovery_history(db: Session = Depends(get_db)): async def discovery_history(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Returns the background listening history for the past 24 hours.""" """Returns the current user's background listening history for the past 24 hours."""
time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24) time_24h_ago = datetime.now(timezone.utc) - timedelta(hours=24)
songs = db.query(DiscoveredSong).filter(DiscoveredSong.detected_at >= time_24h_ago).order_by(DiscoveredSong.detected_at.desc()).all() songs = (
db.query(DiscoveredSong)
.filter(DiscoveredSong.user_id == current_user.id, DiscoveredSong.detected_at >= time_24h_ago)
.order_by(DiscoveredSong.detected_at.desc())
.all()
)
return {"status": "success", "history": songs} return {"status": "success", "history": songs}
@router.post("/{song_id}/swipe") @router.post("/{song_id}/swipe")
async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db)): async def discovery_swipe(song_id: int, liked: bool = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Swipe right (liked=true) or left (liked=false) on a discovered song.""" """Swipe right (liked=true) or left (liked=false) on a discovered song."""
song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first() song = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id, DiscoveredSong.user_id == current_user.id).first()
if not song: if not song:
raise HTTPException(status_code=404, detail="Song not found") raise HTTPException(status_code=404, detail="Song not found")
song.liked = liked song.liked = liked
......
...@@ -4,7 +4,8 @@ from fastapi.responses import FileResponse ...@@ -4,7 +4,8 @@ from fastapi.responses import FileResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack from src.core.database import get_db, LibrarySong, Playlist, PlaylistTrack, User
from src.core.security import get_current_user
router = APIRouter(tags=["Library & Playlists"]) router = APIRouter(tags=["Library & Playlists"])
...@@ -12,59 +13,60 @@ class PlaylistCreate(BaseModel): ...@@ -12,59 +13,60 @@ class PlaylistCreate(BaseModel):
name: str name: str
@router.get("/library") @router.get("/library")
async def get_library(db: Session = Depends(get_db)): async def get_library(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
songs = db.query(LibrarySong).order_by(LibrarySong.added_at.desc()).all() songs = db.query(LibrarySong).filter(LibrarySong.user_id == current_user.id).order_by(LibrarySong.added_at.desc()).all()
return {"status": "success", "library": songs} return {"status": "success", "library": songs}
@router.get("/library/stream/{file_id}") @router.get("/library/stream/{file_id}")
async def stream_audio(file_id: int, db: Session = Depends(get_db)): async def stream_audio(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first() song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
if not song or not song.file_path or not os.path.exists(song.file_path): if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found") raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg") return FileResponse(song.file_path, media_type="audio/mpeg")
@router.get("/library/lyrics/{file_id}") @router.get("/library/lyrics/{file_id}")
async def get_lyrics(file_id: int, db: Session = Depends(get_db)): async def get_lyrics(file_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
song = db.query(LibrarySong).filter(LibrarySong.id == file_id).first() song = db.query(LibrarySong).filter(LibrarySong.id == file_id, LibrarySong.user_id == current_user.id).first()
if not song: if not song:
raise HTTPException(status_code=404, detail="Song not found") raise HTTPException(status_code=404, detail="Song not found")
return {"status": "success", "lyrics": song.lyrics} return {"status": "success", "lyrics": song.lyrics}
@router.post("/library/search") @router.post("/library/search")
async def search_library(query: str = Form(...), db: Session = Depends(get_db)): async def search_library(query: str = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
q = f"%{query}%" q = f"%{query}%"
songs = db.query(LibrarySong).filter( songs = db.query(LibrarySong).filter(
(LibrarySong.title.ilike(q)) | LibrarySong.user_id == current_user.id,
(LibrarySong.artist.ilike(q)) | (LibrarySong.title.ilike(q)) |
(LibrarySong.artist.ilike(q)) |
(LibrarySong.genre.ilike(q)) (LibrarySong.genre.ilike(q))
).all() ).all()
return {"status": "success", "results": songs} return {"status": "success", "results": songs}
@router.get("/playlists") @router.get("/playlists")
async def get_playlists(db: Session = Depends(get_db)): async def get_playlists(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
playlists = db.query(Playlist).order_by(Playlist.created_at.desc()).all() playlists = db.query(Playlist).filter(Playlist.user_id == current_user.id).order_by(Playlist.created_at.desc()).all()
return {"status": "success", "playlists": playlists} return {"status": "success", "playlists": playlists}
@router.post("/playlists") @router.post("/playlists")
async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db)): async def create_playlist(data: PlaylistCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
new_pl = Playlist(name=data.name) new_pl = Playlist(name=data.name, user_id=current_user.id)
db.add(new_pl) db.add(new_pl)
db.commit() db.commit()
db.refresh(new_pl) db.refresh(new_pl)
return {"status": "success", "playlist": new_pl} return {"status": "success", "playlist": new_pl}
@router.post("/playlists/{playlist_id}/add") @router.post("/playlists/{playlist_id}/add")
async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db)): async def add_to_playlist(playlist_id: int, song_id: int = Form(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
pl = db.query(Playlist).filter(Playlist.id == playlist_id).first() pl = db.query(Playlist).filter(Playlist.id == playlist_id, Playlist.user_id == current_user.id).first()
if not pl: if not pl:
raise HTTPException(status_code=404, detail="Playlist not found") raise HTTPException(status_code=404, detail="Playlist not found")
song = db.query(LibrarySong).filter(LibrarySong.id == song_id).first() song = db.query(LibrarySong).filter(LibrarySong.id == song_id, LibrarySong.user_id == current_user.id).first()
if not song: if not song:
raise HTTPException(status_code=404, detail="Song not found") raise HTTPException(status_code=404, detail="Song not found")
# Get max order # Get max order
max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count() max_order = db.query(PlaylistTrack).filter(PlaylistTrack.playlist_id == playlist_id).count()
pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order) pt = PlaylistTrack(playlist_id=playlist_id, song_id=song_id, order=max_order)
db.add(pt) db.add(pt)
db.commit() db.commit()
......
import os import asyncio
import shutil import shutil
import uuid
import urllib.parse import urllib.parse
from typing import List from typing import List
import asyncio
import google.generativeai as genai
from fastapi import APIRouter, HTTPException, UploadFile, File import google.generativeai as genai
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.services.music_identification import identify_with_gemini, identify_audio, fetch_lyrics import src.telegram_worker.telegram_sync as telegram_sync
from src.core.config import logger
from src.core.database import IdentifiedTrack, LibrarySong, User, get_db
from src.core.security import get_current_user
from src.services import storage
from src.services.audio_processing import tag_and_convert_audio from src.services.audio_processing import tag_and_convert_audio
from src.services.music_identification import (
compute_fingerprint,
fetch_lyrics,
identify_audio,
identify_with_gemini,
)
router = APIRouter(prefix="/music", tags=["Music Processing"]) router = APIRouter(prefix="/music", tags=["Music Processing"])
class TagRequest(BaseModel): class TagRequest(BaseModel):
chat_id: int chat_id: int
message_id: int message_id: int
language_preference: str = "native" language_preference: str = "native"
class TagResponse(BaseModel): class TagResponse(BaseModel):
status: str status: str
download_url: str download_url: str
metadata: dict metadata: dict
class FileToRemix(BaseModel): class FileToRemix(BaseModel):
chat_id: int chat_id: int
message_id: int message_id: int
class RemixBatchRequest(BaseModel): class RemixBatchRequest(BaseModel):
files: List[FileToRemix] files: List[FileToRemix]
prompt: str prompt: str
@router.post("/tag", response_model=TagResponse)
async def tag_music(req: TagRequest):
return {
"status": "success",
"download_url": "https://api.staxmusic.com/downloads/tagged_track.mp3",
"metadata": {
"title": "Mock Title",
"artist": "Mock Artist",
"album": "Mock Album",
"genre": "Pop"
}
}
@router.post("/remix/batch") async def _identify_tag_and_store(
async def batch_remix(req: RemixBatchRequest): db: Session,
return {"status": "accepted", "job_id": "mock_job_12345", "message": "Batch remix job accepted and processing in background."} current_user: User,
raw_file_path: str,
request: Request,
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."""
try:
fingerprint = await compute_fingerprint(raw_file_path)
cached = (
db.query(IdentifiedTrack).filter(IdentifiedTrack.fingerprint == fingerprint).first()
if fingerprint else None
)
@router.get("/remix/status/{job_id}") if cached:
async def batch_remix_status(job_id: str): candidate = {
return {"status": "processing", "job_id": job_id, "progress": 45, "message": "Applying AI crossfades..."} 'title': cached.title, 'artist': cached.artist, 'album': cached.album,
'year': cached.year, 'genre': cached.genre, 'track_number': cached.track_number,
'source': cached.source, 'coverart': cached.coverart, 'lyrics': cached.lyrics,
}
else:
candidates = await identify_audio(raw_file_path)
candidate = candidates[0] if candidates else None
@router.post("/upload", response_model=TagResponse) if not candidate:
async def upload_direct(file: UploadFile = File(...)): gemini_result = await identify_with_gemini(raw_file_path, language_preference)
temp_filename = f"/root/antigrav-stax-audio/temp/{uuid.uuid4()}_{file.filename}" candidate = gemini_result if gemini_result else {}
with open(temp_filename, "wb") as buffer:
shutil.copyfileobj(file.file, buffer) if not candidate.get("lyrics"):
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", ""))
try: candidate["lyrics"] = lyrics
candidates = await identify_audio(temp_filename)
candidate = candidates[0] if candidates else None if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre":
title, artist = candidate.get("title", ""), candidate.get("artist", "")
if not candidate: if title and artist and title != "Unknown" and artist != "Unknown":
gemini_result = await identify_with_gemini(temp_filename, "native") try:
candidate = gemini_result if gemini_result else {} model = genai.GenerativeModel('gemini-2.5-flash')
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text."
if not candidate.get("lyrics"): response = await asyncio.to_thread(model.generate_content, prompt)
lyrics = await fetch_lyrics(candidate.get("title", ""), candidate.get("artist", "")) raw_text = response.text.strip()
candidate["lyrics"] = lyrics if "\n" in raw_text:
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1]
if not candidate.get("genre") or candidate.get("genre") == "Unknown Genre": else:
title = candidate.get("title", "") candidate["genre"] = raw_text
artist = candidate.get("artist", "") except Exception:
if title and artist and title != "Unknown" and artist != "Unknown": candidate["genre"] = "Unknown Genre"
if fingerprint:
db.add(IdentifiedTrack(
fingerprint=fingerprint,
title=candidate.get('title', 'Unknown'),
artist=candidate.get('artist', 'Unknown'),
album=candidate.get('album', ''),
year=candidate.get('year', ''),
genre=candidate.get('genre', ''),
track_number=candidate.get('track_number', ''),
source=candidate.get('source', ''),
coverart=candidate.get('coverart', ''),
lyrics=candidate.get('lyrics', ''),
))
try: try:
model = genai.GenerativeModel('gemini-2.5-flash') db.commit()
prompt = f"What is the genre of the song '{title}' by '{artist}'? Reply with ONLY a single genre name (e.g. Pop, Synth-pop, Classical). Do not include any other text." except Exception as e:
response = await asyncio.to_thread(model.generate_content, prompt) # Another concurrent request may have cached this fingerprint first -
raw_text = response.text.strip() # the cache write is best-effort, don't fail the user's tag request over it.
if "\n" in raw_text: db.rollback()
candidate["genre"] = [line.strip() for line in raw_text.split("\n") if line.strip()][-1] logger.error(f"IdentifiedTrack cache write failed: {e}")
else:
candidate["genre"] = raw_text tagged_path = await tag_and_convert_audio(raw_file_path, candidate)
except: final_path, url_path = storage.store_final(current_user.id, tagged_path)
candidate["genre"] = "Unknown Genre"
library_song = LibrarySong(
final_filename = await tag_and_convert_audio(temp_filename, candidate) user_id=current_user.id,
title=candidate.get('title', 'Unknown'),
# move to downloads directory artist=candidate.get('artist', 'Unknown'),
download_path = f"/root/antigrav-stax-audio/downloads/{final_filename}" album=candidate.get('album', ''),
shutil.move(final_filename, download_path) genre=candidate.get('genre', ''),
coverart=candidate.get('coverart', ''),
if os.path.exists(temp_filename): lyrics=candidate.get('lyrics', ''),
os.remove(temp_filename) file_path=final_path,
)
quoted_filename = urllib.parse.quote(final_filename) db.add(library_song)
db.commit()
db.refresh(library_song)
download_url = str(request.base_url).rstrip('/') + urllib.parse.quote(url_path)
return { return {
"status": "success", "status": "success",
"download_url": f"http://91.234.52.134:8000/downloads/{quoted_filename}", "download_url": download_url,
"metadata": { "metadata": {
"title": candidate.get('title', 'Unknown'), "library_song_id": library_song.id,
"artist": candidate.get('artist', 'Unknown'), "title": library_song.title,
"album": candidate.get('album', ''), "artist": library_song.artist,
"genre": candidate.get('genre', ''), "album": library_song.album,
"genre": library_song.genre,
"year": candidate.get('year', ''), "year": candidate.get('year', ''),
"has_lyrics": bool(candidate.get('lyrics')), "has_lyrics": bool(library_song.lyrics),
"lyrics": candidate.get('lyrics', ''), "lyrics": library_song.lyrics,
"cover_art": candidate.get('coverart', '') "cover_art": library_song.coverart,
} },
} }
finally:
storage.cleanup_temp(raw_file_path)
@router.post("/tag", response_model=TagResponse)
async def tag_music(
req: TagRequest,
request: Request,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Finds a specific audio message in one of the current user's Telegram chats, identifies
and tags it, and adds it to their library."""
if not current_user.telegram_session_string:
raise HTTPException(status_code=400, detail="No linked Telegram session")
dest = storage.new_temp_path(f"chat_{req.chat_id}_{req.message_id}")
try:
raw_file_path = await telegram_sync.download_chat_audio(
current_user.telegram_session_string, req.chat_id, req.message_id, dest
)
except Exception as e:
raise HTTPException(status_code=404, detail=f"Could not download audio from chat: {e}")
result = await _identify_tag_and_store(db, current_user, raw_file_path, request, req.language_preference)
return result
@router.post("/remix/batch")
async def batch_remix(req: RemixBatchRequest, current_user: User = Depends(get_current_user)):
raise HTTPException(status_code=501, detail="AI remix isn't implemented yet")
@router.get("/remix/status/{job_id}")
async def batch_remix_status(job_id: str, current_user: User = Depends(get_current_user)):
raise HTTPException(status_code=501, detail="AI remix isn't implemented yet")
@router.post("/upload", response_model=TagResponse)
async def upload_direct(
request: Request,
file: UploadFile = File(...),
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
temp_path = storage.new_temp_path(file.filename)
with open(temp_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
result = await _identify_tag_and_store(db, current_user, temp_path, request)
except Exception as e: except Exception as e:
if os.path.exists(temp_filename):
os.remove(temp_filename)
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
return result
...@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, status ...@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, User, Post, GeoDrop, LiveRoom from src.core.database import get_db, User, Post, GeoDrop, LiveRoom
from src.core.security import get_current_user
from datetime import datetime, timezone from datetime import datetime, timezone
import math import math
...@@ -11,58 +12,59 @@ router = APIRouter( ...@@ -11,58 +12,59 @@ router = APIRouter(
) )
# --- Schemas --- # --- Schemas ---
# None of these take a user id - every write is attributed to the authenticated caller.
class PostCreate(BaseModel): class PostCreate(BaseModel):
user_id: int
song_id: int song_id: int
parent_post_id: int = None parent_post_id: int = None
caption: str = "" caption: str = ""
class GeoDropCreate(BaseModel): class GeoDropCreate(BaseModel):
user_id: int
song_id: int song_id: int
latitude: float latitude: float
longitude: float longitude: float
class LiveRoomCreate(BaseModel): class LiveRoomCreate(BaseModel):
dj_id: int
name: str name: str
# --- Endpoints --- # --- Endpoints ---
# Posts/drops/rooms are shared social content by design, so reads aren't filtered to the
# caller's own rows - only writes are, by deriving the author from the auth token instead of
# trusting a client-supplied user_id/dj_id.
@router.post("/posts", status_code=status.HTTP_201_CREATED) @router.post("/posts", status_code=status.HTTP_201_CREATED)
def create_post(post: PostCreate, db: Session = Depends(get_db)): def create_post(post: PostCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_post = Post(**post.dict()) db_post = Post(user_id=current_user.id, **post.dict())
db.add(db_post) db.add(db_post)
db.commit() db.commit()
db.refresh(db_post) db.refresh(db_post)
return db_post return db_post
@router.get("/posts/{post_id}/tree") @router.get("/posts/{post_id}/tree")
def get_remix_tree(post_id: int, db: Session = Depends(get_db)): def get_remix_tree(post_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
post = db.query(Post).filter(Post.id == post_id).first() post = db.query(Post).filter(Post.id == post_id).first()
if not post: if not post:
raise HTTPException(status_code=404, detail="Post not found") raise HTTPException(status_code=404, detail="Post not found")
children = db.query(Post).filter(Post.parent_post_id == post_id).all() children = db.query(Post).filter(Post.parent_post_id == post_id).all()
return { return {
"post": post, "post": post,
"children": children "children": children
} }
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED) @router.post("/geo-drop", status_code=status.HTTP_201_CREATED)
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db)): def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_drop = GeoDrop(**drop.dict()) db_drop = GeoDrop(user_id=current_user.id, **drop.dict())
db.add(db_drop) db.add(db_drop)
db.commit() db.commit()
db.refresh(db_drop) db.refresh(db_drop)
return db_drop return db_drop
@router.get("/geo-drop/nearby") @router.get("/geo-drop/nearby")
def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db)): def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
all_drops = db.query(GeoDrop).all() all_drops = db.query(GeoDrop).all()
nearby = [] nearby = []
def haversine(lat1, lon1, lat2, lon2): def haversine(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth radius in kilometers R = 6371.0 # Earth radius in kilometers
dlat = math.radians(lat2 - lat1) dlat = math.radians(lat2 - lat1)
...@@ -77,18 +79,18 @@ def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session ...@@ -77,18 +79,18 @@ def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session
dist = haversine(lat, lon, drop.latitude, drop.longitude) dist = haversine(lat, lon, drop.latitude, drop.longitude)
if dist <= radius_km: if dist <= radius_km:
nearby.append({"drop": drop, "distance_km": dist}) nearby.append({"drop": drop, "distance_km": dist})
return sorted(nearby, key=lambda x: x["distance_km"]) return sorted(nearby, key=lambda x: x["distance_km"])
@router.post("/rooms", status_code=status.HTTP_201_CREATED) @router.post("/rooms", status_code=status.HTTP_201_CREATED)
def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db)): def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_room = LiveRoom(**room.dict()) db_room = LiveRoom(dj_id=current_user.id, **room.dict())
db.add(db_room) db.add(db_room)
db.commit() db.commit()
db.refresh(db_room) db.refresh(db_room)
return db_room return db_room
@router.get("/rooms") @router.get("/rooms")
def get_active_rooms(db: Session = Depends(get_db)): def get_active_rooms(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all() rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms return rooms
...@@ -6,7 +6,7 @@ from dotenv import load_dotenv ...@@ -6,7 +6,7 @@ from dotenv import load_dotenv
load_dotenv() load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH") ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
LALAL_API_KEY = os.getenv("LALAL_API_KEY") LALAL_API_KEY = os.getenv("LALAL_API_KEY")
...@@ -14,6 +14,11 @@ LALAL_API_KEY = os.getenv("LALAL_API_KEY") ...@@ -14,6 +14,11 @@ LALAL_API_KEY = os.getenv("LALAL_API_KEY")
DOCS_USERNAME = os.getenv("DOCS_USERNAME") DOCS_USERNAME = os.getenv("DOCS_USERNAME")
DOCS_PASSWORD = os.getenv("DOCS_PASSWORD") DOCS_PASSWORD = os.getenv("DOCS_PASSWORD")
# Signs every access/refresh JWT. Every request goes through this, so unlike the other keys
# above (which degrade gracefully per-request when absent) a missing secret must fail loudly
# at startup rather than silently falling back to something guessable.
JWT_SECRET = os.environ["JWT_SECRET"]
# Setup centralized logging # Setup centralized logging
logging.basicConfig( logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
......
import os import os
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Boolean, Float from sqlalchemy import create_engine, event, Column, Integer, String, DateTime, ForeignKey, Boolean, Float
from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime, timezone from datetime import datetime, timezone
...@@ -9,6 +9,16 @@ if db_dir and not os.path.exists(db_dir): ...@@ -9,6 +9,16 @@ if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir, exist_ok=True) os.makedirs(db_dir, exist_ok=True)
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
if DATABASE_URL.startswith("sqlite"):
# WAL lets readers (cache lookups, library reads) proceed without blocking behind
# writers, instead of sqlite's default rollback-journal mode which locks both ways.
@event.listens_for(engine, "connect")
def _set_sqlite_wal(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.close()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() Base = declarative_base()
...@@ -16,11 +26,33 @@ Base = declarative_base() ...@@ -16,11 +26,33 @@ Base = declarative_base()
class User(Base): class User(Base):
__tablename__ = "users" __tablename__ = "users"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True) username = Column(String, unique=True, index=True, nullable=True)
phone_number = Column(String, unique=True, index=True, nullable=True)
# Pyrogram session string for this user's linked Telegram account. Set on /auth/login,
# used server-side only (by telegram_sync calls) - never serialized back to a client.
telegram_session_string = Column(String, nullable=True)
class RefreshToken(Base):
__tablename__ = "refresh_tokens"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
token_hash = Column(String, unique=True, index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
expires_at = Column(DateTime)
revoked_at = Column(DateTime, nullable=True)
class AuthAttempt(Base):
"""Logged on every /auth/request_code call to rate-limit our own Telegram API usage."""
__tablename__ = "auth_attempts"
id = Column(Integer, primary_key=True, index=True)
phone_number = Column(String, index=True)
ip_address = Column(String, index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class DiscoveredSong(Base): class DiscoveredSong(Base):
__tablename__ = "discovered_songs" __tablename__ = "discovered_songs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
title = Column(String, index=True) title = Column(String, index=True)
artist = Column(String, index=True) artist = Column(String, index=True)
genre = Column(String) genre = Column(String)
...@@ -95,7 +127,23 @@ class LiveRoom(Base): ...@@ -95,7 +127,23 @@ class LiveRoom(Base):
is_active = Column(Boolean, default=True) is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
Base.metadata.create_all(bind=engine) class IdentifiedTrack(Base):
"""Permanent, user-independent cache of prior identification results, keyed by audio
content fingerprint. Lets a song that's already been tagged once (by anyone) skip
Shazam/AcoustID/Gemini/lyrics/genre lookups entirely on the next upload of that audio."""
__tablename__ = "identified_tracks"
id = Column(Integer, primary_key=True, index=True)
fingerprint = Column(String, unique=True, index=True, nullable=False)
title = Column(String)
artist = Column(String)
album = Column(String)
year = Column(String)
genre = Column(String)
track_number = Column(String)
source = Column(String)
coverart = Column(String)
lyrics = Column(String)
identified_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
def get_db(): def get_db():
db = SessionLocal() db = SessionLocal()
......
import hashlib
import uuid
from datetime import datetime, timedelta, timezone
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from src.core.config import JWT_SECRET
from src.core.database import User, get_db
JWT_ALGORITHM = "HS256"
ACCESS_TOKEN_TTL = timedelta(minutes=30)
REFRESH_TOKEN_TTL = timedelta(days=30)
bearer_scheme = HTTPBearer(auto_error=False)
def _create_token(user_id: int, token_type: str, ttl: timedelta) -> str:
now = datetime.now(timezone.utc)
# jti guarantees uniqueness even for two tokens issued to the same user within the same
# second (iat/exp alone are identical then, so the encoded JWT - and its hash - would
# collide with the refresh_tokens.token_hash unique constraint).
payload = {"sub": str(user_id), "type": token_type, "iat": now, "exp": now + ttl, "jti": uuid.uuid4().hex}
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
def create_access_token(user_id: int) -> str:
return _create_token(user_id, "access", ACCESS_TOKEN_TTL)
def create_refresh_token(user_id: int) -> str:
return _create_token(user_id, "refresh", REFRESH_TOKEN_TTL)
def hash_token(token: str) -> str:
"""One-way hash used to store refresh tokens - lets us revoke by lookup without keeping
the raw token (which is bearer-equivalent to a session) at rest."""
return hashlib.sha256(token.encode()).hexdigest()
def decode_token(token: str, expected_type: str) -> dict:
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
if payload.get("type") != expected_type:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token type")
return payload
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
db: Session = Depends(get_db),
) -> User:
if not credentials:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
payload = decode_token(credentials.credentials, expected_type="access")
user = db.query(User).filter(User.id == int(payload["sub"])).first()
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
return user
...@@ -43,18 +43,23 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str: ...@@ -43,18 +43,23 @@ async def tag_and_convert_audio(raw_file_path: str, candidate: dict) -> str:
if track_num: mp3.tags.add(TRCK(encoding=3, text=track_num)) if track_num: mp3.tags.add(TRCK(encoding=3, text=track_num))
if lyrics: if lyrics:
mp3.tags.add(USLT(encoding=3, lang='eng', desc=u'', text=lyrics)) # 'fas' (ISO 639-2/B for Persian) - 'eng' here would mislabel Persian lyrics as English.
mp3.tags.add(USLT(encoding=3, lang='fas', desc=u'', text=lyrics))
if coverart_url: if coverart_url:
image_bytes = await download_image(coverart_url) image_bytes = await download_image(coverart_url)
if image_bytes: if image_bytes:
mp3.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=image_bytes)) mp3.tags.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='Cover', data=image_bytes))
mp3.save(v2_version=3) # v2_version=3 (ID3v2.3) doesn't officially support UTF-8 (encoding=3 above); v2.4 does.
# Persian text saved as v2.3+UTF-8 renders as mojibake in many players.
mp3.save(v2_version=4)
# 3. Rename file # 3. Rename file
safe_title = "".join([c for c in title if c.isalnum() or c==' ']).rstrip() safe_title = "".join([c for c in title if c.isalnum() or c==' ']).rstrip()
final_filename = f"{safe_title}.mp3" if safe_title else "Unknown Track.mp3" final_filename = f"{safe_title}.mp3" if safe_title else "Unknown Track.mp3"
os.rename(mp3_file_path, final_filename) import shutil as _shutil
final_path = os.path.join(os.path.dirname(mp3_file_path) or ".", final_filename)
_shutil.move(mp3_file_path, final_path)
return final_filename return final_path
...@@ -13,6 +13,18 @@ if GEMINI_API_KEY: ...@@ -13,6 +13,18 @@ if GEMINI_API_KEY:
musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com") musicbrainzngs.set_useragent("StaxBot", "0.1", "contact@example.com")
async def compute_fingerprint(file_path: str) -> str | None:
"""Local Chromaprint fingerprint of the audio content - no network call. Used as the
cache key so re-uploads of the same song skip identification entirely. Returns None if
the file can't be decoded/fingerprinted, in which case the caller should skip caching
rather than fail the whole identify/tag flow over it."""
try:
_duration, fingerprint = await asyncio.to_thread(acoustid.fingerprint_file, file_path)
return fingerprint.decode() if isinstance(fingerprint, bytes) else fingerprint
except Exception as e:
logger.error(f"Fingerprinting error: {e}")
return None
async def identify_audio(file_path: str) -> list: async def identify_audio(file_path: str) -> list:
"""Uses Shazamio and AcoustID to identify the audio file. Returns a list of candidates.""" """Uses Shazamio and AcoustID to identify the audio file. Returns a list of candidates."""
candidates = [] candidates = []
...@@ -64,7 +76,8 @@ async def identify_audio(file_path: str) -> list: ...@@ -64,7 +76,8 @@ async def identify_audio(file_path: str) -> list:
album = rel.get('title', album) album = rel.get('title', album)
year = rel.get('date', year)[:4] if rel.get('date') else year year = rel.get('date', year)[:4] if rel.get('date') else year
track_number = f"{rel.get('medium-list', [{}])[0].get('track-list', [{}])[0].get('number', '1')}/{rel.get('medium-list', [{}])[0].get('track-count', '1')}" track_number = f"{rel.get('medium-list', [{}])[0].get('track-list', [{}])[0].get('number', '1')}/{rel.get('medium-list', [{}])[0].get('track-count', '1')}"
except: pass except Exception as e:
logger.error(f"MusicBrainz release lookup failed for recording {recording_id}: {e}")
candidates.append({ candidates.append({
'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre, 'title': title, 'artist': artist, 'album': album, 'year': year, 'genre': genre,
......
"""Local-filesystem storage backend, behind a small interface so a real object store
(S3/MinIO/ArvanCloud) can replace it later without touching callers - see CLAUDE.md rule 6
(providers behind interfaces)."""
import os
import shutil
import uuid
LOCAL_STORAGE_ROOT = os.getenv("LOCAL_STORAGE_ROOT", "./var/storage")
TEMP_DIR = os.path.join(LOCAL_STORAGE_ROOT, "temp")
DOWNLOADS_DIR = os.path.join(LOCAL_STORAGE_ROOT, "downloads")
def _ensure_dirs():
os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(DOWNLOADS_DIR, exist_ok=True)
_ensure_dirs()
def new_temp_path(original_filename: str) -> str:
"""A unique local path under the temp dir to write incoming audio bytes to, before
identification/tagging. Never shared between uploads, unlike the old flat temp dir."""
safe_name = os.path.basename(original_filename or "upload")
return os.path.join(TEMP_DIR, f"{uuid.uuid4()}_{safe_name}")
def store_final(user_id: int, local_path: str) -> tuple[str, str]:
"""Moves a locally-tagged file into durable, per-user storage so two users' identically
titled uploads stop colliding. Returns (absolute_path, url_path); url_path is what the
/downloads StaticFiles mount serves.
"""
filename = os.path.basename(local_path)
user_dir = os.path.join(DOWNLOADS_DIR, str(user_id))
os.makedirs(user_dir, exist_ok=True)
dest_name = f"{uuid.uuid4()}_{filename}"
dest = os.path.join(user_dir, dest_name)
shutil.move(local_path, dest)
url_path = f"/downloads/{user_id}/{dest_name}"
return dest, url_path
def cleanup_temp(path: str):
if path and os.path.exists(path):
os.remove(path)
...@@ -22,6 +22,23 @@ async def get_chats(session_string: str): ...@@ -22,6 +22,23 @@ async def get_chats(session_string: str):
return chats return chats
async def download_chat_audio(session_string: str, chat_id: int, message_id: int, dest_path: str) -> str:
"""Downloads a chat message's audio attachment to dest_path. Returns the path pyrogram
actually wrote to (download_media picks the extension if dest_path is a directory-less
filename without one, so callers should treat the return value as the real path)."""
client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
try:
message = await client.get_messages(chat_id, message_id)
if not message or not message.audio:
raise ValueError(f"No audio attachment on message {message_id} in chat {chat_id}")
downloaded_path = await client.download_media(message, file_name=dest_path)
return downloaded_path
finally:
await client.disconnect()
async def get_chat_music(session_string: str, chat_id: int, limit: int = 50): async def get_chat_music(session_string: str, chat_id: int, limit: int = 50):
client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True) client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect() await client.connect()
......
import os import os
import tempfile
os.environ.setdefault("DOCS_USERNAME", "test-docs-user") os.environ.setdefault("DOCS_USERNAME", "test-docs-user")
os.environ.setdefault("DOCS_PASSWORD", "test-docs-password") os.environ.setdefault("DOCS_PASSWORD", "test-docs-password")
os.environ.setdefault("JWT_SECRET", "test-jwt-secret-do-not-use-in-prod")
# Isolated per test-session DB file, not the dev stax.db - keeps scoping assertions
# (which rely on exact row counts) from being polluted by leftover data across runs.
os.environ.setdefault("DATABASE_URL", f"sqlite:///{tempfile.mkdtemp()}/test_stax.db")
os.environ.setdefault("LOCAL_STORAGE_ROOT", tempfile.mkdtemp())
import itertools
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from src.api.main import app from src.api.main import app
try: from src.core.database import Base, SessionLocal, User, engine
from database import engine, Base from src.core.security import create_access_token
except ImportError:
from src.core.database import engine, Base
@pytest.fixture(scope="session", autouse=True) @pytest.fixture(scope="session", autouse=True)
def setup_database(): def setup_database():
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
yield yield
# We could drop them, but keeping it for now
@pytest.fixture @pytest.fixture
def client(): def client():
with TestClient(app) as c: with TestClient(app) as c:
yield c yield c
@pytest.fixture
def db_session():
db = SessionLocal()
try:
yield db
finally:
db.close()
_user_ids = itertools.count(10_000)
@pytest.fixture
def make_user(db_session):
"""Creates a real User row (as if they'd completed Telegram login) without going through
the actual Telegram auth flow - test_auth.py covers that flow itself with mocks."""
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string"):
uid = next(_user_ids)
user = User(
id=uid,
phone_number=phone_number or f"+1555{uid}",
telegram_session_string=telegram_session_string,
)
db_session.add(user)
db_session.commit()
db_session.refresh(user)
return user
return _make
@pytest.fixture
def auth_as(make_user):
"""Returns a (headers, user) pair for a fresh user - call again for a second, distinct
user when a test needs to assert cross-user isolation."""
def _auth_as(**kwargs):
user = make_user(**kwargs)
token = create_access_token(user.id)
return {"Authorization": f"Bearer {token}"}, user
return _auth_as
def test_auth_request_code(client): from src.api.routers.auth import MAX_REQUESTS_PER_PHONE
response = client.post("/auth/request_code", json={"phone_number": "+1234567890"}) from src.core.database import User
assert response.status_code in [200, 400, 422, 500]
def test_auth_request_code(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
return_value={"phone_code_hash": "hash123", "is_registered": True},
)
response = client.post("/auth/request_code", json={"phone_number": "+15550001111"})
assert response.status_code == 200
assert response.json()["status"] == "success"
assert response.json()["data"]["phone_code_hash"] == "hash123"
def test_auth_request_code_upstream_failure_returns_400(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
side_effect=Exception("Telegram flood wait"),
)
response = client.post("/auth/request_code", json={"phone_number": "+15550002222"})
assert response.status_code == 400
def test_auth_request_code_rate_limited_per_phone(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.request_code",
return_value={"phone_code_hash": "hash123", "is_registered": True},
)
phone = "+15550003333"
for _ in range(MAX_REQUESTS_PER_PHONE):
response = client.post("/auth/request_code", json={"phone_number": phone})
assert response.status_code == 200
response = client.post("/auth/request_code", json={"phone_number": phone})
assert response.status_code == 429
def test_auth_login_missing_fields(client): def test_auth_login_missing_fields(client):
response = client.post("/auth/login", json={"phone_number": "+1234567890"}) response = client.post("/auth/login", json={"phone_number": "+1234567890"})
assert response.status_code == 422 # Unprocessable Entity assert response.status_code == 422
def test_auth_login_issues_jwt_and_never_exposes_session_string(client, db_session, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.login",
return_value={"session_string": "super-secret-telegram-session", "user_id": 918273},
)
response = client.post(
"/auth/login",
json={"phone_number": "+15550004444", "phone_code_hash": "hash123", "code": "11111"},
)
assert response.status_code == 200
body = response.json()
assert "access_token" in body and "refresh_token" in body
assert "super-secret-telegram-session" not in response.text
user = db_session.query(User).filter(User.id == 918273).first()
assert user is not None
assert user.telegram_session_string == "super-secret-telegram-session"
def test_auth_refresh_and_logout(client, mocker):
mocker.patch(
"src.telegram_worker.telegram_auth.login",
return_value={"session_string": "sess-abc", "user_id": 918274},
)
login_res = client.post(
"/auth/login",
json={"phone_number": "+15550005555", "phone_code_hash": "hash123", "code": "11111"},
)
refresh_token = login_res.json()["refresh_token"]
refreshed = client.post("/auth/refresh", json={"refresh_token": refresh_token})
assert refreshed.status_code == 200
new_refresh_token = refreshed.json()["refresh_token"]
# old refresh token was rotated out, reusing it should fail
reused = client.post("/auth/refresh", json={"refresh_token": refresh_token})
assert reused.status_code == 401
logout_res = client.post("/auth/logout", json={"refresh_token": new_refresh_token})
assert logout_res.status_code == 200
after_logout = client.post("/auth/refresh", json={"refresh_token": new_refresh_token})
assert after_logout.status_code == 401
def test_auth_chats_no_token(client): def test_auth_chats_no_token(client):
response = client.get("/auth/chats") response = client.get("/auth/chats")
assert response.status_code == 401 assert response.status_code == 401
def test_auth_chats_music_no_token(client): def test_auth_chats_music_no_token(client):
response = client.get("/auth/chats/123/music") response = client.get("/auth/chats/123/music")
assert response.status_code == 401 assert response.status_code == 401
def test_auth_chats_with_token(client, auth_as, mocker):
headers, _ = auth_as()
mocker.patch(
"src.telegram_worker.telegram_sync.get_chats",
return_value=[{"id": 1, "title": "Test Chat", "type": "private"}],
)
response = client.get("/auth/chats", headers=headers)
assert response.status_code == 200
assert response.json()["chats"][0]["title"] == "Test Chat"
def test_discovery_history(client): from src.core.database import DiscoveredSong
def test_discovery_history_requires_auth(client):
response = client.get("/discovery/history") response = client.get("/discovery/history")
assert response.status_code == 401
def test_discovery_history_scoped_to_current_user(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
db_session.add(DiscoveredSong(user_id=user_a.id, title="Song A", artist="Artist A"))
db_session.add(DiscoveredSong(user_id=user_b.id, title="Song B", artist="Artist B"))
db_session.commit()
response = client.get("/discovery/history", headers=headers_a)
assert response.status_code == 200 assert response.status_code == 200
assert "status" in response.json() titles = [s["title"] for s in response.json()["history"]]
assert "history" in response.json() assert titles == ["Song A"]
assert isinstance(response.json()["history"], list)
def test_discovery_listen_no_file(client): def test_discovery_listen_no_file(client, auth_as):
response = client.post("/discovery/listen") headers, _ = auth_as()
response = client.post("/discovery/listen", headers=headers)
assert response.status_code == 422 assert response.status_code == 422
def test_discovery_swipe_invalid_song(client):
response = client.post("/discovery/99999/swipe", data={"liked": True}) def test_discovery_swipe_invalid_song(client, auth_as):
headers, _ = auth_as()
response = client.post("/discovery/99999/swipe", data={"liked": True}, headers=headers)
assert response.status_code == 404
def test_discovery_swipe_other_users_song_not_found(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
song = DiscoveredSong(user_id=user_a.id, title="Song A", artist="Artist A")
db_session.add(song)
db_session.commit()
db_session.refresh(song)
response = client.post(f"/discovery/{song.id}/swipe", data={"liked": True}, headers=headers_b)
assert response.status_code == 404 assert response.status_code == 404
def test_library_endpoints(client): from src.core.database import LibrarySong
def _add_song(db_session, user_id, title="Test Song", artist="Test Artist"):
song = LibrarySong(user_id=user_id, title=title, artist=artist, genre="Pop")
db_session.add(song)
db_session.commit()
db_session.refresh(song)
return song
def test_library_requires_auth(client):
response = client.get("/library") response = client.get("/library")
assert response.status_code == 200 assert response.status_code == 401
assert "status" in response.json()
assert "library" in response.json()
assert isinstance(response.json()["library"], list) def test_library_scoped_to_current_user(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
_add_song(db_session, user_a.id, title="Song A")
_add_song(db_session, user_b.id, title="Song B")
response_a = client.get("/library", headers=headers_a)
assert response_a.status_code == 200
titles_a = [s["title"] for s in response_a.json()["library"]]
assert titles_a == ["Song A"]
response_b = client.get("/library", headers=headers_b)
titles_b = [s["title"] for s in response_b.json()["library"]]
assert titles_b == ["Song B"]
def test_library_search_scoped(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
_add_song(db_session, user_a.id, title="Ebi Greatest Hits")
_add_song(db_session, user_b.id, title="Ebi Greatest Hits")
def test_library_search(client): response = client.post("/library/search", data={"query": "Ebi"}, headers=headers_a)
response = client.post("/library/search", data={"query": "test"})
assert response.status_code == 200 assert response.status_code == 200
assert "results" in response.json() assert len(response.json()["results"]) == 1
def test_playlists_endpoints(client):
response = client.get("/playlists") def test_library_stream_not_found_for_other_users_song(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, user_b = auth_as()
song = _add_song(db_session, user_a.id)
response = client.get(f"/library/stream/{song.id}", headers=headers_b)
assert response.status_code == 404
def test_playlists_endpoints(client, auth_as):
headers, _ = auth_as()
response = client.get("/playlists", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert "status" in response.json()
assert "playlists" in response.json() assert "playlists" in response.json()
assert isinstance(response.json()["playlists"], list)
# create playlist response = client.post("/playlists", json={"name": "Test Playlist"}, headers=headers)
response = client.post("/playlists", json={"name": "Test Playlist"})
assert response.status_code == 200 assert response.status_code == 200
assert response.json()["status"] == "success"
playlist_id = response.json()["playlist"]["id"] playlist_id = response.json()["playlist"]["id"]
# fetch again response = client.get("/playlists", headers=headers)
response = client.get("/playlists")
assert response.status_code == 200
playlists = response.json()["playlists"] playlists = response.json()["playlists"]
assert any(p["id"] == playlist_id for p in playlists) assert any(p["id"] == playlist_id for p in playlists)
def test_playlist_add_invalid(client):
response = client.post("/playlists/99999/add", data={"song_id": 99999}) def test_playlists_scoped_to_current_user(client, auth_as):
headers_a, _ = auth_as()
headers_b, _ = auth_as()
client.post("/playlists", json={"name": "User A's playlist"}, headers=headers_a)
response_b = client.get("/playlists", headers=headers_b)
assert response_b.json()["playlists"] == []
def test_playlist_add_invalid(client, auth_as):
headers, _ = auth_as()
response = client.post("/playlists/99999/add", data={"song_id": 99999}, headers=headers)
assert response.status_code == 404 assert response.status_code == 404
def test_music_tag(client): from src.core.database import IdentifiedTrack, LibrarySong
response = client.post("/music/tag", json={"chat_id": 1, "message_id": 2, "language_preference": "native"})
assert response.status_code == 200 FAKE_CANDIDATE = {
assert response.json()["status"] == "success" "title": "Test Title",
"artist": "Test Artist",
"album": "Test Album",
"year": "2024",
"genre": "Pop",
"coverart": None,
"lyrics": "la la la",
}
def _mock_pipeline(mocker, final_path="/tmp/does-not-need-to-exist.mp3", url_path="/downloads/1/x.mp3", fingerprint=None):
mocker.patch("src.api.routers.music.compute_fingerprint", return_value=fingerprint)
mocker.patch("src.api.routers.music.identify_audio", return_value=[FAKE_CANDIDATE])
mocker.patch("src.api.routers.music.tag_and_convert_audio", return_value="/tmp/tagged.mp3")
mocker.patch("src.api.routers.music.storage.store_final", return_value=(final_path, url_path))
def test_music_tag_missing_fields(client):
response = client.post("/music/tag", json={"chat_id": 1}) def test_music_tag_requires_auth(client):
response = client.post("/music/tag", json={"chat_id": 1, "message_id": 2})
assert response.status_code == 401
def test_music_tag_missing_fields(client, auth_as):
headers, _ = auth_as()
response = client.post("/music/tag", json={"chat_id": 1}, headers=headers)
assert response.status_code == 422 assert response.status_code == 422
def test_batch_remix_endpoint(client):
response = client.post("/music/remix/batch", json={"files": [{"chat_id": 1, "message_id": 2}], "prompt": "slowed"}) def test_music_tag_no_linked_telegram_session(client, auth_as):
headers, _ = auth_as(telegram_session_string=None)
response = client.post("/music/tag", json={"chat_id": 1, "message_id": 2}, headers=headers)
assert response.status_code == 400
def test_music_tag_success(client, db_session, auth_as, mocker):
headers, user = auth_as()
mocker.patch(
"src.api.routers.music.telegram_sync.download_chat_audio",
return_value="/tmp/downloaded_from_telegram.mp3",
)
_mock_pipeline(mocker)
response = client.post("/music/tag", json={"chat_id": 1, "message_id": 2}, headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert response.json()["status"] == "accepted" body = response.json()
job_id = response.json()["job_id"] assert body["status"] == "success"
assert body["metadata"]["title"] == "Test Title"
# check status
status_res = client.get(f"/music/remix/status/{job_id}") song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert status_res.status_code == 200 assert song is not None
assert status_res.json()["status"] == "processing" assert song.title == "Test Title"
def test_music_upload_no_file(client):
def test_music_remix_batch_not_implemented(client, auth_as):
headers, _ = auth_as()
response = client.post(
"/music/remix/batch",
json={"files": [{"chat_id": 1, "message_id": 2}], "prompt": "slowed"},
headers=headers,
)
assert response.status_code == 501
def test_music_remix_status_not_implemented(client, auth_as):
headers, _ = auth_as()
response = client.get("/music/remix/status/some-job-id", headers=headers)
assert response.status_code == 501
def test_music_upload_requires_auth(client):
response = client.post("/music/upload") response = client.post("/music/upload")
assert response.status_code == 401
def test_music_upload_no_file(client, auth_as):
headers, _ = auth_as()
response = client.post("/music/upload", headers=headers)
assert response.status_code == 422 assert response.status_code == 422
def test_music_upload_success_creates_library_song(client, db_session, auth_as, mocker):
headers, user = auth_as()
_mock_pipeline(mocker)
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
assert response.json()["status"] == "success"
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song is not None
assert song.artist == "Test Artist"
def test_music_upload_new_fingerprint_populates_cache(client, db_session, auth_as, mocker):
headers, _ = auth_as()
fingerprint = "fp-new-song-abc123"
_mock_pipeline(mocker, fingerprint=fingerprint)
identify_audio = mocker.patch("src.api.routers.music.identify_audio", return_value=[FAKE_CANDIDATE])
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
identify_audio.assert_called_once()
cached = db_session.query(IdentifiedTrack).filter(IdentifiedTrack.fingerprint == fingerprint).first()
assert cached is not None
assert cached.title == "Test Title"
assert cached.artist == "Test Artist"
def test_music_upload_cached_fingerprint_skips_identification(client, db_session, auth_as, mocker):
headers, user = auth_as()
fingerprint = "fp-already-known-xyz789"
db_session.add(IdentifiedTrack(
fingerprint=fingerprint,
title="Cached Title",
artist="Cached Artist",
album="Cached Album",
year="1999",
genre="Rock",
track_number="1/1",
source="AcoustID (99%)",
coverart=None,
lyrics="cached lyrics",
))
db_session.commit()
_mock_pipeline(mocker, fingerprint=fingerprint)
identify_audio = mocker.patch("src.api.routers.music.identify_audio")
response = client.post(
"/music/upload",
headers=headers,
files={"file": ("test.mp3", b"fake mp3 bytes", "audio/mpeg")},
)
assert response.status_code == 200
body = response.json()
assert body["metadata"]["title"] == "Cached Title"
assert body["metadata"]["artist"] == "Cached Artist"
identify_audio.assert_not_called()
song = db_session.query(LibrarySong).filter(LibrarySong.user_id == user.id).first()
assert song.title == "Cached Title"
from fastapi.testclient import TestClient def test_social_router_exists(client):
from src.api.main import app response = client.get("/openapi.json", auth=("test-docs-user", "test-docs-password"))
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
client = TestClient(app)
def test_social_router_exists():
response = client.get("/openapi.json", auth=(DOCS_USERNAME, DOCS_PASSWORD))
assert response.status_code == 200 assert response.status_code == 200
assert "/social/posts" in response.json()["paths"] assert "/social/posts" in response.json()["paths"]
assert "/social/geo-drop" in response.json()["paths"] assert "/social/geo-drop" in response.json()["paths"]
def test_create_post():
response = client.post("/social/posts", json={ def test_create_post_requires_auth(client):
"user_id": 1, response = client.post("/social/posts", json={"song_id": 1, "caption": "no token"})
"song_id": 1, assert response.status_code == 401
"caption": "My first remix!"
})
def test_create_post_derives_user_from_token(client, auth_as):
headers, user = auth_as()
response = client.post(
"/social/posts",
json={"song_id": 1, "caption": "My first remix!"},
headers=headers,
)
assert response.status_code == 201 assert response.status_code == 201
assert response.json()["caption"] == "My first remix!" body = response.json()
assert body["caption"] == "My first remix!"
def test_create_geo_drop(): assert body["user_id"] == user.id
response = client.post("/social/geo-drop", json={
"user_id": 1,
"song_id": 1, def test_post_body_cannot_impersonate_another_user(client, auth_as):
"latitude": 34.0522, """The old API took user_id in the body, letting any caller post as anyone. Even if a
"longitude": -118.2437 client still sends one, it must be ignored in favor of the authenticated caller."""
}) headers, user = auth_as()
response = client.post(
"/social/posts",
json={"song_id": 1, "caption": "impersonation attempt", "user_id": 999999},
headers=headers,
)
assert response.status_code == 201
assert response.json()["user_id"] == user.id
def test_create_geo_drop(client, auth_as):
headers, user = auth_as()
response = client.post(
"/social/geo-drop",
json={"song_id": 1, "latitude": 34.0522, "longitude": -118.2437},
headers=headers,
)
assert response.status_code == 201 assert response.status_code == 201
assert response.json()["latitude"] == 34.0522 assert response.json()["latitude"] == 34.0522
assert response.json()["user_id"] == user.id
def test_get_nearby_drops():
response = client.get("/social/geo-drop/nearby?lat=34.05&lon=-118.24&radius_km=10") def test_get_nearby_drops(client, auth_as):
headers, _ = auth_as()
response = client.get("/social/geo-drop/nearby?lat=34.05&lon=-118.24&radius_km=10", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert isinstance(response.json(), list) assert isinstance(response.json(), list)
def test_create_live_room():
response = client.post("/social/rooms", json={ def test_create_live_room(client, auth_as):
"dj_id": 1, headers, user = auth_as()
"name": "Late Night LoFi" response = client.post("/social/rooms", json={"name": "Late Night LoFi"}, headers=headers)
})
assert response.status_code == 201 assert response.status_code == 201
assert response.json()["name"] == "Late Night LoFi" assert response.json()["name"] == "Late Night LoFi"
assert response.json()["dj_id"] == user.id
def test_get_active_rooms(): def test_get_active_rooms(client, auth_as):
response = client.get("/social/rooms") headers, _ = auth_as()
response = client.get("/social/rooms", headers=headers)
assert response.status_code == 200 assert response.status_code == 200
assert isinstance(response.json(), list) assert isinstance(response.json(), list)
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