diff --git a/.env.example b/.env.example index 6f89ee7..b7d5605 100644 --- a/.env.example +++ b/.env.example @@ -13,10 +13,30 @@ TELEGRAM_BOT_TOKEN= # Username бота без @ — нужен для построения ссылки t.me/?start=<код> TELEGRAM_BOT_USERNAME= -# Кому выдать роль преподавателя при первом входе (telegram user id через запятую). -# Свой id можно узнать у @userinfobot. +# Чат или канал клуба, куда бот шлёт объявления, задания и напоминания. +# Добавь бота в чат и отправь там /id — он ответит нужным числом. +TELEGRAM_NOTIFY_CHAT_ID= +# За сколько минут до старта события напоминать. +REMINDER_MINUTES_BEFORE=60 + +# Кому выдать роль преподавателя — telegram id через запятую. +# Свой id узнаешь, отправив боту /id. Проверяется при каждом входе. TEACHER_TELEGRAM_IDS= +# --- вход через OpenID Connect (Authentik) --- +# Issuer берётся из настроек провайдера в Authentik: Applications → Providers → OpenID Configuration Issuer. +# Redirect URI в Authentik: /login/oidc/callback +OIDC_ISSUER= +OIDC_CLIENT_ID= +# Пусто — публичный клиент с PKCE. С секретом — confidential client. +OIDC_CLIENT_SECRET= +OIDC_SCOPES=openid profile email +OIDC_PROVIDER_NAME=Authentik +# Клейм с группами (в Authentik по умолчанию "groups" при включённом scope) и группы, +# дающие роль преподавателя. +OIDC_GROUPS_CLAIM=groups +OIDC_TEACHER_GROUPS=sp-teachers + # --- локальная разработка --- # Включает вход по имени без Telegram на /login/dev. НИКОГДА не включай в проде. DEV_LOGIN_ENABLED=false diff --git a/.gitignore b/.gitignore index 206f8dd..f771021 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,13 @@ data/ .pytest_cache/ .ruff_cache/ msu_sport.egg-info/ + +# Базы и их резервные копии — это данные участников, не код. +*.db +*.db-shm +*.db-wal +sport-backup-* + +# Отчёты покрытия +.coverage +htmlcov/ diff --git a/README.md b/README.md index a24d461..62e8177 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,8 @@ ## Что уже работает **Студент** -- Вход через Telegram-бота (одноразовый код, без публичного домена). +- Вход через Telegram-бота (одноразовый код, без публичного домена) или через + Authentik / любой OpenID Connect-провайдер с маппингом групп на роль. - Привязка аккаунтов Codeforces и LeetCode с подтверждением владения. - Вступление в группу по коду от преподавателя. - Список заданий с прогрессом и дедлайнами, страница задания по задачам. @@ -39,8 +40,19 @@ - Фоновый синкер тянет посылки каждые 10 минут и обновляет каталог раз в сутки. - Новая задача с только что прошедшего контеста подвяжется к посылкам сама, как только попадёт в каталог. -- Интерфейс без внешних зависимостей: иконки — инлайновый SVG-спрайт, - светлая и тёмная темы по системной настройке, ни одного запроса к CDN. +- Навигация — вертикальная рейка слева, на телефоне превращается в нижнюю + панель вкладок. Над страницей — строка ближайшего события с обратным отсчётом, + видна отовсюду. +- Визуальный язык — **плакат**: жёлтое поле, чёрные линейки, тяжёлый гротеск + Unbounded, три цвета. Сложность и статусы кодируются плотностью заливки, а не + цветом; синий — только ссылки, красный — только ошибки и просрочка. + По умолчанию портал светлый — жёлтое поле, независимо от настроек системы. + Тёмная тема — инверсия: чёрное поле, жёлтые линейки. Переключатель внизу рейки + (на телефоне — в шапке): светлая → тёмная → как в системе; выбор хранится + в браузере и применяется до первой отрисовки, без мигания. +- Интерфейс без внешних зависимостей: иконки — инлайновый SVG-спрайт, шрифты + (Unbounded, Golos Text, JetBrains Mono — все OFL) лежат в `app/static/fonts/`, + ни одного запроса к CDN. --- @@ -167,15 +179,30 @@ docker compose cp web:/data/backup.db ./backup-$(date +%F).db --- -## Свой логотип +## Логотип -Положи файл в `app/static/` — он подхватится автоматически, без правок кода: +Знак клуба — герб университета из официального логотипа (Главное здание, венок, +звезда, 1755) в фигурных скобках, знак кода. Без диска и кольца: одним цветом, +компактно. В `app/static/` лежат четыре варианта: + +| Файл | Где используется | +|---|---| +| `logo.svg` | страница входа: герб в скобках + название в три строки, чёрный | +| `logo-dark.svg` | то же жёлтым — для тёмной темы страницы входа | +| `mark.svg` | рейка и мобильная шапка: только `{герб}`; рисуется CSS-маской в цвет текста, поэтому виден на любом фоне | +| `favicon.svg` | вкладка браузера: `{герб}` на жёлтой плашке, чтобы читалось на любой полосе вкладок | + +Герб — товарный знак МГУ: использование в материалах клуба стоит согласовать +с факультетом и следовать брендбуку университета. + +Чтобы заменить своей, положи файл в `app/static/` — подхватится автоматически: | Файл | Куда идёт | |---|---| -| `logo.svg` / `logo.png` | в шапку и на страницу входа | +| `logo.svg` / `logo.png` | на страницу входа (и в рейку, если нет `mark-*`) | | `logo-dark.svg` / `logo-dark.png` | замена для тёмной темы (необязательно) | -| `favicon.png` | иконка вкладки (иначе берётся `logo.*`) | +| `mark.svg` / `mark.png` | компактный знак для рейки; используется как маска, цвет файла не важен | +| `favicon.png` / `favicon.svg` | иконка вкладки (иначе берётся `logo.*`) | SVG предпочтительнее — не мылится на ретине. Для PNG бери высоту от 96 px: в шапке логотип рисуется высотой 24 px, на входе — до 72 px. @@ -207,7 +234,7 @@ docker cp app/static/logo.png sport-web-1:/app/app/static/logo.png ## Настройка Telegram 1. Создай бота у [@BotFather](https://t.me/BotFather), получи токен. -2. Узнай свой telegram id у [@userinfobot](https://t.me/userinfobot). +2. Узнай свой telegram id: отправь боту `/id` (или спроси у [@userinfobot](https://t.me/userinfobot)). 3. Заполни в `.env`: ``` @@ -221,7 +248,82 @@ TEACHER_TELEGRAM_IDS=123456789 # тебе выдастся роль пр страница выдаёт одноразовый код, ты отправляешь его боту, страница сама открывается. `TEACHER_TELEGRAM_IDS` применяется при каждом входе, так что роль преподавателя -нельзя потерять, даже если что-то нажать в интерфейсе. +нельзя потерять, даже если что-то нажать в интерфейсе. Свой id узнаешь, отправив +боту `/id`. Взят именно id, а не `@username`: логин можно сменить, а +освободившийся — занять кому угодно. + +--- + +## Уведомления в Telegram + +Тот же бот, что и для входа, умеет писать в чат. Три события: + +- **опубликовано объявление** — заголовок, время, текст, ссылка; +- **выдано задание** — название, число задач, дедлайн, ссылка на портал; +- **напоминание** за `REMINDER_MINUTES_BEFORE` минут (по умолчанию 60) до старта + события с указанным временем — уходит один раз, отметка хранится в базе. + +Куда уходит: если у группы задан свой чат (страница группы → «Telegram-чат»), +то в него; иначе в общий `TELEGRAM_NOTIFY_CHAT_ID`. Пусто и там — не отправляется. + +Как узнать id чата: добавь бота в чат и отправь `/id` — он ответит числом +вида `-1001234567890`. Для канала бот должен быть администратором. + +Отправка никогда не мешает основному действию: если Telegram недоступен, +объявление всё равно опубликуется, а ошибка попадёт в лог. + +--- + +## Вход через Authentik (OpenID Connect) + +Третий способ входа рядом с Telegram и dev-формой. Подходит любой провайдер +с OIDC discovery — Authentik, Keycloak, Authelia. + +В Authentik: **Applications → Providers → Create → OAuth2/OpenID Provider**. +Тип клиента — Public (тогда работает чистый PKCE) или Confidential (тогда +впиши секрет). Redirect URI — `/login/oidc/callback`. Скоупы — +`openid profile email`; чтобы роль преподавателя выдавалась по группе, +включи в провайдере scope mapping для `groups`. + +``` +OIDC_ISSUER=https://auth.example.org/application/o/sport/ +OIDC_CLIENT_ID=... +OIDC_CLIENT_SECRET= # пусто для public-клиента +OIDC_TEACHER_GROUPS=sp-teachers +``` + +Что происходит при входе: Authorization Code + PKCE, `state` и `nonce` +живут в подписанной cookie 10 минут, код обменивается по бэкенд-каналу, +профиль берётся с userinfo. Пользователь привязывается по `sub` — стабильному +идентификатору провайдера, а не по email. + +**Роль.** Если пользователь состоит хотя бы в одной из `OIDC_TEACHER_GROUPS`, +при каждом входе он получает роль преподавателя. Автоматического понижения нет: +роль могла быть выдана иначе (первый вход, вручную). + +**Честно про проверку токена.** Подпись ID-токена локально не проверяется — +в зависимостях нет JWKS-парсера. Это безопасно, потому что токен приходит +напрямую от провайдера по TLS в обмене кода, а не от браузера; `nonce` +сверяется. Если провайдер окажется за недоверенным прокси — добавь проверку +подписи (PyJWT + cryptography) поверх `app/oidc.py`. + +--- + +## Один участник — несколько способов входа + +Войти можно через Telegram или через Authentik. Чтобы это был **один человек +на портале**, а не два, второй способ привязывается из личного кабинета: +`/accounts` → «Способы входа» → «Привязать». + +- Вошёл через Authentik → привязал Telegram: получил уведомления о заданиях. +- Вошёл через Telegram → привязал Authentik: сможет входить учётной записью + факультета, история и баллы останутся. + +Привязку завершает тот же браузер, который её начал — чужим кодом прицепить +свой Telegram к чужой учётке нельзя. Если этот Telegram или аккаунт провайдера +уже принадлежит другому участнику, привязка отклоняется. + +Отвязать можно любой способ, кроме последнего: иначе человек потеряет доступ. --- @@ -344,8 +446,11 @@ app/ config.py настройки из .env models.py схема базы (SQLAlchemy 2.0) security.py подписанная сессионная кука + oidc.py OpenID Connect: discovery, PKCE, обмен кода + ticker.py ближайшее событие для строки над страницей (middleware) deps.py текущий пользователь, проверка роли bot.py Telegram-бот на long polling + notify.py уведомления в Telegram-чаты: объявления, задания, напоминания scheduler.py фоновый цикл синхронизации cli.py служебные команды platforms/ клиенты Codeforces и LeetCode @@ -365,10 +470,12 @@ app/ _feed.html макрос ленты, переиспользуется на трёх страницах _ui.html макрос пустых состояний _announce.html карточка объявления - static/style.css светлая и тёмная темы + static/style.css визуальный язык «плакат», обе темы static/countdown.js обратный отсчёт в объявлениях + static/theme.js переключатель светлой и тёмной темы + static/fonts/ Unbounded, Golos Text, JetBrains Mono (woff2) + лицензии migrations/ Alembic -tests/ 103 теста +tests/ 107 тестов ``` --- diff --git a/app/bot.py b/app/bot.py index 6ced397..2f29fc0 100644 --- a/app/bot.py +++ b/app/bot.py @@ -115,7 +115,12 @@ async def _handle_update(api: TelegramAPI, update: dict) -> None: return if text.startswith("/id"): - await api.send_message(chat_id, f"Твой telegram id: {sender['id']}") + lines = [f"Твой telegram id: {sender['id']}"] + if (message.get("chat") or {}).get("type") != "private": + lines.append( + f"Id этого чата: {chat_id} — впиши его в настройках группы на портале." + ) + await api.send_message(chat_id, "\n".join(lines)) async def run_bot(stop_event: asyncio.Event) -> None: diff --git a/app/config.py b/app/config.py index 24b8d32..40334f1 100644 --- a/app/config.py +++ b/app/config.py @@ -25,7 +25,21 @@ class Settings(BaseSettings): # Telegram telegram_bot_token: str = "" telegram_bot_username: str = "" + # Telegram id преподавателей через запятую. Id не меняется, в отличие от логина. teacher_telegram_ids: str = "" + # Чат или канал клуба для уведомлений (id вида -1001234567890). Пусто — не слать. + telegram_notify_chat_id: str = "" + # За сколько минут до старта события напоминать. + reminder_minutes_before: int = 60 + + # OpenID Connect (Authentik, Keycloak и любой другой провайдер с discovery). + oidc_issuer: str = "" # https://auth.example.org/application/o/sport/ + oidc_client_id: str = "" + oidc_client_secret: str = "" # пусто — публичный клиент, только PKCE + oidc_scopes: str = "openid profile email" + oidc_provider_name: str = "Authentik" + oidc_groups_claim: str = "groups" + oidc_teacher_groups: str = "" # группы провайдера, дающие роль преподавателя # Локальная разработка без Telegram. dev_login_enabled: bool = False @@ -51,6 +65,19 @@ class Settings(BaseSettings): session_ttl_seconds: int = 60 * 60 * 24 * 30 session_cookie: str = "sport_session" + @property + def oidc_enabled(self) -> bool: + return bool(self.oidc_issuer.strip() and self.oidc_client_id.strip()) + + @property + def oidc_teacher_group_set(self) -> set[str]: + raw = self.oidc_teacher_groups.replace(";", ",").split(",") + return {g.strip() for g in raw if g.strip()} + + @property + def oidc_redirect_uri(self) -> str: + return self.base_url.rstrip("/") + "/login/oidc/callback" + @property def secret_is_insecure(self) -> bool: return self.secret_key.strip() in {"", INSECURE_SECRET} @@ -71,6 +98,7 @@ class Settings(BaseSettings): continue return out + @property def telegram_login_url_template(self) -> str: return f"https://t.me/{self.telegram_bot_username}?start={{code}}" diff --git a/app/main.py b/app/main.py index 7dbaee8..a7a9c03 100644 --- a/app/main.py +++ b/app/main.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio import contextlib import logging +import mimetypes from collections.abc import AsyncIterator from urllib.parse import quote @@ -16,6 +17,7 @@ from app.deps import Forbidden, RedirectToLogin from app.routers import accounts, announcements, auth, feed, leaderboard, student, teacher from app.scheduler import run_scheduler from app.templating import STATIC_DIR, templates +from app.ticker import load_ticker logging.basicConfig( level=logging.INFO, @@ -71,6 +73,9 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: app = FastAPI(title=settings.app_name, lifespan=lifespan, docs_url=None, redoc_url=None) +# У стандартной таблицы MIME нет woff2 — без этого шрифт уходит как octet-stream. +mimetypes.add_type("font/woff2", ".woff2") + if STATIC_DIR.exists(): app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") @@ -83,6 +88,17 @@ app.include_router(leaderboard.router) app.include_router(teacher.router) +@app.middleware("http") +async def attach_ticker(request: Request, call_next): + """Ближайшее событие для строки над страницей. Один лёгкий запрос к SQLite.""" + try: + request.state.ticker = await load_ticker(request) + except Exception: # строка — украшение, страницу из-за неё не роняем + logger.exception("не удалось собрать ticker") + request.state.ticker = None + return await call_next(request) + + @app.exception_handler(RedirectToLogin) async def _redirect_to_login(request: Request, exc: RedirectToLogin): return RedirectResponse(f"/login?next={quote(exc.next_url)}", status_code=303) diff --git a/app/models.py b/app/models.py index 21d6dcb..148dfe5 100644 --- a/app/models.py +++ b/app/models.py @@ -111,6 +111,10 @@ class User(Base): telegram_id: Mapped[int | None] = mapped_column(Integer, unique=True, index=True) telegram_username: Mapped[str | None] = mapped_column(String(64)) + # Идентификатор пользователя у OIDC-провайдера (Authentik). Стабилен, в отличие от email. + oidc_sub: Mapped[str | None] = mapped_column(String(255), unique=True, index=True) + email: Mapped[str | None] = mapped_column(String(255)) + accounts: Mapped[list[PlatformAccount]] = relationship( back_populates="user", cascade="all, delete-orphan", lazy="selectin" ) @@ -203,6 +207,8 @@ class Group(Base): created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) created_at: Mapped[datetime] = mapped_column(default=utcnow) is_archived: Mapped[bool] = mapped_column(Boolean, default=False) + # Telegram-чат группы для уведомлений. Пусто — уходит в общий чат клуба. + telegram_chat_id: Mapped[str | None] = mapped_column(String(32)) memberships: Mapped[list[GroupMembership]] = relationship( back_populates="group", cascade="all, delete-orphan" @@ -315,6 +321,8 @@ class Announcement(Base): pinned: Mapped[bool] = mapped_column(Boolean, default=False) created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) created_at: Mapped[datetime] = mapped_column(default=utcnow) + # Когда ушло напоминание о старте, чтобы не слать дважды. + reminded_at: Mapped[datetime | None] = mapped_column() group: Mapped[Group | None] = relationship(lazy="selectin") @@ -385,6 +393,11 @@ class LoginToken(Base): display_name: Mapped[str | None] = mapped_column(String(120)) confirmed_at: Mapped[datetime | None] = mapped_column() consumed_at: Mapped[datetime | None] = mapped_column() + # Если задано — это не вход, а привязка Telegram к уже существующей учётке. + # SQLite пересоздаёт таблицу при ALTER, поэтому имя ограничения задаём явно. + link_user_id: Mapped[int | None] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE", name="fk_login_token_link_user") + ) class SyncState(Base): diff --git a/app/notify.py b/app/notify.py new file mode 100644 index 0000000..8b0bb5c --- /dev/null +++ b/app/notify.py @@ -0,0 +1,125 @@ +"""Уведомления в Telegram: чат клуба или чат группы. + +Отправка никогда не роняет запрос: ошибка сети — это запись в лог, +а объявление всё равно опубликовано. +""" + +from __future__ import annotations + +import html +import logging +from datetime import timedelta + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.bot import TelegramAPI +from app.config import settings +from app.models import Announcement, Assignment, Group, utcnow +from app.templating import fmt_dt + +logger = logging.getLogger(__name__) + + +def _chat_for(group: Group | None) -> str | None: + if group is not None and group.telegram_chat_id: + return group.telegram_chat_id + return settings.telegram_notify_chat_id or None + + +async def _group_of(session: AsyncSession | None, group_id: int | None) -> Group | None: + """Связь после refresh не загружена; тянем группу явно, чтобы не упасть в async.""" + if session is None or group_id is None: + return None + return await session.get(Group, group_id) + + +async def send(chat_id: str | int, text: str) -> bool: + if not settings.telegram_bot_token: + return False + api = TelegramAPI(settings.telegram_bot_token) + try: + result = await api.call( + "sendMessage", chat_id=chat_id, text=text, parse_mode="HTML", + disable_web_page_preview=True, + ) + return result is not None + finally: + await api.close() + + +def _e(value: object) -> str: + return html.escape(str(value or "")) + + +def announcement_text(item: Announcement) -> str: + lines = [f"📣 {_e(item.title)}"] + if item.starts_at: + when = fmt_dt(item.starts_at) + if item.ends_at: + when += f" — {fmt_dt(item.ends_at, '%H:%M')}" + lines.append(f"🕐 {when}") + if item.body: + lines.append("") + lines.append(_e(item.body)) + if item.url: + lines.append("") + lines.append(f'{_e(item.url_label or "Перейти")}') + return "\n".join(lines) + + +def reminder_text(item: Announcement) -> str: + minutes = max(1, round((item.starts_at - utcnow()).total_seconds() / 60)) + lines = [ + f"⏰ Через {minutes} мин: {_e(item.title)}", + f"🕐 старт {fmt_dt(item.starts_at, '%H:%M')}", + ] + if item.url: + lines.append(f'{_e(item.url_label or "Перейти")}') + return "\n".join(lines) + + +def assignment_text(item: Assignment, problems: int) -> str: + lines = [f"📝 Новое задание: {_e(item.title)}", f"Задач: {problems}"] + if item.deadline: + lines.append(f"Дедлайн: {fmt_dt(item.deadline)}") + base = settings.base_url.rstrip("/") + lines.append(f'Открыть на портале') + return "\n".join(lines) + + +async def notify_announcement(item: Announcement, session: AsyncSession | None = None) -> bool: + chat = _chat_for(await _group_of(session, item.group_id)) + if not chat: + return False + return await send(chat, announcement_text(item)) + + +async def notify_assignment( + item: Assignment, problems: int, session: AsyncSession | None = None +) -> bool: + chat = _chat_for(await _group_of(session, item.group_id)) + if not chat: + return False + return await send(chat, assignment_text(item, problems)) + + +async def send_due_reminders(session: AsyncSession) -> int: + """Напоминания о событиях, которые начнутся в ближайшие N минут.""" + now = utcnow() + horizon = now + timedelta(minutes=settings.reminder_minutes_before) + stmt = select(Announcement).where( + Announcement.starts_at.is_not(None), + Announcement.starts_at > now, + Announcement.starts_at <= horizon, + Announcement.reminded_at.is_(None), + ) + sent = 0 + for item in (await session.execute(stmt)).scalars().all(): + chat = _chat_for(await _group_of(session, item.group_id)) + # Отмечаем даже без чата: иначе каждый круг будем перебирать одно и то же. + item.reminded_at = now + if chat and await send(chat, reminder_text(item)): + sent += 1 + await session.commit() + return sent diff --git a/app/oidc.py b/app/oidc.py new file mode 100644 index 0000000..f0fe302 --- /dev/null +++ b/app/oidc.py @@ -0,0 +1,171 @@ +"""OpenID Connect для входа через Authentik (или другой провайдер с discovery). + +Authorization Code + PKCE. ID-токен приходит по защищённому бэкенд-каналу +прямо от провайдера, поэтому подпись локально не проверяем — сверяем nonce +и берём профиль с userinfo. Публичного JWKS-парсера в зависимостях нет +намеренно: меньше библиотек, меньше поверхности. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import secrets +from dataclasses import dataclass +from urllib.parse import urlencode + +import httpx +from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer + +from app.config import settings + +STATE_COOKIE = "sport_oidc" +STATE_TTL = 600 + + +class OIDCError(RuntimeError): + """Провайдер недоступен, ответ не тот или пользователь отказал.""" + + +@dataclass(slots=True) +class Discovery: + issuer: str + authorization_endpoint: str + token_endpoint: str + userinfo_endpoint: str | None + + +_discovery: Discovery | None = None + + +def _timeout() -> httpx.Timeout: + return httpx.Timeout(settings.http_timeout) + + +async def discover(force: bool = False) -> Discovery: + global _discovery + if _discovery is not None and not force: + return _discovery + url = settings.oidc_issuer.rstrip("/") + "/.well-known/openid-configuration" + try: + async with httpx.AsyncClient(timeout=_timeout()) as client: + response = await client.get(url) + response.raise_for_status() + data = response.json() + except (httpx.HTTPError, ValueError) as exc: + raise OIDCError(f"discovery недоступен: {exc}") from exc + try: + _discovery = Discovery( + issuer=data["issuer"], + authorization_endpoint=data["authorization_endpoint"], + token_endpoint=data["token_endpoint"], + userinfo_endpoint=data.get("userinfo_endpoint"), + ) + except KeyError as exc: + raise OIDCError(f"в discovery нет поля {exc}") from exc + return _discovery + + +def pkce_pair() -> tuple[str, str]: + verifier = secrets.token_urlsafe(64) + digest = hashlib.sha256(verifier.encode()).digest() + challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + return verifier, challenge + + +def _serializer() -> URLSafeTimedSerializer: + return URLSafeTimedSerializer(settings.secret_key, salt="oidc-state-v1") + + +def pack_state(payload: dict) -> str: + return _serializer().dumps(payload) + + +def unpack_state(token: str | None) -> dict | None: + if not token: + return None + try: + return _serializer().loads(token, max_age=STATE_TTL) + except (BadSignature, SignatureExpired): + return None + + +def authorization_url(disc: Discovery, *, state: str, nonce: str, code_challenge: str) -> str: + params = { + "response_type": "code", + "client_id": settings.oidc_client_id, + "redirect_uri": settings.oidc_redirect_uri, + "scope": settings.oidc_scopes, + "state": state, + "nonce": nonce, + "code_challenge": code_challenge, + "code_challenge_method": "S256", + } + return f"{disc.authorization_endpoint}?{urlencode(params)}" + + +async def exchange_code(disc: Discovery, code: str, code_verifier: str) -> dict: + data = { + "grant_type": "authorization_code", + "code": code, + "redirect_uri": settings.oidc_redirect_uri, + "client_id": settings.oidc_client_id, + "code_verifier": code_verifier, + } + if settings.oidc_client_secret: + data["client_secret"] = settings.oidc_client_secret + try: + async with httpx.AsyncClient(timeout=_timeout()) as client: + response = await client.post(disc.token_endpoint, data=data) + except httpx.HTTPError as exc: + raise OIDCError(f"token endpoint недоступен: {exc}") from exc + if response.status_code >= 400: + raise OIDCError(f"провайдер отказал в обмене кода ({response.status_code})") + try: + tokens = response.json() + except ValueError as exc: + raise OIDCError("token endpoint вернул не JSON") from exc + if "id_token" not in tokens: + raise OIDCError("в ответе нет id_token — проверь scope openid") + return tokens + + +def id_token_claims(id_token: str) -> dict: + """Payload JWT без проверки подписи — только для nonce и sub (см. докстринг модуля).""" + try: + payload = id_token.split(".")[1] + payload += "=" * (-len(payload) % 4) + return json.loads(base64.urlsafe_b64decode(payload)) + except (IndexError, ValueError) as exc: + raise OIDCError("id_token не разбирается") from exc + + +async def fetch_userinfo(disc: Discovery, access_token: str) -> dict: + if not disc.userinfo_endpoint: + return {} + try: + async with httpx.AsyncClient(timeout=_timeout()) as client: + response = await client.get( + disc.userinfo_endpoint, headers={"Authorization": f"Bearer {access_token}"} + ) + response.raise_for_status() + return response.json() + except (httpx.HTTPError, ValueError): + # Профиль — украшение; sub и группы обычно есть и в id_token. + return {} + + +def display_name_from(claims: dict) -> str: + for key in ("name", "preferred_username", "nickname", "email"): + value = claims.get(key) + if isinstance(value, str) and value.strip(): + return value.strip()[:120] + return f"user-{claims.get('sub', '')[:8]}" + + +def groups_from(claims: dict) -> set[str]: + raw = claims.get(settings.oidc_groups_claim) + if isinstance(raw, str): + raw = [raw] + return {str(g) for g in raw} if isinstance(raw, list) else set() diff --git a/app/routers/accounts.py b/app/routers/accounts.py index ebc05d7..0362941 100644 --- a/app/routers/accounts.py +++ b/app/routers/accounts.py @@ -4,6 +4,7 @@ from fastapi import APIRouter, Form, Request from fastapi.responses import RedirectResponse from sqlalchemy import select +from app.config import settings from app.deps import CurrentUser, SessionDep from app.models import Platform, PlatformAccount from app.services import verification @@ -38,6 +39,34 @@ async def accounts_page(request: Request, user: CurrentUser): ) +def _login_methods(user) -> int: + """Сколько способов входа осталось. Последний отвязывать нельзя.""" + return sum(1 for value in (user.telegram_id, user.oidc_sub) if value) + + +@router.post("/telegram/unlink") +async def unlink_telegram(session: SessionDep, user: CurrentUser): + if user.telegram_id is None: + return _back(error="Telegram не привязан") + if _login_methods(user) < 2: + return _back(error="Это единственный способ входа — сначала привяжи другой") + user.telegram_id = None + user.telegram_username = None + await session.commit() + return _back(message="Telegram отвязан") + + +@router.post("/oidc/unlink") +async def unlink_oidc(session: SessionDep, user: CurrentUser): + if user.oidc_sub is None: + return _back(error=f"{settings.oidc_provider_name} не привязан") + if _login_methods(user) < 2: + return _back(error="Это единственный способ входа — сначала привяжи другой") + user.oidc_sub = None + await session.commit() + return _back(message=f"{settings.oidc_provider_name} отвязан") + + @router.post("/link") async def link_account( session: SessionDep, diff --git a/app/routers/auth.py b/app/routers/auth.py index bf9bcf9..b22dfed 100644 --- a/app/routers/auth.py +++ b/app/routers/auth.py @@ -2,13 +2,15 @@ from __future__ import annotations import secrets from datetime import timedelta +from urllib.parse import quote from fastapi import APIRouter, Form, Request from fastapi.responses import JSONResponse, RedirectResponse from sqlalchemy import func, select +from app import oidc from app.config import settings -from app.deps import OptionalUser, SessionDep +from app.deps import CurrentUser, OptionalUser, SessionDep, get_optional_user from app.models import LoginToken, Role, User, utcnow from app.security import issue_session from app.templating import templates @@ -64,6 +66,158 @@ async def _resolve_user(session: SessionDep, token: LoginToken) -> User: return user +async def _resolve_oidc_user(session: SessionDep, claims: dict, groups: set[str]) -> User: + sub = str(claims["sub"]) + user = await session.scalar(select(User).where(User.oidc_sub == sub)) + teacher_by_group = bool(groups & settings.oidc_teacher_group_set) + if user is None: + first = await _is_first_user(session) + user = User( + display_name=oidc.display_name_from(claims), + email=claims.get("email"), + oidc_sub=sub, + role=Role.teacher if (first or teacher_by_group) else Role.student, + ) + session.add(user) + else: + user.email = claims.get("email") or user.email + # Группа провайдера — источник истины на повышение. Понижать автоматически + # не станем: преподаватель мог получить роль иначе (первый вход, вручную). + if teacher_by_group: + user.role = Role.teacher + await session.commit() + await session.refresh(user) + return user + + +@router.get("/login/telegram/link") +async def link_telegram_start(request: Request, session: SessionDep, user: CurrentUser): + """Привязка Telegram к уже существующей учётке (например, входу через OIDC).""" + if not (settings.telegram_bot_token and settings.telegram_bot_username): + message = quote("Telegram-бот не настроен") + return RedirectResponse(f"/accounts?err={message}", status_code=303) + + token = LoginToken( + code=secrets.token_urlsafe(9).replace("-", "_"), + expires_at=utcnow() + timedelta(seconds=settings.login_code_ttl_seconds), + link_user_id=user.id, + ) + session.add(token) + await session.commit() + return templates.TemplateResponse( + request, + "link_telegram.html", + { + "user": user, + "code": token.code, + "deep_link": settings.telegram_login_url_template.format(code=token.code), + }, + ) + + +@router.get("/login/oidc") +async def login_oidc_start(request: Request, user: OptionalUser, link: int = 0): + # link=1 — привязать провайдера к текущей учётке, а не входить заново. + linking = bool(link) and user is not None + if user is not None and not linking: + return RedirectResponse("/", status_code=303) + if not settings.oidc_enabled: + return RedirectResponse("/login?err=" + quote("OIDC-вход не настроен"), status_code=303) + try: + disc = await oidc.discover() + except oidc.OIDCError as exc: + message = quote(f"{settings.oidc_provider_name}: {exc}") + return RedirectResponse(f"/login?err={message}", status_code=303) + + state, nonce = secrets.token_urlsafe(24), secrets.token_urlsafe(24) + verifier, challenge = oidc.pkce_pair() + next_url = request.query_params.get("next", "/") + if not next_url.startswith("/") or next_url.startswith("//"): + next_url = "/" + + response = RedirectResponse( + oidc.authorization_url(disc, state=state, nonce=nonce, code_challenge=challenge), + status_code=303, + ) + response.set_cookie( + oidc.STATE_COOKIE, + oidc.pack_state({ + "state": state, "nonce": nonce, "verifier": verifier, + "next": "/accounts" if linking else next_url, + "link_user_id": user.id if linking else None, + }), + max_age=oidc.STATE_TTL, + httponly=True, + samesite="lax", + secure=settings.base_url.startswith("https://"), + path="/login/oidc", + ) + return response + + +@router.get("/login/oidc/callback") +async def login_oidc_callback(request: Request, session: SessionDep): + def fail(message: str) -> RedirectResponse: + response = RedirectResponse("/login?err=" + quote(message), status_code=303) + response.delete_cookie(oidc.STATE_COOKIE, path="/login/oidc") + return response + + if error := request.query_params.get("error"): + detail = request.query_params.get("error_description") or error + return fail(f"{settings.oidc_provider_name}: {detail}") + + saved = oidc.unpack_state(request.cookies.get(oidc.STATE_COOKIE)) + if saved is None or request.query_params.get("state") != saved.get("state"): + return fail("Сессия входа устарела, попробуй ещё раз") + code = request.query_params.get("code") + if not code: + return fail("Провайдер не вернул код") + + try: + disc = await oidc.discover() + tokens = await oidc.exchange_code(disc, code, saved["verifier"]) + claims = oidc.id_token_claims(tokens["id_token"]) + except oidc.OIDCError as exc: + return fail(f"{settings.oidc_provider_name}: {exc}") + + if claims.get("nonce") != saved.get("nonce"): + return fail("Ответ провайдера не совпал с запросом") + if "sub" not in claims: + return fail("В токене нет идентификатора пользователя") + + userinfo = await oidc.fetch_userinfo(disc, tokens.get("access_token", "")) + merged = {**claims, **userinfo} + groups = oidc.groups_from(merged) + + link_user_id = saved.get("link_user_id") + if link_user_id is not None: + current = await get_optional_user(request, session) + if current is None or current.id != link_user_id: + return fail("Войди и начни привязку заново") + taken = await session.scalar( + select(User).where(User.oidc_sub == str(merged["sub"]), User.id != current.id) + ) + if taken is not None: + return fail( + f"Этот аккаунт {settings.oidc_provider_name} уже привязан к другому участнику" + ) + current.oidc_sub = str(merged["sub"]) + current.email = merged.get("email") or current.email + if groups & settings.oidc_teacher_group_set: + current.role = Role.teacher + await session.commit() + ok = quote(f"{settings.oidc_provider_name} привязан") + response = RedirectResponse(f"/accounts?ok={ok}", status_code=303) + response.delete_cookie(oidc.STATE_COOKIE, path="/login/oidc") + return response + + user = await _resolve_oidc_user(session, merged, groups) + target = RedirectResponse(saved.get("next") or "/", status_code=303) + response = _set_session_cookie(target, user.id) + response.delete_cookie(oidc.STATE_COOKIE, path="/login/oidc") + return response + + @router.get("/login") async def login_page(request: Request, session: SessionDep, user: OptionalUser): if user is not None: @@ -87,6 +241,9 @@ async def login_page(request: Request, session: SessionDep, user: OptionalUser): if token else None, "dev_login": settings.dev_login_enabled, + "oidc_enabled": settings.oidc_enabled, + "oidc_name": settings.oidc_provider_name, + "next": request.query_params.get("next", "/"), "error": request.query_params.get("err"), }, ) @@ -107,7 +264,7 @@ async def login_status(code: str, session: SessionDep): @router.get("/login/complete/{code}") -async def login_complete(code: str, session: SessionDep): +async def login_complete(request: Request, code: str, session: SessionDep): token = await session.scalar(select(LoginToken).where(LoginToken.code == code)) now = utcnow() if ( @@ -119,6 +276,30 @@ async def login_complete(code: str, session: SessionDep): ): return RedirectResponse("/login?err=Код+недействителен", status_code=303) + if token.link_user_id is not None: + # Привязку завершает тот же браузер, что её начал, — иначе чужой код + # мог бы прицепить чужой Telegram к этой учётке. + current = await get_optional_user(request, session) + if current is None or current.id != token.link_user_id: + # Неавторизованного /accounts всё равно отправит на вход — ведём сразу туда. + message = quote("Войди и начни привязку заново") + target = "/accounts" if current else "/login" + return RedirectResponse(f"{target}?err={message}", status_code=303) + + taken = await session.scalar( + select(User).where(User.telegram_id == token.telegram_id, User.id != current.id) + ) + if taken is not None: + return RedirectResponse( + "/accounts?err=" + quote("Этот Telegram уже привязан к другому участнику"), + status_code=303, + ) + current.telegram_id = token.telegram_id + current.telegram_username = token.telegram_username + token.consumed_at = now + await session.commit() + return RedirectResponse("/accounts?ok=" + quote("Telegram привязан"), status_code=303) + token.consumed_at = now user = await _resolve_user(session, token) await session.commit() diff --git a/app/routers/teacher.py b/app/routers/teacher.py index 6530b9e..7612867 100644 --- a/app/routers/teacher.py +++ b/app/routers/teacher.py @@ -9,6 +9,7 @@ from fastapi.responses import RedirectResponse from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession +from app import notify from app.deps import SessionDep, TeacherUser from app.models import ( Announcement, @@ -192,6 +193,24 @@ async def group_detail(request: Request, session: SessionDep, user: TeacherUser, ) +@router.post("/groups/{group_id}/chat") +async def set_group_chat( + session: SessionDep, user: TeacherUser, group_id: int, chat_id: str = Form("") +): + group = await session.get(Group, group_id) + if group is None: + return _redirect("/teacher/groups", error="Группа+не+найдена") + chat = chat_id.strip() + if chat and not chat.lstrip("-").isdigit(): + return _redirect( + f"/teacher/groups/{group_id}", error="Id+чата+—+число,+например+-1001234567890" + ) + group.telegram_chat_id = chat or None + await session.commit() + message = "Чат+группы+сохранён" if chat else "Чат+группы+отвязан" + return _redirect(f"/teacher/groups/{group_id}", message=message) + + @router.post("/groups/{group_id}/remove/{user_id}") async def remove_member(session: SessionDep, user: TeacherUser, group_id: int, user_id: int): membership = await session.scalar( @@ -411,7 +430,15 @@ async def create_assignment( session.add(assignment) await session.commit() await session.refresh(assignment) - return _redirect(f"/teacher/assignments/{assignment.id}", message="Задание+выдано") + # После refresh связи не загружены — считаем задачи отдельным запросом. + problems = await session.scalar( + select(func.count()).select_from(ProblemSetItem).where( + ProblemSetItem.problem_set_id == problem_set_id + ) + ) + delivered = await notify.notify_assignment(assignment, int(problems or 0), session) + suffix = "+и+отправлено+в+Telegram" if delivered else "" + return _redirect(f"/teacher/assignments/{assignment.id}", message="Задание+выдано" + suffix) @router.get("/assignments/{assignment_id}") @@ -518,7 +545,7 @@ async def announcements_page(request: Request, session: SessionDep, user: Teache return templates.TemplateResponse( request, "teacher/announcements.html", - {"user": user, "items": items, "groups": groups, "now": utcnow(), **_flash(request)}, + {"user": user, "items": items, "groups": groups, "now_ts": utcnow(), **_flash(request)}, ) @@ -548,21 +575,23 @@ async def create_announcement( if start and end and end <= start: return _redirect("/teacher/announcements", error="Конец+раньше+начала") - session.add( - Announcement( - title=title, - body=body.strip() or None, - url=link or None, - url_label=url_label.strip() or None, - group_id=int(group_id) if group_id.strip() else None, - starts_at=start, - ends_at=end, - pinned=pinned, - created_by_id=user.id, - ) + item = Announcement( + title=title, + body=body.strip() or None, + url=link or None, + url_label=url_label.strip() or None, + group_id=int(group_id) if group_id.strip() else None, + starts_at=start, + ends_at=end, + pinned=pinned, + created_by_id=user.id, ) + session.add(item) await session.commit() - return _redirect("/teacher/announcements", message="Объявление+опубликовано") + await session.refresh(item) + delivered = await notify.notify_announcement(item, session) + suffix = "+и+отправлено+в+Telegram" if delivered else "" + return _redirect("/teacher/announcements", message="Объявление+опубликовано" + suffix) @router.post("/announcements/{announcement_id}/pin") diff --git a/app/scheduler.py b/app/scheduler.py index d9972c7..fad04b1 100644 --- a/app/scheduler.py +++ b/app/scheduler.py @@ -8,6 +8,7 @@ from datetime import datetime, timedelta from app.config import settings from app.db import SessionLocal from app.models import utcnow +from app.notify import send_due_reminders from app.services.catalog import get_state, sync_catalog from app.services.sync import relink_orphan_submissions, sync_all @@ -41,6 +42,9 @@ async def run_once() -> None: added = await sync_all(session) if added: logger.info("новых посылок: %s", added) + reminded = await send_due_reminders(session) + if reminded: + logger.info("отправлено напоминаний: %s", reminded) async def run_scheduler(stop_event: asyncio.Event) -> None: diff --git a/app/static/favicon.svg b/app/static/favicon.svg new file mode 100644 index 0000000..b9ca2d8 --- /dev/null +++ b/app/static/favicon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/app/static/fonts/GolosText-cyrillic.woff2 b/app/static/fonts/GolosText-cyrillic.woff2 new file mode 100644 index 0000000..1f2c45b Binary files /dev/null and b/app/static/fonts/GolosText-cyrillic.woff2 differ diff --git a/app/static/fonts/GolosText-latin.woff2 b/app/static/fonts/GolosText-latin.woff2 new file mode 100644 index 0000000..0a0255c Binary files /dev/null and b/app/static/fonts/GolosText-latin.woff2 differ diff --git a/app/static/fonts/JetBrainsMono-Bold.woff2 b/app/static/fonts/JetBrainsMono-Bold.woff2 new file mode 100644 index 0000000..4917f43 Binary files /dev/null and b/app/static/fonts/JetBrainsMono-Bold.woff2 differ diff --git a/app/static/fonts/JetBrainsMono-Medium.woff2 b/app/static/fonts/JetBrainsMono-Medium.woff2 new file mode 100644 index 0000000..669d04c Binary files /dev/null and b/app/static/fonts/JetBrainsMono-Medium.woff2 differ diff --git a/app/static/fonts/JetBrainsMono-Regular.woff2 b/app/static/fonts/JetBrainsMono-Regular.woff2 new file mode 100644 index 0000000..40da427 Binary files /dev/null and b/app/static/fonts/JetBrainsMono-Regular.woff2 differ diff --git a/app/static/fonts/LICENSES.txt b/app/static/fonts/LICENSES.txt new file mode 100644 index 0000000..646e8b0 --- /dev/null +++ b/app/static/fonts/LICENSES.txt @@ -0,0 +1,3 @@ +JetBrains Mono — © JetBrains, SIL Open Font License 1.1 (см. OFL-JetBrainsMono.txt) +Unbounded — © NaN, SIL Open Font License 1.1, https://github.com/NaNxNaN/Unbounded +Golos Text — © Paratype, SIL Open Font License 1.1, https://github.com/paratype/Golos diff --git a/app/static/fonts/OFL-JetBrainsMono.txt b/app/static/fonts/OFL-JetBrainsMono.txt new file mode 100644 index 0000000..8bee414 --- /dev/null +++ b/app/static/fonts/OFL-JetBrainsMono.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/static/fonts/Unbounded-cyrillic.woff2 b/app/static/fonts/Unbounded-cyrillic.woff2 new file mode 100644 index 0000000..f63226a Binary files /dev/null and b/app/static/fonts/Unbounded-cyrillic.woff2 differ diff --git a/app/static/fonts/Unbounded-latin.woff2 b/app/static/fonts/Unbounded-latin.woff2 new file mode 100644 index 0000000..96d8ff5 Binary files /dev/null and b/app/static/fonts/Unbounded-latin.woff2 differ diff --git a/app/static/logo-dark.svg b/app/static/logo-dark.svg new file mode 100644 index 0000000..f898d07 --- /dev/null +++ b/app/static/logo-dark.svg @@ -0,0 +1,11 @@ + + + + + КЛУБ СПОРТИВНОГО + ПРОГРАММИРОВАНИЯ + + ФИИ МГУ + + diff --git a/app/static/logo.svg b/app/static/logo.svg new file mode 100644 index 0000000..3a79ba8 --- /dev/null +++ b/app/static/logo.svg @@ -0,0 +1,11 @@ + + + + + КЛУБ СПОРТИВНОГО + ПРОГРАММИРОВАНИЯ + + ФИИ МГУ + + diff --git a/app/static/mark.svg b/app/static/mark.svg new file mode 100644 index 0000000..0a6c8b3 --- /dev/null +++ b/app/static/mark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/app/static/style.css b/app/static/style.css index 1d62bce..77eb261 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -1,886 +1,493 @@ /* ============================================================ - Токены + Плакат — визуальный язык портала. + Жёлтое поле, чёрные линейки, один тяжёлый гротеск. Три цвета: + жёлтый, чёрный и белый; синий — только для ссылок, красный — + только для ошибок и просрочки. Сложность и статусы кодируются + плотностью заливки, а не цветом. + Тёмная тема — инверсия: чёрное поле, жёлтые линейки. ============================================================ */ + +@font-face { font-family: "Unbounded"; font-weight: 500 800; font-display: swap; + src: local("Unbounded"), url("fonts/Unbounded-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } +@font-face { font-family: "Unbounded"; font-weight: 500 800; font-display: swap; + src: local("Unbounded"), url("fonts/Unbounded-cyrillic.woff2") format("woff2"); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; } +@font-face { font-family: "Golos Text"; font-weight: 400 600; font-display: swap; + src: local("Golos Text"), url("fonts/GolosText-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } +@font-face { font-family: "Golos Text"; font-weight: 400 600; font-display: swap; + src: local("Golos Text"), url("fonts/GolosText-cyrillic.woff2") format("woff2"); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; } +@font-face { font-family: "JetBrains Mono"; font-weight: 400; font-display: swap; + src: local("JetBrains Mono"), url("fonts/JetBrainsMono-Regular.woff2") format("woff2"); } +@font-face { font-family: "JetBrains Mono"; font-weight: 700; font-display: swap; + src: local("JetBrains Mono Bold"), url("fonts/JetBrainsMono-Bold.woff2") format("woff2"); } + :root { color-scheme: light; + --bg: #f4c430; + --panel: #f4c430; + --panel-2: #f8d24f; - --bg: #f4f5f8; - --bg-soft: #eceef3; - --panel: #ffffff; - --panel-2: #fafbfc; + --ink: #111111; + --text: #111111; + --text-2: #3b3312; + --muted: #6e6030; + --line: #111111; + --line-soft: rgba(17, 17, 17, .28); - --text: #101317; - --text-2: #454c57; - --muted: #767f8c; - --line: #e3e6ec; - --line-strong: #ccd2dc; + --inv-bg: #111111; /* инвертированный блок */ + --inv-text: #f4c430; - /* Синий МГУ. Один токен меняет акцент во всём интерфейсе. */ - --accent: #14448f; - --accent-hover: #0f3a7c; - --accent-soft: #e9eefa; - --accent-text: #123f85; + --accent: #1d4ed8; /* только ссылки */ + --err: #c1121f; /* только ошибки, просрочка, live */ + --err-text: #ffffff; - --ok: #0f7b40; - --ok-soft: #e4f6ec; - --warn: #9a5b04; - --warn-soft: #fdf1df; - --bad: #b4231f; - --bad-soft: #fdebea; - - --gold: #b4820d; - --silver: #6c7585; - --bronze: #9a5f32; - - --r-sm: 7px; - --r: 11px; - --r-lg: 16px; - - --shadow-sm: 0 1px 2px rgba(16, 19, 23, .05); - --shadow: 0 2px 4px rgba(16, 19, 23, .05), 0 8px 20px -12px rgba(16, 19, 23, .18); - --shadow-lg: 0 4px 10px rgba(16, 19, 23, .07), 0 20px 40px -20px rgba(16, 19, 23, .25); + --rule: 3px; + --display: "Unbounded", "Arial Black", Impact, sans-serif; + --sans: "Golos Text", -apple-system, "Segoe UI", Roboto, Arial, sans-serif; + --mono: "JetBrains Mono", Menlo, Consolas, monospace; + --rail: 88px; } + +/* ============================================================ + Тёмная тема. По умолчанию портал светлый — жёлтое поле; тёмная включается + кнопкой (data-theme="dark") или выбором «как в системе» (data-theme="auto"). + Два одинаковых набора правил, менять их нужно вместе. + ============================================================ */ @media (prefers-color-scheme: dark) { - :root { + :root[data-theme="auto"] { color-scheme: dark; - - --bg: #0c0e12; - --bg-soft: #12151b; - --panel: #151920; - --panel-2: #1a1f27; - - --text: #eef1f6; - --text-2: #b9c1cd; - --muted: #8a93a1; - --line: #252b35; - --line-strong: #333b47; - - --accent: #6b9ce6; - --accent-hover: #86b0ee; - --accent-soft: #132340; - --accent-text: #8fb6ee; - - --ok: #4ade80; - --ok-soft: #122a1c; - --warn: #fbbf24; - --warn-soft: #2e2410; - --bad: #f87171; - --bad-soft: #2e1616; - - --gold: #e3b341; - --silver: #9aa4b4; - --bronze: #c98a5c; - - --shadow-sm: 0 1px 2px rgba(0, 0, 0, .35); - --shadow: 0 2px 6px rgba(0, 0, 0, .4), 0 10px 24px -14px rgba(0, 0, 0, .7); - --shadow-lg: 0 6px 14px rgba(0, 0, 0, .45), 0 24px 48px -24px rgba(0, 0, 0, .8); + --bg: #0f0e0a; + --panel: #0f0e0a; + --panel-2: #1a1810; + --ink: #f4c430; + --text: #f4e9c2; + --text-2: #dcc985; + --muted: #a8975a; + --line: #f4c430; + --line-soft: rgba(244, 196, 48, .3); + --inv-bg: #f4c430; + --inv-text: #111111; + --accent: #9dbcff; + --err: #ff5a5a; + --err-text: #111111; } + :root[data-theme="auto"] .only-light { display: none; } + :root[data-theme="auto"] .only-dark { display: block; } + :root[data-theme="auto"] input[type=text], :root[data-theme="auto"] input[type=number], :root[data-theme="auto"] input[type=datetime-local], :root[data-theme="auto"] select, :root[data-theme="auto"] textarea { background: #1a1810; color: var(--text); } } +:root[data-theme="dark"] { + color-scheme: dark; + --bg: #0f0e0a; + --panel: #0f0e0a; + --panel-2: #1a1810; + --ink: #f4c430; + --text: #f4e9c2; + --text-2: #dcc985; + --muted: #a8975a; + --line: #f4c430; + --line-soft: rgba(244, 196, 48, .3); + --inv-bg: #f4c430; + --inv-text: #111111; + --accent: #9dbcff; + --err: #ff5a5a; + --err-text: #111111; +} +:root[data-theme="dark"] .only-light { display: none; } +:root[data-theme="dark"] .only-dark { display: block; } +:root[data-theme="dark"] input[type=text], :root[data-theme="dark"] input[type=number], :root[data-theme="dark"] input[type=datetime-local], :root[data-theme="dark"] select, :root[data-theme="dark"] textarea { background: #1a1810; color: var(--text); } + *, *::before, *::after { box-sizing: border-box; } - html { -webkit-text-size-adjust: 100%; } - body { - margin: 0; - background: var(--bg); - color: var(--text); - font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, - "Helvetica Neue", Arial, sans-serif; - font-size: 14.5px; - line-height: 1.55; + margin: 0; background: var(--bg); color: var(--text); + font-family: var(--sans); font-size: 15px; line-height: 1.5; -webkit-font-smoothing: antialiased; - font-feature-settings: "tnum" 0; } +a { color: inherit; text-decoration: none; } +/* Ссылки в тексте: подчёркивание вместо цвета — плакат остаётся трёхцветным. + На ховере — инверсия, как маркером по бумаге. */ +main a:not([class]) { color: var(--text); text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; } +main a:not([class]):hover { background: var(--ink); color: var(--bg); text-decoration: none; } +::selection { background: var(--ink); color: var(--bg); } +:focus-visible { outline: var(--rule) solid var(--ink); outline-offset: 2px; } -a { color: var(--accent-text); text-decoration: none; } -a:hover { color: var(--accent-hover); } +.mono, .code-box { font-family: var(--mono); } +.num, .points, .value, .rank, .countdown, .bar-value { font-variant-numeric: tabular-nums; } -::selection { background: var(--accent); color: #fff; } +/* ---------- иконки ---------- */ +.icon { width: 1.1em; height: 1.1em; flex: none; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: square; stroke-linejoin: miter; vertical-align: -.18em; } +.icon.lg { width: 1.5em; height: 1.5em; } +.icon.xl { width: 2em; height: 2em; stroke-width: 1.8; } -:focus-visible { - outline: 2px solid var(--accent); - outline-offset: 2px; - border-radius: var(--r-sm); +/* ---------- метки капсом (общий приём) ---------- */ +.lbl, h2, th, label, .badge, .stat .label, .eyebrow, .feed-day, .ticker-label, .brand-text, .nav a, .tabbar a, .legend, .progress-line, .hm-legend, .heatmap-months, .heatmap-weekdays { + font-family: var(--sans); font-weight: 600; text-transform: uppercase; letter-spacing: .1em; } /* ============================================================ - Иконки + Рейка — чёрный блок плаката ============================================================ */ -.icon { - width: 1.1em; - height: 1.1em; - flex: none; - fill: none; - stroke: currentColor; - stroke-width: 1.9; - stroke-linecap: round; - stroke-linejoin: round; - vertical-align: -.18em; +body.with-rail { padding-left: var(--rail); } +.rail { + position: fixed; inset: 0 auto 0 0; width: var(--rail); + background: var(--inv-bg); color: var(--inv-text); + display: flex; flex-direction: column; z-index: 30; } -.icon.lg { width: 1.5em; height: 1.5em; stroke-width: 1.7; } -.icon.xl { width: 2em; height: 2em; stroke-width: 1.5; } - -/* ============================================================ - Шапка - ============================================================ */ -header.top { - position: sticky; - top: 0; - z-index: 20; - background: color-mix(in srgb, var(--panel) 88%, transparent); - backdrop-filter: saturate(1.6) blur(12px); - border-bottom: 1px solid var(--line); +.rail .brand { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 12px 3px 12px; color: var(--inv-text); border-bottom: var(--rule) solid var(--inv-text); } +.rail .brand .icon { width: 30px; height: 30px; } +.rail .brand:hover { text-decoration: none; } +.brand-text { font-size: 9px; text-align: center; line-height: 1.3; } +.brand-logo { max-width: 82px; height: auto; display: block; } +/* Знак как маска: форма из SVG, цвет — текущий цвет текста. */ +.brand-mark { + display: block; width: 84px; height: 60px; + background: currentColor; + -webkit-mask: var(--mark) center / contain no-repeat; + mask: var(--mark) center / contain no-repeat; } +.brand-mark.small { width: 56px; height: 40px; } +.brand-mark.auth-mark { width: 182px; height: 130px; color: var(--ink); } -.top-inner { - max-width: 1220px; - margin: 0 auto; - padding: 11px 22px; - display: flex; - align-items: center; - gap: 8px; - flex-wrap: wrap; -} - -.brand { - display: inline-flex; - align-items: center; - gap: 8px; - font-weight: 640; - font-size: 15px; - letter-spacing: -.01em; - color: var(--text); - margin-right: 8px; -} -.brand .icon { color: var(--accent); } -.brand:hover { color: var(--text); } - -/* Логотип из файла: высоту задаём мы, ширина подстраивается. */ -.brand-logo { height: 24px; width: auto; display: block; flex: none; } +/* Переключатель темы: показываем иконку текущего состояния. */ +[data-theme-toggle] .icon { display: none; } +[data-theme-toggle][data-theme-state="auto"] .t-auto, +[data-theme-toggle][data-theme-state="light"] .t-light, +[data-theme-toggle][data-theme-state="dark"] .t-dark { display: block; } .only-dark { display: none; } -@media (prefers-color-scheme: dark) { - .only-light { display: none; } - .only-dark { display: block; } + +.rail .nav { display: flex; flex-direction: column; } +.nav a, .tabbar a { + display: flex; flex-direction: column; align-items: center; gap: 6px; + padding: 13px 4px 11px; color: var(--inv-text); font-size: 9.5px; letter-spacing: .06em; + border-bottom: 1px solid var(--line-soft); opacity: .78; } +.nav a .icon, .tabbar a .icon { width: 20px; height: 20px; } +.nav a:hover, .tabbar a:hover { opacity: 1; text-decoration: none; } +.nav a.active, .tabbar a.active { opacity: 1; background: var(--inv-text); color: var(--inv-bg); } +.rail-foot { margin-top: auto; display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 14px 0 16px; border-top: var(--rule) solid var(--inv-text); } +.rail .whoami .avatar { width: 36px; height: 36px; } +.rail-btn { background: transparent; border: none; box-shadow: none; color: var(--inv-text); padding: 6px; opacity: .8; } +.rail-btn:hover { opacity: 1; background: transparent; transform: none; } +.tabbar { display: none; } +.mobile-bar { display: none; } -.nav { display: flex; gap: 2px; flex-wrap: wrap; } -.nav a { - display: inline-flex; - align-items: center; - gap: 7px; - padding: 6px 11px; - border-radius: var(--r-sm); - color: var(--muted); - font-weight: 500; - transition: background .13s, color .13s; +/* ---------- строка события — инвертированная полоса ---------- */ +.ticker { + position: sticky; top: 0; z-index: 20; + display: flex; align-items: center; gap: 16px; + min-height: 48px; padding: 8px 28px; + background: var(--inv-bg); color: var(--inv-text); } -.nav a:hover { background: var(--bg-soft); color: var(--text); } -.nav a.active { background: var(--accent-soft); color: var(--accent-text); } -.nav a.teacher-link { color: var(--accent-text); } +.ticker:hover { text-decoration: none; } +.ticker-label { font-size: 10px; opacity: .8; } +.ticker-title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.ticker .countdown { margin-left: auto; background: transparent; color: var(--inv-text); border: 2px solid var(--inv-text); } +.ticker .countdown[data-state="live"] { background: var(--err); color: var(--err-text); border-color: var(--err); } +.ticker-go { display: inline-flex; } -.spacer { flex: 1 1 auto; } - -.top-user { display: flex; align-items: center; gap: 8px; margin-left: auto; } - -.whoami { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 4px 6px 4px 4px; - border-radius: 99px; - border: 1px solid var(--line); - color: var(--text-2); - font-size: 13px; -} - -main { max-width: 1220px; margin: 0 auto; padding: 26px 22px 80px; } +main { max-width: 1180px; margin: 0 auto; padding: 34px 32px 90px; } /* ============================================================ Типографика ============================================================ */ -h1 { - font-size: 25px; - line-height: 1.25; - letter-spacing: -.022em; - font-weight: 660; - margin: 0 0 6px; -} -h2 { - font-size: 13px; - text-transform: uppercase; - letter-spacing: .07em; - font-weight: 620; - color: var(--muted); - margin: 32px 0 12px; - display: flex; - align-items: center; - gap: 8px; -} -h3 { font-size: 15px; font-weight: 620; letter-spacing: -.01em; margin: 0 0 8px; } - -p.sub { color: var(--muted); margin: 0 0 22px; max-width: 72ch; } - +h1 { font-family: var(--display); font-weight: 800; font-size: 44px; line-height: .95; letter-spacing: -.02em; text-transform: uppercase; margin: 0 0 10px; } +h2 { font-size: 11px; color: var(--text); margin: 38px 0 12px; display: flex; align-items: center; gap: 12px; } +h2::before { content: ""; width: 28px; height: var(--rule); background: var(--ink); flex: none; } +h2::after { content: ""; flex: 1; height: 1px; background: var(--line-soft); } +h2 .icon { display: none; } +h3 { font-family: var(--display); font-weight: 800; font-size: 16px; letter-spacing: -.01em; margin: 0 0 10px; line-height: 1.2; } +.eyebrow { font-size: 10px; color: var(--text); margin: 0 0 8px; display: flex; align-items: center; gap: 8px; } +.eyebrow::before { content: "//"; opacity: .5; } +p.sub { color: var(--text-2); margin: 0 0 24px; max-width: 64ch; font-size: 15px; } .muted { color: var(--muted); } .small { font-size: 13px; } -.mono { - font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; - font-size: .92em; -} - -.page-head { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 16px; - flex-wrap: wrap; - margin-bottom: 4px; -} +.page-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 4px; } /* ============================================================ - Карточки и сетки + Карточки — линейки, без заливки ============================================================ */ -.card { - background: var(--panel); - border: 1px solid var(--line); - border-radius: var(--r); - padding: 17px 19px; - margin-bottom: 14px; - box-shadow: var(--shadow-sm); -} -.card.flat { box-shadow: none; background: var(--panel-2); } - +.card { background: var(--panel); border: var(--rule) solid var(--ink); padding: 20px 22px; margin-bottom: 16px; } +.card.flat { border-width: 1px; border-color: var(--line-soft); } +a.card { display: block; color: inherit; transition: background .12s, color .12s; } +a.card:hover { background: var(--inv-bg); color: var(--inv-text); text-decoration: none; } +a.card:hover .muted, a.card:hover h3 .icon { color: inherit; opacity: .85; } .card.stretch { display: flex; flex-direction: column; } .card.stretch .push-bottom { margin-top: auto; padding-top: 12px; } +.callout { border-left-width: 14px; } +.callout.warn { border-left-color: var(--err); } -a.card { - display: block; - color: inherit; - transition: transform .14s ease, box-shadow .14s ease, border-color .14s ease; -} -a.card:hover { - transform: translateY(-2px); - box-shadow: var(--shadow); - border-color: var(--line-strong); - color: inherit; -} -a.card h3 { display: flex; align-items: center; gap: 9px; } -a.card h3 .icon { color: var(--accent); } - -.grid { display: grid; gap: 14px; } +.grid { display: grid; gap: 16px; } .grid.two { grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); } -.grid.three { grid-template-columns: repeat(auto-fit, minmax(290px, 1fr)); } -.grid.stats { grid-template-columns: repeat(auto-fit, minmax(155px, 1fr)); } - +.grid.three { grid-template-columns: repeat(auto-fit, minmax(290px, 1fr)); counter-reset: sec; } +.grid.three > a.card h3::before { counter-increment: sec; content: counter(sec, decimal-leading-zero); font-size: 12px; opacity: .55; margin-right: 6px; } +.grid.three > a.card h3 .icon { display: none; } +.grid.stats { grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 0; border: var(--rule) solid var(--ink); } .row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .between { justify-content: space-between; } -/* ============================================================ - Плитки со статистикой - ============================================================ */ -.stat { - background: var(--panel); - border: 1px solid var(--line); - border-radius: var(--r); - padding: 15px 17px; - box-shadow: var(--shadow-sm); -} -.stat .icon { color: var(--muted); margin-bottom: 6px; } -.stat .value { - font-size: 27px; - font-weight: 660; - letter-spacing: -.03em; - line-height: 1.15; - font-variant-numeric: tabular-nums; -} -.stat .label { color: var(--muted); font-size: 12.5px; margin-top: 2px; } +/* ---------- плитки статистики — ячейки одной таблицы ---------- */ +.stat { padding: 18px 20px 20px; border-right: var(--rule) solid var(--ink); } +.stat:last-child { border-right: none; } +.stat .icon { display: none; } +.stat .value { font-family: var(--display); font-weight: 800; font-size: 52px; line-height: .9; letter-spacing: -.03em; } +.stat .label { font-size: 10px; color: var(--text-2); margin-top: 10px; } -/* ============================================================ - Аватарки - ============================================================ */ -.avatar { - width: 32px; - height: 32px; - border-radius: 50%; - display: inline-flex; - align-items: center; - justify-content: center; - font-size: 11.5px; - font-weight: 640; - letter-spacing: .02em; - flex: none; - background: hsl(var(--h) 62% 92%); - color: hsl(var(--h) 55% 30%); - border: 1px solid hsl(var(--h) 45% 84%); -} -.avatar.sm { width: 24px; height: 24px; font-size: 10px; } -.avatar.lg { width: 52px; height: 52px; font-size: 18px; } - -@media (prefers-color-scheme: dark) { - /* На тёмном фоне пустые клетки сливаются с карточкой — поднимаем контраст. */ - .heatmap i { background: #232932; border-color: #2d343f; } - - .avatar { - background: hsl(var(--h) 38% 20%); - color: hsl(var(--h) 70% 76%); - border-color: hsl(var(--h) 35% 30%); - } -} +/* ---------- аватарки ---------- */ +.avatar { width: 32px; height: 32px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-family: var(--display); font-size: 11px; font-weight: 800; flex: none; background: var(--inv-bg); color: var(--inv-text); } +.avatar.sm { width: 24px; height: 24px; font-size: 9px; } +.avatar.lg { width: 60px; height: 60px; font-size: 20px; } +.rail .avatar { background: var(--inv-text); color: var(--inv-bg); } /* ============================================================ Таблицы ============================================================ */ -.table-wrap { overflow-x: auto; border-radius: var(--r); } - +.table-wrap { overflow-x: auto; } table { width: 100%; border-collapse: collapse; } -th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); } -th { - font-size: 11.5px; - text-transform: uppercase; - letter-spacing: .05em; - color: var(--muted); - font-weight: 620; - white-space: nowrap; -} -tbody tr { transition: background .12s; } +th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line-soft); font-size: 14px; } +th { font-size: 10px; color: var(--text); border-bottom: var(--rule) solid var(--ink); } tbody tr:hover { background: var(--panel-2); } tbody tr:last-child td { border-bottom: none; } -td.num { font-variant-numeric: tabular-nums; } +.card.table-wrap { padding: 0 6px; } /* ============================================================ Формы ============================================================ */ input[type=text], input[type=number], input[type=datetime-local], select, textarea { - width: 100%; - padding: 8px 11px; - border: 1px solid var(--line-strong); - border-radius: var(--r-sm); - background: var(--panel); - color: var(--text); - font: inherit; - transition: border-color .13s, box-shadow .13s; + width: 100%; padding: 10px 12px; + border: var(--rule) solid var(--ink); background: #fff; color: #111; + font: inherit; border-radius: 0; } -input:focus, select:focus, textarea:focus { - outline: none; - border-color: var(--accent); - box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); -} -input::placeholder, textarea::placeholder { color: color-mix(in srgb, var(--muted) 70%, transparent); } - -textarea { - min-height: 130px; - resize: vertical; - font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - font-size: 13px; - line-height: 1.65; -} - -label { - display: block; - font-size: 12.5px; - font-weight: 520; - color: var(--text-2); - margin-bottom: 5px; -} -label.check { - display: inline-flex; - align-items: center; - gap: 7px; - font-weight: 400; - color: var(--text-2); - cursor: pointer; -} -label.check input { width: auto; margin: 0; accent-color: var(--accent); } - -.field { margin-bottom: 13px; } -.inline-form { display: flex; gap: 9px; align-items: flex-end; flex-wrap: wrap; } +input:focus, select:focus, textarea:focus { outline: none; box-shadow: 4px 4px 0 var(--ink); } +input::placeholder, textarea::placeholder { color: #9a8f6a; } +textarea { min-height: 130px; resize: vertical; font-family: var(--mono); font-size: 13px; line-height: 1.6; } +label { display: block; font-size: 10px; color: var(--text); margin-bottom: 6px; } +label.check { display: inline-flex; align-items: center; gap: 8px; text-transform: none; letter-spacing: 0; font-weight: 400; font-size: 14px; cursor: pointer; } +label.check input { width: auto; margin: 0; accent-color: var(--ink); } +.field { margin-bottom: 14px; } +.inline-form { display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap; } .inline-form .field { margin-bottom: 0; } /* ============================================================ - Кнопки + Кнопки — чёрный блок / контур ============================================================ */ button, .btn { - display: inline-flex; - align-items: center; - gap: 7px; - padding: 8px 15px; - border-radius: var(--r-sm); - border: 1px solid transparent; - background: var(--accent); - color: #fff; - font: inherit; - font-weight: 530; - cursor: pointer; - white-space: nowrap; - transition: background .13s, border-color .13s, color .13s, transform .08s; + display: inline-flex; align-items: center; gap: 8px; + padding: 10px 18px; border: var(--rule) solid var(--ink); + background: var(--inv-bg); color: var(--inv-text); + font: inherit; font-weight: 600; text-transform: uppercase; letter-spacing: .08em; font-size: 12px; + cursor: pointer; white-space: nowrap; border-radius: 0; + transition: transform .08s, box-shadow .08s; } -button:hover, .btn:hover { background: var(--accent-hover); color: #fff; } -button:active, .btn:active { transform: translateY(1px); } - -button.ghost, .btn.ghost { - background: var(--panel); - color: var(--text-2); - border-color: var(--line-strong); -} -button.ghost:hover, .btn.ghost:hover { - background: var(--bg-soft); - color: var(--text); - border-color: var(--line-strong); -} - -button.danger, .btn.danger { - background: transparent; - color: var(--muted); - border-color: var(--line); -} -button.danger:hover, .btn.danger:hover { - background: var(--bad-soft); - color: var(--bad); - border-color: transparent; -} - -button.small, .btn.small { padding: 5px 10px; font-size: 12.5px; gap: 5px; } -button.icon-only { padding: 6px; } +button:hover, .btn:hover { color: var(--inv-text); text-decoration: none; transform: translate(-2px, -2px); box-shadow: 4px 4px 0 var(--ink); } +button:active, .btn:active { transform: none; box-shadow: none; } +button.ghost, .btn.ghost { background: transparent; color: var(--text); } +button.ghost:hover, .btn.ghost:hover { color: var(--text); } +button.danger, .btn.danger { background: transparent; color: var(--text); border-color: var(--line-soft); } +button.danger:hover, .btn.danger:hover { background: var(--err); color: var(--err-text); border-color: var(--err); transform: none; box-shadow: none; } +button.small, .btn.small { padding: 6px 11px; font-size: 10.5px; } /* ============================================================ - Бейджи + Бейджи — плотность заливки вместо цвета ============================================================ */ -.badge { - display: inline-flex; - align-items: center; - gap: 5px; - padding: 2.5px 9px; - border-radius: 99px; - font-size: 12px; - font-weight: 520; - line-height: 1.5; - border: 1px solid var(--line); - color: var(--muted); - white-space: nowrap; -} +.badge { display: inline-flex; align-items: center; gap: 5px; padding: 3px 9px; font-size: 10px; border: 1.5px solid var(--ink); color: var(--text); white-space: nowrap; line-height: 1.5; } .badge .icon { width: 1em; height: 1em; } -.badge.ok { background: var(--ok-soft); color: var(--ok); border-color: transparent; } -.badge.warn { background: var(--warn-soft); color: var(--warn); border-color: transparent; } -.badge.bad { background: var(--bad-soft); color: var(--bad); border-color: transparent; } -.badge.info { background: var(--accent-soft); color: var(--accent-text); border-color: transparent; } -.badge.easy { background: var(--ok-soft); color: var(--ok); border-color: transparent; } -.badge.medium { background: var(--warn-soft); color: var(--warn); border-color: transparent; } -.badge.hard { background: var(--bad-soft); color: var(--bad); border-color: transparent; } -.badge.rating { font-variant-numeric: tabular-nums; } - -.tag { - display: inline-block; - padding: 2.5px 9px; - border-radius: var(--r-sm); - background: var(--bg-soft); - color: var(--text-2); - font-size: 12px; - margin: 0 5px 5px 0; - border: 1px solid var(--line); -} +.badge.easy { border-width: 1.5px; } +.badge.medium { border-width: 3px; padding: 1.5px 7.5px; } +.badge.hard, .badge.ok, .badge.info { background: var(--inv-bg); color: var(--inv-text); border-color: var(--inv-bg); } +.badge.warn { border-width: 3px; padding: 1.5px 7.5px; } +.badge.bad { background: var(--err); color: var(--err-text); border-color: var(--err); } +.badge.hot { background: var(--inv-bg); color: var(--inv-text); } +a.badge:hover { text-decoration: none; opacity: .85; } +.tag { display: inline-block; padding: 3px 9px; font-size: 12px; margin: 0 6px 6px 0; border: 1.5px solid var(--ink); } /* ============================================================ - Флеш-сообщения + Флеши ============================================================ */ -.flash { - display: flex; - align-items: flex-start; - gap: 9px; - padding: 11px 15px; - border-radius: var(--r); - margin-bottom: 16px; - font-size: 13.5px; - border: 1px solid transparent; -} -.flash .icon { margin-top: .15em; } -.flash.ok { background: var(--ok-soft); color: var(--ok); } -.flash.err { background: var(--bad-soft); color: var(--bad); } +.flash { display: flex; align-items: flex-start; gap: 10px; padding: 12px 16px; margin-bottom: 18px; font-weight: 600; border: var(--rule) solid var(--ink); } +.flash.ok { background: var(--inv-bg); color: var(--inv-text); } +.flash.err { background: var(--err); color: var(--err-text); border-color: var(--err); } /* ============================================================ Прогресс ============================================================ */ -.bar { - height: 7px; - border-radius: 99px; - background: var(--bg-soft); - overflow: hidden; - border: 1px solid var(--line); -} -.bar > span { - display: block; - height: 100%; - border-radius: 99px; - background: linear-gradient(90deg, var(--accent), color-mix(in srgb, var(--accent) 55%, var(--ok))); - transition: width .3s ease; -} -.bar.done > span { background: var(--ok); } -.progress-line { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 10px; - font-size: 12.5px; - color: var(--muted); - margin-top: 7px; -} -.progress-line b { color: var(--text); font-variant-numeric: tabular-nums; } +.bar { height: 14px; border: 2px solid var(--ink); background: transparent; overflow: hidden; } +.bar > span { display: block; height: 100%; background: var(--ink); transition: width .3s; } +.progress-line { display: flex; justify-content: space-between; font-size: 10px; margin-top: 8px; color: var(--text-2); } +.progress-line b { color: var(--text); } /* ============================================================ - Матрица решений + Матрица — вердикты плотностью ============================================================ */ -.matrix td, .matrix th { text-align: center; padding: 7px 5px; } -.matrix td:first-child, .matrix th:first-child { - text-align: left; - position: sticky; - left: 0; - background: var(--panel); - min-width: 190px; - box-shadow: 1px 0 0 var(--line); -} -.matrix tbody tr:hover td:first-child { background: var(--panel-2); } -.matrix th a { color: var(--muted); font-variant-numeric: tabular-nums; } - -.cell { - display: inline-flex; - align-items: center; - justify-content: center; - width: 25px; - height: 25px; - border-radius: var(--r-sm); - font-size: 13px; - border: 1px solid transparent; -} -.cell .icon { width: 14px; height: 14px; stroke-width: 2.6; } -.cell.solved_in_time { background: var(--ok-soft); color: var(--ok); } -.cell.solved_late { background: var(--warn-soft); color: var(--warn); } -.cell.solved_before { background: var(--bg-soft); color: var(--muted); border-color: var(--line); } -.cell.not_solved { background: transparent; color: var(--line-strong); } -.cell.not_solved::after { content: "·"; font-size: 18px; line-height: 1; } - -.legend { display: flex; gap: 16px; flex-wrap: wrap; font-size: 12.5px; color: var(--muted); } -.legend span.item { display: inline-flex; align-items: center; gap: 6px; } +.matrix td, .matrix th { text-align: center; padding: 6px 4px; } +.matrix td:first-child, .matrix th:first-child { text-align: left; position: sticky; left: 0; background: var(--panel); min-width: 190px; } +.matrix th a { color: var(--text); } +.cell { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border: 2px solid var(--ink); font-weight: 800; } +.cell .icon { width: 14px; height: 14px; stroke-width: 3.2; } +.cell.solved_in_time { background: var(--inv-bg); color: var(--inv-text); } +.cell.solved_late { background: transparent; color: var(--text); } +.cell.solved_before { border-style: dashed; color: var(--muted); } +.cell.not_solved { border-color: var(--line-soft); border-style: dotted; } +.legend { display: flex; gap: 18px; flex-wrap: wrap; font-size: 10px; margin-top: 12px; } +.legend span.item { display: inline-flex; align-items: center; gap: 8px; } /* ============================================================ - Лента решений + Лента ============================================================ */ .feed { display: flex; flex-direction: column; } - -.feed-day { - font-size: 11.5px; - text-transform: uppercase; - letter-spacing: .06em; - font-weight: 620; - color: var(--muted); - padding: 16px 0 8px; -} +.feed-day { font-size: 10px; padding: 18px 0 8px; display: flex; align-items: center; gap: 12px; } +.feed-day::after { content: ""; flex: 1; height: 1px; background: var(--line-soft); } .feed-day:first-child { padding-top: 0; } - -.feed-item { - display: flex; - gap: 12px; - padding: 11px 13px; - border-radius: var(--r); - border: 1px solid transparent; - transition: background .13s, border-color .13s; -} -.feed-item:hover { background: var(--panel-2); border-color: var(--line); } - +.feed-item { display: flex; gap: 14px; padding: 12px 0; border-bottom: 1px solid var(--line-soft); } +.feed-item:last-child { border-bottom: none; } .feed-body { min-width: 0; flex: 1; } -.feed-head { - display: flex; - align-items: baseline; - gap: 8px; - flex-wrap: wrap; -} -.feed-head .who { font-weight: 580; color: var(--text); } -.feed-head .when { color: var(--muted); font-size: 12.5px; margin-left: auto; white-space: nowrap; } -.feed-what { - display: flex; - align-items: baseline; - gap: 8px; - flex-wrap: nowrap; - margin-top: 2px; -} -/* Галочка фиксирована, переносится только сам заголовок. */ -.feed-what .tick { color: var(--ok); flex: none; } +.feed-head { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; } +.feed-head .who { font-weight: 600; color: var(--text); } +.feed-head .when { color: var(--muted); font-size: 12px; margin-left: auto; white-space: nowrap; } +.feed-what { display: flex; align-items: baseline; gap: 10px; flex-wrap: nowrap; margin-top: 3px; } +.feed-what .tick { flex: none; font-family: var(--display); font-size: 10px; font-weight: 800; padding: 2px 6px; background: var(--inv-bg); color: var(--inv-text); line-height: 1.5; } +.feed-what .tick .icon { display: none; } +.feed-what .tick::before { content: "AC"; } .feed-what .title-wrap { min-width: 0; } -.feed-what .title { font-weight: 500; color: var(--text); } -.feed-meta { margin-top: 4px; display: flex; gap: 8px; flex-wrap: wrap; font-size: 12.5px; } +.feed-what .title { font-weight: 600; color: var(--text); } +.feed-meta { margin-top: 6px; display: flex; gap: 6px; flex-wrap: wrap; } /* ============================================================ Лидерборд ============================================================ */ -.rank { - font-weight: 660; - font-variant-numeric: tabular-nums; - color: var(--muted); - white-space: nowrap; - width: 1%; -} -.rank .icon { margin-right: 3px; } -.rank.m1 { color: var(--gold); } -.rank.m2 { color: var(--silver); } -.rank.m3 { color: var(--bronze); } -tr.me { background: var(--accent-soft); } -tr.me:hover { background: var(--accent-soft); } -tr.me td:first-child { box-shadow: inset 3px 0 0 var(--accent); } -.points { font-variant-numeric: tabular-nums; font-weight: 620; font-size: 15px; } +.rank { font-family: var(--display); font-weight: 800; font-size: 18px; white-space: nowrap; width: 1%; text-align: center; } +.rank .icon { display: none; } +td.rank.m1, td.rank.m2, td.rank.m3 { background: var(--inv-bg); color: var(--inv-text); } +td.rank.m2, td.rank.m3 { opacity: .75; } +tr.me { outline: var(--rule) solid var(--ink); outline-offset: -3px; } +.points { font-family: var(--display); font-weight: 800; font-size: 18px; } /* ============================================================ Карта активности ============================================================ */ .heatmap-scroll { overflow-x: auto; padding-bottom: 4px; } -.heatmap-body { display: flex; gap: 6px; } - +.heatmap-body { display: flex; gap: 8px; } .heatmap { display: flex; gap: 3px; } .hm-col { display: grid; grid-template-rows: repeat(7, 12px); gap: 3px; } - -.heatmap i, -.hm-legend i { - width: 12px; - height: 12px; - border-radius: 3px; - display: block; - background: var(--bg-soft); - border: 1px solid var(--line-strong); -} -.heatmap i.l1, .hm-legend i.l1 { background: color-mix(in srgb, var(--ok) 28%, var(--bg-soft)); border-color: transparent; } -.heatmap i.l2, .hm-legend i.l2 { background: color-mix(in srgb, var(--ok) 52%, var(--bg-soft)); border-color: transparent; } -.heatmap i.l3, .hm-legend i.l3 { background: color-mix(in srgb, var(--ok) 76%, var(--bg-soft)); border-color: transparent; } -.heatmap i.l4, .hm-legend i.l4 { background: var(--ok); border-color: transparent; } -/* Дни после сегодняшнего в календаре есть, но их не должно быть видно. */ -.heatmap i.future { background: transparent; border-color: transparent; } - -.heatmap-weekdays { - display: grid; - grid-template-rows: repeat(7, 12px); - gap: 3px; - font-size: 9.5px; - line-height: 12px; - color: var(--muted); - text-align: right; - padding-right: 2px; -} - -.heatmap-months { - display: flex; - gap: 3px; - height: 15px; - font-size: 10.5px; - color: var(--muted); - margin-left: 24px; -} -/* Слот равен ширине столбца; подпись месяца свободно выходит вправо. */ +.heatmap i, .hm-legend i { width: 12px; height: 12px; display: block; border: 1px solid var(--line-soft); background: transparent; } +.heatmap i.l1, .hm-legend i.l1 { background: color-mix(in srgb, var(--ink) 25%, transparent); border-color: transparent; } +.heatmap i.l2, .hm-legend i.l2 { background: color-mix(in srgb, var(--ink) 50%, transparent); border-color: transparent; } +.heatmap i.l3, .hm-legend i.l3 { background: color-mix(in srgb, var(--ink) 75%, transparent); border-color: transparent; } +.heatmap i.l4, .hm-legend i.l4 { background: var(--ink); border-color: transparent; } +.heatmap i.future { border-color: transparent; } +.heatmap-weekdays { display: grid; grid-template-rows: repeat(7, 12px); gap: 3px; font-size: 8px; line-height: 12px; text-align: right; padding-right: 2px; letter-spacing: 0; } +.heatmap-months { display: flex; gap: 3px; height: 16px; font-size: 9px; margin-left: 26px; letter-spacing: .04em; } .hm-slot { width: 12px; flex: none; white-space: nowrap; } - -.hm-legend { display: inline-flex; align-items: center; gap: 3px; } +.hm-legend { display: inline-flex; align-items: center; gap: 4px; font-size: 9px; } .hm-legend i { width: 11px; height: 11px; } -/* ============================================================ - Прочее - ============================================================ */ -.code-box { - font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - font-size: 14px; - background: var(--bg-soft); - border: 1px dashed var(--line-strong); - border-radius: var(--r-sm); - padding: 11px 13px; - word-break: break-all; - user-select: all; - text-align: center; - letter-spacing: .02em; -} - -.empty { - color: var(--muted); - padding: 34px 20px; - text-align: center; - display: flex; - flex-direction: column; - align-items: center; - gap: 9px; - font-size: 13.5px; -} -.empty .icon { color: var(--line-strong); } -td .empty { padding: 26px 12px; } - -.callout { - border-left: 3px solid var(--accent); - background: var(--accent-soft); - border-radius: 0 var(--r) var(--r) 0; -} -.callout.warn { border-left-color: var(--warn); background: var(--warn-soft); } - -.auth-shell { max-width: 460px; margin: 7vh auto 0; } -.auth-logo { - width: 56px; height: 56px; - display: flex; align-items: center; justify-content: center; - border-radius: var(--r-lg); - background: var(--accent-soft); - color: var(--accent-text); - margin-bottom: 16px; -} -/* Файловый логотип показываем как есть, без цветной подложки. */ -.auth-logo.bare { width: auto; height: auto; background: none; border-radius: 0; } -.auth-logo.bare img { max-height: 72px; max-width: 260px; width: auto; height: auto; } - -.divider { height: 1px; background: var(--line); margin: 16px 0; border: none; } - -.bar-row { - display: grid; - grid-template-columns: minmax(72px, 30%) 1fr auto; - align-items: center; - gap: 10px; - padding: 4px 0; - font-size: 13px; -} +/* ---------- полосы ---------- */ +.bar-row { display: grid; grid-template-columns: minmax(72px, 30%) 1fr auto; align-items: center; gap: 12px; padding: 5px 0; font-size: 13px; } .bar-label { color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.bar-track { height: 8px; border-radius: 99px; background: var(--bg-soft); overflow: hidden; } -.bar-fill { display: block; height: 100%; border-radius: 99px; background: var(--accent); min-width: 2px; } -.bar-fill.easy { background: var(--ok); } -.bar-fill.medium { background: var(--warn); } -.bar-fill.hard { background: var(--bad); } -.bar-value { font-variant-numeric: tabular-nums; color: var(--muted); min-width: 2.2em; text-align: right; } +.bar-track { height: 12px; border: 2px solid var(--ink); overflow: hidden; } +.bar-fill { display: block; height: 100%; background: var(--ink); min-width: 2px; } +.bar-fill.easy { opacity: .35; } .bar-fill.medium { opacity: .65; } .bar-fill.hard { opacity: 1; } +.bar-value { min-width: 2.2em; text-align: right; font-weight: 600; font-size: 12px; } -.profile-head { - display: flex; - gap: 16px; - align-items: flex-start; - flex-wrap: wrap; - margin-bottom: 20px; -} -.profile-sync { display: flex; flex-direction: column; align-items: flex-end; gap: 5px; } -@media (max-width: 760px) { - .profile-sync { align-items: flex-start; width: 100%; } -} - -.assignment-line { padding: 9px 0; border-bottom: 1px solid var(--line); } +/* ---------- профиль ---------- */ +.profile-head { display: flex; gap: 18px; align-items: flex-start; flex-wrap: wrap; margin-bottom: 24px; } +.profile-sync { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; } +.assignment-line { padding: 10px 0; border-bottom: 1px solid var(--line-soft); } .assignment-line:last-child { border-bottom: none; padding-bottom: 0; } -.assignment-line .bar { margin-top: 7px; } +.assignment-line .bar { margin-top: 8px; } -/* ---- Объявления ---- */ -.announce { - background: var(--panel); - border: 1px solid var(--line); - border-radius: var(--r); - padding: 16px 18px; - box-shadow: var(--shadow-sm); - display: flex; - flex-direction: column; - gap: 9px; - align-items: flex-start; -} -.announce.pinned { border-color: var(--accent); } -.announce-head { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 12px; - width: 100%; - flex-wrap: wrap; -} -.announce-head h3 { margin: 0; } -.announce .pin { color: var(--warn); } +/* ============================================================ + Объявления и отсчёт + ============================================================ */ +.announce { border: var(--rule) solid var(--ink); padding: 20px 22px; display: flex; flex-direction: column; gap: 10px; align-items: flex-start; background: var(--panel); } +.announce.pinned { background: var(--inv-bg); color: var(--inv-text); } +.announce.pinned .muted, .announce.pinned .announce-body { color: inherit; opacity: .85; } +.announce.pinned .badge { border-color: var(--inv-text); color: var(--inv-text); background: transparent; } +.announce.pinned .btn { background: var(--inv-text); color: var(--inv-bg); border-color: var(--inv-text); } +.announce.pinned .btn:hover { box-shadow: 4px 4px 0 var(--inv-text); color: var(--inv-bg); } +.announce.pinned .countdown { background: var(--inv-text); color: var(--inv-bg); border-color: var(--inv-text); } +.announce-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; width: 100%; flex-wrap: wrap; } +.announce-head h3 { margin: 0; font-size: 20px; } +.announce .pin { display: none; } .announce-meta { gap: 8px; margin: 0; } .announce-body { margin: 0; color: var(--text-2); white-space: pre-line; } -.countdown { - font-variant-numeric: tabular-nums; - font-size: 13px; - font-weight: 570; - padding: 3px 10px; - border-radius: 99px; - white-space: nowrap; - background: var(--bg-soft); - color: var(--muted); - border: 1px solid var(--line); -} -.countdown[data-state="upcoming"] { background: var(--warn-soft); color: var(--warn); border-color: transparent; } -.countdown[data-state="live"] { background: var(--ok-soft); color: var(--ok); border-color: transparent; } -.countdown[data-state="past"] { opacity: .7; } +.countdown { font-family: var(--display); font-weight: 800; font-size: 14px; letter-spacing: .01em; padding: 6px 12px; white-space: nowrap; background: var(--inv-bg); color: var(--inv-text); border: 2px solid var(--inv-bg); } +.countdown[data-state="live"] { background: var(--err); color: var(--err-text); border-color: var(--err); display: inline-flex; align-items: center; gap: 8px; } +.countdown[data-state="live"]::before { content: ""; width: 8px; height: 8px; background: currentColor; animation: pulse 1.2s ease-in-out infinite; } +.countdown[data-state="past"] { opacity: .55; } +@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .25; } } +@media (prefers-reduced-motion: reduce) { .countdown[data-state="live"]::before { animation: none; } } -.steps { display: grid; gap: 10px; counter-reset: step; } -.step { - display: flex; - align-items: flex-start; - gap: 13px; - padding: 13px 15px; - border: 1px solid var(--line); - border-radius: var(--r); - background: var(--panel); - color: inherit; - transition: border-color .14s, transform .14s; -} -.step:hover { border-color: var(--accent); transform: translateX(2px); color: inherit; } -.step .num { - counter-increment: step; - width: 25px; height: 25px; - flex: none; - display: inline-flex; align-items: center; justify-content: center; - border-radius: 50%; - background: var(--accent-soft); - color: var(--accent-text); - font-size: 12.5px; - font-weight: 640; -} -.step .num::before { content: counter(step); } -.step.done { background: var(--panel-2); } -.step.done .num { background: var(--ok-soft); color: var(--ok); } +/* ---------- шаги первого запуска ---------- */ +.steps { display: grid; gap: 0; counter-reset: step; border: var(--rule) solid var(--ink); } +.step { display: flex; align-items: center; gap: 16px; padding: 16px 18px; border-bottom: var(--rule) solid var(--ink); color: inherit; } +.step:last-child { border-bottom: none; } +.step:hover { background: var(--inv-bg); color: var(--inv-text); text-decoration: none; } +.step:hover .step-hint { color: inherit; opacity: .8; } +.step .num { counter-increment: step; width: 40px; height: 40px; flex: none; display: inline-flex; align-items: center; justify-content: center; background: var(--inv-bg); color: var(--inv-text); font-family: var(--display); font-weight: 800; font-size: 14px; } +.step:hover .num { background: var(--inv-text); color: var(--inv-bg); } +.step .num::before { content: counter(step, decimal-leading-zero); } .step.done .num::before { content: "✓"; } -.step.done .step-title { color: var(--muted); text-decoration: line-through; } -.step-title { font-weight: 570; } -.step-hint { font-size: 12.5px; color: var(--muted); } +.step.done .step-title { text-decoration: line-through; opacity: .6; } +.step-title { font-family: var(--display); font-weight: 800; font-size: 15px; } +.step-hint { font-size: 13px; color: var(--muted); } details.formula { margin-top: 6px; } -details.formula summary { - cursor: pointer; - color: var(--accent-text); - font-size: 13px; - list-style: none; -} +details.formula summary { cursor: pointer; color: var(--text); text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; font-size: 13px; list-style: none; font-weight: 600; } details.formula summary::-webkit-details-marker { display: none; } details.formula summary::before { content: "▸ "; } details.formula[open] summary::before { content: "▾ "; } details.formula ul { margin: 8px 0 0; padding-left: 20px; color: var(--text-2); font-size: 13px; } -details.formula li { margin-bottom: 3px; } -/* Второстепенные колонки лидерборда на узких экранах только мешают. */ -@media (max-width: 900px) { - .col-extra { display: none; } -} +/* ---------- прочее ---------- */ +.code-box { font-size: 16px; font-weight: 700; letter-spacing: .06em; background: var(--inv-bg); color: var(--inv-text); padding: 14px; word-break: break-all; user-select: all; text-align: center; } +.empty { color: var(--text-2); padding: 34px 20px; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 10px; font-size: 14px; border: var(--rule) dashed var(--line-soft); } +.empty .icon { opacity: .5; } +.card > .empty { margin: -8px; } +.auth-shell { max-width: 520px; margin: 8vh auto 0; } +.auth-logo { width: 72px; height: 72px; display: flex; align-items: center; justify-content: center; background: var(--inv-bg); color: var(--inv-text); margin-bottom: 22px; } +.auth-logo.bare { width: auto; height: auto; background: none; } +.auth-logo.bare img { max-height: 96px; max-width: 340px; width: auto; height: auto; } +.divider { height: 1px; background: var(--line-soft); margin: 16px 0; border: none; } +/* ============================================================ + Адаптив + ============================================================ */ +@media (max-width: 900px) { .col-extra { display: none; } } @media (max-width: 760px) { - main { padding: 18px 14px 56px; } - .top-inner { padding: 9px 14px; gap: 8px; row-gap: 6px; } - - /* Бренд и пользователь — первая строка, навигация — вторая, с подписями. - Иконки без подписей на мобильном превращались в ребус. */ - .brand { flex: 1 1 auto; margin-right: 0; font-size: 14px; } - .top-user { margin-left: 0; } - .nav { - order: 3; - flex-basis: 100%; - flex-wrap: nowrap; - overflow-x: auto; - scrollbar-width: none; - padding-bottom: 2px; - margin: 0 -14px; - padding-inline: 14px; + body.with-rail { padding-left: 0; padding-bottom: 70px; } + .rail { display: none; } + .mobile-bar { + display: flex; align-items: center; gap: 12px; + padding: 4px 10px 4px 14px; background: var(--inv-bg); color: var(--inv-text); } - .nav::-webkit-scrollbar { display: none; } - /* Иначе не видно, что строка едет вбок. */ - .nav { - -webkit-mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 28px), transparent 100%); - mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 28px), transparent 100%); + .mobile-bar .rail-btn { margin-left: auto; color: var(--inv-text); } + .mobile-brand { + display: flex; align-items: center; gap: 12px; flex: 0 1 auto; min-width: 0; + padding: 4px 0; color: var(--inv-text); + font-family: var(--sans); font-weight: 600; text-transform: uppercase; letter-spacing: .1em; font-size: 11px; } - .nav a { padding: 6px 10px; font-size: 13px; } - .whoami span.name { display: none; } - - h1 { font-size: 21px; } - h2 { margin-top: 26px; } + .mobile-brand .icon { width: 28px; height: 28px; } + .mobile-brand:hover { text-decoration: none; } + .tabbar { position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; display: flex; background: var(--inv-bg); padding: 0 0 env(safe-area-inset-bottom); border-top: var(--rule) solid var(--inv-text); } + .tabbar a { flex: 1; min-width: 0; padding: 9px 2px 7px; border-bottom: none; border-right: 1px solid var(--line-soft); font-size: 8px; letter-spacing: .04em; } + .tabbar a:last-child { border-right: none; } + .tabbar a span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; } + .ticker { padding: 8px 14px; gap: 10px; } + .ticker-label { display: none; } + .ticker .countdown { font-size: 11px; padding: 4px 8px; } + main { padding: 20px 16px 40px; } + h1 { font-size: 30px; } + h2 { margin-top: 28px; } .grid.two, .grid.three { grid-template-columns: 1fr; } - .empty { padding: 24px 14px; } - textarea { font-size: 12.5px; } + .grid.stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .stat { border-right: none; border-bottom: var(--rule) solid var(--ink); } + .stat:nth-child(odd) { border-right: var(--rule) solid var(--ink); } + .stat .value { font-size: 40px; } + .profile-sync { align-items: flex-start; width: 100%; } } diff --git a/app/static/telegram-login.js b/app/static/telegram-login.js new file mode 100644 index 0000000..d6c6508 --- /dev/null +++ b/app/static/telegram-login.js @@ -0,0 +1,62 @@ +/* Вход и привязка через Telegram: опрос подтверждения и автозакрытие вкладки t.me. + + Ссылку открываем сами через window.open, чтобы сохранить ссылку на вкладку + и закрыть её, когда бот подтвердит. Без скрипта ссылка работает обычным + образом (target="_blank" rel="noopener"), только вкладка останется висеть. */ +(function () { + "use strict"; + + var root = document.querySelector("[data-tg-code]"); + if (!root) return; + + var code = root.getAttribute("data-tg-code"); + var statusEl = document.getElementById("tg-status"); + var expired = root.getAttribute("data-tg-expired") || "Код истёк — обнови страницу."; + var opened = null; + var tries = 0; + + var link = document.querySelector("[data-tg-link]"); + if (link) { + link.addEventListener("click", function (event) { + // Без noopener, иначе window.open вернёт null и закрывать будет нечего. + var win = window.open(link.href, "_blank"); + if (win) { + opened = win; + event.preventDefault(); + } + }); + } + + function closeOpened() { + try { + if (opened && !opened.closed) opened.close(); + } catch (e) { + /* вкладку мог закрыть сам пользователь */ + } + } + + function stop(timer, message) { + clearInterval(timer); + if (statusEl) statusEl.textContent = message; + } + + var timer = setInterval(async function () { + if (++tries > 150) { + stop(timer, expired); + return; + } + try { + var response = await fetch("/login/status/" + encodeURIComponent(code)); + var data = await response.json(); + if (data.state === "confirmed") { + clearInterval(timer); + closeOpened(); + window.location = data.next; + } else if (data.state === "expired" || data.state === "unknown") { + stop(timer, expired); + } + } catch (e) { + /* сеть моргнула — попробуем на следующем тике */ + } + }, 2000); +})(); diff --git a/app/static/theme.js b/app/static/theme.js new file mode 100644 index 0000000..7eb2bf3 --- /dev/null +++ b/app/static/theme.js @@ -0,0 +1,56 @@ +/* Переключатель темы: светлая → тёмная → как в системе. + Выбор хранится в localStorage и применяется к . + Начальное значение ставит инлайновый скрипт в , чтобы не мигало. */ +(function () { + "use strict"; + + var KEY = "sport-theme"; + // Порядок обхода; первый — значение по умолчанию. + var ORDER = ["light", "dark", "auto"]; + var LABELS = { + auto: "Тема: как в системе", + light: "Тема: светлая", + dark: "Тема: тёмная", + }; + + function read() { + try { + var value = localStorage.getItem(KEY); + return ORDER.indexOf(value) >= 0 ? value : "light"; + } catch (e) { + return "light"; + } + } + + function apply(value) { + var root = document.documentElement; + // Атрибут ставим всегда, включая "auto": без него CSS даёт светлую тему. + root.setAttribute("data-theme", value); + + var buttons = document.querySelectorAll("[data-theme-toggle]"); + for (var i = 0; i < buttons.length; i++) { + buttons[i].setAttribute("data-theme-state", value); + buttons[i].title = LABELS[value]; + buttons[i].setAttribute("aria-label", LABELS[value]); + } + } + + function cycle() { + var next = ORDER[(ORDER.indexOf(read()) + 1) % ORDER.length]; + try { + localStorage.setItem(KEY, next); + } catch (e) { + /* приватный режим — тема продержится до перезагрузки */ + } + apply(next); + } + + apply(read()); + document.addEventListener("click", function (event) { + var button = event.target.closest("[data-theme-toggle]"); + if (button) { + event.preventDefault(); + cycle(); + } + }); +})(); diff --git a/app/templates/_feed.html b/app/templates/_feed.html index a779632..5a22d1b 100644 --- a/app/templates/_feed.html +++ b/app/templates/_feed.html @@ -41,7 +41,7 @@ {% else %}
{{ icon("activity", "xl") }} -
Пока тихо. Как только кто-нибудь из группы решит задачу, она появится здесь.
+
Пока тихо. Здесь появятся решения группы.
{% endfor %} diff --git a/app/templates/_icons.html b/app/templates/_icons.html index 463487d..4f0c25d 100644 --- a/app/templates/_icons.html +++ b/app/templates/_icons.html @@ -110,6 +110,17 @@ + + + + + + + + + + + diff --git a/app/templates/accounts.html b/app/templates/accounts.html index 69647fc..3f479e9 100644 --- a/app/templates/accounts.html +++ b/app/templates/accounts.html @@ -3,10 +3,52 @@ {% block content %}

Аккаунты платформ

- Портал читает только публичные данные. Пароли и токены не запрашиваются и не хранятся — - достаточно подтвердить, что профиль твой. + Только публичные данные: пароли и токены не нужны.

+

{{ icon("shield") }} Способы входа

+
+
+
+

{{ icon("send") }} Telegram

+ {% if user.telegram_id %}{{ icon("check") }} привязан + {% else %}не привязан{% endif %} +
+ {% if user.telegram_id %} +

{% if user.telegram_username %}@{{ user.telegram_username }}{% else %}id {{ user.telegram_id }}{% endif %}

+

Вход и уведомления о заданиях.

+
+ +
+ {% else %} +

Добавит вход через бота и уведомления.

+ {{ icon("link") }} Привязать + {% endif %} +
+ +
+
+

{{ icon("shield") }} {{ settings.oidc_provider_name }}

+ {% if user.oidc_sub %}{{ icon("check") }} привязан + {% elif settings.oidc_enabled %}не привязан + {% else %}не настроен{% endif %} +
+ {% if user.oidc_sub %} +

{{ user.email or "единый аккаунт факультета" }}

+

Вход по учётной записи факультета.

+
+ +
+ {% elif settings.oidc_enabled %} +

Добавит вход по учётной записи факультета.

+ {{ icon("link") }} Привязать + {% else %} +

Не настроен на этом портале.

+ {% endif %} +
+
+ +

{{ icon("code") }} Аккаунты платформ

{% for platform in platforms %} {% set account = user.account_for(platform) %} @@ -30,8 +72,8 @@

{% if platform.value == "leetcode" %}

- Публично LeetCode отдаёт последние 20 принятых решений. Синк идёт каждые - {{ settings.sync_interval_seconds // 60 }} мин — этого хватает. + LeetCode отдаёт публично последние 20 решений. Синк — каждые + {{ settings.sync_interval_seconds // 60 }} мин, этого хватает.

{% endif %} {% if account.last_sync_error %} @@ -58,14 +100,14 @@
-

После подтверждения код можно убрать из профиля.

+

Потом код можно убрать.

{% endif %} {% else %}

{% if platform.value == "codeforces" %} - Хэндл — то, что стоит в адресе профиля: codeforces.com/profile/tourist + Как в адресе профиля: codeforces.com/profile/tourist {% else %} - Username — то, что стоит в адресе профиля: leetcode.com/u/lee215 + Как в адресе профиля: leetcode.com/u/lee215 {% endif %}

diff --git a/app/templates/announcements.html b/app/templates/announcements.html index fcd4f32..312ee0d 100644 --- a/app/templates/announcements.html +++ b/app/templates/announcements.html @@ -5,6 +5,7 @@ {% block content %}
+

анонсы

Объявления

Анонсы соревнований, сборы и новости клуба.

diff --git a/app/templates/assignment.html b/app/templates/assignment.html index b684a4c..2994e91 100644 --- a/app/templates/assignment.html +++ b/app/templates/assignment.html @@ -59,7 +59,7 @@ {% endif %}

- Задачи, решённые до выдачи задания, не засчитываются{% if assignment.count_prior_solves %} — - но в этом задании преподаватель включил их зачёт{% endif %}. + {% if assignment.count_prior_solves %}В этом задании засчитываются и задачи, + решённые до выдачи.{% else %}Решённое до выдачи задания не засчитывается.{% endif %}

{% endblock %} diff --git a/app/templates/base.html b/app/templates/base.html index 2589059..00c58ae 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -5,6 +5,16 @@ {% block title %}{{ settings.app_name }}{% endblock %} + {# Тему ставим до первой отрисовки, иначе при загрузке мигает светлым. #} + {% if favicon_asset %} @@ -12,65 +22,102 @@ {% endif %} - + {% include "_icons.html" %} {% set path = request.url.path if request else "" %} -{% macro navlink(href, name, label, match=None) -%} - {% set m = match or href %} - +{% macro navlink(href, name, label, extra="") -%} + {% set is_active = (path == href) or (href != '/' and path.startswith(href)) %} + {{ icon(name) }}{{ label }} {%- endmacro %} +{% macro navitems() -%} + {{ navlink("/", "tasks", "Задания") }} + {{ navlink("/announcements", "megaphone", "Анонсы") }} + {{ navlink("/feed", "activity", "Лента") }} + {{ navlink("/leaderboard", "trophy", "Лидерборд") }} + {{ navlink("/accounts", "link", "Аккаунты") }} + {% if user.is_teacher %}{{ navlink("/teacher", "shield", "Жюри", "teacher-link") }}{% endif %} +{%- endmacro %} {% if user %} -
-
- {# В шапке короткая форма: полное название клуба ломает строку рядом с меню. - Целиком оно есть на странице входа и в заголовке вкладки. #} - - {% if brand_logo %} - - {% if brand_logo_dark %} - - {% endif %} - {% else %} - {{ icon("msu", "lg") }} +{# Рейка слева: тёмная полоса на светлой бумаге. На телефоне становится нижней панелью. #} +
+ + + {% endif %} -
- {% if ok %}
{{ icon("check") }}{{ ok }}
{% endif %} - {% if error %}
{{ icon("alert") }}{{ error }}
{% endif %} - {% block content %}{% endblock %} -
+
+ {% if user %} + {# На телефоне рейка скрыта — знак и имя клуба живут в компактной шапке. #} +
+ + {% if brand_mark %} + + {% else %} + {{ icon("msu", "lg") }} + {% endif %} + {{ settings.app_short_name }} + + +
+ {% endif %} + {% if user and ticker %} + {# Ближайшее событие — с любой страницы. #} + + {{ "идёт" if ticker.state(now()) == "live" else "следующее" }} + {{ ticker.title }} + {{ + "идёт сейчас" if ticker.state(now()) == "live" else "скоро" }} + {{ icon("chevron") }} + + {% endif %} + +
+ {% if ok %}
{{ icon("check") }}{{ ok }}
{% endif %} + {% if error %}
{{ icon("alert") }}{{ error }}
{% endif %} + {% block content %}{% endblock %} +
+
+ + diff --git a/app/templates/dashboard.html b/app/templates/dashboard.html index dcef80b..cbf7771 100644 --- a/app/templates/dashboard.html +++ b/app/templates/dashboard.html @@ -4,14 +4,15 @@ {% from "_announce.html" import announce_card %} {% block title %}Задания — {{ settings.app_name }}{% endblock %} {% block content %} +

главная

Привет, {{ user.display_name }}

-

Твои задания и то, чем сейчас живёт клуб.

+

Задания и жизнь клуба.

{% if missing_accounts %}

{{ icon("link") }} Привяжи аккаунты

- Без подтверждённого аккаунта решения не засчитываются. Не привязано: + Без них решения не засчитываются. Не привязано: {% for p in missing_accounts %}{{ p.title }} {% endfor %}

{{ icon("plus") }} Привязать @@ -77,7 +78,7 @@ {% else %}

- {{ icon("inbox") }} Заданий пока нет. Вступи в группу по коду от преподавателя ↓ + {{ icon("inbox") }} Заданий пока нет — вступи в группу по коду ↓

{% endif %} diff --git a/app/templates/event.html b/app/templates/event.html index 2867009..e6db230 100644 --- a/app/templates/event.html +++ b/app/templates/event.html @@ -21,9 +21,9 @@

{{ icon("trophy") }} Правила

- За каждую решённую задачу — {{ event.points_per_problem | pts }} баллов, - за полный комплект — ещё {{ event.full_clear_bonus | pts }}. - Засчитываются только решения, отправленные внутри окна ивента. + {{ event.points_per_problem | pts }} за задачу, + {{ event.full_clear_bonus | pts }} за полный комплект. + Считаются только решения внутри окна.

diff --git a/app/templates/feed.html b/app/templates/feed.html index ee98101..420e729 100644 --- a/app/templates/feed.html +++ b/app/templates/feed.html @@ -4,10 +4,10 @@ {% block content %}
+

протокол

Лента решений

- {% if user.is_teacher %}Что решают в клубе — в порядке поступления. - {% else %}Что решают ребята из твоей группы.{% endif %} + {% if user.is_teacher %}Что решают в клубе.{% else %}Что решают в твоей группе.{% endif %} Событие — первое принятое решение задачи.

diff --git a/app/templates/leaderboard.html b/app/templates/leaderboard.html index 3fec367..76e645d 100644 --- a/app/templates/leaderboard.html +++ b/app/templates/leaderboard.html @@ -4,20 +4,21 @@ {% block content %}
+

табло

Лидерборд

{% if my_place and rows | length > 1 %}Твоё место — {{ my_place }} из {{ rows | length }}.{% endif %} - Баллы начисляются за задачи из заданий и клубных ивентов. + За задачи из заданий и ивентов.

Как считаются баллы
  • LeetCode: Easy — 1, Medium — 3, Hard — 5 баллов.
  • -
  • Codeforces: рейтинг задачи делится на 200 (задача 1600 → 8 баллов).
  • +
  • Codeforces: рейтинг ÷ 200 (задача 1600 → 8 баллов).
  • Решено после дедлайна — половина баллов.
  • -
  • Первым в группе решил задачу — плюс 2.
  • -
  • Закрыл всё задание целиком — плюс 5.
  • -
  • Задачи, решённые до выдачи задания, не засчитываются.
  • +
  • Первым в группе — плюс 2.
  • +
  • Задание целиком — плюс 5.
  • +
  • Решённое до выдачи задания не считается.
diff --git a/app/templates/link_telegram.html b/app/templates/link_telegram.html new file mode 100644 index 0000000..7ce3b34 --- /dev/null +++ b/app/templates/link_telegram.html @@ -0,0 +1,20 @@ +{% extends "base.html" %} +{% block title %}Привязка Telegram — {{ settings.app_name }}{% endblock %} +{% block content %} +

привязка

+

Telegram

+

Вход и уведомления через бота. Аккаунт на портале останется тем же.

+ +
+

Отправь боту /start — страница вернётся сама.

+

+ {{ icon("send") }} Открыть бота

+
+ {{ icon("clock") }}Ждём подтверждения… код живёт {{ settings.login_code_ttl_seconds // 60 }} минут. +
+
+ Отмена +
+ +{% endblock %} diff --git a/app/templates/login.html b/app/templates/login.html index dd836d0..77464c2 100644 --- a/app/templates/login.html +++ b/app/templates/login.html @@ -2,7 +2,13 @@ {% block title %}Вход — {{ settings.app_name }}{% endblock %} {% block content %}
- {% if brand_logo %} + {% if brand_mark %} + {# Только знак: название клуба на этой странице и так стоит заголовком. #} + + {% elif brand_logo %}