Author SHA1 Message Date
ahp 8a585fc718 fix(deploy): persist the Whisper cache and clarify the compose env file
- HF_HOME=/data/huggingface on api and worker: the model cache sat in
  the container filesystem, so every recreate (down/up, --build, a new
  image) re-downloaded the model weights — and transcription failed
  outright wherever the Hugging Face Hub is unreachable
- the postgres healthcheck probes $POSTGRES_USER / $POSTGRES_DB instead
  of a hardcoded sokhan
- compose interpolates from the .env next to deploy/docker-compose.yml,
  not the one at the repo root: the quickstart in both READMEs and the
  .env.example header now say cp .env.example deploy/.env, and the
  missing-password error names that path
2026-11-26 16:26:03 +03:30
ahp 1304b13999 fix(deploy): pre-create /data owned by appuser in the backend image
Uploaded audio lives under DATA_DIR (/data, the sokhan-data named
volume). The image never created that directory, so Docker made the
mount point root-owned on first start and every upload failed with
PermissionError once the process runs as appuser.

Docker seeds a new named volume with the mount point's ownership, so
creating /data/audio in the image, owned by appuser, fixes fresh
installs without an entrypoint chown.
2026-11-26 16:25:33 +03:30
24 changed files with 51 additions and 575 deletions

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
# Sokhan configuration
# Copy this file to .env and adjust the values.
# For docker compose, copy it to deploy/.env instead.
# Every variable below has a working default for local development.
# --- Core ---
+13 -19
View File
@@ -5,6 +5,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
## [Unreleased]
### Fixed
- Compose: the Whisper model cache now lives on the `sokhan-data` volume
(`HF_HOME=/data/huggingface`). Previously it sat in the container's own
filesystem, so every recreate (`down`/`up`, `--build`, a new image)
re-downloaded the weights — and transcription failed outright where the
Hugging Face Hub is unreachable.
- Compose: the postgres healthcheck probes the configured `POSTGRES_USER` and
`POSTGRES_DB` instead of a hardcoded `sokhan`.
- Quickstart (both READMEs) and `.env.example` now say to copy the env file to
`deploy/.env`; the missing-password error names that path too. Copying it to
the repo root left `POSTGRES_PASSWORD` unset for compose.
### Added
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
@@ -52,15 +65,6 @@ 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
@@ -82,16 +86,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
under it. Applied across LICENSE, both READMEs, CITATION.cff, both
pyproject.toml files, web/package.json, the landing site copy, the demo
Space metadata and the fine-tuned model card.
- The header shows the signed-in account as an avatar with the email's
initial. It opens a menu with the full email and Sign out, instead of a
truncated email that disappeared on narrow screens.
### Fixed
- 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.
## [1.4.1] - 2026-11-26
+5 -1
View File
@@ -145,6 +145,8 @@ faster-whisper، یک ورکر Celery، یک داشبورد Next.js که فار
```bash
git clone https://github.com/Abolfazlrwm/sokhan.git
cd sokhan
cp .env.example deploy/.env # compose فایل .env کنار فایل compose را می‌خواند
# در deploy/.env مقدار POSTGRES_PASSWORD را یک رمز طولانی و تصادفی بگذارید
docker compose -f deploy/docker-compose.yml up -d --build
```
@@ -152,7 +154,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
- API و مستندات: http://localhost:8000/docs
ورکر مدل Whisper تنظیم‌شده را در اولین رونویسی دانلود می‌کند
(`WHISPER_MODEL_SIZE`، پیش‌فرض `small`). برای فعال‌کردن خلاصه‌سازی،
(`WHISPER_MODEL_SIZE`، پیش‌فرض `small`) و آن را روی ولوم `sokhan-data`
(`HF_HOME=/data/huggingface`) نگه می‌دارد، پس ساخت دوبارهٔ کانتینرها مدل را
دوباره دانلود نمی‌کند. برای فعال‌کردن خلاصه‌سازی،
`SUMMARY_ENABLED=true` و متغیرهای LLM خود را در فایل `.env` کنار
`docker-compose.yml` بگذارید. برای اعمال مهاجرت‌های اسکیما به‌صورت دستی:
+5 -1
View File
@@ -143,6 +143,8 @@ default — a GPU is not required.
```bash
git clone https://github.com/Abolfazlrwm/sokhan.git
cd sokhan
cp .env.example deploy/.env # compose reads the .env next to the compose file
# edit deploy/.env and set POSTGRES_PASSWORD to a long random value
docker compose -f deploy/docker-compose.yml up -d --build
```
@@ -150,7 +152,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
- API and docs: http://localhost:8000/docs
The worker downloads the configured Whisper model on first transcription
(`WHISPER_MODEL_SIZE`, default `small`). To enable summaries, set
(`WHISPER_MODEL_SIZE`, default `small`) and caches it on the `sokhan-data`
volume (`HF_HOME=/data/huggingface`), so recreating the containers does not
download it again. To enable summaries, set
`SUMMARY_ENABLED=true` and your LLM variables in a `.env` file next to
`docker-compose.yml`. To apply schema migrations manually:
+3 -3
View File
@@ -12,9 +12,9 @@ COPY alembic ./alembic
RUN pip install --no-cache-dir .
# Non-root runtime user; uvicorn binds 8000 (unprivileged) and the app keeps
# no local writable state (postgres via DATABASE_URL).
RUN useradd --system --uid 1000 --create-home appuser
RUN useradd --system --uid 1000 --create-home appuser \
&& mkdir -p /data/audio \
&& chown -R appuser:appuser /data
USER appuser
EXPOSE 8000
+1 -17
View File
@@ -7,17 +7,15 @@ 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, Response, status
from fastapi import APIRouter, Depends, HTTPException, 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
@@ -99,20 +97,6 @@ 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.
-37
View File
@@ -62,40 +62,3 @@ 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
-12
View File
@@ -9,10 +9,6 @@ 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)."""
@@ -50,11 +46,6 @@ 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",
@@ -73,7 +64,6 @@ 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":
@@ -91,7 +81,6 @@ 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()
@@ -101,7 +90,6 @@ 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()
+5 -51
View File
@@ -3,8 +3,6 @@
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
@@ -13,17 +11,10 @@ from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
Message,
User,
)
from sokhan_bot import texts
from sokhan_bot.client import (
AuthError,
BackendError,
FileTooLongError,
QuotaError,
SokhanClient,
)
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
from sokhan_bot.split import split_message
from sokhan_bot.store import TokenStore
@@ -31,8 +22,6 @@ 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(
@@ -93,35 +82,10 @@ 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:
@@ -129,7 +93,7 @@ class Handlers:
if not token:
return
try:
info = self._authed(message.chat.id, message.from_user, self.client.get_quota)
info = self.client.get_quota(token)
except BackendError:
await message.answer(texts.SERVER_UNREACHABLE)
return
@@ -173,9 +137,7 @@ class Handlers:
await message.answer("شناسهٔ پردازش را بنویس، مثلاً: /track 3f2a…")
return
try:
job = self._authed(
message.chat.id, message.from_user, lambda t: self.client.get_job(t, job_id)
)
job = self.client.get_job(token, job_id)
except BackendError:
await message.answer(texts.UNKNOWN_JOB)
return
@@ -234,11 +196,7 @@ class Handlers:
return
try:
job_id = self._authed(
message.chat.id,
message.from_user,
lambda t: self.client.upload_audio(t, filename, content),
)
job_id = self.client.upload_audio(token, filename, content)
except FileTooLongError as exc:
await message.answer(
texts.FILE_TOO_LONG.format(
@@ -271,11 +229,7 @@ class Handlers:
job_id = callback.data.split(":", 1)[1]
try:
job = self._authed(
callback.message.chat.id,
callback.from_user,
lambda t: self.client.get_job(t, job_id),
)
job = self.client.get_job(token, job_id)
except BackendError:
await callback.answer(texts.UNKNOWN_JOB, show_alert=True)
return
+1 -9
View File
@@ -19,7 +19,7 @@ import time
from aiogram import Bot
from sokhan_bot import texts
from sokhan_bot.client import AuthError, SokhanClient
from sokhan_bot.client import SokhanClient
from sokhan_bot.split import split_message
from sokhan_bot.store import TokenStore
@@ -75,14 +75,6 @@ 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
-6
View File
@@ -42,12 +42,6 @@ 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:
+1 -18
View File
@@ -2,7 +2,7 @@
import httpx
import pytest
from sokhan_bot.client import AuthError, BackendError, FileTooLongError, QuotaError, SokhanClient
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
from sokhan_bot.config import BotSettings
@@ -88,20 +88,3 @@ 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)
-128
View File
@@ -1,128 +0,0 @@
"""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)]
-12
View File
@@ -47,15 +47,3 @@ 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
+4 -3
View File
@@ -5,12 +5,12 @@ services:
POSTGRES_USER: ${POSTGRES_USER:-sokhan}
# Required on purpose: shipping a default credential means every
# deployment that forgets the .env runs an open database.
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}
POSTGRES_DB: ${POSTGRES_DB:-sokhan}
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U sokhan"]
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 3s
retries: 10
@@ -33,10 +33,11 @@ services:
build:
context: ../backend
environment: &backend-env
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}@postgres:5432/${POSTGRES_DB:-sokhan}
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}@postgres:5432/${POSTGRES_DB:-sokhan}
REDIS_URL: redis://redis:6379/0
CELERY_ENABLED: "true"
DATA_DIR: /data
HF_HOME: /data/huggingface
SOKHAN_CORS_ORIGINS: ${SOKHAN_CORS_ORIGINS:-}
WHISPER_MODEL_SIZE: ${WHISPER_MODEL_SIZE:-medium}
WHISPER_DEVICE: ${WHISPER_DEVICE:-cpu}
+1 -7
View File
@@ -15,13 +15,7 @@
"new": "New transcription",
"archive": "Archive",
"switchToEn": "English",
"switchToFa": "فارسی",
"signIn": "Sign in",
"signOut": "Sign out",
"accountMenu": "Account",
"accountMenuFor": "Account menu for {email}",
"signedInLabel": "Signed in as",
"signedIn": "Signed in"
"switchToFa": "فارسی"
},
"landing": {
"headline": "From speech to text, in moments",
+1 -7
View File
@@ -15,13 +15,7 @@
"new": "رونویسی تازه",
"archive": "آرشیو",
"switchToEn": "English",
"switchToFa": "فارسی",
"signIn": "ورود",
"signOut": "خروج",
"accountMenu": "حساب کاربری",
"accountMenuFor": "منوی حساب {email}",
"signedInLabel": "وارد شده با",
"signedIn": "وارد شده‌ای"
"switchToFa": "فارسی"
},
"landing": {
"headline": "از گفتار به متن، در چند لحظه",
+3 -9
View File
@@ -1,10 +1,9 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { 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";
@@ -14,12 +13,6 @@ 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("");
@@ -78,7 +71,8 @@ export default function LoginPage() {
: mode === "register"
? await register(email.trim(), password)
: await tokenLogin(code.trim());
setToken(result.api_token, result.email);
setToken(result.api_token);
router.push("/new");
} catch (error) {
setPending(false);
if (error instanceof ApiError) {
+5 -3
View File
@@ -1,7 +1,6 @@
import { getTranslations, setRequestLocale } from "next-intl/server";
import { ArrowRight, GraduationCap, TextSearch, Voicemail, type LucideIcon } from "lucide-react";
import { Link } from "@/i18n/navigation";
import { LoginCta } from "@/components/login-cta";
const waveBars = [12, 20, 30, 22, 34, 40, 28, 16, 26, 36, 20, 30, 14, 24, 32, 18, 26, 12, 22, 16];
@@ -70,9 +69,12 @@ export default async function LandingPage({
{t("startCta")}
<ArrowRight className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
</Link>
<LoginCta 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">
<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")}
</LoginCta>
</Link>
</div>
<svg
viewBox="0 0 200 48"
-114
View File
@@ -1,114 +0,0 @@
"use client";
import { useEffect, useId, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { ChevronDown, LogOut, UserRound } from "lucide-react";
/**
* The signed-in account in the header: an avatar with the email's initial
* that opens a small menu showing the full address and Sign out. The full
* email no longer has to squeeze into the header row (where it was
* truncated or hidden on narrow screens).
*/
export function AccountMenu({
email,
signingOut,
onSignOut,
}: {
email: string | null;
signingOut: boolean;
onSignOut: () => void;
}) {
const t = useTranslations("nav");
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const signOutRef = useRef<HTMLButtonElement>(null);
const menuId = useId();
useEffect(() => {
if (!open) return;
signOutRef.current?.focus();
function onPointerDown(event: PointerEvent) {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
}
function onKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") {
setOpen(false);
buttonRef.current?.focus();
}
}
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("keydown", onKeyDown);
};
}, [open]);
const initial = email ? email.charAt(0).toUpperCase() : null;
return (
<div ref={rootRef} className="relative">
<button
ref={buttonRef}
type="button"
onClick={() => setOpen((value) => !value)}
aria-haspopup="menu"
aria-expanded={open}
aria-controls={open ? menuId : undefined}
aria-label={email ? t("accountMenuFor", { email }) : t("accountMenu")}
className="flex items-center gap-1 rounded-full p-0.5 text-stone-500 transition-colors hover:text-stone-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
>
<span
className="flex h-9 w-9 items-center justify-center rounded-full bg-teal-100 text-sm font-bold text-teal-800"
aria-hidden="true"
>
{initial ?? <UserRound className="h-5 w-5" />}
</span>
<ChevronDown
className={`hidden h-4 w-4 transition-transform sm:block ${open ? "rotate-180" : ""}`}
aria-hidden="true"
/>
</button>
{open ? (
<div
id={menuId}
role="menu"
aria-label={t("accountMenu")}
className="absolute end-0 top-full z-50 mt-2 w-64 overflow-hidden rounded-xl border border-stone-200 bg-white shadow-lg"
>
<div className="border-b border-stone-100 px-4 py-3">
<p className="text-xs text-stone-500">{email ? t("signedInLabel") : t("accountMenu")}</p>
{email ? (
<p
dir="ltr"
className="mt-0.5 break-all text-start text-sm font-medium text-stone-900"
>
{email}
</p>
) : (
<p className="mt-0.5 text-sm font-medium text-stone-900">{t("signedIn")}</p>
)}
</div>
<button
ref={signOutRef}
type="button"
role="menuitem"
onClick={() => {
setOpen(false);
onSignOut();
}}
disabled={signingOut}
className="flex w-full items-center gap-2 px-4 py-2.5 text-sm font-medium text-stone-700 transition-colors hover:bg-stone-50 hover:text-stone-900 focus-visible:bg-stone-50 focus-visible:outline-none disabled:opacity-60"
>
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
{t("signOut")}
</button>
</div>
) : null}
</div>
);
}
-16
View File
@@ -1,16 +0,0 @@
"use client";
import type { ReactNode } from "react";
import { Link } from "@/i18n/navigation";
import { useSession } from "@/lib/session";
/** The landing page's sign-in button; hidden once the visitor is signed in. */
export function LoginCta({ className, children }: { className: string; children: ReactNode }) {
const { ready, signedIn } = useSession();
if (!ready || signedIn) return null;
return (
<Link href="/login" className={className}>
{children}
</Link>
);
}
+1 -27
View File
@@ -1,27 +1,14 @@
"use client";
import { useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { AudioLines, LogIn } from "lucide-react";
import { AccountMenu } from "@/components/account-menu";
import { AudioLines } 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";
@@ -73,19 +60,6 @@ export function SiteHeader() {
>
{otherLocale === "en" ? "EN" : "فا"}
</button>
{ready && signedIn && (
<AccountMenu email={email} signingOut={signingOut} onSignOut={handleSignOut} />
)}
{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>
+1 -38
View File
@@ -5,9 +5,6 @@
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";
@@ -100,48 +97,14 @@ export function getToken(): string | null {
return window.localStorage.getItem(TOKEN_STORAGE_KEY);
}
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 {
export function setToken(token: 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 {
-37
View File
@@ -1,37 +0,0 @@
// 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 };
}