Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1f8a9919b
|
||
|
|
7a3dab88c8
|
||
|
|
752c972669
|
||
|
|
9ba610d081
|
No files matched your search
+19
-6
@@ -52,6 +52,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
and duration caps: 30 min on WebGPU, 10 min on WASM, 60 MB per file —
|
||||
no input can wedge the demo at an eternal "processing" state anymore.
|
||||
|
||||
- `POST /auth/logout` revokes the caller's token (204). An account has a
|
||||
single active token, so it signs out every client holding it.
|
||||
|
||||
- The dashboard header shows the sign-in state: a **Sign in** button when
|
||||
signed out, the account email and **Sign out** when signed in. Sign out
|
||||
revokes the token on the server and works even when the API is
|
||||
unreachable. The landing page's sign-in button is hidden and the login
|
||||
page redirects to the upload page for a signed-in user.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Demo hang fix**: audio was decoded inside an `AudioContext` forced to
|
||||
@@ -76,12 +85,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
|
||||
### Fixed
|
||||
|
||||
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
|
||||
read-only volume) now answers **503** with a short message on `POST /jobs`
|
||||
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
|
||||
the log. The real `OSError` is logged server-side, a partially written
|
||||
file is removed, and the API logs an error at startup when `DATA_DIR`
|
||||
is not writable.
|
||||
- The Telegram bot recovers when the API revokes the token it cached for a
|
||||
chat (a newer sign-in or a logout of the same account). Every request
|
||||
used to fail from then on; the bot now drops the token, re-registers
|
||||
once and retries, and `/start` only shows a connect code that works.
|
||||
|
||||
### Removed
|
||||
|
||||
- The landing page's separate sign-in button; signing in lives in
|
||||
the header, and "Get started" sends signed-out visitors to the login
|
||||
page.
|
||||
|
||||
## [1.4.1] - 2026-11-26
|
||||
|
||||
|
||||
@@ -7,15 +7,17 @@ Deliberately lightweight for v1:
|
||||
- POST /auth/telegram lets the bot create or resume an account per Telegram id
|
||||
- POST /auth/token-login lets a user paste the connect code shown by the bot
|
||||
to link their browser session
|
||||
- POST /auth/logout revokes the caller's token
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.api.deps import get_current_user
|
||||
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import User
|
||||
@@ -97,6 +99,20 @@ def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> Auth
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def logout(user: User = Depends(get_current_user), session: Session = Depends(get_db)) -> Response:
|
||||
"""Revoke the caller's token so it stops working everywhere.
|
||||
|
||||
An account has a single active token, so this signs out every client
|
||||
that holds it: other browsers, API scripts and, for Telegram accounts,
|
||||
the bot (which re-registers on its next request). The new token is
|
||||
never returned; signing in again issues a fresh one.
|
||||
"""
|
||||
user.token_hash = token_hash(generate_token())
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/telegram", response_model=AuthResponse)
|
||||
def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
"""Register-or-login used by the Telegram bot.
|
||||
|
||||
@@ -25,14 +25,6 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
|
||||
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
|
||||
|
||||
|
||||
class StorageUnavailableError(Exception):
|
||||
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
|
||||
|
||||
It is a server fault, not a bad upload, so the API answers 503 and the
|
||||
real OSError stays in the server log instead of reaching the client.
|
||||
"""
|
||||
|
||||
|
||||
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
|
||||
"""Decode any media file to mono float32 PCM at 16 kHz."""
|
||||
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
|
||||
@@ -110,23 +102,12 @@ def audio_dir() -> Path:
|
||||
|
||||
|
||||
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
|
||||
"""Persist an upload under DATA_DIR/audio with a safe extension.
|
||||
|
||||
Raises StorageUnavailableError when the directory or file cannot be
|
||||
written; a partially written file is removed first.
|
||||
"""
|
||||
"""Persist an upload under DATA_DIR/audio with a safe extension."""
|
||||
suffix = Path(original_filename).suffix.lower()
|
||||
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
|
||||
suffix = ".bin"
|
||||
try:
|
||||
path = audio_dir() / f"{job_id}{suffix}"
|
||||
except OSError as exc:
|
||||
raise StorageUnavailableError(str(exc)) from exc
|
||||
try:
|
||||
path.write_bytes(data)
|
||||
except OSError as exc:
|
||||
delete_audio(path)
|
||||
raise StorageUnavailableError(str(exc)) from exc
|
||||
path = audio_dir() / f"{job_id}{suffix}"
|
||||
path.write_bytes(data)
|
||||
return path
|
||||
|
||||
|
||||
|
||||
+1
-19
@@ -10,13 +10,11 @@ import os
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from sokhan import __version__
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.core.audio import StorageUnavailableError, audio_dir
|
||||
from sokhan.db import configure, create_all
|
||||
|
||||
logger = logging.getLogger("sokhan")
|
||||
@@ -29,14 +27,6 @@ def create_app() -> FastAPI:
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
configure()
|
||||
create_all()
|
||||
try:
|
||||
audio_dir()
|
||||
except OSError as exc:
|
||||
logger.error(
|
||||
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
|
||||
"it is; in Docker check the volume is owned by the app user",
|
||||
exc,
|
||||
)
|
||||
if not settings.celery_enabled:
|
||||
logger.warning(
|
||||
"CELERY_ENABLED=false - jobs run inline in the API process; "
|
||||
@@ -78,14 +68,6 @@ def create_app() -> FastAPI:
|
||||
app.include_router(routes_openai.router)
|
||||
app.include_router(routes_admin.router)
|
||||
|
||||
@app.exception_handler(StorageUnavailableError)
|
||||
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
|
||||
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
content={"detail": "upload storage is unavailable, try again later"},
|
||||
)
|
||||
|
||||
@app.get("/")
|
||||
def root() -> dict:
|
||||
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
|
||||
|
||||
@@ -62,3 +62,40 @@ def test_telegram_register_or_login(client):
|
||||
def test_jobs_require_token(client):
|
||||
response = client.get("/jobs")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def _bearer(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_logout_revokes_the_token(client):
|
||||
token = client.post("/auth/register", json=REGISTER).json()["api_token"]
|
||||
assert client.get("/quota", headers=_bearer(token)).status_code == 200
|
||||
|
||||
response = client.post("/auth/logout", headers=_bearer(token))
|
||||
|
||||
assert response.status_code == 204
|
||||
assert client.get("/quota", headers=_bearer(token)).status_code == 401
|
||||
# The revoked token is no longer a valid connect code either.
|
||||
assert client.post("/auth/token-login", json={"api_token": token}).status_code == 401
|
||||
|
||||
|
||||
def test_logout_twice_with_the_same_token_is_rejected(client):
|
||||
token = client.post("/auth/register", json=REGISTER).json()["api_token"]
|
||||
client.post("/auth/logout", headers=_bearer(token))
|
||||
|
||||
assert client.post("/auth/logout", headers=_bearer(token)).status_code == 401
|
||||
|
||||
|
||||
def test_logout_requires_a_token(client):
|
||||
assert client.post("/auth/logout").status_code == 401
|
||||
|
||||
|
||||
def test_signing_in_after_logout_issues_a_working_token(client):
|
||||
first = client.post("/auth/register", json=REGISTER).json()["api_token"]
|
||||
client.post("/auth/logout", headers=_bearer(first))
|
||||
|
||||
second = client.post("/auth/login", json=REGISTER).json()["api_token"]
|
||||
|
||||
assert second != first
|
||||
assert client.get("/quota", headers=_bearer(second)).status_code == 200
|
||||
@@ -1,8 +1,5 @@
|
||||
import io
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from docx import Document
|
||||
|
||||
|
||||
@@ -191,51 +188,3 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
|
||||
|
||||
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
|
||||
assert client.get("/jobs", headers=headers).json()["total"] == 0
|
||||
|
||||
|
||||
def _make_data_dir_unwritable(tmp_path):
|
||||
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
|
||||
shutil.rmtree(tmp_path / "data")
|
||||
(tmp_path / "data").write_text("not a directory")
|
||||
|
||||
|
||||
def test_upload_answers_503_when_storage_is_unwritable(
|
||||
client, auth, wav_bytes, fake_engine, tmp_path
|
||||
):
|
||||
_make_data_dir_unwritable(tmp_path)
|
||||
|
||||
response = _upload(client, auth, wav_bytes)
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
|
||||
# No job row is left behind for an upload that was never stored.
|
||||
assert client.get("/jobs", headers=auth).json()["total"] == 0
|
||||
|
||||
|
||||
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
|
||||
client, auth, wav_bytes, fake_engine, tmp_path
|
||||
):
|
||||
_make_data_dir_unwritable(tmp_path)
|
||||
|
||||
response = client.post(
|
||||
"/v1/audio/transcriptions",
|
||||
files={"file": ("test.wav", wav_bytes, "audio/wav")},
|
||||
data={"language": "fa", "response_format": "json"},
|
||||
headers=auth,
|
||||
)
|
||||
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
|
||||
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
|
||||
|
||||
def write_fails_midway(self, data):
|
||||
self.open("wb").write(data[:1])
|
||||
raise OSError(28, "No space left on device")
|
||||
|
||||
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
|
||||
|
||||
with pytest.raises(StorageUnavailableError):
|
||||
save_upload(b"RIFF....", "job-1", "clip.wav")
|
||||
assert list(audio_dir().iterdir()) == []
|
||||
@@ -9,6 +9,10 @@ class BackendError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AuthError(BackendError):
|
||||
"""The API rejected the token (401): revoked by a logout or a newer sign-in."""
|
||||
|
||||
|
||||
class QuotaError(BackendError):
|
||||
"""The user's monthly allowance is exhausted (402, code=quota_exceeded)."""
|
||||
|
||||
@@ -46,6 +50,11 @@ class SokhanClient:
|
||||
def _headers(self, token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
@staticmethod
|
||||
def _raise_for_auth(response: httpx.Response) -> None:
|
||||
if response.status_code == 401:
|
||||
raise AuthError("token rejected")
|
||||
|
||||
def register_telegram(self, telegram_id: int, username: str | None) -> str:
|
||||
response = self._client.post(
|
||||
f"{self.settings.api_base_url}/auth/telegram",
|
||||
@@ -64,6 +73,7 @@ class SokhanClient:
|
||||
files={"file": (filename, content)},
|
||||
headers=self._headers(token),
|
||||
)
|
||||
self._raise_for_auth(response)
|
||||
if response.status_code == 402:
|
||||
detail = response.json().get("detail", {})
|
||||
if detail.get("code") == "file_too_long":
|
||||
@@ -81,6 +91,7 @@ class SokhanClient:
|
||||
f"{self.settings.api_base_url}/jobs/{job_id}",
|
||||
headers=self._headers(token),
|
||||
)
|
||||
self._raise_for_auth(response)
|
||||
if response.status_code != 200:
|
||||
raise BackendError(f"job fetch failed with status {response.status_code}")
|
||||
return response.json()
|
||||
@@ -90,6 +101,7 @@ class SokhanClient:
|
||||
f"{self.settings.api_base_url}/quota",
|
||||
headers=self._headers(token),
|
||||
)
|
||||
self._raise_for_auth(response)
|
||||
if response.status_code != 200:
|
||||
raise BackendError(f"quota fetch failed with status {response.status_code}")
|
||||
return response.json()
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import io
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import TypeVar
|
||||
|
||||
from aiogram import Bot, F, Router
|
||||
from aiogram.filters import Command, CommandObject, CommandStart
|
||||
@@ -11,10 +13,17 @@ from aiogram.types import (
|
||||
InlineKeyboardButton,
|
||||
InlineKeyboardMarkup,
|
||||
Message,
|
||||
User,
|
||||
)
|
||||
|
||||
from sokhan_bot import texts
|
||||
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
|
||||
from sokhan_bot.client import (
|
||||
AuthError,
|
||||
BackendError,
|
||||
FileTooLongError,
|
||||
QuotaError,
|
||||
SokhanClient,
|
||||
)
|
||||
from sokhan_bot.split import split_message
|
||||
from sokhan_bot.store import TokenStore
|
||||
|
||||
@@ -22,6 +31,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_RATE_LIMIT_SECONDS = 10.0
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def _job_keyboard(job_id: str, web_base_url: str) -> InlineKeyboardMarkup:
|
||||
return InlineKeyboardMarkup(
|
||||
@@ -82,10 +93,35 @@ class Handlers:
|
||||
self.store.set(message.chat.id, token)
|
||||
return token
|
||||
|
||||
def _authed(self, chat_id: int, user: User, call: Callable[[str], T]) -> T:
|
||||
"""Run `call(token)`, re-registering once if the API revoked the token.
|
||||
|
||||
A web logout or a newer sign-in revokes the token cached for this
|
||||
chat; without the retry every later request would fail. Raises
|
||||
BackendError when the backend is unreachable or rejects again.
|
||||
"""
|
||||
token = self.store.get(chat_id)
|
||||
if token:
|
||||
try:
|
||||
return call(token)
|
||||
except AuthError:
|
||||
logger.info("token for chat %s was revoked; re-registering", chat_id)
|
||||
self.store.forget(chat_id)
|
||||
token = self.client.register_telegram(user.id, user.username)
|
||||
self.store.set(chat_id, token)
|
||||
return call(token)
|
||||
|
||||
async def start(self, message: Message) -> None:
|
||||
token = await self._ensure_token(message)
|
||||
if not token:
|
||||
return
|
||||
# The cached token doubles as the connect code, so make sure it still
|
||||
# works before showing it; a backend outage keeps the cached one.
|
||||
try:
|
||||
self._authed(message.chat.id, message.from_user, self.client.get_quota)
|
||||
except BackendError:
|
||||
pass
|
||||
token = self.store.get(message.chat.id) or token
|
||||
await message.answer(texts.WELCOME.format(connect_code=token))
|
||||
|
||||
async def quota(self, message: Message) -> None:
|
||||
@@ -93,7 +129,7 @@ class Handlers:
|
||||
if not token:
|
||||
return
|
||||
try:
|
||||
info = self.client.get_quota(token)
|
||||
info = self._authed(message.chat.id, message.from_user, self.client.get_quota)
|
||||
except BackendError:
|
||||
await message.answer(texts.SERVER_UNREACHABLE)
|
||||
return
|
||||
@@ -137,7 +173,9 @@ class Handlers:
|
||||
await message.answer("شناسهٔ پردازش را بنویس، مثلاً: /track 3f2a…")
|
||||
return
|
||||
try:
|
||||
job = self.client.get_job(token, job_id)
|
||||
job = self._authed(
|
||||
message.chat.id, message.from_user, lambda t: self.client.get_job(t, job_id)
|
||||
)
|
||||
except BackendError:
|
||||
await message.answer(texts.UNKNOWN_JOB)
|
||||
return
|
||||
@@ -196,7 +234,11 @@ class Handlers:
|
||||
return
|
||||
|
||||
try:
|
||||
job_id = self.client.upload_audio(token, filename, content)
|
||||
job_id = self._authed(
|
||||
message.chat.id,
|
||||
message.from_user,
|
||||
lambda t: self.client.upload_audio(t, filename, content),
|
||||
)
|
||||
except FileTooLongError as exc:
|
||||
await message.answer(
|
||||
texts.FILE_TOO_LONG.format(
|
||||
@@ -229,7 +271,11 @@ class Handlers:
|
||||
|
||||
job_id = callback.data.split(":", 1)[1]
|
||||
try:
|
||||
job = self.client.get_job(token, job_id)
|
||||
job = self._authed(
|
||||
callback.message.chat.id,
|
||||
callback.from_user,
|
||||
lambda t: self.client.get_job(t, job_id),
|
||||
)
|
||||
except BackendError:
|
||||
await callback.answer(texts.UNKNOWN_JOB, show_alert=True)
|
||||
return
|
||||
|
||||
@@ -19,7 +19,7 @@ import time
|
||||
from aiogram import Bot
|
||||
|
||||
from sokhan_bot import texts
|
||||
from sokhan_bot.client import SokhanClient
|
||||
from sokhan_bot.client import AuthError, SokhanClient
|
||||
from sokhan_bot.split import split_message
|
||||
from sokhan_bot.store import TokenStore
|
||||
|
||||
@@ -75,6 +75,14 @@ class CompletionNotifier:
|
||||
|
||||
try:
|
||||
job = await asyncio.to_thread(self.client.get_job, token, job_id)
|
||||
except AuthError:
|
||||
# Revoked by a web logout or a newer sign-in. The poller has
|
||||
# no Telegram user to re-register with, so it asks for /start.
|
||||
logger.warning("token for chat %s was revoked; untracking job %s", chat_id, job_id)
|
||||
self.store.forget(chat_id)
|
||||
self.store.untrack(job_id)
|
||||
await self._send(chat_id, texts.NEED_START)
|
||||
continue
|
||||
except Exception:
|
||||
logger.exception("job fetch failed (%s); will retry", job_id)
|
||||
continue
|
||||
|
||||
@@ -42,6 +42,12 @@ class TokenStore:
|
||||
self._tokens[str(chat_id)] = token
|
||||
self._save()
|
||||
|
||||
def forget(self, chat_id: int) -> None:
|
||||
"""Drop a chat's token, e.g. after the API revoked it."""
|
||||
with self._lock:
|
||||
if self._tokens.pop(str(chat_id), None) is not None:
|
||||
self._save()
|
||||
|
||||
def track(self, job_id: str, chat_id: int) -> None:
|
||||
"""Watch a job so the notifier can push its transcript when it finishes."""
|
||||
with self._lock:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
|
||||
from sokhan_bot.client import AuthError, BackendError, FileTooLongError, QuotaError, SokhanClient
|
||||
from sokhan_bot.config import BotSettings
|
||||
|
||||
|
||||
@@ -88,3 +88,20 @@ def test_get_plans_parses_catalogue():
|
||||
plans = client.get_plans()
|
||||
assert [plan["code"] for plan in plans] == ["free", "pro"]
|
||||
assert plans[1]["max_file_minutes"] == 180
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"call",
|
||||
[
|
||||
lambda client: client.upload_audio("tok", "voice.ogg", b"bytes"),
|
||||
lambda client: client.get_job("tok", "job-1"),
|
||||
lambda client: client.get_quota("tok"),
|
||||
],
|
||||
)
|
||||
def test_revoked_token_raises_auth_error(call):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(401, json={"detail": "invalid token"})
|
||||
|
||||
with _client(handler) as client:
|
||||
with pytest.raises(AuthError):
|
||||
call(client)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""The bot recovers when the API revokes a chat's cached token (web logout)."""
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sokhan_bot import texts
|
||||
from sokhan_bot.client import AuthError, BackendError
|
||||
from sokhan_bot.handlers import Handlers
|
||||
from sokhan_bot.notify import CompletionNotifier
|
||||
from sokhan_bot.store import TokenStore
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""Accepts only `valid_token`; /auth/telegram hands out `fresh-<n>`."""
|
||||
|
||||
def __init__(self, valid_token: str) -> None:
|
||||
self.valid_token = valid_token
|
||||
self.registrations = 0
|
||||
self.settings = SimpleNamespace(web_base_url="http://web.test")
|
||||
|
||||
def _check(self, token: str) -> None:
|
||||
if token != self.valid_token:
|
||||
raise AuthError("token rejected")
|
||||
|
||||
def register_telegram(self, telegram_id: int, username: str | None) -> str:
|
||||
self.registrations += 1
|
||||
self.valid_token = f"fresh-{self.registrations}"
|
||||
return self.valid_token
|
||||
|
||||
def get_quota(self, token: str) -> dict:
|
||||
self._check(token)
|
||||
return {
|
||||
"plan": "free",
|
||||
"used_minutes": 1.0,
|
||||
"limit_minutes": 30,
|
||||
"remaining_minutes": 29.0,
|
||||
"max_file_minutes": 10,
|
||||
}
|
||||
|
||||
def get_job(self, token: str, job_id: str) -> dict:
|
||||
self._check(token)
|
||||
return {"status": "processing", "progress": 50.0}
|
||||
|
||||
|
||||
class FakeMessage:
|
||||
def __init__(self, chat_id: int = 42) -> None:
|
||||
self.chat = SimpleNamespace(id=chat_id)
|
||||
self.from_user = SimpleNamespace(id=chat_id, username="sara")
|
||||
self.answers: list[str] = []
|
||||
|
||||
async def answer(self, text: str, **_: object) -> None:
|
||||
self.answers.append(text)
|
||||
|
||||
|
||||
def _handlers(tmp_path, cached_token: str, client: FakeClient) -> Handlers:
|
||||
store = TokenStore(str(tmp_path / "store.json"))
|
||||
store.set(42, cached_token)
|
||||
return Handlers(client, store)
|
||||
|
||||
|
||||
def test_quota_re_registers_once_after_the_token_was_revoked(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
handlers = _handlers(tmp_path, "revoked", client)
|
||||
message = FakeMessage()
|
||||
|
||||
asyncio.run(handlers.quota(message))
|
||||
|
||||
assert client.registrations == 1
|
||||
assert handlers.store.get(42) == "fresh-1"
|
||||
assert message.answers and texts.SERVER_UNREACHABLE not in message.answers
|
||||
|
||||
|
||||
def test_a_valid_token_is_used_without_re_registering(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
handlers = _handlers(tmp_path, "current", client)
|
||||
|
||||
asyncio.run(handlers.quota(FakeMessage()))
|
||||
|
||||
assert client.registrations == 0
|
||||
assert handlers.store.get(42) == "current"
|
||||
|
||||
|
||||
def test_start_shows_a_working_connect_code_after_revocation(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
handlers = _handlers(tmp_path, "revoked", client)
|
||||
message = FakeMessage()
|
||||
|
||||
asyncio.run(handlers.start(message))
|
||||
|
||||
assert "fresh-1" in message.answers[-1]
|
||||
assert "revoked" not in message.answers[-1]
|
||||
|
||||
|
||||
def test_backend_outage_still_reports_unreachable(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
|
||||
def unreachable(token: str) -> dict:
|
||||
raise BackendError("down")
|
||||
|
||||
client.get_quota = unreachable
|
||||
handlers = _handlers(tmp_path, "current", client)
|
||||
message = FakeMessage()
|
||||
|
||||
asyncio.run(handlers.quota(message))
|
||||
|
||||
assert message.answers == [texts.SERVER_UNREACHABLE]
|
||||
assert client.registrations == 0
|
||||
|
||||
|
||||
def test_poller_untracks_and_asks_for_start_when_revoked(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
store = TokenStore(str(tmp_path / "store.json"))
|
||||
store.set(42, "revoked")
|
||||
store.track("job-1", 42)
|
||||
sent: list[tuple[int, str]] = []
|
||||
|
||||
notifier = CompletionNotifier(bot=None, client=client, store=store)
|
||||
|
||||
async def fake_send(chat_id: int, text: str) -> bool:
|
||||
sent.append((chat_id, text))
|
||||
return True
|
||||
|
||||
notifier._send = fake_send
|
||||
asyncio.run(notifier.poll_once())
|
||||
|
||||
assert store.tracked() == []
|
||||
assert store.get(42) is None
|
||||
assert sent == [(42, texts.NEED_START)]
|
||||
@@ -47,3 +47,15 @@ def test_legacy_token_file_is_migrated(tmp_path):
|
||||
reloaded = TokenStore(str(path))
|
||||
assert reloaded.get(123) == "legacy-token"
|
||||
assert [job_id for job_id, _, _ in reloaded.tracked()] == ["job-x"]
|
||||
|
||||
|
||||
def test_forget_drops_a_token_and_persists(tmp_path):
|
||||
path = str(tmp_path / "store.json")
|
||||
store = TokenStore(path)
|
||||
store.set(42, "old-token")
|
||||
|
||||
store.forget(42)
|
||||
store.forget(99) # unknown chats are a no-op
|
||||
|
||||
assert store.get(42) is None
|
||||
assert TokenStore(path).get(42) is None
|
||||
@@ -15,13 +15,16 @@
|
||||
"new": "New transcription",
|
||||
"archive": "Archive",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی"
|
||||
"switchToFa": "فارسی",
|
||||
"signIn": "Sign in",
|
||||
"signOut": "Sign out",
|
||||
"signedInAs": "Signed in as {email}",
|
||||
"signOutOf": "Sign out of {email}"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "From speech to text, in moments",
|
||||
"subheadline": "Upload an audio file or record straight away — Sokhan turns it into an accurate Persian transcript and hands you a short summary alongside.",
|
||||
"startCta": "Get started",
|
||||
"loginCta": "Sign in",
|
||||
"featuresTitle": "Where Sokhan helps",
|
||||
"featuresSubtitle": "From lecture notes to a friend's voice message — every recording deserves its text.",
|
||||
"featureLectureTitle": "Lectures & meetings",
|
||||
|
||||
@@ -15,13 +15,16 @@
|
||||
"new": "رونویسی تازه",
|
||||
"archive": "آرشیو",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی"
|
||||
"switchToFa": "فارسی",
|
||||
"signIn": "ورود",
|
||||
"signOut": "خروج",
|
||||
"signedInAs": "واردشده با {email}",
|
||||
"signOutOf": "خروج از حساب {email}"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "از گفتار به متن، در چند لحظه",
|
||||
"subheadline": "فایل صوتی را بارگذاری کن یا مستقیم ضبط کن؛ سخن آن را با دقت بالا به متن فارسی تبدیل میکند و خلاصهای کوتاه هم کنارش تحویل میدهد.",
|
||||
"startCta": "شروع کنید",
|
||||
"loginCta": "ورود",
|
||||
"featuresTitle": "سخن کجا به کارت میآید؟",
|
||||
"featuresSubtitle": "از جزوهٔ درس تا پیام صوتی دوستان؛ هر صدایی متن خودش را دارد.",
|
||||
"featureLectureTitle": "درس و جلسه",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, login, register, setToken, tokenLogin } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
type Mode = "login" | "register" | "code";
|
||||
|
||||
@@ -13,6 +14,12 @@ export default function LoginPage() {
|
||||
const t = useTranslations("login");
|
||||
const te = useTranslations("errors");
|
||||
const router = useRouter();
|
||||
const { ready, signedIn } = useSession();
|
||||
|
||||
// Already signed in: the login form has nothing to offer.
|
||||
useEffect(() => {
|
||||
if (ready && signedIn) router.replace("/new");
|
||||
}, [ready, signedIn, router]);
|
||||
|
||||
const [mode, setMode] = useState<Mode>("login");
|
||||
const [email, setEmail] = useState("");
|
||||
@@ -71,8 +78,7 @@ export default function LoginPage() {
|
||||
: mode === "register"
|
||||
? await register(email.trim(), password)
|
||||
: await tokenLogin(code.trim());
|
||||
setToken(result.api_token);
|
||||
router.push("/new");
|
||||
setToken(result.api_token, result.email);
|
||||
} catch (error) {
|
||||
setPending(false);
|
||||
if (error instanceof ApiError) {
|
||||
|
||||
@@ -69,12 +69,6 @@ export default async function LandingPage({
|
||||
{t("startCta")}
|
||||
<ArrowRight className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
</Link>
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
{t("loginCta")}
|
||||
</Link>
|
||||
</div>
|
||||
<svg
|
||||
viewBox="0 0 200 48"
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { AudioLines } from "lucide-react";
|
||||
import { AudioLines, LogIn, LogOut } from "lucide-react";
|
||||
import { Link, usePathname, useRouter } from "@/i18n/navigation";
|
||||
import { logout } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
export function SiteHeader() {
|
||||
const t = useTranslations("nav");
|
||||
const locale = useLocale();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const { ready, signedIn, email } = useSession();
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
|
||||
async function handleSignOut() {
|
||||
setSigningOut(true);
|
||||
await logout();
|
||||
setSigningOut(false);
|
||||
router.replace("/login");
|
||||
}
|
||||
|
||||
const otherLocale = locale === "fa" ? "en" : "fa";
|
||||
|
||||
@@ -60,6 +72,38 @@ export function SiteHeader() {
|
||||
>
|
||||
{otherLocale === "en" ? "EN" : "فا"}
|
||||
</button>
|
||||
{ready && signedIn && (
|
||||
<>
|
||||
{email && (
|
||||
<span
|
||||
className="hidden max-w-48 truncate text-sm text-stone-500 md:inline"
|
||||
title={t("signedInAs", { email })}
|
||||
>
|
||||
{email}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
disabled={signingOut}
|
||||
aria-label={email ? t("signOutOf", { email }) : t("signOut")}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-2 text-sm font-medium text-stone-600 transition-colors hover:bg-stone-100 hover:text-stone-900 focus-visible:ring-2 focus-visible:ring-teal-700 disabled:opacity-60 sm:px-3"
|
||||
>
|
||||
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t("signOut")}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{ready && !signedIn && pathname !== "/login" && (
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg bg-teal-700 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-teal-600 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
<LogIn className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t("signIn")}</span>
|
||||
<span className="sr-only sm:hidden">{t("signIn")}</span>
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
+38
-1
@@ -5,6 +5,9 @@
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000";
|
||||
|
||||
export const TOKEN_STORAGE_KEY = "sokhan_token";
|
||||
export const EMAIL_STORAGE_KEY = "sokhan_email";
|
||||
/** Fired on this tab whenever the stored session changes (sign-in or out). */
|
||||
export const SESSION_CHANGE_EVENT = "sokhan:session-change";
|
||||
|
||||
export type JobStatus = "queued" | "processing" | "completed" | "failed";
|
||||
export type TranscriptFormat = "txt" | "srt" | "vtt" | "json" | "docx";
|
||||
@@ -97,14 +100,48 @@ export function getToken(): string | null {
|
||||
return window.localStorage.getItem(TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
export function getEmail(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(EMAIL_STORAGE_KEY);
|
||||
}
|
||||
|
||||
function notifySessionChange(): void {
|
||||
window.dispatchEvent(new Event(SESSION_CHANGE_EVENT));
|
||||
}
|
||||
|
||||
export function setToken(token: string, email?: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(TOKEN_STORAGE_KEY, token);
|
||||
if (email) window.localStorage.setItem(EMAIL_STORAGE_KEY, email);
|
||||
else window.localStorage.removeItem(EMAIL_STORAGE_KEY);
|
||||
notifySessionChange();
|
||||
}
|
||||
|
||||
export function clearToken(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(TOKEN_STORAGE_KEY);
|
||||
window.localStorage.removeItem(EMAIL_STORAGE_KEY);
|
||||
notifySessionChange();
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the token on the server, then forget it locally. The local
|
||||
* session is cleared even when the API is unreachable or already rejects
|
||||
* the token, so signing out always works from the user's point of view.
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
} catch {
|
||||
// Offline or API down: the local sign-out below still happens.
|
||||
}
|
||||
}
|
||||
clearToken();
|
||||
}
|
||||
|
||||
function redirectToLogin(): void {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Reactive view of the stored session for client components. The token
|
||||
// lives in localStorage (see api.ts); this hook re-renders on sign-in and
|
||||
// sign-out in this tab (SESSION_CHANGE_EVENT) and in other tabs ("storage").
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { SESSION_CHANGE_EVENT, getEmail, getToken } from "@/lib/api";
|
||||
|
||||
// Accounts created by the Telegram bot get a synthetic address that means
|
||||
// nothing to the user, so it is not shown.
|
||||
const SYNTHETIC_EMAIL_SUFFIX = "@telegram.sokhan.local";
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
window.addEventListener("storage", onChange);
|
||||
window.addEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
return () => {
|
||||
window.removeEventListener("storage", onChange);
|
||||
window.removeEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
};
|
||||
}
|
||||
|
||||
const onServer = () => false;
|
||||
|
||||
export interface Session {
|
||||
/** False during SSR and the first client render, before storage is readable. */
|
||||
ready: boolean;
|
||||
signedIn: boolean;
|
||||
/** The account email, or null when unknown or a Telegram placeholder. */
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
export function useSession(): Session {
|
||||
const ready = useSyncExternalStore(subscribe, () => true, onServer);
|
||||
const signedIn = useSyncExternalStore(subscribe, () => getToken() !== null, onServer);
|
||||
const storedEmail = useSyncExternalStore(subscribe, getEmail, () => null);
|
||||
const email = storedEmail && !storedEmail.endsWith(SYNTHETIC_EMAIL_SUFFIX) ? storedEmail : null;
|
||||
return { ready, signedIn, email };
|
||||
}
|
||||
Reference in new issue
Block a user